gocron/modules/rpc/server/server.go

66 lines
1.5 KiB
Go
Raw Normal View History

2017-05-25 14:32:40 +00:00
package server
import (
"golang.org/x/net/context"
"net"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc"
pb "github.com/ouqiang/gocron/modules/rpc/proto"
2017-05-26 10:09:07 +00:00
"github.com/ouqiang/gocron/modules/utils"
"google.golang.org/grpc/credentials"
2017-05-25 14:32:40 +00:00
)
type Server struct {}
func (s Server) Run(ctx context.Context, req *pb.TaskRequest) (*pb.TaskResponse, error) {
2017-05-29 07:09:41 +00:00
defer func() {
if err := recover(); err != nil {
grpclog.Println(err)
}
} ()
2017-05-26 13:59:01 +00:00
output, err := utils.ExecShell(ctx, req.Command)
2017-05-25 14:32:40 +00:00
resp := new(pb.TaskResponse)
2017-05-26 10:09:07 +00:00
resp.Output = output
2017-05-27 05:10:57 +00:00
if err != nil {
resp.Error = err.Error()
} else {
resp.Error = ""
}
2017-05-25 14:32:40 +00:00
2017-05-27 05:10:57 +00:00
return resp, nil
2017-05-25 14:32:40 +00:00
}
func Start(addr, certFile, keyFile string) {
defer func() {
if err := recover(); err != nil {
grpclog.Println("panic", err)
}
} ()
2017-05-26 10:09:07 +00:00
l, err := net.Listen("tcp", addr)
2017-05-25 14:32:40 +00:00
if err != nil {
grpclog.Fatal(err)
}
var s *grpc.Server
if certFile != "" {
// TLS认证
creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)
if err != nil {
grpclog.Fatalf("Failed to generate credentials %v", err)
}
s = grpc.NewServer(grpc.Creds(creds))
pb.RegisterTaskServer(s, Server{})
grpclog.Printf("listen %s with TLS", addr)
} else {
s = grpc.NewServer()
pb.RegisterTaskServer(s, Server{})
grpclog.Println("listen ", addr)
}
2017-05-26 13:59:01 +00:00
err = s.Serve(l)
if err != nil {
grpclog.Fatal(err)
}
2017-05-25 14:32:40 +00:00
}