-
Notifications
You must be signed in to change notification settings - Fork 52
/
client.go
427 lines (356 loc) · 9.64 KB
/
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package client
import (
"context"
"encoding/json"
"github.com/apex/log"
"github.com/cenkalti/backoff/v4"
config2 "github.com/crawlab-team/crawlab-core/config"
"github.com/crawlab-team/crawlab-core/constants"
"github.com/crawlab-team/crawlab-core/entity"
"github.com/crawlab-team/crawlab-core/errors"
"github.com/crawlab-team/crawlab-core/grpc/middlewares"
"github.com/crawlab-team/crawlab-core/interfaces"
"github.com/crawlab-team/crawlab-core/node/config"
"github.com/crawlab-team/crawlab-core/utils"
grpc2 "github.com/crawlab-team/crawlab-grpc"
"github.com/crawlab-team/go-trace"
"github.com/spf13/viper"
"go.uber.org/dig"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"io"
"sync"
"time"
)
type Client struct {
// dependencies
nodeCfgSvc interfaces.NodeConfigService
// settings
cfgPath string
address interfaces.Address
timeout time.Duration
// internals
conn *grpc.ClientConn
stream grpc2.NodeService_SubscribeClient
msgCh chan *grpc2.StreamMessage
err error
// grpc clients
ModelDelegateClient grpc2.ModelDelegateClient
ModelBaseServiceClient grpc2.ModelBaseServiceClient
NodeClient grpc2.NodeServiceClient
TaskClient grpc2.TaskServiceClient
PluginClient grpc2.PluginServiceClient
}
func (c *Client) Init() (err error) {
// do nothing
return nil
}
func (c *Client) Start() (err error) {
// connect
if err := c.connect(); err != nil {
return err
}
// register rpc services
if err := c.Register(); err != nil {
return err
}
// subscribe
if err := c.subscribe(); err != nil {
return err
}
// handle stream message
go c.handleStreamMessage()
return nil
}
func (c *Client) Stop() (err error) {
// skip if connection is nil
if c.conn == nil {
return nil
}
// grpc server address
address := c.address.String()
// unsubscribe
if err := c.unsubscribe(); err != nil {
return err
}
log.Infof("grpc client unsubscribed from %s", address)
// close connection
if err := c.conn.Close(); err != nil {
return err
}
log.Infof("grpc client disconnected from %s", address)
return nil
}
func (c *Client) Register() (err error) {
// model delegate
c.ModelDelegateClient = grpc2.NewModelDelegateClient(c.conn)
// model base service
c.ModelBaseServiceClient = grpc2.NewModelBaseServiceClient(c.conn)
// node
c.NodeClient = grpc2.NewNodeServiceClient(c.conn)
// task
c.TaskClient = grpc2.NewTaskServiceClient(c.conn)
// plugin
c.PluginClient = grpc2.NewPluginServiceClient(c.conn)
// log
log.Infof("grpc client registered client services")
return nil
}
func (c *Client) GetModelDelegateClient() (res grpc2.ModelDelegateClient) {
return c.ModelDelegateClient
}
func (c *Client) GetModelBaseServiceClient() (res grpc2.ModelBaseServiceClient) {
return c.ModelBaseServiceClient
}
func (c *Client) GetNodeClient() grpc2.NodeServiceClient {
return c.NodeClient
}
func (c *Client) GetTaskClient() grpc2.TaskServiceClient {
return c.TaskClient
}
func (c *Client) GetPluginClient() grpc2.PluginServiceClient {
return c.PluginClient
}
func (c *Client) SetAddress(address interfaces.Address) {
c.address = address
}
func (c *Client) SetTimeout(timeout time.Duration) {
c.timeout = timeout
}
func (c *Client) Context() (ctx context.Context, cancel context.CancelFunc) {
return context.WithTimeout(context.Background(), c.timeout)
}
func (c *Client) NewRequest(d interface{}) (req *grpc2.Request) {
var data []byte
switch d.(type) {
case []byte:
data = d.([]byte)
default:
var err error
data, err = json.Marshal(d)
if err != nil {
panic(err)
}
}
return &grpc2.Request{
NodeKey: c.nodeCfgSvc.GetNodeKey(),
Data: data,
}
}
func (c *Client) GetConfigPath() (path string) {
return c.cfgPath
}
func (c *Client) SetConfigPath(path string) {
c.cfgPath = path
}
func (c *Client) NewModelBaseServiceRequest(id interfaces.ModelId, params interfaces.GrpcBaseServiceParams) (req *grpc2.Request, err error) {
data, err := json.Marshal(params)
if err != nil {
return nil, trace.TraceError(err)
}
msg := &entity.GrpcBaseServiceMessage{
ModelId: id,
Data: data,
}
return c.NewRequest(msg), nil
}
func (c *Client) GetMessageChannel() (msgCh chan *grpc2.StreamMessage) {
return c.msgCh
}
func (c *Client) Restart() (err error) {
if c.needRestart() {
return c.Start()
}
return nil
}
func (c *Client) IsStarted() (res bool) {
return c.conn != nil
}
func (c *Client) IsClosed() (res bool) {
if c.conn != nil {
return c.conn.GetState() == connectivity.Shutdown
}
return false
}
func (c *Client) Err() (err error) {
return c.err
}
func (c *Client) connect() (err error) {
return backoff.RetryNotify(c._connect, backoff.NewExponentialBackOff(), utils.BackoffErrorNotify("grpc client connect"))
}
func (c *Client) _connect() (err error) {
// grpc server address
address := c.address.String()
// timeout context
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
// connection
// TODO: configure dial options
var opts []grpc.DialOption
opts = append(opts, grpc.WithInsecure())
opts = append(opts, grpc.WithBlock())
opts = append(opts, grpc.WithChainUnaryInterceptor(middlewares.GetAuthTokenUnaryChainInterceptor(c.nodeCfgSvc)))
opts = append(opts, grpc.WithChainStreamInterceptor(middlewares.GetAuthTokenStreamChainInterceptor(c.nodeCfgSvc)))
c.conn, err = grpc.DialContext(ctx, address, opts...)
if err != nil {
_ = trace.TraceError(err)
return errors.ErrorGrpcClientFailedToStart
}
log.Infof("grpc client connected to %s", address)
return nil
}
func (c *Client) subscribe() (err error) {
return backoff.RetryNotify(c._subscribe, backoff.NewExponentialBackOff(), utils.BackoffErrorNotify("grpc client subscribe"))
}
func (c *Client) _subscribe() (err error) {
req := c.NewRequest(&entity.NodeInfo{
Key: c.nodeCfgSvc.GetNodeKey(),
IsMaster: false,
})
c.stream, err = c.GetNodeClient().Subscribe(context.Background(), req)
if err != nil {
return trace.TraceError(err)
}
// log
log.Infof("grpc client subscribed to remote server")
return nil
}
func (c *Client) unsubscribe() (err error) {
req := c.NewRequest(&entity.NodeInfo{
Key: c.nodeCfgSvc.GetNodeKey(),
IsMaster: false,
})
if _, err = c.GetNodeClient().Unsubscribe(context.Background(), req); err != nil {
return trace.TraceError(err)
}
return nil
}
func (c *Client) handleStreamMessage() {
for {
// resubscribe if stream is set to nil
if c.stream == nil {
if err := backoff.RetryNotify(c.subscribe, backoff.NewExponentialBackOff(), utils.BackoffErrorNotify("grpc client subscribe")); err != nil {
log.Errorf("subscribe")
return
}
}
// receive stream message
msg, err := c.stream.Recv()
if err != nil {
// set error
c.err = err
// end
if err == io.EOF {
log.Infof("received EOF signal, disconnecting")
return
}
// connection closed
if c.IsClosed() {
return
}
// error
trace.PrintError(err)
c.stream = nil
time.Sleep(1 * time.Second)
continue
}
// send stream message to channel
c.msgCh <- msg
// reset error
c.err = nil
}
}
func (c *Client) needRestart() bool {
switch c.conn.GetState() {
case connectivity.Shutdown, connectivity.TransientFailure:
return true
case connectivity.Idle, connectivity.Connecting, connectivity.Ready:
return false
default:
return false
}
}
func NewClient(opts ...Option) (res interfaces.GrpcClient, err error) {
// client
client := &Client{
address: entity.NewAddress(&entity.AddressOptions{
Host: constants.DefaultGrpcClientRemoteHost,
Port: constants.DefaultGrpcClientRemotePort,
}),
timeout: 10 * time.Second,
msgCh: make(chan *grpc2.StreamMessage),
}
// apply options
for _, opt := range opts {
opt(client)
}
// dependency injection
c := dig.New()
if err := c.Provide(config.ProvideConfigService(client.GetConfigPath())); err != nil {
return nil, err
}
if err := c.Invoke(func(nodeCfgSvc interfaces.NodeConfigService) {
client.nodeCfgSvc = nodeCfgSvc
}); err != nil {
return nil, err
}
// init
if err := client.Init(); err != nil {
return nil, err
}
return client, nil
}
func ProvideClient(path string, opts ...Option) func() (res interfaces.GrpcClient, err error) {
if path == "" {
path = config2.DefaultConfigPath
}
opts = append(opts, WithConfigPath(path))
return func() (res interfaces.GrpcClient, err error) {
return NewClient(opts...)
}
}
var clientStore = sync.Map{}
func GetClient(path string, opts ...Option) (c interfaces.GrpcClient, err error) {
res, ok := clientStore.Load(path)
if !ok {
return createClient(path, opts...)
}
c, ok = res.(interfaces.GrpcClient)
if !ok {
return createClient(path, opts...)
}
return c, nil
}
func ForceGetClient(path string, opts ...Option) (p interfaces.GrpcClient, err error) {
return createClient(path, opts...)
}
func createClient(path string, opts ...Option) (client2 interfaces.GrpcClient, err error) {
viperAddress := viper.GetString("grpc.address")
if viperAddress != "" {
address, err := entity.NewAddressFromString(viperAddress)
if err != nil {
return nil, err
}
opts = append(opts, WithAddress(address))
}
viperCfgPath := viper.GetString("config.path")
if viperCfgPath != "" {
opts = append(opts, WithConfigPath(viperCfgPath))
}
c := dig.New()
if err := c.Provide(ProvideClient(path, opts...)); err != nil {
return nil, trace.TraceError(err)
}
if err := c.Invoke(func(client interfaces.GrpcClient) {
client2 = client
}); err != nil {
return nil, trace.TraceError(err)
}
clientStore.Store(path, client2)
return client2, nil
}
func ProvideGetClient(path string, opts ...Option) func() (res interfaces.GrpcClient, err error) {
return func() (res interfaces.GrpcClient, err error) {
return GetClient(path, opts...)
}
}