/
base.go
1770 lines (1526 loc) · 42.2 KB
/
base.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
// Copyright 2014-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package execution
// IMPORTANT - please remember to override the opener, destructor and
// message methods in individual operators whenever there are actions
// to be taken on children operators, so as to ensure correct operation
// and avoid hangs destruction and contain memory consumption
import (
"fmt"
"reflect"
"sync"
go_atomic "sync/atomic"
"time"
atomic "github.com/couchbase/go-couchbase/platform"
"github.com/couchbase/query/datastore"
"github.com/couchbase/query/errors"
"github.com/couchbase/query/expression"
"github.com/couchbase/query/logging"
"github.com/couchbase/query/util"
"github.com/couchbase/query/value"
)
type timePhases int
const (
_NOTIME = timePhases(iota)
_EXECTIME
_KERNTIME
_SERVTIME
)
var _PHASENAMES = []string{
_NOTIME: "",
_EXECTIME: "running",
_KERNTIME: "kernel",
_SERVTIME: "services",
}
type annotatedChannel chan value.AnnotatedValue
// Execution operators have a complex life.
// Though the norm is that they are created, they run and they complete, some
// are not even designed to run (eg channel), some will be stopped half way, some
// will be delayed by an overloaded kernel and will only manage to start when the
// request has in fact completed, and some will not start at all (eg their parent
// hasn't managed to start).
// Transitioning states and freeing resources is tricky.
// For starters, cleaning resources can't wait for operators that haven't started to
// complete, because they may never get to start, leading to a fat deadly embrace.
// The Done() method therefore does not wait for latecomers.
// This means that it is not safe to destruct what hasn't started, because they might
// come to life later and will need certain information to notify other operators:
// _KILLED operators will have to clean up after themselves and remove any residual
// references to other objects so as to help the GC.
// This also means that it is not safe to pool _KILLED operators, as they may later
// come to life.
// The Done() method should only be called when it is known that no further actions
// are going to be sent, and the request as completed, either naturally, or via an
// OpStop(), as, as much as we try, it's difficult to control race conditions when
// SendAction() should take decisions based on structures that are being torn down.
// This means that sending further actions should be prevented before Done() is called,
// and after.
// Also, since we can't guarantee that operators will come to stop naturally, it's
// probably safer to send a stop before calling Done() even on a successful execution.
// At the same time, it's not safe to dispose of operators that haven't started without
// first signaling related operators (parent and stop), because that too will
// lead to deadly embraces.
// Conversely, dormant operators should never change state during request execution,
// because marking them as inactive will terminate early a result stream.
// It should be safe to pool an operator that has successfully been stopped, but
// our current policy is not to take chances.
// Finally, should a panic occur, it's not safe to clean up, but the operator that
// is terminating in error should still try to notify other operators, so that a stall
// can be avoided.
type opState int
const (
// not yet active
_CREATED = opState(iota)
_DORMANT
_LATE // forcibly terminating before starting
// operating
_RUNNING
_STOPPING
_HALTING
// terminated - terminally!
_PANICKED
_HALTED
// terminated - possibly temporarily
_STOPPED
_COMPLETED
// paused - ready to reopen
_PAUSED
// disposed
_DONE
_ENDED
_KILLED
)
// an operator action can be a STOP or a PAUSE
type opAction int
const (
_ACTION_STOP = opAction(iota)
_ACTION_PAUSE
)
type phaseMap struct {
primary Phases
index Phases
}
var indexerPhase = map[datastore.IndexType]phaseMap{
datastore.GSI: phaseMap{PRIMARY_SCAN_GSI, INDEX_SCAN_GSI},
datastore.FTS: phaseMap{PRIMARY_SCAN_FTS, INDEX_SCAN_FTS},
datastore.SEQ_SCAN: phaseMap{PRIMARY_SCAN_SEQ, INDEX_SCAN_SEQ},
}
type base struct {
valueExchange
externalStop func(bool)
funcLock sync.RWMutex
handleLock sync.RWMutex
conn *datastore.IndexConnection
stopChannel stopChannel
quota uint64
input Operator
output Operator
stop OpSendAction
parent Operator
once util.Once
serializable bool
serialized bool
inline bool
doSend func(this *base, op Operator, item value.AnnotatedValue) bool
closeConsumer bool
batch []value.AnnotatedValue
timePhase timePhases
startTime util.Time
execPhase Phases
phaseTimes func(*Context, Phases, time.Duration)
execTime time.Duration
kernTime time.Duration
servTime time.Duration
inDocs int64
outDocs int64
phaseSwitches int64
stopped bool
isRoot bool
bit uint8
operatorCtx opContext
rootContext *Context
childrenLeft int32
activeCond sync.Cond
activeLock sync.Mutex
opState opState
phase Phases
inactiveFlag bool
stash Operator
handlesInActive bool // whether new handles can be created under this operator
handles map[*executionHandle]bool // stores all the currently active handles created under this operator
}
const _ITEM_CAP = 512
const _MAP_POOL_CAP = 512
var pipelineCap atomic.AlignedInt64
func init() {
atomic.StoreInt64(&pipelineCap, int64(_ITEM_CAP))
SetPipelineBatch(0)
}
func SetPipelineCap(pcap int64) {
if pcap < 1 {
pcap = _ITEM_CAP
}
atomic.StoreInt64(&pipelineCap, pcap)
}
func GetPipelineCap() int64 {
pcap := atomic.LoadInt64(&pipelineCap)
if pcap > 0 {
return pcap
} else {
return _ITEM_CAP
}
}
func (this *base) getBase() *base {
return this
}
// Constructor, (re)opener, closer, destructor
func newBase(dest *base, context *Context) {
*dest = base{}
newValueExchange(&dest.valueExchange, context.GetPipelineCap())
dest.execPhase = PHASES
dest.phaseTimes = emptyPhaseTimes
dest.activeCond.L = &dest.activeLock
dest.doSend = parallelSend
dest.closeConsumer = false
dest.quota = context.ProducerThrottleQuota()
dest.operatorCtx = opContext{dest, context}
}
// The output of this operator will be redirected elsewhere, so we
// allocate a minimal itemChannel.
func newRedirectBase(dest *base, context *Context) {
*dest = base{}
newValueExchange(&dest.valueExchange, 1)
dest.execPhase = PHASES
dest.phaseTimes = emptyPhaseTimes
dest.activeCond.L = &dest.activeLock
dest.doSend = parallelSend
dest.closeConsumer = false
dest.operatorCtx = opContext{dest, context}
}
// This operator will be serialised - allocate valueExchange dynamically
//
// A few ground rules for serializable operators:
// - must always be called in a sequence
// - must follow a producer in a sequence
// - beforeItems() must not yield, to avoid stalls
func newSerializedBase(dest *base, context *Context) {
*dest = base{}
newValueExchange(&dest.valueExchange, 1)
dest.execPhase = PHASES
dest.phaseTimes = emptyPhaseTimes
dest.activeCond.L = &dest.activeLock
dest.doSend = parallelSend
dest.closeConsumer = false
dest.serializable = true
dest.quota = context.ProducerThrottleQuota()
dest.operatorCtx = opContext{dest, context}
}
func (this *base) setInline() {
this.inline = true
}
func (this *base) copy(dest *base) {
*dest = base{}
newValueExchange(&dest.valueExchange, int64(cap(this.valueExchange.items)))
if this.valueExchange.children != nil {
dest.trackChildren(cap(this.valueExchange.children))
}
dest.input = this.input
if this.output == nil && this.stash != nil {
dest.output = this.stash
} else {
dest.output = this.output
}
dest.parent = this.parent
dest.execPhase = this.execPhase
dest.phaseTimes = this.phaseTimes
dest.activeCond.L = &dest.activeLock
dest.serializable = this.serializable
dest.inline = this.inline
dest.serialized = false
dest.doSend = parallelSend
dest.closeConsumer = false
dest.quota = this.quota
dest.operatorCtx = opContext{dest, this.operatorCtx.Context}
dest.phase = this.phase
}
// reset the operator to an initial state
// it's the caller's responsability to make sure the operator has
// stopped, or, at least, will definitely stop: if not this method
// might wait indefinitely
func (this *base) reopen(context *Context) bool {
return this.baseReopen(context)
}
func (this *base) close(context *Context) {
if this.inactiveFlag {
logging.Debugf("[%p] Operator already closed", this)
return
}
err := recover()
if err != nil {
panic(err)
}
this.valueExchange.close()
// MB-27362 avoid serialized close recursion
if this.output != nil && this.closeConsumer {
base := this.output.getBase()
serializedClose(this.output, base, context)
}
this.inactive()
// operators that never enter a _RUNNING state have to clean after themselves when they finally go
if this.opState == _KILLED || this.opState == _PAUSED {
this.valueExchange.dispose()
this.stopChannel = nil
this.input = nil
this.output = nil
this.parent = nil
this.stop = nil
}
}
// flag terminal early failure (when children don't get to start)
func (this *base) fail(context *Context) {
this.close(context)
if this.isRoot {
context.CloseResults()
}
}
func (this *base) Done() {
this.baseDone()
}
func (this *base) baseDone() {
this.activeCond.L.Lock()
// if it hasn't started, kill it
switch this.opState {
case _CREATED, _PAUSED:
this.opState = _KILLED
case _DORMANT:
this.opState = _DONE
// otherwise wait
case _RUNNING, _HALTING, _STOPPING:
this.activeCond.Wait()
}
// from now on, this operator can't be touched
switch this.opState {
case _LATE:
// MB-47358 before being forcibly disposed, a _LATE operator must notify parents
this.opState = _KILLED
parent := this.parent
stop := this.stop
this.parent = nil
this.stop = nil
this.activeCond.L.Unlock()
this.notifyParent1(parent)
this.notifyStop1(stop)
return
case _COMPLETED, _STOPPED:
this.opState = _DONE
case _HALTED:
this.opState = _ENDED
}
rootContext := this.rootContext
if this.opState == _DONE || this.opState == _ENDED {
this.valueExchange.dispose()
this.rootContext = nil
this.stopChannel = nil
this.input = nil
this.output = nil
this.parent = nil
this.stop = nil
}
this.activeCond.L.Unlock()
if rootContext != nil {
rootContext.done()
}
}
// reopen for the terminal operator case
func (this *base) baseReopen(context *Context) bool {
this.activeCond.L.Lock()
// still running, just wait
if this.opState == _CREATED || this.opState == _RUNNING ||
this.opState == _STOPPING || this.opState == _HALTING {
this.activeCond.Wait()
}
// the request terminated, a stop was sent, or something catastrophic happened
// cannot reopen, bail out
if this.opState == _HALTED || this.opState == _DONE || this.opState == _ENDED ||
this.opState == _LATE || this.opState == _KILLED || this.opState == _PANICKED {
this.activeCond.L.Unlock()
return false
}
// opState of _PAUSED is safe to reopen, just follow through and set to _CREATED state
if this.stopChannel != nil {
// drain the stop channel
select {
case <-this.stopChannel:
default:
}
}
if this.conn != nil {
this.conn = nil
}
this.handlesInActive = false
this.handles = nil
this.childrenLeft = 0
this.stopped = false
this.serialized = false
this.doSend = parallelSend
this.closeConsumer = false
this.opState = _CREATED
this.valueExchange.reset()
this.once.Reset()
this.inactiveFlag = false
this.restoreOutput()
this.activeCond.L.Unlock()
return true
}
// setUp
func (this *base) trackChildren(count int) {
this.valueExchange.trackChildren(count)
}
func (this *base) ValueExchange() *valueExchange {
return &this.valueExchange
}
func (this *base) exchangeMove(dest *base) {
this.valueExchange.move(&dest.valueExchange)
}
// for those operators that really use channels
func (this *base) newStopChannel() {
this.stopChannel = make(stopChannel, 1)
}
func (this *base) stopCh() stopChannel {
return this.stopChannel
}
func (this *base) Input() Operator {
return this.input
}
func (this *base) SetInput(op Operator) {
this.input = op
}
func (this *base) Output() Operator {
return this.output
}
func (this *base) SetOutput(op Operator) {
this.output = op
base := op.getBase()
// propagate inline operators
if base != this && base.serialized {
this.doSend = serializedSend
this.closeConsumer = true
} else {
this.doSend = parallelSend
}
}
func (this *base) stashOutput() {
if this.closeConsumer && this.output != nil {
this.stash = this.output
this.output = nil
}
}
func (this *base) restoreOutput() {
if this.output == nil && this.stash != nil {
this.output = this.stash
}
}
func (this *base) Stop() OpSendAction {
return this.stop
}
func (this *base) SetStop(op OpSendAction) {
this.stop = op
}
func (this *base) Parent() Operator {
return this.parent
}
func (this *base) SetParent(parent Operator) {
this.parent = parent
}
func (this *base) Bit() uint8 {
return this.bit
}
func (this *base) SetBit(b uint8) {
this.bit = b
}
func (this *base) SetRoot(context *Context) {
this.isRoot = true
this.rootContext = context
}
func (this *base) SetKeepAlive(children int, context *Context) {
this.childrenLeft = int32(children)
}
func (this *base) IsSerializable() bool {
return this.serializable
}
// IsParallel has meaning independent of IsSerializable
func (this *base) IsParallel() bool {
// by default operators are not parallel; those that are override this
return false
}
func (this *base) SerializeOutput(op Operator, context *Context) {
this.output = op
this.doSend = serializedSend
this.closeConsumer = true
base := op.getBase()
base.serialized = true
}
// fork operator
// MB-55658 in order to avoid escaping to the heap, avoid anonymous functions
type opForkDesc struct {
op Operator
context *Context
parent value.Value
}
func opFork(p interface{}) {
d := p.(opForkDesc)
d.op.RunOnce(d.context, d.parent)
}
func (this *base) fork(op Operator, context *Context, parent value.Value) {
base := op.getBase()
if base.inline || base.serialized {
phase := this.timePhase
this.switchPhase(_NOTIME)
op.RunOnce(context, parent)
this.switchPhase(phase)
} else {
util.Fork(opFork, opForkDesc{op, context, parent})
}
}
// value and message exchange
//
// The rules are simple - we always receive from input and send onto output.
// Use SetInput() and SetOutput() as required.
// Output by default set to our own item channel.
// If you need to receive from a specific operator, set your input to that operator.
// If you need to fan out - set multiple inputs to the same producer operator
// If you need to fan in - create a channel operator, set the producer outputs to
// the channel, set the consumer input to the channel.
//
// The boolean return value is always true unless a stop signal has been received.
// The returned item is nil on no more data (usually, a channel close).
// The child return value is >=0 if a child message has been received.
// stop the operator
func OpStop(op Operator) {
op.SendAction(_ACTION_STOP)
}
// send an action
func (this *base) SendAction(action opAction) {
this.baseSendAction(action)
}
func (this *base) setExternalStop(stop func(bool)) {
this.funcLock.Lock()
this.externalStop = stop
this.funcLock.Unlock()
}
func (this *base) addHandle(handle *executionHandle) {
this.handleLock.Lock()
if this.handles == nil {
this.handles = make(map[*executionHandle]bool)
}
this.handles[handle] = true
this.handleLock.Unlock()
}
func (this *base) deleteHandle(handle *executionHandle) {
this.handleLock.Lock()
if this.handles != nil {
delete(this.handles, handle)
}
this.handleLock.Unlock()
}
func (this *base) getHandlesInActive() bool {
return this.handlesInActive
}
func (this *base) isRunning() bool {
state := this.opState
return state == _RUNNING
}
// action for the terminal operator case
func (this *base) baseSendAction(action opAction) bool {
// CREATED and DORMANT cannot apply, as they have neither sent or received
// PANICKED, COMPLETED, STOPPED and HALTED have already sent a notifyStop
// DONE, ENDED and KILLED can no longer be operated upon
if this.stopped && !this.valueExchange.isWaiting() {
switch this.opState {
case _PAUSED:
if action == _ACTION_PAUSE {
return true
}
// _ACTION_STOP has to take the slow route
case _RUNNING, _STOPPING, _HALTING:
return true
default:
return false
}
}
// STOPPED, COMPLETED, HALTED, DONE, ENDED, KILLED have already sent signals or stopped operating
rv := false
this.activeCond.L.Lock()
switch this.opState {
case _CREATED:
if action == _ACTION_PAUSE {
this.opState = _PAUSED
rv = true
} else { // _ACTION_STOP
this.opState = _LATE
}
this.activeCond.L.Unlock()
case _PAUSED:
if action == _ACTION_STOP {
this.opState = _LATE
} else { // action == _ACTION_PAUSE, no-op
rv = true
}
this.activeCond.L.Unlock()
case _RUNNING:
if action == _ACTION_STOP {
this.opState = _HALTING
} else {
this.opState = _STOPPING
}
this.activeCond.L.Unlock()
rv = true
this.valueExchange.sendStop()
case _STOPPING:
if action == _ACTION_STOP {
this.opState = _HALTING
}
this.activeCond.L.Unlock()
rv = true
case _HALTING:
this.activeCond.L.Unlock()
rv = true
default:
this.activeCond.L.Unlock()
}
this.funcLock.RLock()
if this.externalStop != nil {
this.externalStop(action == _ACTION_STOP)
}
this.funcLock.RUnlock()
if action == _ACTION_STOP {
this.handleLock.RLock()
// stop all the handles that are open
for handle := range this.handles {
handle.externalStop()
delete(this.handles, handle)
}
this.handleLock.RUnlock()
// set this flag to indicate that no further interaction must be allowed with these handles
// and that no new handles must be created under this operator
this.handlesInActive = true
}
return rv
}
func (this *base) chanSendAction(action opAction) {
this.activeCond.L.Lock()
if this.opState == _CREATED {
if action == _ACTION_PAUSE {
this.opState = _PAUSED
} else { // _ACTION_STOP
this.opState = _LATE
}
this.activeCond.L.Unlock()
} else if this.opState == _PAUSED {
if action == _ACTION_STOP {
this.opState = _LATE
} // else action == _ACTION_PAUSE, no-op
this.activeCond.L.Unlock()
} else if this.opState == _RUNNING {
if action == _ACTION_STOP {
this.opState = _HALTING
} else {
this.opState = _STOPPING
}
this.activeCond.L.Unlock()
this.switchPhase(_NOTIME)
this.valueExchange.sendStop()
select {
case this.stopChannel <- 0:
default:
}
this.switchPhase(_EXECTIME)
} else {
this.activeCond.L.Unlock()
}
}
func (this *base) connSendAction(conn *datastore.IndexConnection, action opAction) {
this.activeCond.L.Lock()
if this.opState == _CREATED {
if action == _ACTION_PAUSE {
this.opState = _PAUSED
} else { // _ACTION_STOP
this.opState = _LATE
}
this.activeCond.L.Unlock()
} else if this.opState == _PAUSED {
if action == _ACTION_STOP {
this.opState = _LATE
} // else action == _ACTION_PAUSE, no-op
this.activeCond.L.Unlock()
} else if this.opState == _RUNNING {
if action == _ACTION_STOP {
this.opState = _HALTING
} else {
this.opState = _STOPPING
}
this.activeCond.L.Unlock()
phase := this.timePhase
this.switchPhase(_KERNTIME)
this.valueExchange.sendStop()
if conn != nil {
conn.SendStop()
}
this.switchPhase(phase)
} else {
this.activeCond.L.Unlock()
}
}
func (this *base) sendItem(item value.AnnotatedValue) bool {
return this.sendItemOp(this.output, item)
}
func (this *base) sendItemOp(op Operator, item value.AnnotatedValue) bool {
if this.stopped {
return false
}
ok := this.doSend(this, op, item)
if ok {
// sendItem tracks outgoing documents for most operators
this.addOutDocs(1)
} else {
this.stopped = true
}
return ok
}
// send data down a channel
func parallelSend(this *base, op Operator, item value.AnnotatedValue) bool {
this.switchPhase(_KERNTIME)
ok := this.valueExchange.sendItem(op.ValueExchange(), item, this.quota)
this.switchPhase(_EXECTIME)
return ok
}
func (this *base) getItem() (value.AnnotatedValue, bool) {
return this.getItemOp(this.input)
}
func (this *base) getItemOp(op Operator) (value.AnnotatedValue, bool) {
if this.stopped {
return nil, false
}
this.switchPhase(_KERNTIME)
val, ok := this.ValueExchange().getItem(op.ValueExchange())
this.switchPhase(_EXECTIME)
if !ok {
this.stopped = true
}
return val, ok
}
func (this *base) queuedItems() int {
if this.input == nil {
return 0
}
return this.input.ValueExchange().queuedItems()
}
func (this *base) getItemValue(channel value.ValueChannel) (value.Value, bool) {
this.switchPhase(_KERNTIME)
defer this.switchPhase(_EXECTIME)
select {
case <-this.stopChannel: // Never closed
this.stopped = true
return nil, false
default:
}
select {
case item, ok := <-channel:
if ok {
// getItemValue does not keep track of
// incoming documents
return item, true
}
// no more data
return nil, true
case <-this.stopChannel: // Never closed
this.stopped = true
return nil, false
}
}
func (this *base) getItemEntry(conn *datastore.IndexConnection) (*datastore.IndexEntry, bool) {
this.conn = conn
if this.stopped {
return nil, false
}
// this is used explictly to get keys from the indexer
// so by definition we are tracking service time
this.switchPhase(_SERVTIME)
item, ok := conn.Sender().GetEntry()
this.switchPhase(_EXECTIME)
if !ok {
this.stopped = true
return nil, false
}
return item, ok
}
func (this *base) getItemChildren() (value.AnnotatedValue, int, bool) {
return this.getItemChildrenOp(this.input)
}
func (this *base) getItemChildrenOp(op Operator) (value.AnnotatedValue, int, bool) {
this.switchPhase(_KERNTIME)
val, child, ok := this.ValueExchange().getItemChildren(op.ValueExchange())
this.switchPhase(_EXECTIME)
if !ok {
this.stopped = true
}
return val, child, ok
}
// wait for at least n children to complete
func (this *base) childrenWait(n int) bool {
this.switchPhase(_KERNTIME)
for n > 0 {
// no values are actually coming
child, ok := this.ValueExchange().retrieveChild()
if !ok {
this.stopped = true
this.switchPhase(_EXECTIME)
return false
}
if child >= 0 {
n--
}
}
this.switchPhase(_EXECTIME)
return true
}
// wait for at least n children to complete ignoring stop messages
func (this *base) childrenWaitNoStop(ops ...Operator) {
this.switchPhase(_KERNTIME)
for _, o := range ops {
b := o.getBase()
b.activeCond.L.Lock()
switch b.opState {
case _RUNNING, _STOPPING, _HALTING:
// signal reliably sent
b.activeCond.Wait()
case _COMPLETED, _STOPPED, _HALTED:
// signal reliably sent, but already stopped
case _LATE:
// signal reliably sent, but never started
case _CREATED, _PAUSED, _KILLED, _PANICKED:
// signal reliably not sent
default:
// we are waiting after we've sent a stop but before we have terminated
// flag bad states
assert(false, fmt.Sprintf("child has unexpected state %v", b.opState))
}
b.activeCond.L.Unlock()
}
this.switchPhase(_EXECTIME)
}
type consumer interface {
beforeItems(context *Context, parent value.Value) bool
processItem(item value.AnnotatedValue, context *Context) bool
afterItems(context *Context)
readonly() bool
}
func (this *base) runConsumer(cons consumer, context *Context, parent value.Value, cleanup func()) {
this.once.Do(func() {
defer context.Recover(this) // Recover from any panic
active := this.active()
if this.execPhase != PHASES {
this.setExecPhase(this.execPhase, context)
}
this.switchPhase(_EXECTIME)
if this.serialized == true {
ok := true
defer func() {
this.switchPhase(_NOTIME) // accrue current phase's time
if !ok {
if cleanup != nil {
cleanup()
}
this.notify()
this.close(context)
}
}()
if !active || (context.Readonly() && !cons.readonly()) {
ok = false
} else {
ok = cons.beforeItems(context, parent)
}
if ok {
this.fork(this.input, context, parent)
}
return
}
defer func() {
err := recover()
if err != nil {
panic(err)
}
if active {
this.batch = nil
}
// avoid potential to call close twice on the consumer
if this.closeConsumer && this.output != nil && this.output == this.parent && this.parent.getBase().childrenLeft != 0 {
this.closeConsumer = false
}
if cleanup != nil {
cleanup()
}
this.notify()
this.switchPhase(_NOTIME)
this.close(context)
}()