gocron/modules/rpc/server/server.go

59 lines
1.3 KiB
Go
Raw Normal View History

2017-05-25 14:32:40 +00:00
package server
import (
2017-09-16 09:58:33 +00:00
"github.com/ouqiang/gocron/modules/rpc/auth"
pb "github.com/ouqiang/gocron/modules/rpc/proto"
"github.com/ouqiang/gocron/modules/utils"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
"net"
2017-05-25 14:32:40 +00:00
)
2017-09-16 09:58:33 +00:00
type Server struct{}
2017-05-25 14:32:40 +00:00
2017-09-16 09:58:33 +00:00
func (s Server) Run(ctx context.Context, req *pb.TaskRequest) (*pb.TaskResponse, error) {
defer func() {
if err := recover(); err != nil {
grpclog.Println(err)
}
}()
output, err := utils.ExecShell(ctx, req.Command)
resp := new(pb.TaskResponse)
resp.Output = output
if err != nil {
resp.Error = err.Error()
} else {
resp.Error = ""
}
2017-05-25 14:32:40 +00:00
2017-09-16 09:58:33 +00:00
return resp, nil
2017-05-25 14:32:40 +00:00
}
2017-09-16 09:58:33 +00:00
func Start(addr string, enableTLS bool, certificate auth.Certificate) {
l, err := net.Listen("tcp", addr)
if err != nil {
grpclog.Fatal(err)
}
2017-09-16 09:58:33 +00:00
var s *grpc.Server
if enableTLS {
tlsConfig, err := certificate.GetTLSConfigForServer()
if err != nil {
grpclog.Fatal(err)
}
opt := grpc.Creds(credentials.NewTLS(tlsConfig))
s = grpc.NewServer(opt)
pb.RegisterTaskServer(s, Server{})
grpclog.Printf("listen %s with TLS", addr)
} else {
s = grpc.NewServer()
pb.RegisterTaskServer(s, Server{})
grpclog.Printf("listen %s", addr)
}
2017-09-16 09:58:33 +00:00
err = s.Serve(l)
grpclog.Fatal(err)
2017-05-25 14:32:40 +00:00
}