-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpool.go
1248 lines (1055 loc) · 45.6 KB
/
pool.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
// ** goworkerpool.com **********************************************************************************************
// ** github.com/enriquebris/goworkerpool **
// ** v0.10.0 *******************************************************************************************************
package goworkerpool
import (
"fmt"
"sync"
"github.com/enriquebris/goconcurrentcounter"
"github.com/enriquebris/goconcurrentqueue"
)
const (
// Statuses
// Wait in-progress status
waitInProgress = "wait.in.progress"
// KillAllWorkers in-progress status
killAllWorkersInProgress = "kill.all.workers.in.progress"
// is dispatcher alive? status
dispatcherInProgress = "dispatcher.in.progress"
triggerZeroTotalWorkers = "trigger.zero.total.workers"
triggerWaitUntilNSuccesses = "trigger.wait.until.n.successes"
// max amount of possible workers
defaultMaxWorkers = 100
)
// PoolFunc defines the function signature to be implemented by the workers
type PoolFunc func(interface{}) bool
// PoolCallback defines the callback function signature
type PoolCallback func(interface{})
// dispatcherGeneralFunc function to be executed by the dispatcher (could be part of an action)
type dispatcherGeneralFunc func()
type Pool struct {
// tasks' queue
tasks goconcurrentqueue.Queue
// tasks that panicked at the worker
panicTasks goconcurrentqueue.Queue
// actions' queue
actions goconcurrentqueue.Queue
// map of workers
workers sync.Map
// available workers (available means idle)
availableWorkers goconcurrentqueue.Queue
// default worker's function
defaultWorkerFunc PoolFunc
// channel to enqueue a signal if a task or action was enqueued
activityChan chan struct{}
// channel to send worker's feedback to let dispatcher knows that the worker should be re-enqueued into availableWorkers
dispatcherWorkerFeedbackChan chan workerFeedback
// channel to let the dispatcher knows whether the workers could be resumed
resumeWorkers chan struct{}
// channel to enqueue a signal if all workers were killed
noWorkersChan chan struct{}
// channel to send a signal once initial amount of workers are up
waitUntilInitialWorkersAreUp chan struct{}
// next available ID for new worker
newWorkerID goconcurrentcounter.Int
// metrics
// total workers
totalWorkers goconcurrentcounter.Int
// to keep track the successful tasks
taskSuccesses goconcurrentcounter.Int
// amount of workers processing actions/tasks
totalWorkersInProgress goconcurrentcounter.Int
// external channels
// to send a signal to an external listener once a new worker is created
externalNewWorkerChan chan int
// to send a signal to an external listener once a worker is terminated
externalKilledWorkerChan chan int
// log
logVerbose bool
logChan chan PoolLog
// general information map (actions in progress, etc)
generalInfoMap sync.Map
}
// NewPool is deprecated since version 0.10.0, please do not use it. Use NewPoolWithOptions instead.
// NewPool builds and returns a new Pool.
// This function will be removed on version 1.0.0
// Parameters:
// initialWorkers = amount of workers to start up at initialization
// maxOperationsInQueue = maximum amount of actions/tasks that could be enqueued at the same time
// logVerbose = true ==> output logs
func NewPool(initialWorkers int, maxOperationsInQueue int, logVerbose bool) *Pool {
// wrong data entry
if initialWorkers < 0 || maxOperationsInQueue <= 0 {
return nil
}
ret := &Pool{}
ret.initialize(PoolOptions{
TotalInitialWorkers: uint(initialWorkers),
MaxWorkers: defaultMaxWorkers,
MaxOperationsInQueue: uint(maxOperationsInQueue),
WaitUntilInitialWorkersAreUp: false,
LogVerbose: logVerbose,
})
return ret
}
// NewPoolWithOptions builds and returns a Pool.
// This function will return error if any of the following scenarios occurs:
// - MaxWorkers == 0
// - MaxOperationsInQueue == 0
func NewPoolWithOptions(options PoolOptions) (*Pool, error) {
// validate entry values
// MaxWorkers
if options.MaxWorkers == 0 {
return nil, newPoolError(ErrorData, "MaxWorkers should be greater than zero")
}
// MaxOperationsInQueue
if options.MaxOperationsInQueue == 0 {
return nil, newPoolError(ErrorData, "MaxOperationsInQueue should be greater than zero")
}
pool := &Pool{}
// new worker channel
pool.SetNewWorkerChan(options.NewWorkerChan)
//pool.initialize(int(options.TotalInitialWorkers), int(options.MaxOperationsInQueue), int(options.MaxWorkers))
pool.initialize(options)
if options.WaitUntilInitialWorkersAreUp {
// wait until all initial workers are up and running
<-pool.waitUntilInitialWorkersAreUp
}
return pool, nil
}
// initialize initializes the Pool
func (st *Pool) initialize(options PoolOptions) {
st.tasks = goconcurrentqueue.NewFIFO()
st.panicTasks = goconcurrentqueue.NewFIFO()
st.actions = goconcurrentqueue.NewFIFO()
st.availableWorkers = goconcurrentqueue.NewFIFO()
// initialize channels
st.activityChan = make(chan struct{}, int(options.MaxOperationsInQueue))
st.dispatcherWorkerFeedbackChan = make(chan workerFeedback, int(options.MaxWorkers))
st.noWorkersChan = make(chan struct{})
st.waitUntilInitialWorkersAreUp = make(chan struct{}, 2)
// initialize newWorkerID (0)
st.newWorkerID = goconcurrentcounter.NewIntChan(0)
// initialize totalWorkers
st.totalWorkers = goconcurrentcounter.NewIntChan(0)
// add a trigger function to send a signal once all initial workers are up
st.totalWorkers.SetTriggerOnValue(int(options.TotalInitialWorkers), "WaitUntilInitialWorkersAreUp", func(currentValue int, previousValue int) {
// remove the trigger function
st.totalWorkers.EnqueueToRunAfterCurrentTriggerFunctions(func(currentValue int, previousValue int) {
st.totalWorkers.UnsetTriggerOnValue(int(options.TotalInitialWorkers), "WaitUntilInitialWorkersAreUp")
})
// send the signal
st.waitUntilInitialWorkersAreUp <- struct{}{}
if options.WaitUntilInitialWorkersAreUp {
// send an extra signal to the NewPoolWithOptions function
st.waitUntilInitialWorkersAreUp <- struct{}{}
}
close(st.waitUntilInitialWorkersAreUp)
})
// metrics
// zero successful tasks at initialization
st.taskSuccesses = goconcurrentcounter.NewIntChan(0)
// total workers in progress
st.totalWorkersInProgress = goconcurrentcounter.NewIntChan(0)
// start running the dispatcher in a separate GR
go st.dispatcher()
// start running the dispatcherWorkerFeedback in a separate GR
go st.dispatcherWorkerFeedback()
// initialize workers
for i := 0; i < int(options.TotalInitialWorkers); i++ {
if err := st.AddWorker(); err != nil {
// log if the following action fails
st.logError("initialize.AddWorker", err)
}
}
// send signal if totalWorkers == 0 (all workers are down)
st.totalWorkers.SetTriggerOnValue(0, triggerZeroTotalWorkers, func(currentValue int, previousValue int) {
// remove the "killAllWorkersInProgress" flag (if active)
if st.getStatus(killAllWorkersInProgress) {
st.setStatus(killAllWorkersInProgress, false)
}
// sends only the signal if Wait() was invoked and it is running
if st.getStatus(waitInProgress) {
st.getNoWorkersChan() <- struct{}{}
}
})
}
// *************************************************************************************************************
// ** Dispatcher **********************************************************************************************
// *************************************************************************************************************
// dispatcher keeps listening activityChan and dispatches tasks and actions
func (st *Pool) dispatcher() {
keepWorking := true
for keepWorking {
var (
noAction = true
noTask = true
actn action
tsk *task
preFunc dispatcherGeneralFunc = nil
sendToWorker bool = true
)
// flag: "dispatcher is alive"
st.setStatus(dispatcherInProgress, true)
select {
case _, ok := <-st.activityChan:
if !ok {
// st.activityChan is closed
keepWorking = false
break
}
// check actions
if rawAction, err := st.actions.Dequeue(); err != nil {
queueError, ok := err.(*goconcurrentqueue.QueueError)
if ok && queueError.Code() == goconcurrentqueue.QueueErrorCodeEmptyQueue {
noAction = true
} else {
// error at action dequeue
st.logError("dispatcher.action.dequeue", err)
continue
}
} else {
noAction = false
actn, _ = rawAction.(action)
// get the action's function
preFunc = actn.PreExternalFunc
// get the action's SendToWorker (it defines whether the action should be sent to the worker or executed by the dispatcher)
sendToWorker = actn.SendToWorker
}
if noAction {
// check tasks / jobs
if rawTask, err := st.tasks.Dequeue(); err != nil {
queueError, ok := err.(*goconcurrentqueue.QueueError)
if ok && queueError.Code() == goconcurrentqueue.QueueErrorCodeEmptyQueue {
// no new task to process
noTask = true
} else {
// error at task dequeue
st.logError("dispatcher.task.dequeue", err)
continue
}
} else {
noTask = false
tsk, _ = rawTask.(*task)
// check whether a late action (coming as a task) should be processed by the dispatcher (not by the worker)
if tsk.Code == taskLateAction {
// even knowing that the task's data contains an action, it should be sent as a task, later the
// worker would transform the data
tmpAction, ok := tsk.Data.(action)
if !ok {
st.logError("dispatcher.taskLateAction unexpected type", nil)
continue
}
// get the action's SendToWorker (it defines whether the action should be sent to the worker or executed by the dispatcher)
sendToWorker = tmpAction.SendToWorker
// get the action's function
preFunc = tmpAction.PreExternalFunc
}
}
}
if noAction && noTask {
// return a unexpected error: the activityChan received a signal but there isn't an action nor a task
st.logError("no action/task at dispatcher.dequeue", newPoolError(ErrorDispatcherNoActionNoTask, "no action/task at dispatcher.dequeue"))
continue
} else {
// check whether a function should be executed
if preFunc != nil {
preFunc()
}
// check whether the data should be sent to a worker
if !sendToWorker {
// do not send the data to a worker
continue
}
// now we have the action/task, so let's get the next available worker to process it
if rawWorker, err := st.availableWorkers.DequeueOrWaitForNextElement(); err != nil {
st.logError("dispatcher.availableWorker.dequeue", err)
// as the worker dequeue failed, then reEnqueue the action/job
if noAction {
// re-enqueue the task
if err := st.AddTask(tsk); err != nil {
st.logError("dispatcher.reEnqueue.AddTask", err)
}
} else {
// re-enqueue the action
if err := st.addAction(actn.Code, actn.SendToWorker, actn.PreExternalFunc); err != nil {
st.logError("dispatcher.reEnqueue.AddAction", err)
}
}
continue
} else {
// there is no need to verify the *worker type
wkr, _ := rawWorker.(*worker)
if noTask {
// process the action
wkr.ProcessAction(actn)
} else {
// TODO ::: catch errors here, send them by the errors channel
// process the task
wkr.ProcessTask(tsk)
}
// The worker would be re-enqueued into availableWorkers based on the feedback sent after the processing
// phase. This feedback would be sent directly from the same worker to the pool's function: dispatcherWorkerFeedback
}
}
}
}
// flag: "dispatcher is no longer alive"
st.setStatus(dispatcherInProgress, false)
}
// dispatcherWorkerFeedback keeps listening the dispatcherWorkerFeedbackChan to re-enqueue workers in availableWorkers
func (st *Pool) dispatcherWorkerFeedback() {
keepWorking := true
for keepWorking {
select {
case workerFeedback := <-st.dispatcherWorkerFeedbackChan:
// TODO ::: send the worker's object from the worker instead of the workerID and measure how faster it is, and how much memory is involved.
// this way it avoids to do the st.workers.Load(workerFeedback.workerID) and stops the execution because the st.workers lock !!!
// get the worker
//wkr := workerFeedback.wkr
rawWorker, ok := st.workers.Load(workerFeedback.workerID)
if !ok {
st.logError("dispatcherWorkerFeedback.unknown worker", newPoolError(ErrorWorkerNotFound, fmt.Sprintf("Missing worker %v could not be removed", workerFeedback.workerID)))
continue
}
wkr, ok := rawWorker.(*worker)
if !ok {
st.logError("dispatcherWorkerFeedback.worker", newPoolError(ErrorWorkerType, fmt.Sprintf("Wrong worker's type for id: %v", workerFeedback.workerID)))
continue
}
if workerFeedback.reEnqueueWorker {
// try to re-enqueue it
if err := st.availableWorkers.Enqueue(wkr); err != nil {
st.logError("dispatcherWorkerFeedback.availableWorkers.Enqueue", err)
} else {
continue
}
}
// remove the worker
if err := st.removeWorker(wkr.GetID()); err != nil {
st.logError("dispatcherWorkerFeedback.removeWorker", err)
}
// TODO ::: keep track of the "not" re-enqueued workers
}
}
}
// *************************************************************************************************************
// ** Tasks/Actions operations *********************************************************************************
// *************************************************************************************************************
// addTask enqueues a task / job
func (st *Pool) addTask(taskType int, data interface{}, fn PoolFunc, callbackFn PoolCallback) error {
job := &task{
Code: taskType,
Data: data,
Func: fn,
CallbackFunc: callbackFn,
Valid: true,
}
// enqueue the regular task
if err := st.tasks.Enqueue(job); err != nil {
return err
}
// send a signal over doSomethingChan (to let operationsHandler knows that there is "something" to do)
select {
case st.activityChan <- struct{}{}:
// do nothing, the signal was successfully sent
default:
// the channel is full so the signal couldn't be enqueued
// set the job as invalid ==> if a worker picks it will be skipped without further processing
job.Valid = false
return newPoolError(ErrorDispatcherChannelFull, "task couldn't be enqueued because the operations(tasks/actions) queue is at full capacity")
}
return nil
}
// addAction enqueue an action
func (st *Pool) addAction(actionCode string, sendToWorker bool, preExternalFunc dispatcherGeneralFunc) error {
actn := action{
Code: actionCode,
SendToWorker: sendToWorker,
PreExternalFunc: preExternalFunc,
}
if err := st.actions.Enqueue(actn); err != nil {
return err
}
// send a signal over activityChan (to let operationsHandler knows that there is "something" to do)
select {
case st.activityChan <- struct{}{}:
// do nothing, the signal was successfully sent
default:
// the channel is full so the signal couldn't be enqueued
return newPoolError(ErrorDispatcherChannelFull, "action couldn't be enqueued because the operations(tasks/actions) queue is at full capacity")
}
return nil
}
// AddTask enqueues a task (into a FIFO queue).
//
// The parameter for the task's data accepts any type (interface{}).
//
// Workers (if any) will be listening to and picking up tasks from this queue. If no workers are alive nor idle,
// the task will stay in the queue until any worker will be ready to pick it up and start processing it.
//
// The queue in which this function enqueues the tasks has a limit (it was set up at pool initialization). It means that AddTask will wait
// for a free queue slot to enqueue a new task in case the queue is at full capacity.
//
// AddTask returns an error if no new tasks could be enqueued at the execution time. No new tasks could be enqueued during
// a certain amount of time when WaitUntilNSuccesses meets the stop condition, or in other words: when KillAllWorkers is
// in progress.
func (st *Pool) AddTask(data interface{}) error {
// verify KillAllWorkers operation is not in progress
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, messageKillAllWorkersInProgress)
}
// verify worker default function handler
if st.defaultWorkerFunc == nil {
return newPoolError(ErrorNoDefaultWorkerFunction, "Missing default handler function to process this task")
}
return st.addTask(taskRegular, data, st.defaultWorkerFunc, nil)
}
// AddTaskCallback enqueues a job and a callback function into a FIFO queue.
//
// The parameter for the job's data accepts any data type (interface{}).
//
// Workers will be listening to and picking up jobs from this queue. If no workers are alive nor idle,
// the job will stay in the queue until any worker will be ready to pick it up and start processing it.
//
// The worker who picks up this job and callback will process the job first and later will invoke the callback function,
// passing the job's data as a parameter.
//
// The queue in which this function enqueues the jobs has a capacity limit (it was set up at pool initialization). This
// means that AddTaskCallback will wait for a free queue slot to enqueue a new job in case the queue is at full capacity.
//
// AddTaskCallback will return an error if no new tasks could be enqueued at the execution time. No new tasks could be enqueued during
// a certain amount of time when WaitUntilNSuccesses meets the stop condition.
func (st *Pool) AddTaskCallback(data interface{}, callbackFn PoolCallback) error {
// verify callbackFn
if callbackFn == nil {
return newPoolError(ErrorData, "Callback function should not be nil")
}
// verify KillAllWorkers operation is not in progress
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, messageKillAllWorkersInProgress)
}
// verify worker default function handler
if st.defaultWorkerFunc == nil {
return newPoolError(ErrorNoDefaultWorkerFunction, "Missing default handler function to process this task")
}
return st.addTask(taskRegular, data, st.defaultWorkerFunc, callbackFn)
}
// AddCallback enqueues a callback function into a FIFO queue.
//
// Workers (if alive) will be listening to and picking up jobs from this queue. If no workers are alive nor idle,
// the job will stay in the queue until any worker will be ready to pick it up and start processing it.
//
// The worker who picks up this job will only invoke the callback function, passing nil as a parameter.
//
// The queue in which this function enqueues the jobs has a limit (it was set up at pool initialization). It means that AddCallback will wait
// for a free queue slot to enqueue a new job in case the queue is at full capacity.
//
// AddCallback will return an error if no new tasks could be enqueued at the execution time. No new tasks could be enqueued during
// a certain amount of time when WaitUntilNSuccesses meets the stop condition.
func (st *Pool) AddCallback(callbackFn PoolCallback) error {
// verify callbackFn
if callbackFn == nil {
return newPoolError(ErrorData, "Callback function should not be nil")
}
// verify KillAllWorkers operation is not in progress
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, messageKillAllWorkersInProgress)
}
// TODO ::: why do we need a defaultWorkerFunc to execute the callback ???
// verify worker default function handler
if st.defaultWorkerFunc == nil {
return newPoolError(ErrorNoDefaultWorkerFunction, "Missing default handler function to process this task")
}
return st.addTask(taskRegular, nil, nil, callbackFn)
}
// *************************************************************************************************************
// ** Worker's operations *************************************************************************************
// *************************************************************************************************************
// StartWorkers is deprecated since version 0.10.0, please do not use it.
// Why is StartWorkers deprecated? There is no need to explicitly starts up the workers as they automatically
// start up once created.
//
// For backward compatibility, this function only returns nil.
// StartWorkers will be removed on version 1.0.0
//
// Prior to version 0.10.0, the goal for this function was to start up the amount of workers pre-defined at pool instantiation.
func (st *Pool) StartWorkers() error {
return nil
}
// StartWorkersAndWait is deprecated since version 0.10.0, please do not use it.
// Use WaitUntilInitialWorkersAreUp instead.
// Why is StartWorkersAndWait deprecated? Workers are started up once they get created, there is no need to do it explicitly.
//
// For backward compatibility, this function will return WaitUntilInitialWorkersAreUp.
// StartWorkersAndWait will be removed on version 1.0.0
//
// Prior to version 0.10.0, the goal of this function was to start up all workers pre-defined at pool instantiation
// and wait until until all them were up and running.
func (st *Pool) StartWorkersAndWait() error {
return st.WaitUntilInitialWorkersAreUp()
}
// SetWorkerFunc sets the worker's default function handler.
// This function will be invoked each time a worker pulls a new job, and should return true to let know that the job
// was successfully completed, or false in other case.
func (st *Pool) SetWorkerFunc(fn PoolFunc) {
st.defaultWorkerFunc = fn
}
// getNoWorkersChan returns the channel over which the "no workers" signal travels
func (st *Pool) getNoWorkersChan() chan struct{} {
return st.noWorkersChan
}
// getNewWorkerID returns an incremental ID for the next worker to be created.
// This is a concurrent-safe function.
func (st *Pool) getNewWorkerID() int {
defer st.newWorkerID.Update(1)
return st.newWorkerID.GetValue()
}
// AddWorker adds a new worker to the pool.
//
// This is an asynchronous operation, but you can be notified through a channel every time a new worker is started.
// The channel (optional) could be set using SetNewWorkerChan(chan) or at initialization (PoolOptions.NewWorkerChan in NewPoolWithOptions).
//
// AddWorker returns an error if at least one of the following statements is true:
// - the worker could not be started
// - there is a "in course" KillAllWorkers operation
func (st *Pool) AddWorker() error {
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, messageKillAllWorkersInProgress)
}
// build the worker
wkr := newWorker(st.getNewWorkerID())
// save new worker into the map
st.workers.Store(wkr.GetID(), wkr)
// setup action external functions
st.setupWorkerActionExternalFunctions(wkr)
// increment the totalWorkers counter
st.totalWorkers.Update(1)
// add the new worker into the available workers list
if err := st.availableWorkers.Enqueue(wkr); err != nil {
// TODO ::: verify the following log in the testings
st.logError("AddWorker.availableWorkers.Enqueue", err)
if errRemoveWorker := st.removeWorker(wkr.GetID()); errRemoveWorker != nil {
st.logError("AddWorker.removeWorker", errRemoveWorker)
}
return err
}
// setup the new worker (add all external dependencies)
st.setupWorker(wkr)
// start listening requests (actions / tasks)
wkr.Listen()
// notify the user through the pre-configured external channel
if st.externalNewWorkerChan != nil {
// non-blocking operation
select {
case st.externalNewWorkerChan <- 1:
default:
// signal couldn't be sent over the external channel
st.logError("AddWorker.externalNewWorkerChan - signal couldn't be sent over the external channel once a new worker was created", newPoolError(ErrorFullCapacityChannel, "AddWorker.externalNewWorkerChan - signal couldn't be sent over the external channel once a new worker was created"))
}
}
return nil
}
// AddWorkers adds n extra workers to the pool.
//
// This is an asynchronous operation, but you can be notified through a channel every time a new worker is started.
// The channel (optional) could be set using SetNewWorkerChan(chan) or at initialization (PoolOptions.NewWorkerChan in NewPoolWithOptions).
//
// AddWorkers returns an error if at least one of the following statements are true:
// - parameter n <= 0
// - a worker could not be started
// - there is a "in course" KillAllWorkers operation
func (st *Pool) AddWorkers(n int) error {
if n <= 0 {
return newPoolError(ErrorData, "Amount of workers should be greater than zero")
}
errors := make([]error, 0)
for i := 0; i < n; i++ {
if err := st.AddWorker(); err != nil {
errors = append(errors, err)
}
}
if len(errors) > 0 {
err := newPoolError(ErrorEmbeddedErrors, "Some internal AddWorkers' operations failed.")
err.AddEmbeddedErrors(errors)
return err
}
return nil
}
// setupWorker sets up the worker:
// - adds all external dependencies:
// - external task successes
// - external function for actions/tasks
func (st *Pool) setupWorker(wkr *worker) {
// link the taskSuccesses counter with the new worker
wkr.SetExternalTaskSuccesses(st.taskSuccesses)
// external functions for actions/tasks
// function to be executed just before start processing a task
wkr.SetExternalPreTaskFunc(func() {
st.totalWorkersInProgress.Update(1)
})
// function to be executed after a task gets processed (by the worker)
wkr.SetExternalPostTaskFunc(func() {
st.totalWorkersInProgress.Update(-1)
})
// function to be executed just before start processing an action (by the worker)
wkr.SetExternalPreActionFunc(func() {
st.totalWorkersInProgress.Update(1)
})
// function to be executed after an action gets processed
wkr.SetExternalPostActionFunc(func() {
st.totalWorkersInProgress.Update(-1)
})
}
// removeWorker closes and removes a worker (from the workers' map)
// note: this function doesn't remove the worker from the availableWorkers queue
func (st *Pool) removeWorker(workerID int) error {
//st.availableWorkers.Lock()
//defer st.availableWorkers.Unlock()
if rawWkr, ok := st.workers.Load(workerID); ok {
// remove the workers entry
st.workers.Delete(workerID)
// decrement the workers counter
st.totalWorkers.Update(-1)
wkr, okTypeAssertion := rawWkr.(*worker)
if !okTypeAssertion {
return newPoolError(ErrorWorkerType, fmt.Sprintf("worker %v could not be removed due to type error", workerID))
}
// close the worker
wkr.Close()
// notify the user through the pre-configured external channel
if st.externalKilledWorkerChan != nil {
// non-blocking operation
select {
case st.externalKilledWorkerChan <- 1:
default:
// signal couldn't be sent over the external channel
st.logError("removeWorker.externalKilledWorkerChan - signal couldn't be sent over the external channel once a worker was terminated", nil)
}
}
return nil
}
return newPoolError(ErrorWorkerNotFound, fmt.Sprintf("Missing worker %v could not be removed", workerID))
}
// SetTotalWorkers adjusts the number of live workers.
//
// In case it needs to kill some workers (in order to adjust the total based on the given parameter), it will wait until
// their current jobs get processed (in case they are processing jobs).
//
// This is an asynchronous operation, but you can be notified through a channel every time a new worker is started.
// The channel (optional) can be defined at SetNewWorkerChan(chan).
//
// SetTotalWorkers returns an error in the following scenarios:
// - There is a "in course" KillAllWorkers operation.
func (st *Pool) SetTotalWorkers(n int) error {
if n < 0 {
return newPoolError(ErrorData, "total workers must be >= 0")
}
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, messageKillAllWorkersInProgress)
}
totalWorkers := st.GetTotalWorkers()
// n < totalWorkers
if n < totalWorkers {
return st.KillWorkers(totalWorkers - n)
}
// n > totalWorkers
if n > totalWorkers {
return st.AddWorkers(n - totalWorkers)
}
// n == totalWorkers, no changes needed
return nil
}
// *************************************************************************************************************
// ** Worker's operations: kill && lateKill *******************************************************************
// *************************************************************************************************************
// KillWorker kills an idle worker.
// The kill signal has a higher priority than the enqueued jobs. It means that a worker will be killed once it finishes its current job although there are unprocessed jobs in the queue.
// Use LateKillWorker() in case you need to wait until current enqueued jobs get processed.
// It returns an error in case there is a "in course" KillAllWorkers operation.
func (st *Pool) KillWorker() error {
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, messageKillAllWorkersInProgress)
}
return st.killWorker()
}
// killWorker sends a signal to kill the next available(idle) worker
func (st *Pool) killWorker() error {
return st.addAction(actionKillWorker, true, nil)
}
// KillWorkers kills n idle workers.
// If n > GetTotalWorkers(), only current amount of workers will be terminated.
// The kill signal has a higher priority than the enqueued jobs. It means that a worker will be killed once it finishes its current job, no matter if there are unprocessed jobs in the queue.
// Use LateKillAllWorkers() ot LateKillWorker() in case you need to wait until current enqueued jobs get processed.
// It returns an error in the following scenarios:
// - there is a "in course" KillAllWorkers operation
// -
func (st *Pool) KillWorkers(n int) error {
if n <= 0 {
return newPoolError(ErrorData, "Incorrect number of workers")
}
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, messageKillAllWorkersInProgress)
}
errors := make([]error, 0)
totalWorkers := st.GetTotalWorkers()
// adjust n
if n > totalWorkers {
n = totalWorkers
}
for i := 0; i < n; i++ {
if err := st.killWorker(); err != nil {
// count how many attempts failed
errors = append(errors, err)
}
}
if len(errors) > 0 {
// return a generic error containing single errors
err := newPoolError(ErrorEmbeddedErrors, "Some internal KillWorkers' operations failed.")
err.AddEmbeddedErrors(errors)
return err
}
return nil
}
// KillAllWorkers kills all live workers (the number of live workers is determined at the moment this action is processed).
// If a worker is processing a job, it will not be immediately killed, the pool will wait until the current job gets processed.
//
// The following functions will return error if invoked during KillAllWorkers execution:
//
// - KillWorker
// - KillWorkers
// - LateKillWorker
// - LateKillWorkers
// - LateKillAllWorkers
// - AddWorker
// - AddWorkers
// - SetTotalWorkers
func (st *Pool) KillAllWorkers() error {
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, "KillAllWorkers already in progress")
}
// this flag will be removed once all workers were down
st.setStatus(killAllWorkersInProgress, true)
// 1 - get total workers
totalWorkers := st.GetTotalWorkers()
embeddedErrors := make([]error, 0)
// 2 - send "kill worker" message to all workers
for i := 0; i < totalWorkers; i++ {
if err := st.killWorker(); err != nil {
embeddedErrors = append(embeddedErrors, err)
}
}
if len(embeddedErrors) > 0 {
err := newPoolError(ErrorEmbeddedErrors, "Some internal KillAllWorkers' operations failed")
err.AddEmbeddedErrors(embeddedErrors)
return err
}
return nil
}
// KillAllWorkersAndWait kills all workers (the amount of workers is determined at the moment this action is processed).
// This function waits until current alive workers are down. This is the difference between KillAllWorkersAndWait() and KillAllWorkers()
// If a worker is processing a job, it will not be immediately terminated, the pool will wait until the current job gets processed.
//
// The following functions will return error if invoked during this function execution:
//
// - KillWorker
// - KillWorkers
// - LateKillWorker
// - LateKillWorkers
// - LateKillAllWorkers
// - AddWorker
// - AddWorkers
// - SetTotalWorkers
func (st *Pool) KillAllWorkersAndWait() error {
// kill all workers
if err := st.KillAllWorkers(); err != nil {
return err
}
// wait until all workers are down
waitForKillAllWorkersAndWait := make(chan struct{}, 1)
// 1 - trigger a named function on totalWorkers (0)
st.totalWorkers.SetTriggerOnValue(0, "KillAllWorkersAndWait", func(currentValue int, previousValue int) {
// enqueue to run after trigger functions
st.totalWorkers.EnqueueToRunAfterCurrentTriggerFunctions(func(currentValue int, previousValue int) {
// remove the named trigger
st.totalWorkers.UnsetTriggerOnValue(0, "KillAllWorkersAndWait")
})
// it's done, send the signal
waitForKillAllWorkersAndWait <- struct{}{}
})
<-waitForKillAllWorkersAndWait
return nil
}
// LateKillWorker kills a worker only after current enqueued jobs get processed.
// It returns an error in case there is a "in course" KillAllWorkers operation.
func (st *Pool) LateKillWorker() error {
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, messageKillAllWorkersInProgress)
}
// enqueues the action as a task because it is a "late" action that would be executed after the current enqueued tasks
return st.addTask(taskLateAction, action{
Code: actionLateKillWorker,
SendToWorker: true,
}, nil,
nil)
}
// LateKillWorkers kills n workers only after all current jobs get processed.
// If n > GetTotalWorkers(), only current amount of workers will be terminated.
// It returns an error in case there is a "in course" KillAllWorkers operation.
func (st *Pool) LateKillWorkers(n int) error {
if n <= 0 {
return newPoolError(ErrorData, "Incorrect number of workers")
}
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, messageKillAllWorkersInProgress)
}
// Enqueues an action as a late task. This action (the PreExternalFunc) would be executed by the dispatcher, not by
// the workers (SendToWorker==false).
return st.addTask(
taskLateAction,
action{
Code: actionLateKillWorkers,
SendToWorker: false,
PreExternalFunc: func() {
totalWorkers := st.GetTotalWorkers()
// adjust n based on current amount of workers
if n > totalWorkers {
n = totalWorkers
}
if err := st.KillWorkers(n); err != nil {
st.logError("LateKillWorkers.KillWorkers", err)
}
},
},
nil,
nil)
}
// LateKillAllWorkers kills all live workers only after all current jobs get processed.
// By "current jobs" it means: the number of enqueued jobs in the exact moment this function get executed.
// It returns an error for the following scenarios:
// - there is a "in course" KillAllWorkers operation.
// - the operations' queue (where tasks/actions get enqueued) is at full capacity
func (st *Pool) LateKillAllWorkers() error {
if st.getStatus(killAllWorkersInProgress) {
return newPoolError(ErrorKillAllWorkersInProgress, messageKillAllWorkersInProgress)
}
// Enqueues an action as a late task. This action (the PreExternalFunc) would be executed by the dispatcher, not by
// the workers (SendToWorker==false).
return st.addTask(
taskLateAction,
action{
Code: actionLateKillAllWorkers,
SendToWorker: false,
PreExternalFunc: func() {
st.KillAllWorkers()
},
},
nil,
nil)
}
// *************************************************************************************************************
// ** Wait functions ******************************************************************************************
// *************************************************************************************************************
// Wait waits while at least a worker is up and running
func (st *Pool) Wait() error {
if st.totalWorkers.GetValue() == 0 {
return nil