gocron/modules/rpc/server/server.go

99 lines
2.1 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"
"google.golang.org/grpc/metadata"
"errors"
2017-05-25 14:32:40 +00:00
)
type Server struct
{
Token string
}
func (s Server) auth(ctx context.Context) error {
// 验证token是否有效
meta, ok := metadata.FromContext(ctx)
if !ok {
return errors.New("missing metadata")
}
token, ok := meta["token"]
if !ok {
return errors.New("missing param token")
}
if token[0] != s.Token {
return errors.New("invalid token")
}
return nil
}
2017-05-25 14:32:40 +00:00
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)
}
} ()
if s.Token != "" {
err := s.auth(ctx)
if err != nil {
return nil, 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, token 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
server := Server{Token: token}
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
}