forked from chyeh/nqm-agent
/
rpc.go
93 lines (74 loc) · 1.59 KB
/
rpc.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"log"
"math"
"net/rpc"
"time"
"github.com/Cepave/common/model"
"github.com/toolkits/net"
)
type SingleConnRpcClient struct {
rpcClient *rpc.Client
RpcServer string
Timeout time.Duration
}
var (
req model.NqmTaskRequest
rpcClient SingleConnRpcClient
)
func (this *SingleConnRpcClient) close() {
if this.rpcClient != nil {
this.rpcClient.Close()
this.rpcClient = nil
}
}
func (this *SingleConnRpcClient) insureConn() {
if this.rpcClient != nil {
return
}
var err error
var retry int = 1
for {
if this.rpcClient != nil {
return
}
this.rpcClient, err = net.JsonRpcClient("tcp", this.RpcServer, this.Timeout)
if err == nil {
return
}
log.Println("[ hbs ] Error on query:", err)
if retry > 6 {
retry = 1
}
time.Sleep(time.Duration(math.Pow(2.0, float64(retry))) * time.Second)
retry++
}
}
func (this *SingleConnRpcClient) Call(method string, args interface{}, reply interface{}) error {
this.insureConn()
timeout := time.Duration(50 * time.Second)
done := make(chan error)
go func() {
err := this.rpcClient.Call(method, args, reply)
done <- err
}()
select {
case <-time.After(timeout):
log.Printf("[WARN] rpc call timeout %v => %v", this.rpcClient, this.RpcServer)
this.close()
case err := <-done:
if err != nil {
this.close()
return err
}
}
return nil
}
func InitRPC() {
rpcClient.RpcServer = GetGeneralConfig().Hbs.RPCServer
req = model.NqmTaskRequest{
Hostname: GetGeneralConfig().Hostname,
IpAddress: GetGeneralConfig().IPAddress,
ConnectionId: GetGeneralConfig().ConnectionID,
}
}