-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathagent.go
74 lines (64 loc) · 2.09 KB
/
agent.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
package agent
import (
"log"
"net"
"strings"
"time"
"github.com/smallnest/agent/codec"
"github.com/smallnest/agent/pb"
"github.com/smallnest/rpcx"
"github.com/smallnest/rpcx/clientselector"
context "golang.org/x/net/context"
"google.golang.org/grpc"
)
var client *rpcx.Client
var server *grpc.Server
func StartAgent(addr string, registry string, opts []string) {
client = createClientSelector(registry, opts...)
lis, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
server = grpc.NewServer()
pb.RegisterAgentServer(server, &agentServer{})
if err := server.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
func Stop() {
server.Stop()
}
type agentServer struct{}
func (s *agentServer) Call(ctx context.Context, req *pb.RpcRequest) (*pb.RpcReply, error) {
//invoke services in rpcx
var reply []byte
err := client.Call(req.Name, req.Data, &reply)
rpcReply := &pb.RpcReply{}
if err == nil {
rpcReply.Data = reply
}
return rpcReply, err
}
func createClientSelector(registry string, opts ...string) *rpcx.Client {
var s rpcx.ClientSelector
switch registry {
case "zookeeper":
s = clientselector.NewZooKeeperClientSelector(strings.Split(opts[0], ","), opts[1], 2*time.Minute, rpcx.WeightedRoundRobin, time.Minute)
case "etcdv3":
s = clientselector.NewEtcdV3ClientSelector(strings.Split(opts[0], ","), opts[1], 2*time.Minute, rpcx.WeightedRoundRobin, time.Minute)
case "consul":
s = clientselector.NewConsulClientSelector(opts[0], opts[1], 2*time.Minute, rpcx.WeightedRoundRobin, time.Minute)
case "multi":
servers := strings.Split(opts[0], ",")
var serverPeers []*clientselector.ServerPeer
for _, server := range servers {
serverPeers = append(serverPeers, &clientselector.ServerPeer{Network: "tcp", Address: server})
}
s = clientselector.NewMultiClientSelector(serverPeers, rpcx.WeightedRoundRobin, time.Minute)
case "direct":
s = &rpcx.DirectClientSelector{Network: opts[0], Address: opts[1], DialTimeout: 10 * time.Second}
}
client := rpcx.NewClient(s)
client.ClientCodecFunc = codec.NewClientCodec
return client
}