-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
server.go
96 lines (85 loc) · 2.21 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package server
import (
"net"
"os"
"os/signal"
"syscall"
"time"
"github.com/ouqiang/gocron/internal/modules/rpc/auth"
pb "github.com/ouqiang/gocron/internal/modules/rpc/proto"
"github.com/ouqiang/gocron/internal/modules/utils"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
)
type Server struct{}
var keepAlivePolicy = keepalive.EnforcementPolicy{
MinTime: 10 * time.Second,
PermitWithoutStream: true,
}
var keepAliveParams = keepalive.ServerParameters{
MaxConnectionIdle: 30 * time.Second,
Time: 30 * time.Second,
Timeout: 3 * time.Second,
}
func (s Server) Run(ctx context.Context, req *pb.TaskRequest) (*pb.TaskResponse, error) {
defer func() {
if err := recover(); err != nil {
log.Error(err)
}
}()
log.Infof("execute cmd start: [id: %d cmd: %s]", req.Id, req.Command)
output, err := utils.ExecShell(ctx, req.Command)
resp := new(pb.TaskResponse)
resp.Output = output
if err != nil {
resp.Error = err.Error()
} else {
resp.Error = ""
}
log.Infof("execute cmd end: [id: %d cmd: %s err: %s]", req.Id, req.Command, resp.Error)
return resp, nil
}
func Start(addr string, enableTLS bool, certificate auth.Certificate) {
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(err)
}
opts := []grpc.ServerOption{
grpc.KeepaliveParams(keepAliveParams),
grpc.KeepaliveEnforcementPolicy(keepAlivePolicy),
}
if enableTLS {
tlsConfig, err := certificate.GetTLSConfigForServer()
if err != nil {
log.Fatal(err)
}
opt := grpc.Creds(credentials.NewTLS(tlsConfig))
opts = append(opts, opt)
}
server := grpc.NewServer(opts...)
pb.RegisterTaskServer(server, Server{})
log.Infof("server listen on %s", addr)
go func() {
err = server.Serve(l)
if err != nil {
log.Fatal(err)
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
for {
s := <-c
log.Infoln("收到信号 -- ", s)
switch s {
case syscall.SIGHUP:
log.Infoln("收到终端断开信号, 忽略")
case syscall.SIGINT, syscall.SIGTERM:
log.Info("应用准备退出")
server.GracefulStop()
return
}
}
}