-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_grpc.go
577 lines (507 loc) · 14.4 KB
/
server_grpc.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
package boomer
import (
"context"
"fmt"
"net"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/rs/zerolog/log"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
"github.com/httprunner/boomer/data"
"github.com/httprunner/boomer/grpc/messager"
)
type WorkerNode struct {
ID string `json:"id"`
IP string `json:"ip"`
OS string `json:"os"`
Arch string `json:"arch"`
State int32 `json:"state"`
Heartbeat int32 `json:"heartbeat"`
UserCount int64 `json:"user_count"`
WorkerCPUUsage float64 `json:"worker_cpu_usage"`
CPUUsage float64 `json:"cpu_usage"`
CPUWarningEmitted bool `json:"cpu_warning_emitted"`
WorkerMemoryUsage float64 `json:"worker_memory_usage"`
MemoryUsage float64 `json:"memory_usage"`
stream chan *messager.StreamResponse
mutex sync.RWMutex
disconnectedChan chan bool
}
func newWorkerNode(id, ip, os, arch string) *WorkerNode {
stream := make(chan *messager.StreamResponse, 100)
return &WorkerNode{State: StateInit, ID: id, IP: ip, OS: os, Arch: arch, Heartbeat: 3, stream: stream, disconnectedChan: make(chan bool)}
}
func (w *WorkerNode) getState() int32 {
return atomic.LoadInt32(&w.State)
}
func (w *WorkerNode) setState(state int32) {
atomic.StoreInt32(&w.State, state)
}
func (w *WorkerNode) isStarting() bool {
return w.getState() == StateRunning || w.getState() == StateSpawning
}
func (w *WorkerNode) isStopping() bool {
return w.getState() == StateStopping
}
func (w *WorkerNode) isAvailable() bool {
state := w.getState()
return state != StateMissing && state != StateQuitting
}
func (w *WorkerNode) isReady() bool {
state := w.getState()
return state == StateInit || state == StateStopped
}
func (w *WorkerNode) updateHeartbeat(heartbeat int32) {
atomic.StoreInt32(&w.Heartbeat, heartbeat)
}
func (w *WorkerNode) getHeartbeat() int32 {
return atomic.LoadInt32(&w.Heartbeat)
}
func (w *WorkerNode) updateUserCount(spawnCount int64) {
atomic.StoreInt64(&w.UserCount, spawnCount)
}
func (w *WorkerNode) getUserCount() int64 {
return atomic.LoadInt64(&w.UserCount)
}
func (w *WorkerNode) updateCPUUsage(cpuUsage float64) {
w.mutex.Lock()
defer w.mutex.Unlock()
w.CPUUsage = cpuUsage
}
func (w *WorkerNode) getCPUUsage() float64 {
w.mutex.RLock()
defer w.mutex.RUnlock()
return w.CPUUsage
}
func (w *WorkerNode) updateWorkerCPUUsage(workerCPUUsage float64) {
w.mutex.Lock()
defer w.mutex.Unlock()
w.WorkerCPUUsage = workerCPUUsage
}
func (w *WorkerNode) getWorkerCPUUsage() float64 {
w.mutex.RLock()
defer w.mutex.RUnlock()
return w.WorkerCPUUsage
}
func (w *WorkerNode) updateCPUWarningEmitted(cpuWarningEmitted bool) {
w.mutex.Lock()
defer w.mutex.Unlock()
w.CPUWarningEmitted = cpuWarningEmitted
}
func (w *WorkerNode) getCPUWarningEmitted() bool {
w.mutex.RLock()
defer w.mutex.RUnlock()
return w.CPUWarningEmitted
}
func (w *WorkerNode) updateWorkerMemoryUsage(workerMemoryUsage float64) {
w.mutex.Lock()
defer w.mutex.Unlock()
w.WorkerMemoryUsage = workerMemoryUsage
}
func (w *WorkerNode) getWorkerMemoryUsage() float64 {
w.mutex.RLock()
defer w.mutex.RUnlock()
return w.WorkerMemoryUsage
}
func (w *WorkerNode) updateMemoryUsage(memoryUsage float64) {
w.mutex.Lock()
defer w.mutex.Unlock()
w.MemoryUsage = memoryUsage
}
func (w *WorkerNode) getMemoryUsage() float64 {
w.mutex.RLock()
defer w.mutex.RUnlock()
return w.MemoryUsage
}
func (w *WorkerNode) setStream(stream chan *messager.StreamResponse) {
w.mutex.Lock()
defer w.mutex.Unlock()
w.stream = stream
}
func (w *WorkerNode) getStream() chan *messager.StreamResponse {
w.mutex.RLock()
defer w.mutex.RUnlock()
return w.stream
}
func (w *WorkerNode) getWorkerInfo() WorkerNode {
w.mutex.RLock()
defer w.mutex.RUnlock()
return WorkerNode{
ID: w.ID,
IP: w.IP,
OS: w.OS,
Arch: w.Arch,
State: w.getState(),
Heartbeat: w.getHeartbeat(),
UserCount: w.getUserCount(),
WorkerCPUUsage: w.getWorkerCPUUsage(),
CPUUsage: w.getCPUUsage(),
CPUWarningEmitted: w.getCPUWarningEmitted(),
WorkerMemoryUsage: w.getWorkerMemoryUsage(),
MemoryUsage: w.getMemoryUsage(),
}
}
type grpcServer struct {
messager.UnimplementedMessageServer
masterHost string
masterPort int
server *grpc.Server
clients *sync.Map
fromWorker chan *genericMessage
disconnectedChan chan bool
shutdownChan chan bool
wg sync.WaitGroup
}
var (
errMissingMetadata = status.Errorf(codes.InvalidArgument, "missing metadata")
errInvalidToken = status.Errorf(codes.Unauthenticated, "invalid token")
)
func logger(format string, a ...interface{}) {
// FIXME: support server-side and client-side logging to files
log.Info().Msg(fmt.Sprintf(format, a...))
}
// valid validates the authorization.
func valid(authorization []string) bool {
if len(authorization) < 1 {
return false
}
token := strings.TrimPrefix(authorization[0], "Bearer ")
return token == "httprunner-secret-token"
}
func serverUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
// authentication (token verification)
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errMissingMetadata
}
if !valid(md["authorization"]) {
return nil, errInvalidToken
}
m, err := handler(ctx, req)
if err != nil {
logger("RPC failed with error %v", err)
}
return m, err
}
// serverWrappedStream wraps around the embedded grpc.ServerStream, and intercepts the RecvMsg and
// SendMsg method call.
type serverWrappedStream struct {
grpc.ServerStream
}
func (w *serverWrappedStream) RecvMsg(m interface{}) error {
logger("Receive a message (Type: %T) at %s", m, time.Now().Format(time.RFC3339))
return w.ServerStream.RecvMsg(m)
}
func (w *serverWrappedStream) SendMsg(m interface{}) error {
logger("Send a message (Type: %T) at %v", m, time.Now().Format(time.RFC3339))
return w.ServerStream.SendMsg(m)
}
func newServerWrappedStream(s grpc.ServerStream) grpc.ServerStream {
return &serverWrappedStream{s}
}
func serverStreamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
// authentication (token verification)
md, ok := metadata.FromIncomingContext(ss.Context())
if !ok {
return errMissingMetadata
}
if !valid(md["authorization"]) {
return errInvalidToken
}
err := handler(srv, newServerWrappedStream(ss))
if err != nil {
logger("RPC failed with error %v", err)
}
return err
}
func newServer(masterHost string, masterPort int) (server *grpcServer) {
log.Info().Msg("Boomer is built with grpc support.")
server = &grpcServer{
masterHost: masterHost,
masterPort: masterPort,
clients: &sync.Map{},
fromWorker: make(chan *genericMessage, 100),
disconnectedChan: make(chan bool),
shutdownChan: make(chan bool),
wg: sync.WaitGroup{},
}
return server
}
func (s *grpcServer) start() (err error) {
addr := fmt.Sprintf("%v:%v", s.masterHost, s.masterPort)
// Create tls based credential.
creds, err := credentials.NewServerTLSFromFile(data.Path("x509/server_cert.pem"), data.Path("x509/server_key.pem"))
if err != nil {
log.Fatal().Msg(fmt.Sprintf("failed to load key pair: %s", err))
}
opts := []grpc.ServerOption{
grpc.UnaryInterceptor(serverUnaryInterceptor),
grpc.StreamInterceptor(serverStreamInterceptor),
// Enable TLS for all incoming connections.
grpc.Creds(creds),
}
lis, err := net.Listen("tcp", addr)
if err != nil {
log.Error().Err(err).Msg("failed to listen")
return
}
// create gRPC server
s.server = grpc.NewServer(opts...)
// register message server
messager.RegisterMessageServer(s.server, s)
reflection.Register(s.server)
// start grpc server
go func() {
err = s.server.Serve(lis)
if err != nil {
log.Error().Err(err).Msg("failed to serve")
return
}
}()
return nil
}
func (s *grpcServer) Register(ctx context.Context, req *messager.RegisterRequest) (*messager.RegisterResponse, error) {
// get client ip
p, _ := peer.FromContext(ctx)
clientIp := strings.Split(p.Addr.String(), ":")[0]
// store worker information
wn := newWorkerNode(req.NodeID, clientIp, req.Os, req.Arch)
s.clients.Store(req.NodeID, wn)
log.Warn().Str("worker id", req.NodeID).Msg("worker joined")
return &messager.RegisterResponse{Code: "0", Message: "register successful"}, nil
}
func (s *grpcServer) SignOut(_ context.Context, req *messager.SignOutRequest) (*messager.SignOutResponse, error) {
// delete worker information
s.clients.Delete(req.NodeID)
log.Warn().Str("worker id", req.NodeID).Msg("worker quited")
return &messager.SignOutResponse{Code: "0", Message: "sign out successful"}, nil
}
func (s *grpcServer) validClientToken(token string) bool {
_, ok := s.clients.Load(token)
return ok
}
func (s *grpcServer) BidirectionalStreamingMessage(srv messager.Message_BidirectionalStreamingMessageServer) error {
s.wg.Add(1)
defer s.wg.Done()
token, ok := extractToken(srv.Context())
if !ok {
return status.Error(codes.Unauthenticated, "missing token header")
}
ok = s.validClientToken(token)
if !ok {
return status.Error(codes.Unauthenticated, "invalid token")
}
go s.sendMsg(srv, token)
FOR:
for {
select {
case <-srv.Context().Done():
break FOR
case <-s.disconnectedChannel():
break FOR
default:
msg, err := srv.Recv()
if st, ok := status.FromError(err); ok {
switch st.Code() {
case codes.OK:
s.fromWorker <- newGenericMessage(msg.Type, msg.Data, msg.NodeID)
log.Info().
Str("nodeID", msg.NodeID).
Str("type", msg.Type).
Interface("data", msg.Data).
Msg("receive data from worker")
case codes.Unavailable, codes.Canceled, codes.DeadlineExceeded:
s.fromWorker <- newQuitMessage(token)
break FOR
default:
log.Error().Err(err).Msg("failed to get stream from client")
break FOR
}
}
}
}
log.Info().Str("worker id", token).Msg("bidirectional stream closed")
return nil
}
func (s *grpcServer) sendMsg(srv messager.Message_BidirectionalStreamingMessageServer, id string) {
stream := s.getWorkersByID(id).getStream()
for {
select {
case <-srv.Context().Done():
return
case <-s.disconnectedChannel():
return
case res := <-stream:
if s, ok := status.FromError(srv.Send(res)); ok {
switch s.Code() {
case codes.OK:
log.Info().
Str("nodeID", res.NodeID).
Str("type", res.Type).
Interface("data", res.Data).
Interface("profile", res.Profile).
Msg("send data to worker")
case codes.Unavailable, codes.Canceled, codes.DeadlineExceeded:
log.Warn().Msg(fmt.Sprintf("client (%s) terminated connection", id))
return
default:
log.Warn().Msg(fmt.Sprintf("failed to send to client (%s): %v", id, s.Err()))
return
}
}
}
}
}
func (s *grpcServer) sendBroadcasts(msg *genericMessage) {
s.clients.Range(func(key, value interface{}) bool {
if workerInfo, ok := value.(*WorkerNode); ok {
if !workerInfo.isAvailable() {
return true
}
workerInfo.getStream() <- &messager.StreamResponse{
Type: msg.Type,
Profile: msg.Profile,
Data: msg.Data,
NodeID: workerInfo.ID,
Tasks: msg.Tasks,
}
}
return true
})
}
func (s *grpcServer) stopServer(ctx context.Context) {
ch := make(chan struct{})
go func() {
defer close(ch)
// close listeners to stop accepting new connections,
// will block on any existing transports
s.server.GracefulStop()
}()
// wait until all pending RPCs are finished
select {
case <-ch:
case <-ctx.Done():
// took too long, manually close open transports
// e.g. watch streams
s.server.Stop()
// concurrent GracefulStop should be interrupted
<-ch
}
}
func (s *grpcServer) close() {
// close client requests with request timeout
timeout := 2 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
s.stopServer(ctx)
cancel()
// disconnecting workers
close(s.disconnectedChan)
// waiting to close bidirectional stream
s.wg.Wait()
}
func (s *grpcServer) recvChannel() chan *genericMessage {
return s.fromWorker
}
func (s *grpcServer) shutdownChannel() chan bool {
return s.shutdownChan
}
func (s *grpcServer) disconnectedChannel() chan bool {
return s.disconnectedChan
}
func (s *grpcServer) getWorkersByState(state int32) (wns []*WorkerNode) {
s.clients.Range(func(key, value interface{}) bool {
if workerInfo, ok := value.(*WorkerNode); ok {
if workerInfo.getState() == state {
wns = append(wns, workerInfo)
}
}
return true
})
return wns
}
func (s *grpcServer) getWorkersByID(id string) (wn *WorkerNode) {
s.clients.Range(func(key, value interface{}) bool {
if workerInfo, ok := value.(*WorkerNode); ok {
if workerInfo.ID == id {
wn = workerInfo
}
}
return true
})
return wn
}
func (s *grpcServer) getWorkersLengthByState(state int32) (l int) {
s.clients.Range(func(key, value interface{}) bool {
if workerInfo, ok := value.(*WorkerNode); ok {
if workerInfo.getState() == state {
l++
}
}
return true
})
return
}
func (s *grpcServer) getAllWorkers() (wns []WorkerNode) {
s.clients.Range(func(key, value interface{}) bool {
if workerInfo, ok := value.(*WorkerNode); ok {
wns = append(wns, workerInfo.getWorkerInfo())
}
return true
})
return wns
}
func (s *grpcServer) getClients() *sync.Map {
return s.clients
}
func (s *grpcServer) getAvailableClientsLength() (l int) {
s.clients.Range(func(key, value interface{}) bool {
if workerInfo, ok := value.(*WorkerNode); ok {
if workerInfo.isAvailable() {
l++
}
}
return true
})
return
}
func (s *grpcServer) getReadyClientsLength() (l int) {
s.clients.Range(func(key, value interface{}) bool {
if workerInfo, ok := value.(*WorkerNode); ok {
if workerInfo.isReady() {
l++
}
}
return true
})
return
}
func (s *grpcServer) getStartingClientsLength() (l int) {
s.clients.Range(func(key, value interface{}) bool {
if workerInfo, ok := value.(*WorkerNode); ok {
if workerInfo.isStarting() {
l++
}
}
return true
})
return
}
func (s *grpcServer) getCurrentUsers() (l int) {
s.clients.Range(func(key, value interface{}) bool {
if workerInfo, ok := value.(*WorkerNode); ok {
if workerInfo.isStarting() {
l += int(workerInfo.getUserCount())
}
}
return true
})
return
}