forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 3
/
rpc_client.go
393 lines (321 loc) · 8.6 KB
/
rpc_client.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package rpc
import (
"crypto/tls"
"errors"
"net"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/sirupsen/logrus"
"github.com/gocraft/health"
uuid "github.com/satori/go.uuid"
"github.com/TykTechnologies/gorpc"
)
var (
GlobalRPCCallTimeout = 30 * time.Second
GlobalRPCPingTimeout = 60 * time.Second
Log = &logrus.Logger{}
Instrument *health.Stream
clientSingleton *gorpc.Client
clientSingletonMu sync.Mutex
funcClientSingleton *gorpc.DispatcherClient
clientIsConnected bool
dispatcher = gorpc.NewDispatcher()
addedFuncs = make(map[string]bool)
config Config
getGroupLoginCallback func(string, string) interface{}
emergencyModeCallback func()
emergencyModeLoadedCallback func()
// rpcLoadCount is a counter to check if this is a cold boot
rpcLoadCount int
rpcEmergencyMode bool
rpcEmergencyModeLoaded bool
killChan = make(chan int)
killed bool
id string
rpcLoginMu sync.Mutex
reLoginRunning uint32
rpcConnectMu sync.Mutex
)
const (
ClientSingletonCall = "gorpcClientCall"
FuncClientSingletonCall = "gorpcDispatcherClientCall"
)
type Config struct {
UseSSL bool `json:"use_ssl"`
SSLInsecureSkipVerify bool `json:"ssl_insecure_skip_verify"`
ConnectionString string `json:"connection_string"`
RPCKey string `json:"rpc_key"`
APIKey string `json:"api_key"`
GroupID string `json:"group_id"`
CallTimeout int `json:"call_timeout"`
PingTimeout int `json:"ping_timeout"`
RPCPoolSize int `json:"rpc_pool_size"`
}
func IsEmergencyMode() bool {
return rpcEmergencyMode
}
func LoadCount() int {
return rpcLoadCount
}
func Reset() {
clientSingleton.Stop()
clientIsConnected = false
clientSingleton = nil
funcClientSingleton = nil
rpcLoadCount = 0
rpcEmergencyMode = false
rpcEmergencyModeLoaded = false
}
func ResetEmergencyMode() {
rpcEmergencyModeLoaded = false
rpcEmergencyMode = false
}
func EmitErrorEvent(jobName string, funcName string, err error) {
if Instrument == nil {
return
}
job := Instrument.NewJob(jobName)
if emitErr := job.EventErr(funcName, err); emitErr != nil {
Log.WithError(emitErr).WithFields(logrus.Fields{
"jobName": jobName,
"funcName": funcName,
})
}
}
func EmitErrorEventKv(jobName string, funcName string, err error, kv map[string]string) {
if Instrument == nil {
return
}
job := Instrument.NewJob(jobName)
if emitErr := job.EventErrKv(funcName, err, kv); emitErr != nil {
Log.WithError(emitErr).WithFields(logrus.Fields{
"jobName": jobName,
"funcName": funcName,
"kv": kv,
})
}
}
// Connect will establish a connection to the RPC server specified in connection options
func Connect(connConfig Config, suppressRegister bool, dispatcherFuncs map[string]interface{},
getGroupLoginFunc func(string, string) interface{},
emergencyModeFunc func(),
emergencyModeLoadedFunc func()) bool {
rpcConnectMu.Lock()
defer rpcConnectMu.Unlock()
config = connConfig
getGroupLoginCallback = getGroupLoginFunc
emergencyModeCallback = emergencyModeFunc
emergencyModeLoadedCallback = emergencyModeLoadedFunc
if clientIsConnected {
Log.Debug("Using RPC singleton for connection")
return true
}
if clientSingleton != nil {
return rpcEmergencyMode != true
}
// RPC Client is unset
// Set up the cache
Log.Info("Setting new RPC connection!")
connID := uuid.NewV4().String()
// Length should fit into 1 byte. Protection if we decide change uuid in future.
if len(connID) > 255 {
panic("connID is too long")
}
if config.UseSSL {
clientCfg := &tls.Config{
InsecureSkipVerify: config.SSLInsecureSkipVerify,
}
clientSingleton = gorpc.NewTLSClient(config.ConnectionString, clientCfg)
} else {
clientSingleton = gorpc.NewTCPClient(config.ConnectionString)
}
if Log.Level != logrus.DebugLevel {
clientSingleton.LogError = gorpc.NilErrorLogger
}
clientSingleton.OnConnect = onConnectFunc
clientSingleton.Conns = config.RPCPoolSize
if clientSingleton.Conns == 0 {
clientSingleton.Conns = 20
}
clientSingleton.Dial = func(addr string) (conn net.Conn, err error) {
dialer := &net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 30 * time.Second,
}
useSSL := config.UseSSL
if useSSL {
cfg := &tls.Config{
InsecureSkipVerify: config.SSLInsecureSkipVerify,
}
conn, err = tls.DialWithDialer(dialer, "tcp", addr, cfg)
} else {
conn, err = dialer.Dial("tcp", addr)
}
if err != nil {
EmitErrorEventKv(
ClientSingletonCall,
"dial",
err,
map[string]string{
"addr": addr,
"useSSL": strconv.FormatBool(useSSL),
},
)
return
}
conn.Write([]byte("proto2"))
conn.Write([]byte{byte(len(connID))})
conn.Write([]byte(connID))
return conn, nil
}
clientSingleton.Start()
loadDispatcher(dispatcherFuncs)
if funcClientSingleton == nil {
funcClientSingleton = dispatcher.NewFuncClient(clientSingleton)
}
if !Login() {
return false
}
if !suppressRegister {
register()
go checkDisconnect()
}
return true
}
func reAttemptLogin(err error) bool {
if atomic.LoadUint32(&reLoginRunning) == 1 {
return false
}
atomic.StoreUint32(&reLoginRunning, 1)
rpcLoginMu.Lock()
if rpcLoadCount == 0 && !rpcEmergencyModeLoaded {
Log.Warning("[RPC Store] --> Detected cold start, attempting to load from cache")
Log.Warning("[RPC Store] ----> Found APIs... beginning emergency load")
rpcEmergencyModeLoaded = true
if emergencyModeLoadedCallback != nil {
go emergencyModeLoadedCallback()
}
}
rpcLoginMu.Unlock()
time.Sleep(time.Second * 3)
atomic.StoreUint32(&reLoginRunning, 0)
if strings.Contains(err.Error(), "Cannot obtain response during timeout") {
reConnect()
return false
}
Log.Warning("[RPC Store] Login failed, waiting 3s to re-attempt")
return Login()
}
func GroupLogin() bool {
if getGroupLoginCallback == nil {
Log.Error("GroupLogin call back is not set")
return false
}
groupLoginData := getGroupLoginCallback(config.APIKey, config.GroupID)
ok, err := FuncClientSingleton("LoginWithGroup", groupLoginData)
if err != nil {
Log.WithError(err).Error("RPC Login failed")
EmitErrorEventKv(
FuncClientSingletonCall,
"LoginWithGroup",
err,
map[string]string{
"GroupID": config.GroupID,
},
)
rpcEmergencyMode = true
go reAttemptLogin(err)
return false
}
if ok == false {
Log.Error("RPC Login incorrect")
rpcEmergencyMode = true
go reAttemptLogin(errors.New("Login incorrect"))
return false
}
Log.Debug("[RPC Store] Group Login complete")
rpcLoadCount++
// Recovery
if rpcEmergencyMode {
rpcEmergencyMode = false
rpcEmergencyModeLoaded = false
if emergencyModeCallback != nil {
emergencyModeCallback()
}
}
return true
}
func Login() bool {
Log.Debug("[RPC Store] Login initiated")
if len(config.APIKey) == 0 {
Log.Fatal("No API Key set!")
}
// If we have a group ID, lets login as a group
if config.GroupID != "" {
return GroupLogin()
}
ok, err := FuncClientSingleton("Login", config.APIKey)
if err != nil {
Log.WithError(err).Error("RPC Login failed")
EmitErrorEvent(FuncClientSingletonCall, "Login", err)
rpcEmergencyMode = true
go reAttemptLogin(err)
return false
}
if ok == false {
Log.Error("RPC Login incorrect")
rpcEmergencyMode = true
go reAttemptLogin(errors.New("Login incorrect"))
return false
}
Log.Debug("[RPC Store] Login complete")
rpcLoadCount++
if rpcEmergencyMode {
rpcEmergencyMode = false
rpcEmergencyModeLoaded = false
if emergencyModeCallback != nil {
emergencyModeCallback()
}
}
return true
}
func FuncClientSingleton(funcName string, request interface{}) (interface{}, error) {
return funcClientSingleton.CallTimeout(funcName, request, GlobalRPCCallTimeout)
}
func onConnectFunc(conn net.Conn) (net.Conn, string, error) {
clientSingletonMu.Lock()
defer clientSingletonMu.Unlock()
clientIsConnected = true
remoteAddr := conn.RemoteAddr().String()
Log.WithField("remoteAddr", remoteAddr).Debug("connected to RPC server")
return conn, remoteAddr, nil
}
func Disconnect() bool {
clientIsConnected = false
return true
}
func reConnect() {
// no-op, let the gorpc client handle it.
}
func register() {
id = uuid.NewV4().String()
Log.Debug("RPC Client registered")
}
func checkDisconnect() {
res := <-killChan
Log.WithField("res", res).Info("RPC Client disconnecting")
killed = true
Disconnect()
}
func loadDispatcher(dispatcherFuncs map[string]interface{}) {
for funcName, funcBody := range dispatcherFuncs {
if addedFuncs[funcName] {
continue
}
dispatcher.AddFunc(funcName, funcBody)
addedFuncs[funcName] = true
}
}