/
flusher.go
516 lines (429 loc) · 16.9 KB
/
flusher.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
// 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 (
"fmt"
"github.com/couchbase/indexing/secondary/common"
"github.com/couchbase/indexing/secondary/logging"
"sync"
)
//Flusher is the only component which does read/dequeue from a MutationQueue.
//As MutationQueue has a restriction of only single reader and writer per vbucket,
//flusher should not be invoked concurrently for a single MutationQueue.
type Flusher interface {
//PersistUptoTS will flush the mutation queue upto Timestamp provided.
//Can be stopped anytime by closing StopChannel.
//Sends SUCCESS on the MsgChannel when its done flushing till TS.
//Any error condition is reported back on the MsgChannel.
//Caller can wait on MsgChannel after closing StopChannel
//to get notified about shutdown completion.
PersistUptoTS(q MutationQueue, streamId common.StreamId, bucket string, indexInstMap common.IndexInstMap,
indexPartnMap IndexPartnMap, ts Timestamp, changeVec []bool, stopch StopChannel) MsgChannel
//DrainUptoTS will flush the mutation queue upto Timestamp
//provided without actually persisting it.
//Can be stopped anytime by closing the StopChannel.
//Sends SUCCESS on the MsgChannel when its done flushing till timestamp.
//Any error condition is reported back on the MsgChannel.
//Caller can wait on MsgChannel after closing StopChannel
//to get notified about shutdown completion.
DrainUptoTS(q MutationQueue, streamId common.StreamId, bucket string, ts Timestamp,
changeVec []bool, stopch StopChannel) MsgChannel
//Persist will keep flushing the mutation queue till caller closes
//the stop channel.Can be stopped anytime by closing the StopChannel.
//Any error condition is reported back on the MsgChannel.
//Caller can wait on MsgChannel after closing StopChannel to get
//notified about shutdown completion.
Persist(q MutationQueue, streamId common.StreamId, bucket string, indexInstMap common.IndexInstMap,
indexPartnMap IndexPartnMap, stopch StopChannel) MsgChannel
//Drain will keep flushing the mutation queue till caller closes
//the stop channel without actually persisting the mutations.
//Can be stopped anytime by closing the StopChannel.
//Any error condition is reported back on the MsgChannel.
//Caller can wait on MsgChannel after closing StopChannel to get
//notified about shutdown completion.
Drain(q MutationQueue, streamId common.StreamId, bucket string, stopch StopChannel) MsgChannel
//IsTimestampGreaterThanQueueLWT checks if each Vbucket in the Queue
//has mutation with Seqno lower than the corresponding Seqno present
//in the specified timestamp.
IsQueueLWTLowerThanTimestamp(q MutationQueue, ts Timestamp) bool
//GetQueueLWT returns the lowest seqno for each vbucket in the queue
GetQueueLWT(q MutationQueue) Timestamp
//GetQueueHWT returns the highest seqno for each vbucket in the queue
GetQueueHWT(q MutationQueue) Timestamp
}
type flusher struct {
indexInstMap common.IndexInstMap
indexPartnMap IndexPartnMap
config common.Config
stats *IndexerStats
}
//NewFlusher returns new instance of flusher
func NewFlusher(config common.Config, stats *IndexerStats) *flusher {
return &flusher{config: config, stats: stats}
}
//PersistUptoTS will flush the mutation queue upto the
//Timestamp provided. This function will be used when:
//1. Flushing Maintenance Queue
//2. Flushing Maintenance Catchup Queue
//3. Flushing Backfill Queue
//
//Can be stopped anytime by closing StopChannel.
//Sends SUCCESS on the MsgChannel when its done flushing till timestamp.
//Any error condition is reported back on the MsgChannel.
//Caller can wait on MsgChannel after closing StopChannel to get notified
//about shutdown completion.
func (f *flusher) PersistUptoTS(q MutationQueue, streamId common.StreamId,
bucket string, indexInstMap common.IndexInstMap, indexPartnMap IndexPartnMap,
ts Timestamp, changeVec []bool, stopch StopChannel) MsgChannel {
logging.Verbosef("Flusher::PersistUptoTS %v %v Timestamp: %v PartnMap %v",
streamId, bucket, ts, indexPartnMap)
f.indexInstMap = common.CopyIndexInstMap(indexInstMap)
f.indexPartnMap = CopyIndexPartnMap(indexPartnMap)
msgch := make(MsgChannel)
go f.flushQueue(q, streamId, bucket, ts, changeVec, true, stopch, msgch)
return msgch
}
//DrainUptoTS will flush the mutation queue upto the Timestamp
//provided without actually persisting it.
//Can be stopped anytime by closing the StopChannel.
//Sends SUCCESS on the MsgChannel when its done flushing till timestamp.
//Any error condition is reported back on the MsgChannel.
//Caller can wait on MsgChannel after closing StopChannel to get notified
//about shutdown completion.
func (f *flusher) DrainUptoTS(q MutationQueue, streamId common.StreamId,
bucket string, ts Timestamp, changeVec []bool, stopch StopChannel) MsgChannel {
logging.Verbosef("Flusher::DrainUptoTS %v %v Timestamp: %v",
streamId, bucket, ts)
msgch := make(MsgChannel)
go f.flushQueue(q, streamId, bucket, ts, changeVec, false, stopch, msgch)
return msgch
}
//Persist will keep flushing the mutation queue till caller closes
//the stop channel. This function will be used when:
//1. Flushing Backfill Catchup Queue
//
//Can be stopped anytime by closing the StopChannel.
//Any error condition is reported back on the MsgChannel.
//Caller can wait on MsgChannel after closing StopChannel to get notified
//about shutdown completion.
func (f *flusher) Persist(q MutationQueue, streamId common.StreamId,
bucket string, indexInstMap common.IndexInstMap, indexPartnMap IndexPartnMap,
stopch StopChannel) MsgChannel {
logging.Verbosef("Flusher::Persist %v %v", streamId, bucket)
f.indexInstMap = common.CopyIndexInstMap(indexInstMap)
f.indexPartnMap = CopyIndexPartnMap(indexPartnMap)
msgch := make(MsgChannel)
go f.flushQueue(q, streamId, bucket, nil, nil, true, stopch, msgch)
return msgch
}
//Drain will keep flushing the mutation queue till caller closes
//the stop channel without actually persisting the mutations
//Can be stopped anytime by closing the StopChannel.
//Any error condition is reported back on the MsgChannel.
//Caller can wait on MsgChannel after closing StopChannel to get notified
//about shutdown completion.
func (f *flusher) Drain(q MutationQueue, streamId common.StreamId,
bucket string, stopch StopChannel) MsgChannel {
logging.Verbosef("Flusher::Drain %v %v", streamId, bucket)
msgch := make(MsgChannel)
go f.flushQueue(q, streamId, bucket, nil, nil, false, stopch, msgch)
return msgch
}
//flushQueue starts and waits for actual workers to flush the mutation queue.
//This function will close the done channel once all workers have finished.
//It also listens on the stop channel and will stop all workers if stop signal is received.
func (f *flusher) flushQueue(q MutationQueue, streamId common.StreamId, bucket string,
ts Timestamp, changeVec []bool, persist bool, stopch StopChannel, msgch MsgChannel) {
var wg sync.WaitGroup
var i uint16
numVbuckets := q.GetNumVbuckets()
//create stop channel for each worker, to propagate the stop signal
var workerStopChannels []StopChannel
//create msg channel for workers to provide messages
workerMsgCh := make(MsgChannel, numVbuckets)
for i = 0; i < numVbuckets; i++ {
if ts == nil {
wg.Add(1)
stopch := make(StopChannel)
workerStopChannels = append(workerStopChannels, stopch)
go f.flushSingleVbucket(q, streamId, bucket, Vbucket(i),
persist, stopch, workerMsgCh, &wg)
} else {
if changeVec[i] {
wg.Add(1)
stopch := make(StopChannel)
workerStopChannels = append(workerStopChannels, stopch)
go f.flushSingleVbucketUptoSeqno(q, streamId, bucket, Vbucket(i),
ts[i], persist, stopch, workerMsgCh, &wg)
}
}
}
allWorkersDoneCh := make(DoneChannel)
//wait for all workers to finish
go func() {
logging.Tracef("Flusher::flushQueue Waiting for workers to finish Stream %v", streamId)
wg.Wait()
//send signal on channel to indicate all workers have finished
logging.Tracef("Flusher::flushQueue All workers finished for Stream %v", streamId)
close(allWorkersDoneCh)
}()
workerAborted := false
//wait for upstream to signal stop or for all workers to signal done
//or workers to send any message
select {
case <-stopch:
logging.Debugf("Flusher::flushQueue Stopping All Workers")
//stop all workers
for _, ch := range workerStopChannels {
close(ch)
}
//wait for all workers to stop
<-allWorkersDoneCh
logging.Debugf("Flusher::flushQueue Stopped All Workers")
//wait for notification of all workers finishing
case <-allWorkersDoneCh:
//handle any message from workers
case <-workerMsgCh:
workerAborted = true
<-allWorkersDoneCh
}
if workerAborted {
msgch <- &MsgError{}
} else {
msgch <- &MsgSuccess{}
}
}
//flushSingleVbucket is the actual implementation which flushes the given queue
//for a single vbucket till stop signal
func (f *flusher) flushSingleVbucket(q MutationQueue, streamId common.StreamId,
bucket string, vbucket Vbucket, persist bool, stopch StopChannel,
workerMsgCh MsgChannel, wg *sync.WaitGroup) {
defer wg.Done()
logging.Tracef("Flusher::flushSingleVbucket Started worker to flush vbucket: "+
"%v for stream: %v", vbucket, streamId)
mutch, qstopch, err := q.Dequeue(vbucket)
if err != nil {
//TODO
}
ok := true
var mut *MutationKeys
bucketStats := f.stats.buckets[mut.meta.bucket]
//Process till supervisor asks to stop on the channel
for ok {
select {
case mut, ok = <-mutch:
if ok {
if !persist {
//No persistence is required. Just skip this mutation.
continue
}
f.flushSingleMutation(mut, streamId)
if bucketStats != nil {
bucketStats.mutationQueueSize.Add(-1)
}
}
case <-stopch:
qstopch <- true
return
}
}
}
//flushSingleVbucket is the actual implementation which flushes the given queue
//for a single vbucket till the given seqno or till the stop signal(whichever is earlier)
func (f *flusher) flushSingleVbucketUptoSeqno(q MutationQueue, streamId common.StreamId,
bucket string, vbucket Vbucket, seqno Seqno, persist bool, stopch StopChannel,
workerMsgCh MsgChannel, wg *sync.WaitGroup) {
defer wg.Done()
logging.LazyTrace(func() string {
return fmt.Sprintf("Flusher::flushSingleVbucketUptoSeqno Started worker to flush vbucket: "+
"%v till Seqno: %v for Stream: %v", vbucket, seqno, streamId)
})
mutch, errch, err := q.DequeueUptoSeqno(vbucket, seqno)
if err != nil {
//TODO
}
ok := true
var mut *MutationKeys
bucketStats := f.stats.buckets[bucket]
//Read till the channel is closed by queue indicating it has sent all the
//sequence numbers requested
for ok {
select {
case mut, ok = <-mutch:
if ok {
if !persist {
//No persistence is required. Just skip this mutation.
continue
}
f.flushSingleMutation(mut, streamId)
mut.Free()
if bucketStats != nil {
bucketStats.mutationQueueSize.Add(-1)
}
}
case <-errch:
workerMsgCh <- &MsgError{}
return
}
}
}
//flushSingleMutation talks to persistence layer to store the mutations
//Any error from persistence layer is sent back on workerMsgCh
func (f *flusher) flushSingleMutation(mut *MutationKeys, streamId common.StreamId) {
switch streamId {
case common.MAINT_STREAM, common.INIT_STREAM, common.CATCHUP_STREAM:
f.flush(mut, streamId)
default:
logging.Errorf("Flusher::flushSingleMutation Invalid StreamId: %v", streamId)
}
}
func (f *flusher) flush(mutk *MutationKeys, streamId common.StreamId) {
logging.LazyTrace(func() string {
return fmt.Sprintf("Flusher::flush Flushing Stream %v Mutations %v", streamId, logging.TagUD(mutk))
})
var processedUpserts []common.IndexInstId
for _, mut := range mutk.mut {
var idxInst common.IndexInst
var ok bool
if idxInst, ok = f.indexInstMap[mut.uuid]; !ok {
logging.LazyTrace(func() string {
return fmt.Sprintf("Flusher::flush Unknown Index Instance Id %v. "+
"Skipped Mutation Key %v", mut.uuid, logging.TagUD(mut.key))
})
continue
}
//Skip this mutation if the index doesn't belong to the stream being flushed
if streamId != idxInst.Stream && streamId != common.CATCHUP_STREAM {
logging.LazyTrace(func() string {
return fmt.Sprintf("Flusher::flush Found Mutation For IndexId: %v Stream: %v In "+
"Stream: %v. Skipped Mutation Key %v", idxInst.InstId, idxInst.Stream,
streamId, logging.TagUD(mut.key))
})
continue
}
//Skip mutations for indexes in DELETED state. This may happen if complete
//couldn't happen when processing drop index.
if idxInst.State == common.INDEX_STATE_DELETED {
logging.LazyTrace(func() string {
return fmt.Sprintf("Flusher::flush Found Mutation For IndexId: %v In "+
"DELETED State. Skipped Mutation Key %v", idxInst.InstId, logging.TagUD(mut.key))
})
continue
}
switch mut.command {
case common.Upsert:
processedUpserts = append(processedUpserts, mut.uuid)
f.processUpsert(mut, mutk.docid, mutk.meta)
case common.Deletion:
f.processDelete(mut, mutk.docid, mutk.meta)
case common.UpsertDeletion:
//skip UpsertDeletion if index has immutable partition
if idxInst.Defn.Immutable {
continue
}
var skipUpsertDeletion bool
//if Upsert has been processed for this IndexInstId,
//skip processing UpsertDeletion
for _, id := range processedUpserts {
if id == mut.uuid {
skipUpsertDeletion = true
}
}
if skipUpsertDeletion {
continue
} else {
f.processDelete(mut, mutk.docid, mutk.meta)
}
default:
logging.Errorf("Flusher::flush Unknown mutation type received. Skipped %v",
logging.TagUD(mut.key))
}
}
}
func (f *flusher) processUpsert(mut *Mutation, docid []byte, meta *MutationMeta) {
idxInst, _ := f.indexInstMap[mut.uuid]
partnId := idxInst.Pc.GetPartitionIdByPartitionKey(mut.partnkey)
var partnInstMap PartitionInstMap
var ok bool
if partnInstMap, ok = f.indexPartnMap[mut.uuid]; !ok {
logging.Errorf("Flusher::processUpsert Missing Partition Instance Map"+
"for IndexInstId: %v. Skipped Mutation Key: %v", mut.uuid, logging.TagUD(mut.key))
return
}
if partnInst, ok := partnInstMap[partnId]; ok {
slice := partnInst.Sc.GetSliceByIndexKey(common.IndexKey(mut.key))
if err := slice.Insert(mut.key, docid, meta); err != nil {
logging.Errorf("Flusher::processUpsert Error indexing Key: %s "+
"docid: %s in Slice: %v. Error: %v. Skipped.",
logging.TagUD(mut.key), logging.TagStrUD(docid), slice.Id(), err)
if err2 := slice.Delete(docid, meta); err2 != nil {
logging.Errorf("Flusher::processUpsert Error removing entry due to error %v Key: %s "+
"docid: %s in Slice: %v. Error: %v", err, logging.TagUD(mut.key), logging.TagStrUD(docid), slice.Id(), err2)
}
}
} else {
logging.Debugf("Flusher::processUpsert Partition Instance not found "+
"for Id: %v Skipped Mutation Key: %v", partnId, logging.TagUD(mut.key))
}
}
func (f *flusher) processDelete(mut *Mutation, docid []byte, meta *MutationMeta) {
var partnInstMap PartitionInstMap
var ok bool
if partnInstMap, ok = f.indexPartnMap[mut.uuid]; !ok {
logging.Errorf("Flusher:processDelete Missing Partition Instance Map"+
"for IndexInstId: %v. Skipped Mutation Key: %v", mut.uuid, logging.TagUD(mut.key))
return
}
for _, partnInst := range partnInstMap {
slice := partnInst.Sc.GetSliceByIndexKey(common.IndexKey(mut.key))
if err := slice.Delete(docid, meta); err != nil {
logging.Errorf("Flusher::processDelete Error Deleting DocId: %v "+
"from Slice: %v", logging.TagStrUD(docid), slice.Id())
}
}
}
//IsTimestampGreaterThanQueueLWT checks if each Vbucket in the Queue has
//mutation with Seqno lower than the corresponding Seqno present in the
//specified timestamp.
func (f *flusher) IsQueueLWTLowerThanTimestamp(q MutationQueue, ts Timestamp) bool {
//each individual vbucket seqno should be lower than or equal to timestamp seqno
for i, t := range ts {
mut := q.PeekHead(Vbucket(i))
if mut.meta.seqno > t {
return false
}
}
return true
}
//GetQueueLWT returns the lowest seqno for each vbucket in the queue
func (f *flusher) GetQueueLWT(q MutationQueue) Timestamp {
ts := NewTimestamp(int(q.GetNumVbuckets()))
var i uint16
for i = 0; i < q.GetNumVbuckets(); i++ {
if mut := q.PeekHead(Vbucket(i)); mut != nil {
ts[i] = mut.meta.seqno
} else {
ts[i] = 0
}
}
return ts
}
//GetQueueHWT returns the highest seqno for each vbucket in the queue
func (f *flusher) GetQueueHWT(q MutationQueue) Timestamp {
ts := NewTimestamp(int(q.GetNumVbuckets()))
var i uint16
for i = 0; i < q.GetNumVbuckets(); i++ {
if mut := q.PeekTail(Vbucket(i)); mut != nil {
ts[i] = mut.meta.seqno
} else {
ts[i] = 0
}
}
return ts
}