-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.go
1416 lines (1244 loc) · 34.3 KB
/
runner.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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package boomer
import (
"fmt"
"math/rand"
"os"
"runtime/debug"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/jinzhu/copier"
"github.com/olekukonko/tablewriter"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/httprunner/boomer/grpc/messager"
)
const (
StateInit = iota + 1 // initializing
StateSpawning // spawning
StateRunning // running
StateStopping // stopping
StateStopped // stopped
StateQuitting // quitting
StateMissing // missing
)
func getStateName(state int32) (stateName string) {
switch state {
case StateInit:
stateName = "initializing"
case StateSpawning:
stateName = "spawning"
case StateRunning:
stateName = "running"
case StateStopping:
stateName = "stopping"
case StateStopped:
stateName = "stopped"
case StateQuitting:
stateName = "quitting"
case StateMissing:
stateName = "missing"
}
return
}
const (
reportStatsInterval = 3 * time.Second
heartbeatInterval = 1 * time.Second
heartbeatLiveness = 3 * time.Second
stateMachineInterval = 1 * time.Second
)
type Loop struct {
loopCount int64 // more than 0
acquiredCount int64 // count acquired of load testing
finishedCount int64 // count finished of load testing
}
func (l *Loop) isFinished() bool {
// return true when there are no remaining loop count to test
return atomic.LoadInt64(&l.finishedCount) == l.loopCount
}
func (l *Loop) acquire() bool {
// get one ticket when there are still remaining loop count to test
// return true when getting ticket successfully
if atomic.LoadInt64(&l.acquiredCount) < l.loopCount {
atomic.AddInt64(&l.acquiredCount, 1)
return true
}
return false
}
func (l *Loop) increaseFinishedCount() {
atomic.AddInt64(&l.finishedCount, 1)
}
type Controller struct {
mutex sync.RWMutex
once sync.Once
currentClientsNum int64 // current clients count
spawnCount int64 // target clients to spawn
spawnRate float64
rebalance chan bool // dynamically balance boomer running parameters
spawnDone chan struct{}
tasks []*Task
}
func (c *Controller) setSpawn(spawnCount int64, spawnRate float64) {
c.mutex.Lock()
defer c.mutex.Unlock()
if spawnCount > 0 {
atomic.StoreInt64(&c.spawnCount, spawnCount)
}
if spawnRate > 0 {
c.spawnRate = spawnRate
}
}
func (c *Controller) setSpawnCount(spawnCount int64) {
if spawnCount > 0 {
atomic.StoreInt64(&c.spawnCount, spawnCount)
}
}
func (c *Controller) setSpawnRate(spawnRate float64) {
c.mutex.Lock()
defer c.mutex.Unlock()
if spawnRate > 0 {
c.spawnRate = spawnRate
}
}
func (c *Controller) getSpawnCount() int64 {
c.mutex.RLock()
defer c.mutex.RUnlock()
return atomic.LoadInt64(&c.spawnCount)
}
func (c *Controller) getSpawnRate() float64 {
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.spawnRate
}
func (c *Controller) getSpawnDone() chan struct{} {
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.spawnDone
}
func (c *Controller) getCurrentClientsNum() int64 {
c.mutex.RLock()
defer c.mutex.RUnlock()
return atomic.LoadInt64(&c.currentClientsNum)
}
func (c *Controller) spawnCompete() {
close(c.spawnDone)
}
func (c *Controller) getRebalanceChan() chan bool {
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.rebalance
}
func (c *Controller) isFinished() bool {
// return true when workers acquired
return atomic.LoadInt64(&c.currentClientsNum) == atomic.LoadInt64(&c.spawnCount)
}
func (c *Controller) acquire() bool {
// get one ticket when there are still remaining spawn count to test
// return true when getting ticket successfully
if atomic.LoadInt64(&c.currentClientsNum) < atomic.LoadInt64(&c.spawnCount) {
atomic.AddInt64(&c.currentClientsNum, 1)
return true
}
return false
}
func (c *Controller) erase() bool {
// return true if acquiredCount > spawnCount
if atomic.LoadInt64(&c.currentClientsNum) > atomic.LoadInt64(&c.spawnCount) {
atomic.AddInt64(&c.currentClientsNum, -1)
return true
}
return false
}
func (c *Controller) increaseFinishedCount() {
atomic.AddInt64(&c.currentClientsNum, -1)
}
func (c *Controller) reset() {
c.mutex.Lock()
defer c.mutex.Unlock()
atomic.StoreInt64(&c.spawnCount, 0)
c.spawnRate = 0
atomic.StoreInt64(&c.currentClientsNum, 0)
c.spawnDone = make(chan struct{})
c.rebalance = make(chan bool)
c.tasks = []*Task{}
c.once = sync.Once{}
}
type runner struct {
state int32
tasks []*Task
totalTaskWeight int
mutex sync.RWMutex
rateLimiter RateLimiter
rateLimitEnabled bool
stats *requestStats
spawnCount int64 // target clients to spawn
spawnRate float64
runTime int64
controller *Controller
loop *Loop // specify loop count for testcase, count = loopCount * spawnCount
// stop signals the run goroutine should shutdown.
stopChan chan bool
// all running workers(goroutines) will select on this channel.
// stopping is closed by run goroutine on shutdown.
stoppingChan chan bool
// done is closed when all goroutines from start() complete.
doneChan chan bool
// when this channel is closed, all statistics are reported successfully
reportedChan chan bool
// close this channel will stop all goroutines used in runner.
closeChan chan bool
// wgMu blocks concurrent waitgroup mutation while boomer stopping
wgMu sync.RWMutex
// wg is used to wait for all running workers(goroutines) that depends on the boomer state
// to exit when stopping the boomer.
wg sync.WaitGroup
outputs []Output
}
func (r *runner) setSpawnRate(spawnRate float64) {
r.mutex.Lock()
defer r.mutex.Unlock()
if spawnRate > 0 {
r.spawnRate = spawnRate
}
}
func (r *runner) getSpawnRate() float64 {
r.mutex.RLock()
defer r.mutex.RUnlock()
return r.spawnRate
}
func (r *runner) setRunTime(runTime int64) {
atomic.StoreInt64(&r.runTime, runTime)
}
func (r *runner) getRunTime() int64 {
return atomic.LoadInt64(&r.runTime)
}
func (r *runner) getSpawnCount() int64 {
return atomic.LoadInt64(&r.spawnCount)
}
func (r *runner) setSpawnCount(spawnCount int64) {
atomic.StoreInt64(&r.spawnCount, spawnCount)
}
// safeRun runs fn and recovers from unexpected panics.
// it prevents panics from Task.Fn crashing boomer.
func (r *runner) safeRun(fn func()) {
defer func() {
// don't panic
err := recover()
if err != nil {
stackTrace := debug.Stack()
errMsg := fmt.Sprintf("%v", err)
os.Stderr.Write([]byte(errMsg))
os.Stderr.Write([]byte("\n"))
os.Stderr.Write(stackTrace)
}
}()
fn()
}
func (r *runner) addOutput(o Output) {
r.outputs = append(r.outputs, o)
}
func (r *runner) outputOnStart() {
size := len(r.outputs)
if size == 0 {
return
}
wg := sync.WaitGroup{}
wg.Add(size)
for _, output := range r.outputs {
go func(o Output) {
o.OnStart()
wg.Done()
}(output)
}
wg.Wait()
}
func (r *runner) outputOnEvent(data map[string]interface{}) {
size := len(r.outputs)
if size == 0 {
return
}
wg := sync.WaitGroup{}
wg.Add(size)
for _, output := range r.outputs {
go func(o Output) {
o.OnEvent(data)
wg.Done()
}(output)
}
wg.Wait()
}
func (r *runner) outputOnStop() {
defer func() {
r.outputs = make([]Output, 0)
}()
size := len(r.outputs)
if size == 0 {
return
}
wg := sync.WaitGroup{}
wg.Add(size)
for _, output := range r.outputs {
go func(o Output) {
o.OnStop()
wg.Done()
}(output)
}
wg.Wait()
}
func (r *runner) reportStats() {
data := r.stats.collectReportData()
data["user_count"] = r.controller.getCurrentClientsNum()
data["state"] = atomic.LoadInt32(&r.state)
r.outputOnEvent(data)
}
func (r *runner) reportTestResult() {
// convert stats in total
var statsTotal interface{} = r.stats.total.serialize()
entryTotalOutput, err := deserializeStatsEntry(statsTotal)
if err != nil {
return
}
duration := time.Duration(entryTotalOutput.LastRequestTimestamp-entryTotalOutput.StartTime) * time.Millisecond
currentTime := time.Now()
println(fmt.Sprint("=========================================== Statistics Summary =========================================="))
println(fmt.Sprintf("Current time: %s, Users: %v, Duration: %v, Accumulated Transactions: %d Passed, %d Failed",
currentTime.Format("2006/01/02 15:04:05"), r.controller.getCurrentClientsNum(), duration, r.stats.transactionPassed, r.stats.transactionFailed))
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Name", "# requests", "# fails", "Median", "Average", "Min", "Max", "Content Size", "# reqs/sec", "# fails/sec"})
row := make([]string, 10)
row[0] = entryTotalOutput.Name
row[1] = strconv.FormatInt(entryTotalOutput.NumRequests, 10)
row[2] = strconv.FormatInt(entryTotalOutput.NumFailures, 10)
row[3] = strconv.FormatInt(entryTotalOutput.medianResponseTime, 10)
row[4] = strconv.FormatFloat(entryTotalOutput.avgResponseTime, 'f', 2, 64)
row[5] = strconv.FormatInt(entryTotalOutput.MinResponseTime, 10)
row[6] = strconv.FormatInt(entryTotalOutput.MaxResponseTime, 10)
row[7] = strconv.FormatInt(entryTotalOutput.avgContentLength, 10)
row[8] = strconv.FormatFloat(entryTotalOutput.currentRps, 'f', 2, 64)
row[9] = strconv.FormatFloat(entryTotalOutput.currentFailPerSec, 'f', 2, 64)
table.Append(row)
table.Render()
println()
}
func (r *runner) reset() {
r.controller.reset()
r.stats.clearAll()
r.stoppingChan = make(chan bool)
r.doneChan = make(chan bool)
r.reportedChan = make(chan bool)
}
func (r *runner) runTimeCheck(runTime int64) {
if runTime <= 0 {
return
}
stopTime := time.Now().Unix() + runTime
ticker := time.NewTicker(time.Second)
for {
select {
case <-r.stopChan:
return
case <-ticker.C:
if time.Now().Unix() > stopTime {
r.stop()
return
}
}
}
}
func (r *runner) spawnWorkers(spawnCount int64, spawnRate float64, quit chan bool, spawnCompleteFunc func()) {
r.updateState(StateSpawning)
log.Info().
Int64("spawnCount", spawnCount).
Float64("spawnRate", spawnRate).
Msg("Spawning workers")
r.controller.setSpawn(spawnCount, spawnRate)
for {
select {
case <-quit:
// quit spawning goroutine
log.Info().Msg("Quitting spawning workers")
return
default:
if r.isStarting() && r.controller.acquire() {
// spawn workers with rate limit
sleepTime := time.Duration(1000000/r.controller.getSpawnRate()) * time.Microsecond
time.Sleep(sleepTime)
// loop count per worker
var workerLoop *Loop
if r.loop != nil {
workerLoop = &Loop{loopCount: atomic.LoadInt64(&r.loop.loopCount) / r.controller.spawnCount}
}
r.goAttach(func() {
for {
select {
case <-quit:
r.controller.increaseFinishedCount()
return
default:
if workerLoop != nil && !workerLoop.acquire() {
r.controller.increaseFinishedCount()
return
}
if r.rateLimitEnabled {
blocked := r.rateLimiter.Acquire()
if !blocked {
task := r.getTask()
r.safeRun(task.Fn)
}
} else {
task := r.getTask()
r.safeRun(task.Fn)
}
if workerLoop != nil {
// finished count of total
r.loop.increaseFinishedCount()
// finished count of single worker
workerLoop.increaseFinishedCount()
if r.loop.isFinished() {
go r.stop()
r.controller.increaseFinishedCount()
return
}
}
if r.controller.erase() {
return
}
}
}
})
continue
}
r.controller.once.Do(
func() {
// spawning compete
r.controller.spawnCompete()
if spawnCompleteFunc != nil {
spawnCompleteFunc()
}
r.updateState(StateRunning)
},
)
<-r.controller.getRebalanceChan()
if r.isStarting() {
// rebalance spawn count
r.controller.setSpawn(r.getSpawnCount(), r.getSpawnRate())
}
}
}
}
// goAttach creates a goroutine on a given function and tracks it using
// the runner waitgroup.
// The passed function should interrupt on r.stoppingNotify().
func (r *runner) goAttach(f func()) {
r.wgMu.RLock() // this blocks with ongoing close(s.stopping)
defer r.wgMu.RUnlock()
select {
case <-r.stoppingChan:
log.Warn().Msg("runner has stopped; skipping GoAttach")
return
default:
}
// now safe to add since waitgroup wait has not started yet
r.wg.Add(1)
go func() {
defer r.wg.Done()
f()
}()
}
// setTasks will set the runner's task list AND the total task weight
// which is used to get a random task later
func (r *runner) setTasks(t []*Task) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.tasks = t
weightSum := 0
for _, task := range r.tasks {
weightSum += task.Weight
}
r.totalTaskWeight = weightSum
}
func (r *runner) getTask() *Task {
r.mutex.RLock()
defer r.mutex.RUnlock()
tasksCount := len(r.tasks)
if tasksCount == 0 {
log.Error().Msg("no valid testcase found")
os.Exit(1)
} else if tasksCount == 1 {
// Fast path
return r.tasks[0]
}
rs := rand.New(rand.NewSource(time.Now().UnixNano()))
totalWeight := r.totalTaskWeight
if totalWeight <= 0 {
// If all the tasks have not weights defined, they have the same chance to run
randNum := rs.Intn(tasksCount)
return r.tasks[randNum]
}
randNum := rs.Intn(totalWeight)
runningSum := 0
for _, task := range r.tasks {
runningSum += task.Weight
if runningSum > randNum {
return task
}
}
return nil
}
func (r *runner) statsStart() {
ticker := time.NewTicker(reportStatsInterval)
for {
select {
// record stats
case t := <-r.stats.transactionChan:
r.stats.logTransaction(t.name, t.success, t.elapsedTime, t.contentSize)
case m := <-r.stats.requestSuccessChan:
r.stats.logRequest(m.requestType, m.name, m.responseTime, m.responseLength)
case n := <-r.stats.requestFailureChan:
r.stats.logRequest(n.requestType, n.name, n.responseTime, 0)
r.stats.logError(n.requestType, n.name, n.errMsg)
// report stats
case <-ticker.C:
r.reportStats()
// close reportedChan and return if the last stats is reported successfully
if !r.isStarting() && !r.isStopping() {
close(r.reportedChan)
log.Info().Msg("Quitting statsStart")
return
}
}
}
}
func (r *runner) stop() {
// stop previous goroutines without blocking
// those goroutines will exit when r.safeRun returns
r.gracefulStop()
if r.rateLimitEnabled {
r.rateLimiter.Stop()
}
r.updateState(StateStopped)
}
// gracefulStop stops the boomer gracefully, and shuts down the running goroutine.
// gracefulStop should be called after a start(), otherwise it will block forever.
// When stopping leader, Stop transfers its leadership to one of its peers
// before stopping the boomer.
// gracefulStop terminates the boomer and performs any necessary finalization.
// Do and Process cannot be called after Stop has been invoked.
func (r *runner) gracefulStop() {
select {
case r.stopChan <- true:
case <-r.doneChan:
return
}
<-r.doneChan
}
// stopNotify returns a channel that receives a bool type value
// when the runner is stopped.
func (r *runner) stopNotify() <-chan bool { return r.doneChan }
func (r *runner) getState() int32 {
return atomic.LoadInt32(&r.state)
}
func (r *runner) updateState(state int32) {
log.Debug().Int32("from", atomic.LoadInt32(&r.state)).Int32("to", state).Msg("update runner state")
atomic.StoreInt32(&r.state, state)
}
func (r *runner) isStarting() bool {
return r.getState() == StateRunning || r.getState() == StateSpawning
}
func (r *runner) isStopping() bool {
return r.getState() == StateStopping
}
type localRunner struct {
runner
profile *Profile
}
func newLocalRunner(spawnCount int64, spawnRate float64) *localRunner {
return &localRunner{
runner: runner{
state: StateInit,
stats: newRequestStats(),
spawnCount: spawnCount,
spawnRate: spawnRate,
controller: &Controller{},
outputs: make([]Output, 0),
stopChan: make(chan bool),
closeChan: make(chan bool),
wg: sync.WaitGroup{},
wgMu: sync.RWMutex{},
},
}
}
func (r *localRunner) start() {
r.updateState(StateInit)
// init localRunner
r.reset()
// start rate limiter
if r.rateLimitEnabled {
r.rateLimiter.Start()
}
// output setup
r.outputOnStart()
go r.runTimeCheck(r.getRunTime())
go r.spawnWorkers(r.getSpawnCount(), r.getSpawnRate(), r.stoppingChan, nil)
defer func() {
// block concurrent waitgroup adds in GoAttach while stopping
r.wgMu.Lock()
r.updateState(StateStopping)
close(r.stoppingChan)
close(r.controller.rebalance)
r.wgMu.Unlock()
// wait for goroutines before closing
r.wg.Wait()
close(r.doneChan)
// wait until all stats are reported successfully
<-r.reportedChan
// report test result
r.reportTestResult()
// output teardown
r.outputOnStop()
r.updateState(StateQuitting)
}()
// start stats report
go r.statsStart()
<-r.stopChan
}
func (r *localRunner) stop() {
if r.runner.isStarting() {
r.runner.stop()
}
}
// workerRunner connects to the master, spawns goroutines and collects stats.
type workerRunner struct {
runner
nodeID string
masterHost string
masterPort int
client *grpcClient
profile *Profile
testCasesBytes []byte
tasksChan chan *task
mutex sync.Mutex
ignoreQuit bool
}
func newWorkerRunner(masterHost string, masterPort int) (r *workerRunner) {
r = &workerRunner{
runner: runner{
stats: newRequestStats(),
outputs: make([]Output, 0),
controller: &Controller{},
stopChan: make(chan bool),
closeChan: make(chan bool),
},
masterHost: masterHost,
masterPort: masterPort,
nodeID: getNodeID(),
tasksChan: make(chan *task, 10),
mutex: sync.Mutex{},
ignoreQuit: false,
}
return r
}
func (r *workerRunner) spawnComplete() {
data := make(map[string][]byte)
data["count"] = Int64ToBytes(r.controller.getSpawnCount())
r.client.sendChannel() <- newGenericMessage("spawning_complete", data, r.nodeID)
}
func (r *workerRunner) onSpawnMessage(msg *genericMessage) {
r.client.sendChannel() <- newGenericMessage("spawning", nil, r.nodeID)
if msg.Profile == nil {
log.Error().Msg("miss profile")
}
profile := BytesToProfile(msg.Profile)
r.setSpawnCount(profile.SpawnCount)
r.setSpawnRate(profile.SpawnRate)
if msg.Tasks == nil && len(r.tasks) == 0 {
log.Error().Msg("miss tasks")
}
r.tasksChan <- &task{
Profile: profile,
TestCasesBytes: msg.Tasks,
}
log.Info().Msg("on spawn message successfully")
}
func (r *workerRunner) onRebalanceMessage(msg *genericMessage) {
if msg.Profile == nil {
log.Error().Msg("miss profile")
}
profile := BytesToProfile(msg.Profile)
r.setSpawnCount(profile.SpawnCount)
r.setSpawnRate(profile.SpawnRate)
r.tasksChan <- &task{
Profile: profile,
}
log.Info().Msg("on rebalance message successfully")
}
// Runner acts as a state machine.
func (r *workerRunner) onMessage(msg *genericMessage) {
switch r.getState() {
case StateInit:
switch msg.Type {
case "spawn":
r.onSpawnMessage(msg)
case "quit":
if r.ignoreQuit {
log.Warn().Msg("master already quit, waiting to reconnect master.")
break
}
r.close()
}
case StateSpawning:
fallthrough
case StateRunning:
switch msg.Type {
case "spawn":
r.onSpawnMessage(msg)
case "rebalance":
r.onRebalanceMessage(msg)
case "stop":
r.stop()
case "quit":
r.stop()
if r.ignoreQuit {
log.Warn().Msg("master already quit, waiting to reconnect master.")
break
}
r.close()
log.Info().Msg("Recv quit message from master, all the goroutines are stopped")
}
case StateStopped:
switch msg.Type {
case "spawn":
r.onSpawnMessage(msg)
case "quit":
if r.ignoreQuit {
log.Warn().Msg("master already quit, waiting to reconnect master.")
break
}
r.close()
}
}
}
func (r *workerRunner) onStopped() {
r.client.sendChannel() <- newGenericMessage("client_stopped", nil, r.nodeID)
}
func (r *workerRunner) onQuiting() {
if r.getState() != StateQuitting {
r.client.sendChannel() <- newQuitMessage(r.nodeID)
}
r.updateState(StateQuitting)
}
func (r *workerRunner) startListener() {
for {
select {
case msg := <-r.client.recvChannel():
r.onMessage(msg)
case <-r.closeChan:
return
}
}
}
// run worker service
func (r *workerRunner) run() {
println("==================== HttpRunner Worker for Distributed Load Testing ==================== ")
r.updateState(StateInit)
r.client = newClient(r.masterHost, r.masterPort, r.nodeID)
println(fmt.Sprintf("ready to connect master to %s:%d", r.masterHost, r.masterPort))
err := r.client.start()
if err != nil {
log.Error().Err(err).Msg(fmt.Sprintf("failed to connect to master(%s:%d)", r.masterHost, r.masterPort))
}
// register worker information to master
if err = r.client.register(r.client.config.ctx); err != nil {
log.Error().Err(err).Msg("failed to register")
}
err = r.client.newBiStreamClient()
if err != nil {
log.Error().Err(err).Msg("failed to establish bidirectional stream, waiting master launched")
}
go r.client.recv()
go r.client.send()
defer func() {
// wait for goroutines before closing
r.wg.Wait()
// notify master that worker is quitting
r.onQuiting()
ticker := time.NewTicker(1 * time.Second)
if r.client != nil {
// waitting for quit message is sent to master
select {
case <-r.client.disconnectedChannel():
case <-ticker.C:
log.Warn().Msg("timeout waiting for sending quit message to master, boomer will quit any way.")
}
// sign out from master
if err = r.client.signOut(r.client.config.ctx); err != nil {
log.Info().Err(err).Msg("failed to sign out")
}
// close grpc client
r.client.close()
}
}()
// listen to master
go r.startListener()
// tell master, I'm ready
log.Info().Msg("send client ready signal")
r.client.sendChannel() <- newClientReadyMessageToMaster(r.nodeID)
// heartbeat
// See: https://github.com/locustio/locust/commit/a8c0d7d8c588f3980303358298870f2ea394ab93
ticker := time.NewTicker(heartbeatInterval)
for {
select {
case <-ticker.C:
if r.getState() == StateMissing {
err = r.client.register(r.client.config.ctx)
if err != nil {
continue
}
err = r.client.newBiStreamClient()
if err != nil {
continue
}
r.updateState(StateInit)
}
if atomic.LoadInt32(&r.client.failCount) > 3 {
go r.stop()
if !r.isStarting() && !r.isStopping() {
r.updateState(StateMissing)
}
continue
}
CPUUsage := GetCurrentCPUPercent()
MemoryUsage := GetCurrentMemoryPercent()
PidCPUUsage := GetCurrentPidCPUUsage()
PidMemoryUsage := GetCurrentPidMemoryUsage()
data := map[string][]byte{
"state": Int64ToBytes(int64(r.getState())),
"current_cpu_usage": Float64ToByte(CPUUsage),
"current_pid_cpu_usage": Float64ToByte(PidCPUUsage),
"current_memory_usage": Float64ToByte(MemoryUsage),
"current_pid_memory_usage": Float64ToByte(PidMemoryUsage),
"current_users": Int64ToBytes(r.controller.getCurrentClientsNum()),
}
r.client.sendChannel() <- newGenericMessage("heartbeat", data, r.nodeID)
case <-r.closeChan:
return
}
}
}
func (r *workerRunner) start() {
r.mutex.Lock()
defer r.mutex.Unlock()
r.updateState(StateInit)
r.reset()
// start rate limiter
if r.rateLimitEnabled {
r.rateLimiter.Start()
}
r.outputOnStart()
go r.runTimeCheck(r.getRunTime())
go r.spawnWorkers(r.getSpawnCount(), r.getSpawnRate(), r.stoppingChan, r.spawnComplete)
defer func() {
// block concurrent waitgroup adds in GoAttach while stopping
r.wgMu.Lock()
r.updateState(StateStopping)
close(r.controller.rebalance)
close(r.stoppingChan)
r.wgMu.Unlock()
// wait for goroutines before closing
r.wg.Wait()
// reset loop
if r.loop != nil {
r.loop = nil
}
close(r.doneChan)
// wait until all stats are reported successfully
<-r.reportedChan
// report test result
r.reportTestResult()
// output teardown
r.outputOnStop()
// notify master that worker is stopped
r.onStopped()
}()
// start stats report
go r.statsStart()
<-r.stopChan
}
func (r *workerRunner) stop() {
if r.isStarting() {
r.runner.stop()
}
}