gocron/modules/rpc/client/client.go

36 lines
896 B
Go
Raw Normal View History

2017-05-25 14:32:40 +00:00
package client
import (
"google.golang.org/grpc"
pb "github.com/ouqiang/gocron/modules/rpc/proto"
"golang.org/x/net/context"
2017-05-26 10:09:07 +00:00
"fmt"
2017-05-26 13:59:01 +00:00
"time"
2017-05-27 05:10:57 +00:00
"errors"
2017-05-25 14:32:40 +00:00
)
2017-05-27 05:10:57 +00:00
func Exec(ip string, port int, taskReq *pb.TaskRequest) (string, error) {
2017-05-26 10:09:07 +00:00
addr := fmt.Sprintf("%s:%d", ip, port);
conn, err := grpc.Dial(addr, grpc.WithInsecure())
2017-05-25 14:32:40 +00:00
if err != nil {
2017-05-27 05:10:57 +00:00
return "", err
2017-05-25 14:32:40 +00:00
}
defer conn.Close()
c := pb.NewTaskClient(conn)
2017-05-26 13:59:01 +00:00
if taskReq.Timeout <= 0 || taskReq.Timeout > 86400 {
taskReq.Timeout = 86400
}
timeout := time.Duration(taskReq.Timeout) * time.Second
2017-05-27 13:42:18 +00:00
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
2017-05-26 13:59:01 +00:00
resp, err := c.Run(ctx, taskReq)
2017-05-25 14:32:40 +00:00
if err != nil {
2017-05-27 05:10:57 +00:00
return "", err
2017-05-25 14:32:40 +00:00
}
2017-05-26 10:09:07 +00:00
2017-05-27 05:10:57 +00:00
if resp.Error == "" {
return resp.Output, nil
}
return resp.Output, errors.New(resp.Error)
2017-05-25 14:32:40 +00:00
}