/
scan_scatter.go
711 lines (557 loc) · 15.4 KB
/
scan_scatter.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
// Copyright (c) 2014 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
package indexer
import (
"bytes"
"errors"
"fmt"
"github.com/couchbase/indexing/secondary/common"
"github.com/couchbase/indexing/secondary/logging"
"github.com/couchbase/indexing/secondary/pipeline"
"runtime"
"sync"
"sync/atomic"
)
var ErrFinishCallback error = errors.New("Callback done due to error")
const (
NoPick = -1
Done = -2
)
//--------------------------
// scatter range scan
//--------------------------
func getPartitionId(request *ScanRequest, pos int) common.PartitionId {
// For nil-snapshot, it has empty list of snapshot. So return 0, since there won't be any stats.
// For non-partitioned index, len(request.PartitionIds) is either 1 or 0. If it is 1, then
// request.PartitionIds[0] returns partitionId 0.
//
if len(request.PartitionIds) > pos {
return request.PartitionIds[pos]
}
return common.PartitionId(0)
}
func scatter(request *ScanRequest, scan Scan, snapshots []SliceSnapshot, cb EntryCallback, config common.Config) (err error) {
if len(snapshots) == 0 {
return
}
if len(snapshots) == 1 {
partitionId := getPartitionId(request, 0)
return scanOne(request, scan, snapshots, partitionId, cb)
}
return scanMultiple(request, scan, snapshots, cb, config)
}
func scanMultiple(request *ScanRequest, scan Scan, snapshots []SliceSnapshot, cb EntryCallback, config common.Config) (err error) {
var wg sync.WaitGroup
notifych := make(chan bool, 1)
killch := make(chan bool, 1)
donech := make(chan bool, 1)
errch := make(chan error, len(snapshots)+100)
sorted := request.Sorted
queues := make([]*Queue, len(snapshots))
size, limit := queueSize(len(snapshots), sorted, config)
for i := 0; i < len(snapshots); i++ {
partitionId := getPartitionId(request, i)
var m *allocator
if v := request.connCtx.Get(fmt.Sprintf("%v%v", ScanQueue, partitionId)); v == nil {
bufPool := request.connCtx.GetBufPool(partitionId)
m = newAllocator(int64(size), bufPool)
} else {
m = v.(*allocator)
}
queues[i] = NewQueue(int64(size), int64(limit), notifych, m)
}
defer func() {
for i, queue := range queues {
queue.Close()
queue.Free()
partitionId := getPartitionId(request, i)
if m := queue.GetAllocator(); m != nil {
//logging.Debugf("Free allocator %p partition id %v count %v malloc %v", m, partitionId, m.count, m.numMalloc)
request.connCtx.Put(fmt.Sprintf("%v%v", ScanQueue, partitionId), m)
}
}
}()
// run gather
if sorted {
go gather(request, queues, donech, notifych, killch, errch, cb)
} else {
go forward(request, queues, donech, notifych, killch, errch, cb)
}
// run scatter
for i, snap := range snapshots {
wg.Add(1)
partitionId := getPartitionId(request, i)
go scanSingleSlice(request, scan, request.Ctxs[i], snap, partitionId, queues[i], &wg, errch, nil)
}
// wait for scatter to be done
wg.Wait()
errcnt := len(errch)
for i := 0; i < errcnt; i++ {
err = <-errch
if err == pipeline.ErrSupervisorKill || err == ErrLimitReached {
break
}
}
if err != nil {
// stop gather go-routine
close(killch)
errch <- err
}
// wait for gather to be done
<-donech
enqCount := int64(0)
deqCount := int64(0)
for _, queue := range queues {
enqCount += queue.EnqueueCount()
deqCount += queue.DequeueCount()
}
logging.Debugf("scan_scatter.scanMultiple: scan done. enqueue count %v dequeue count %v", enqCount, deqCount)
return
}
func scanOne(request *ScanRequest, scan Scan, snapshots []SliceSnapshot, partitionId common.PartitionId, cb EntryCallback) (err error) {
errch := make(chan error, 1)
count := scanSingleSlice(request, scan, request.Ctxs[0], snapshots[0], partitionId, nil, nil, errch, cb)
logging.Debugf("scan_scatter:scanOnce: scan done. Count %v", count)
errcnt := len(errch)
for i := 0; i < errcnt; i++ {
err = <-errch
if err == pipeline.ErrSupervisorKill || err == ErrLimitReached {
break
}
}
return
}
func scanSingleSlice(request *ScanRequest, scan Scan, ctx IndexReaderContext, snap SliceSnapshot, partitionId common.PartitionId,
queue *Queue, wg *sync.WaitGroup, errch chan error, cb EntryCallback) (count int) {
defer func() {
if wg != nil {
wg.Done()
}
request.Stats.updatePartitionStats(partitionId, func(ps *IndexStats) {
ps.numRowsScanned.Add(int64(count))
})
}()
handler := func(entry []byte) error {
// Do not call enqueue when there is error.
if len(errch) != 0 {
return ErrFinishCallback
}
count++
if queue != nil {
var r Row
if !request.isPrimary {
entry1 := secondaryIndexEntry(entry)
r.len = entry1.lenKey()
}
r.key = entry
queue.Enqueue(&r)
return nil
} else {
return cb(entry)
}
}
var err error
if scan.ScanType == AllReq {
err = snap.Snapshot().All(ctx, handler)
} else if scan.ScanType == LookupReq {
err = snap.Snapshot().Range(ctx, scan.Equals, scan.Equals, Both, handler)
} else if scan.ScanType == RangeReq || scan.ScanType == FilterRangeReq {
err = snap.Snapshot().Range(ctx, scan.Low, scan.High, scan.Incl, handler)
}
if err != nil {
if err != ErrFinishCallback {
errch <- err
}
if queue != nil {
queue.Close()
}
} else if queue != nil {
// If there is no error, tells gather routine that I am done.
// Do not call enqueue when there is error.
var r Row
r.last = true
queue.Enqueue(&r)
}
return
}
//--------------------------
// scatter count
//--------------------------
func scatterCount(request *ScanRequest, snapshots []SliceSnapshot, stop StopChannel) (count uint64, err error) {
if len(snapshots) == 0 {
return
}
var wg sync.WaitGroup
errch := make(chan error, len(snapshots))
// run scatter
for i, snap := range snapshots {
wg.Add(1)
go countSingleSlice(request, request.Ctxs[i], snap, &wg, errch, stop, &count)
}
// wait for scatter to be done
wg.Wait()
if len(errch) > 0 {
err = <-errch
}
return
}
func countSingleSlice(request *ScanRequest, ctx IndexReaderContext, snap SliceSnapshot, wg *sync.WaitGroup, errch chan error, stopch StopChannel, count *uint64) {
defer func() {
wg.Done()
}()
var err error
var cnt uint64
if len(request.Keys) > 0 {
cnt, err = snap.Snapshot().CountLookup(ctx, request.Keys, stopch)
} else if request.Low.Bytes() == nil && request.High.Bytes() == nil {
cnt, err = snap.Snapshot().CountTotal(ctx, stopch)
} else {
cnt, err = snap.Snapshot().CountRange(ctx, request.Low, request.High, request.Incl, stopch)
}
if err != nil {
errch <- err
} else {
atomic.AddUint64(count, cnt)
}
}
//--------------------------
// scatter multi-count
//--------------------------
func scatterMultiCount(request *ScanRequest, scan Scan, snapshots []SliceSnapshot, previousRows [][]byte, stop StopChannel) (count uint64, err error) {
if len(snapshots) == 0 {
return
}
var wg sync.WaitGroup
errch := make(chan error, len(snapshots))
// run scatter
for i, snap := range snapshots {
wg.Add(1)
go multiCountSingleSlice(request, scan, request.Ctxs[i], snap, previousRows[i], &wg, errch, stop, &count)
}
// wait for scatter to be done
wg.Wait()
if len(errch) > 0 {
err = <-errch
}
return
}
func multiCountSingleSlice(request *ScanRequest, scan Scan, ctx IndexReaderContext, snap SliceSnapshot, previousRow []byte, wg *sync.WaitGroup,
errch chan error, stopch StopChannel, count *uint64) {
defer func() {
wg.Done()
}()
var err error
var cnt uint64
if scan.ScanType == AllReq {
cnt, err = snap.Snapshot().MultiScanCount(ctx, MinIndexKey, MaxIndexKey, Both, scan, request.Distinct, stopch)
} else if scan.ScanType == LookupReq || scan.ScanType == RangeReq || scan.ScanType == FilterRangeReq {
cnt, err = snap.Snapshot().MultiScanCount(ctx, scan.Low, scan.High, scan.Incl, scan, request.Distinct, stopch)
}
if err != nil {
errch <- err
} else {
atomic.AddUint64(count, cnt)
}
}
//--------------------------
// scatter stats
//--------------------------
func scatterStats(request *ScanRequest, snapshots []SliceSnapshot, stop StopChannel) (count uint64, err error) {
if len(snapshots) == 0 {
return
}
var wg sync.WaitGroup
errch := make(chan error, len(snapshots))
// run scatter
for i, snap := range snapshots {
wg.Add(1)
go statsSingleSlice(request, request.Ctxs[i], snap, &wg, errch, stop, &count)
}
// wait for scatter to be done
wg.Wait()
if len(errch) > 0 {
err = <-errch
}
return
}
func statsSingleSlice(request *ScanRequest, ctx IndexReaderContext, snap SliceSnapshot, wg *sync.WaitGroup,
errch chan error, stopch StopChannel, count *uint64) {
defer func() {
wg.Done()
}()
var err error
var cnt uint64
if request.Low.Bytes() == nil && request.High.Bytes() == nil {
cnt, err = snap.Snapshot().StatCountTotal()
} else {
cnt, err = snap.Snapshot().CountRange(ctx, request.Low, request.High, request.Incl, stopch)
}
if err != nil {
errch <- err
} else {
atomic.AddUint64(count, cnt)
}
}
//--------------------------
// scatter fast count
//--------------------------
func scatterFastCount(request *ScanRequest, scan Scan, snapshots []SliceSnapshot, stop StopChannel) (count uint64, err error) {
if len(snapshots) == 0 {
return
}
var wg sync.WaitGroup
errch := make(chan error, len(snapshots))
// run scatter
for i, snap := range snapshots {
wg.Add(1)
go fastCountSingleSlice(request, scan, request.Ctxs[i], snap, &wg, errch, stop, &count)
}
// wait for scatter to be done
wg.Wait()
if len(errch) > 0 {
err = <-errch
}
return
}
func fastCountSingleSlice(request *ScanRequest, scan Scan, ctx IndexReaderContext, snap SliceSnapshot, wg *sync.WaitGroup,
errch chan error, stopch StopChannel, count *uint64) {
defer func() {
wg.Done()
}()
var err error
var cnt uint64
var nullCnt uint64
desc := false
if request.IndexInst.Defn.HasDescending() {
//fast count only works for first leading key
if request.IndexInst.Defn.Desc[0] {
desc = true
}
}
if !desc {
if scan.Incl == Low || scan.Incl == Both {
cnt, err = snap.Snapshot().CountTotal(ctx, stopch)
} else if scan.Incl == Neither {
nullCnt, err = snap.Snapshot().CountRange(ctx, scan.Low, scan.Low, Both, stopch)
if err == nil {
cnt, err = snap.Snapshot().CountTotal(ctx, stopch)
}
}
} else {
//for desc, inclusion gets flipped to High
if scan.Incl == High || scan.Incl == Both {
cnt, err = snap.Snapshot().CountTotal(ctx, stopch)
} else if scan.Incl == Neither {
//for desc, nulls collate on the higher end
nullCnt, err = snap.Snapshot().CountRange(ctx, scan.High, scan.High, Both, stopch)
if err == nil {
cnt, err = snap.Snapshot().CountTotal(ctx, stopch)
}
}
}
if err != nil {
errch <- err
} else {
cnt = cnt - nullCnt
atomic.AddUint64(count, cnt)
}
}
//--------------------------
// gather range scan
//--------------------------
func scan_sort(request *ScanRequest, queues []*Queue, rows []Row, sorted []int) bool {
size := len(queues)
for i := 0; i < size; i++ {
sorted[i] = i
}
for i := 0; i < size-1; i++ {
if !queues[sorted[i]].Peek(&rows[sorted[i]]) {
return false
}
for j := i + 1; j < size; j++ {
if !queues[sorted[j]].Peek(&rows[sorted[j]]) {
return false
}
if rows[sorted[i]].last && !rows[sorted[j]].last ||
(!rows[sorted[i]].last && !rows[sorted[j]].last &&
compareKey(request, &rows[sorted[i]], &rows[sorted[j]]) > 0) {
tmp := sorted[i]
sorted[i] = sorted[j]
sorted[j] = tmp
}
}
}
return true
}
//
// Gather results from multiple connections
// rows - buffer of rows from each scatter gorountine
// sorted - sorted order of the rows
//
func scan_pick(request *ScanRequest, queues []*Queue, rows []Row, sorted []int) int {
size := len(queues)
if !queues[sorted[0]].Peek(&rows[sorted[0]]) {
return NoPick
}
pos := 0
for i := 1; i < size; i++ {
if !queues[sorted[i]].Peek(&rows[sorted[i]]) {
return NoPick
}
// last value always sorted last
if rows[sorted[pos]].last && !rows[sorted[i]].last ||
(!rows[sorted[pos]].last && !rows[sorted[i]].last &&
compareKey(request, &rows[sorted[pos]], &rows[sorted[i]]) > 0) {
tmp := sorted[pos]
sorted[pos] = sorted[i]
sorted[i] = tmp
pos = i
} else {
break
}
}
for i := 0; i < size; i++ {
if !rows[sorted[i]].last {
return sorted[0]
}
}
return Done
}
func gather(request *ScanRequest, queues []*Queue, donech chan bool, notifych chan bool, killch chan bool,
errch chan error, cb EntryCallback) {
defer close(donech)
ensembleSize := len(queues)
sorted := make([]int, ensembleSize)
rows := make([]Row, ensembleSize)
for i := 0; i < ensembleSize; i++ {
rows[i].init(newAllocator(0, queues[i].GetBytesBuf()))
}
defer func() {
for i := 0; i < ensembleSize; i++ {
rows[i].freeKeyBuf()
}
}()
// initial sort
isSorted := false
for !isSorted {
if len(errch) != 0 {
return
}
isSorted = scan_sort(request, queues, rows, sorted)
if !isSorted {
select {
case <-notifych:
continue
case <-killch:
return
}
}
}
for {
var id int
if len(errch) != 0 {
return
}
id = scan_pick(request, queues, rows, sorted)
if id == Done {
break
}
if id == NoPick {
select {
case <-notifych:
continue
case <-killch:
return
}
}
if queues[id].Dequeue(&rows[id]) {
if err := cb(rows[id].key); err != nil {
errch <- err
// unblock all producers
for _, queue := range queues {
queue.Close()
}
return
}
}
}
}
func forward(request *ScanRequest, queues []*Queue, donech chan bool, notifych chan bool, killch chan bool,
errch chan error, cb EntryCallback) {
defer close(donech)
ensembleSize := len(queues)
rows := make([]Row, ensembleSize)
for i := 0; i < ensembleSize; i++ {
rows[i].init(newAllocator(0, queues[i].GetBytesBuf()))
}
defer func() {
for i := 0; i < ensembleSize; i++ {
rows[i].freeKeyBuf()
}
}()
for {
if len(errch) != 0 {
return
}
count := 0
found := false
for i := 0; i < ensembleSize; i++ {
if queues[i].Peek(&rows[i]) {
if rows[i].last {
count++
continue
}
found = true
if queues[i].Dequeue(&rows[i]) {
if err := cb(rows[i].key); err != nil {
errch <- err
// unblock all producers
for _, queue := range queues {
queue.Close()
}
return
}
}
}
}
if count == ensembleSize {
return
}
if !found {
select {
case <-notifych:
continue
case <-killch:
return
}
}
}
}
func compareKey(request *ScanRequest, k1 *Row, k2 *Row) int {
if request.isPrimary {
return comparePrimaryKey(k1, k2)
}
return compareSecKey(k1, k2)
}
func comparePrimaryKey(k1 *Row, k2 *Row) int {
return bytes.Compare(k1.key, k2.key)
}
func compareSecKey(k1 *Row, k2 *Row) int {
return bytes.Compare(k1.key[:k1.len], k2.key[:k2.len])
}
func queueSize(partition int, sorted bool, cfg common.Config) (int, int) {
size := cfg["scan.queue_size"].Int()
limit := cfg["scan.notify_count"].Int()
numCpu := runtime.GOMAXPROCS(0)
if numCpu >= partition || !sorted {
return size, limit
}
ratio := partition / numCpu
return ratio * size, limit
}