forked from membase/ep-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtapconnection.cc
More file actions
2082 lines (1876 loc) · 75.6 KB
/
tapconnection.cc
File metadata and controls
2082 lines (1876 loc) · 75.6 KB
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
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2010 NorthScale, 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.
*/
#include "config.h"
#include "ep_engine.h"
#include "dispatcher.hh"
#define STATWRITER_NAMESPACE tap
#include "statwriter.hh"
#undef STATWRITER_NAMESPACE
const uint8_t TapEngineSpecific::nru(1);
const short int TapEngineSpecific::sizeRevSeqno(8);
const short int TapEngineSpecific::sizeExtra(1);
const short int TapEngineSpecific::sizeTotal(9);
void TapEngineSpecific::readSpecificData(tap_event_t ev, void *engine_specific,
uint16_t nengine, uint64_t *seqnum,
uint8_t *extra)
{
uint8_t ex;
if (ev == TAP_CHECKPOINT_START || ev == TAP_CHECKPOINT_END || ev == TAP_DELETION ||
ev == TAP_MUTATION)
{
assert(nengine >= sizeRevSeqno);
memcpy(seqnum, engine_specific, sizeRevSeqno);
*seqnum = ntohll(*seqnum);
if (ev == TAP_MUTATION && nengine == sizeTotal) {
uint8_t *dptr = (uint8_t *)engine_specific + sizeRevSeqno;
memcpy(&ex, (void *)dptr, sizeExtra);
*extra = ex;
}
}
}
uint16_t TapEngineSpecific::packSpecificData(tap_event_t ev, TapProducer *tp,
uint64_t seqnum, bool referenced)
{
uint64_t seqno;
uint16_t nengine = 0;
if (ev == TAP_MUTATION || ev == TAP_DELETION || ev == TAP_CHECKPOINT_START) {
seqno = htonll(seqnum);
memcpy(tp->specificData, (void *)&seqno, sizeRevSeqno);
if (ev == TAP_MUTATION && referenced) {
// transfer item nru reference bit in item extra byte
uint8_t itemNru = TapEngineSpecific::nru;
memcpy(&tp->specificData[sizeRevSeqno], (void*)&itemNru, sizeExtra);
nengine = sizeTotal;
} else {
nengine = sizeRevSeqno;
}
}
return nengine;
}
Atomic<uint64_t> TapConnection::tapCounter(1);
TapConnection::TapConnection(EventuallyPersistentEngine &theEngine,
const void *c, const std::string &n) :
engine(theEngine),
cookie(c),
name(n),
created(ep_current_time()),
connToken(gethrtime()),
expiryTime((rel_time_t)-1),
connected(true),
disconnect(false),
supportAck(false),
supportCheckpointSync(false),
reserved(false),
stats(engine.getEpStats()) { }
TapConnection::~TapConnection() {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"%s Remove tap connection instance.\n", logHeader());
}
template <typename T>
void TapConnection::addStat(const char *nm, T val, ADD_STAT add_stat, const void *c) {
std::stringstream tap;
tap << name << ":" << nm;
std::stringstream value;
value << val;
std::string n = tap.str();
add_casted_stat(n.data(), value.str().data(), add_stat, c);
}
const void *TapConnection::getCookie() const {
return cookie;
}
void TapConnection::releaseReference(bool force)
{
if (force || reserved) {
engine.releaseCookie(cookie);
setReserved(false);
}
}
const char *TapConnection::logHeader() {
return logString.c_str();
}
const char *TapConnection::opaqueCmdToString(uint32_t opaque_code) {
switch(opaque_code) {
case TAP_OPAQUE_ENABLE_AUTO_NACK:
return "opaque_enable_auto_nack";
case TAP_OPAQUE_INITIAL_VBUCKET_STREAM:
return "initial_vbucket_stream";
case TAP_OPAQUE_ENABLE_CHECKPOINT_SYNC:
return "enable_checkpoint_sync";
case TAP_OPAQUE_OPEN_CHECKPOINT:
return "open_checkpoint";
case TAP_OPAQUE_CLOSE_TAP_STREAM:
return "close_tap_stream";
case TAP_OPAQUE_CLOSE_BACKFILL:
return "close_backfill";
case TAP_OPAQUE_COMPLETE_VB_FILTER_CHANGE:
return "complete_vb_filter_change";
}
return "unknown";
}
class TapConfigChangeListener : public ValueChangedListener {
public:
TapConfigChangeListener(TapConfig &c) : config(c) {
// EMPTY
}
virtual void sizeValueChanged(const std::string &key, size_t value) {
if (key.compare("tap_ack_grace_period") == 0) {
config.setAckGracePeriod(value);
} else if (key.compare("tap_ack_initial_sequence_number") == 0) {
config.setAckInitialSequenceNumber(value);
} else if (key.compare("tap_ack_interval") == 0) {
config.setAckInterval(value);
} else if (key.compare("tap_ack_window_size") == 0) {
config.setAckWindowSize(value);
} else if (key.compare("tap_bg_max_pending") == 0) {
config.setBgMaxPending(value);
} else if (key.compare("tap_backlog_limit") == 0) {
config.setBackfillBacklogLimit(value);
}
}
virtual void floatValueChanged(const std::string &key, float value) {
if (key.compare("tap_backoff_period") == 0) {
config.setBackoffSleepTime(value);
} else if (key.compare("tap_requeue_sleep_time") == 0) {
config.setRequeueSleepTime(value);
} else if (key.compare("tap_backfill_resident") == 0) {
config.setBackfillResidentThreshold(value);
}
}
private:
TapConfig &config;
};
TapConfig::TapConfig(EventuallyPersistentEngine &e)
: engine(e)
{
Configuration &config = engine.getConfiguration();
ackWindowSize = config.getTapAckWindowSize();
ackInterval = config.getTapAckInterval();
ackGracePeriod = config.getTapAckGracePeriod();
ackInitialSequenceNumber = config.getTapAckInitialSequenceNumber();
bgMaxPending = config.getTapBgMaxPending();
backoffSleepTime = config.getTapBackoffPeriod();
requeueSleepTime = config.getTapRequeueSleepTime();
backfillBacklogLimit = config.getTapBacklogLimit();
backfillResidentThreshold = config.getTapBackfillResident();
}
void TapConfig::addConfigChangeListener(EventuallyPersistentEngine &engine) {
Configuration &configuration = engine.getConfiguration();
configuration.addValueChangedListener("tap_ack_grace_period",
new TapConfigChangeListener(engine.getTapConfig()));
configuration.addValueChangedListener("tap_ack_initial_sequence_number",
new TapConfigChangeListener(engine.getTapConfig()));
configuration.addValueChangedListener("tap_ack_interval",
new TapConfigChangeListener(engine.getTapConfig()));
configuration.addValueChangedListener("tap_ack_window_size",
new TapConfigChangeListener(engine.getTapConfig()));
configuration.addValueChangedListener("tap_bg_max_pending",
new TapConfigChangeListener(engine.getTapConfig()));
configuration.addValueChangedListener("tap_backoff_period",
new TapConfigChangeListener(engine.getTapConfig()));
configuration.addValueChangedListener("tap_requeue_sleep_time",
new TapConfigChangeListener(engine.getTapConfig()));
configuration.addValueChangedListener("tap_backlog_limit",
new TapConfigChangeListener(engine.getTapConfig()));
configuration.addValueChangedListener("tap_backfill_resident",
new TapConfigChangeListener(engine.getTapConfig()));
}
TapProducer::TapProducer(EventuallyPersistentEngine &theEngine,
const void *c,
const std::string &n,
uint32_t f):
TapConnection(theEngine, c, n),
queue(NULL),
queueSize(0),
flags(f),
recordsFetched(0),
pendingFlush(false),
reconnects(0),
paused(false),
backfillAge(0),
dumpQueue(false),
doTakeOver(false),
takeOverCompletionPhase(false),
doRunBackfill(false),
backfillCompleted(true),
pendingBackfillCounter(0),
diskBackfillCounter(0),
totalBackfillBacklogs(0),
vbucketFilter(),
queueMemSize(0),
queueFill(0),
queueDrain(0),
seqno(theEngine.getTapConfig().getAckInitialSequenceNumber()),
seqnoReceived(theEngine.getTapConfig().getAckInitialSequenceNumber() - 1),
seqnoAckRequested(theEngine.getTapConfig().getAckInitialSequenceNumber() - 1),
notifySent(false),
suspended(false),
registeredTAPClient(false),
lastMsgTime(ep_current_time()),
isLastAckSucceed(false),
isSeqNumRotated(false),
numNoops(0),
tapFlagByteorderSupport(false),
specificData(NULL)
{
evaluateFlags();
queue = new std::list<queued_item>;
specificData = new uint8_t[TapEngineSpecific::sizeTotal];
if (supportAck) {
expiryTime = ep_current_time() + engine.getTapConfig().getAckGracePeriod();
}
if (cookie != NULL) {
setReserved(true);
}
setLogHeader("TAP (Producer) " + getName() + " -");
}
void TapProducer::evaluateFlags()
{
std::stringstream ss;
if (flags & TAP_CONNECT_FLAG_DUMP) {
dumpQueue = true;
ss << ",dump";
}
if (flags & TAP_CONNECT_SUPPORT_ACK) {
TapVBucketEvent hi(TAP_OPAQUE, 0, (vbucket_state_t)htonl(TAP_OPAQUE_ENABLE_AUTO_NACK));
addVBucketHighPriority(hi);
supportAck = true;
ss << ",ack";
}
if (flags & TAP_CONNECT_FLAG_BACKFILL) {
ss << ",backfill";
}
if (flags & TAP_CONNECT_FLAG_LIST_VBUCKETS) {
ss << ",vblist";
}
if (flags & TAP_CONNECT_FLAG_TAKEOVER_VBUCKETS) {
ss << ",takeover";
}
if (flags & TAP_CONNECT_CHECKPOINT) {
TapVBucketEvent event(TAP_OPAQUE, 0,
(vbucket_state_t)htonl(TAP_OPAQUE_ENABLE_CHECKPOINT_SYNC));
addVBucketHighPriority(event);
supportCheckpointSync = true;
ss << ",checkpoints";
}
if (ss.str().length() > 0) {
std::stringstream m;
m.setf(std::ios::hex);
m << flags << " (" << ss.str().substr(1) << ")";
flagsText.assign(m.str());
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s TAP connection option flags %s\n",
logHeader(), m.str().c_str());
}
}
void TapProducer::setBackfillAge(uint64_t age, bool reconnect) {
if (reconnect) {
if (!(flags & TAP_CONNECT_FLAG_BACKFILL)) {
age = backfillAge;
}
if (age == backfillAge) {
// we didn't change the critera...
return;
}
}
if (flags & TAP_CONNECT_FLAG_BACKFILL) {
backfillAge = age;
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s Backfill age set to %llu\n",
logHeader(), age);
}
}
void TapProducer::setVBucketFilter(const std::vector<uint16_t> &vbuckets,
bool notifyCompletion)
{
LockHolder lh(queueLock);
VBucketFilter diff;
// time to join the filters..
if (flags & TAP_CONNECT_FLAG_LIST_VBUCKETS) {
VBucketFilter filter(vbuckets);
diff = vbucketFilter.filter_diff(filter);
const std::set<uint16_t> &vset = diff.getVBSet();
const VBucketMap &vbMap = engine.getEpStore()->getVBuckets();
// Remove TAP cursors from the vbuckets that don't belong to the new vbucket filter.
for (std::set<uint16_t>::const_iterator it = vset.begin(); it != vset.end(); ++it) {
if (vbucketFilter(*it)) {
RCPtr<VBucket> vb = vbMap.getBucket(*it);
if (vb) {
vb->checkpointManager.removeTAPCursor(name);
}
backfillVBuckets.erase(*it);
backFillVBucketFilter.removeVBucket(*it);
}
}
std::stringstream ss;
ss << logHeader() << ": Changing the vbucket filter from "
<< vbucketFilter << " to "
<< filter << " (diff: " << diff << ")" << std::endl;
getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "%s\n",
ss.str().c_str());
vbucketFilter = filter;
std::stringstream f;
f << vbucketFilter;
filterText.assign(f.str());
}
// Note that we do re-evaluete all entries when we suck them out of the
// queue to send them..
if (flags & TAP_CONNECT_FLAG_TAKEOVER_VBUCKETS) {
std::list<TapVBucketEvent> nonVBucketOpaqueMessages;
std::list<TapVBucketEvent> vBucketOpaqueMessages;
// Clear vbucket state change messages with a higher priority.
while (!vBucketHighPriority.empty()) {
TapVBucketEvent msg = vBucketHighPriority.front();
vBucketHighPriority.pop();
if (msg.event == TAP_OPAQUE) {
uint32_t opaqueCode = (uint32_t) msg.state;
if (opaqueCode == htonl(TAP_OPAQUE_ENABLE_AUTO_NACK) ||
opaqueCode == htonl(TAP_OPAQUE_ENABLE_CHECKPOINT_SYNC)) {
nonVBucketOpaqueMessages.push_back(msg);
} else {
vBucketOpaqueMessages.push_back(msg);
}
}
}
// Add non-vbucket opaque messages back to the high priority queue.
std::list<TapVBucketEvent>::iterator iter = nonVBucketOpaqueMessages.begin();
while (iter != nonVBucketOpaqueMessages.end()) {
addVBucketHighPriority_UNLOCKED(*iter);
++iter;
}
// Clear vbucket state changes messages with a lower priority.
while (!vBucketLowPriority.empty()) {
vBucketLowPriority.pop();
}
// Add new vbucket state change messages with a higher or lower priority.
const std::set<uint16_t> &vset = vbucketFilter.getVBSet();
for (std::set<uint16_t>::const_iterator it = vset.begin();
it != vset.end(); ++it) {
TapVBucketEvent hi(TAP_VBUCKET_SET, *it, vbucket_state_pending);
TapVBucketEvent lo(TAP_VBUCKET_SET, *it, vbucket_state_active);
addVBucketHighPriority_UNLOCKED(hi);
addVBucketLowPriority_UNLOCKED(lo);
}
// Add vbucket opaque messages back to the high priority queue.
iter = vBucketOpaqueMessages.begin();
while (iter != vBucketOpaqueMessages.end()) {
addVBucketHighPriority_UNLOCKED(*iter);
++iter;
}
doTakeOver = true;
}
if (notifyCompletion) {
TapVBucketEvent notification(TAP_OPAQUE, 0,
(vbucket_state_t)htonl(TAP_OPAQUE_COMPLETE_VB_FILTER_CHANGE));
addVBucketHighPriority_UNLOCKED(notification);
}
}
void TapProducer::registerTAPCursor(const std::map<uint16_t, uint64_t> &lastCheckpointIds) {
LockHolder lh(queueLock);
uint64_t current_time = (uint64_t)ep_real_time();
std::vector<uint16_t> backfill_vbuckets;
const VBucketMap &vbuckets = engine.getEpStore()->getVBuckets();
size_t numOfVBuckets = vbuckets.getSize();
for (size_t i = 0; i < numOfVBuckets; ++i) {
assert(i <= std::numeric_limits<uint16_t>::max());
uint16_t vbid = static_cast<uint16_t>(i);
if (vbucketFilter(vbid)) {
RCPtr<VBucket> vb = vbuckets.getBucket(vbid);
if (!vb) {
tapCheckpointState.erase(vbid);
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s VBucket %d not found for TAP cursor. Skip it...\n",
logHeader(), vbid);
continue;
}
uint64_t chk_id_to_start = 0;
std::map<uint16_t, uint64_t>::const_iterator it = lastCheckpointIds.find(vbid);
if (it != lastCheckpointIds.end()) {
// Now, we assume that the checkpoint Id for a given vbucket is monotonically
// increased.
chk_id_to_start = it->second + 1;
} else {
// If a TAP client doesn't specify the last closed checkpoint Id for a given vbucket,
// check if the checkpoint manager currently has the cursor for that TAP client.
uint64_t cid = vb->checkpointManager.getCheckpointIdForTAPCursor(name);
chk_id_to_start = cid > 0 ? cid : 1;
}
std::map<uint16_t, TapCheckpointState>::iterator cit = tapCheckpointState.find(vbid);
if (cit != tapCheckpointState.end()) {
cit->second.currentCheckpointId = chk_id_to_start;
} else {
TapCheckpointState st(vbid, chk_id_to_start, checkpoint_start);
tapCheckpointState[vbid] = st;
}
// If backfill is currently running for this vbucket, skip the cursor registration.
if (backfillVBuckets.find(vbid) != backfillVBuckets.end()) {
cit = tapCheckpointState.find(vbid);
assert(cit != tapCheckpointState.end());
cit->second.currentCheckpointId = 0;
cit->second.state = backfill;
continue;
}
// As TAP dump option simply requires the snapshot of each vbucket, simply schedule
// backfill and skip the checkpoint cursor registration.
if (dumpQueue) {
if (vb->getState() == vbucket_state_active && vb->ht.getNumItems() > 0) {
backfill_vbuckets.push_back(vbid);
}
continue;
}
// Check if this TAP producer completed the replication before shutdown or crash.
bool prev_session_completed =
engine.getTapConnMap().prevSessionReplicaCompleted(name);
// Check if the unified queue contains the checkpoint to start with.
bool chk_exists = vb->checkpointManager.registerTAPCursor(name,
chk_id_to_start,
closedCheckpointOnly,
registeredTAPClient);
if(!prev_session_completed || !chk_exists) {
uint64_t chk_id;
tap_checkpoint_state cstate;
if (backfillAge < current_time) {
chk_id = 0;
cstate = backfill;
if (vb->checkpointManager.getOpenCheckpointId() > 0) {
// If the current open checkpoint is 0, it means that this vbucket is still
// receiving backfill items from another node. Once the backfill is done,
// we will schedule the backfill for this tap connection separately.
backfill_vbuckets.push_back(vbid);
}
} else { // Backfill age is in the future, simply start from the first checkpoint.
chk_id = vb->checkpointManager.getCheckpointIdForTAPCursor(name);
cstate = checkpoint_start;
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"%s Backfill age is greater than current time."
" Full backfill is not required for vbucket %d\n",
logHeader(), vbid);
}
cit = tapCheckpointState.find(vbid);
assert(cit != tapCheckpointState.end());
cit->second.currentCheckpointId = chk_id;
cit->second.state = cstate;
} else {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"%s The checkpoint to start with is still in memory. "
"Full backfill is not required for vbucket %d\n",
logHeader(), vbid);
}
} else { // The vbucket doesn't belong to this tap connection anymore.
tapCheckpointState.erase(vbid);
}
}
if (backfill_vbuckets.size() > 0) {
if (backfillAge < current_time) {
scheduleBackfill_UNLOCKED(backfill_vbuckets);
}
}
}
bool TapProducer::windowIsFull() {
if (!supportAck) {
return false;
}
const TapConfig &config = engine.getTapConfig();
uint32_t limit = config.getAckWindowSize() * config.getAckInterval();
if (seqno >= seqnoReceived) {
if ((seqno - seqnoReceived) <= limit) {
return false;
}
} else {
uint32_t n = static_cast<uint32_t>(-1) - seqnoReceived + seqno;
if (n <= limit) {
return false;
}
}
return true;
}
bool TapProducer::requestAck(tap_event_t event, uint16_t vbucket) {
LockHolder lh(queueLock);
if (!supportAck) {
// If backfill was scheduled before, check if the backfill is completed or not.
checkBackfillCompletion_UNLOCKED();
return false;
}
bool explicitEvent = false;
if (supportCheckpointSync && (event == TAP_MUTATION || event == TAP_DELETION)) {
std::map<uint16_t, TapCheckpointState>::iterator map_it =
tapCheckpointState.find(vbucket);
if (map_it != tapCheckpointState.end()) {
map_it->second.lastSeqNum = seqno;
if (map_it->second.lastItem || map_it->second.state == checkpoint_end) {
// Always ack for the last item or any items that were NAcked after the cursor
// reaches to the checkpoint end.
explicitEvent = true;
}
}
}
++seqno;
if (seqno == 0) {
isSeqNumRotated = true;
seqno = 1;
}
if (event == TAP_VBUCKET_SET ||
event == TAP_OPAQUE ||
event == TAP_CHECKPOINT_START ||
event == TAP_CHECKPOINT_END) {
explicitEvent = true;
}
const TapConfig &config = engine.getTapConfig();
uint32_t ackInterval = config.getAckInterval();
return explicitEvent ||
(seqno - 1) % ackInterval == 0 || // ack at a regular interval
(!backfillCompleted && getBackfillQueueSize_UNLOCKED() == 0) ||
emptyQueue_UNLOCKED(); // but if we're almost up to date, ack more often
}
void TapProducer::clearQueues_UNLOCKED() {
size_t mem_overhead = 0;
// Clear fg-fetched items.
queue->clear();
mem_overhead += (queueSize * sizeof(queued_item));
queueSize = 0;
queueMemSize = 0;
// Clear bg-fetched items.
while (!backfilledItems.empty()) {
Item *i(backfilledItems.front());
assert(i);
delete i;
backfilledItems.pop();
}
mem_overhead += (bgResultSize * sizeof(Item *));
bgResultSize = 0;
// Reset bg result size in a checkpoint state.
std::map<uint16_t, TapCheckpointState>::iterator it = tapCheckpointState.begin();
for (; it != tapCheckpointState.end(); ++it) {
it->second.bgResultSize = 0;
}
// Clear the checkpoint message queue as well
while (!checkpointMsgs.empty()) {
checkpointMsgs.pop();
}
// Clear the vbucket state message queues
while (!vBucketHighPriority.empty()) {
vBucketHighPriority.pop();
}
while (!vBucketLowPriority.empty()) {
vBucketLowPriority.pop();
}
// Clear the tap logs
mem_overhead += (tapLog.size() * sizeof(TapLogElement));
tapLog.clear();
stats.memOverhead.decr(mem_overhead);
assert(stats.memOverhead.get() < GIGANTOR);
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s Clear the tap queues by force\n",
logHeader());
}
void TapProducer::rollback() {
LockHolder lh(queueLock);
if (registeredTAPClient && closedCheckpointOnly && backfillCompleted) {
// If the connection is for a registered TAP client that is only interested in closed
// checkpoints, we don't need to resend unACKed items to the client because its replication
// cursor is reset to the beginning of the checkpoint to which the cursor currently belongs.
clearQueues_UNLOCKED();
seqno = engine.getTapConfig().getAckInitialSequenceNumber();
seqnoReceived = seqno -1;
seqnoAckRequested = seqno - 1;
checkpointMsgCounter = 0;
return;
}
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s Connection is re-established. Rollback unacked messages...",
logHeader());
size_t checkpoint_msg_sent = 0;
size_t tapLogSize = 0;
size_t opaque_msg_sent = 0;
std::list<TapLogElement>::iterator i = tapLog.begin();
while (i != tapLog.end()) {
switch (i->event) {
case TAP_VBUCKET_SET:
{
TapVBucketEvent e(i->event, i->vbucket, i->state);
if (i->state == vbucket_state_pending) {
addVBucketHighPriority_UNLOCKED(e);
} else {
addVBucketLowPriority_UNLOCKED(e);
}
}
break;
case TAP_CHECKPOINT_START:
case TAP_CHECKPOINT_END:
++checkpoint_msg_sent;
addCheckpointMessage_UNLOCKED(i->item);
break;
case TAP_FLUSH:
addEvent_UNLOCKED(i->item);
break;
case TAP_DELETION:
case TAP_MUTATION:
{
if (supportCheckpointSync) {
std::map<uint16_t, TapCheckpointState>::iterator map_it =
tapCheckpointState.find(i->vbucket);
if (map_it != tapCheckpointState.end()) {
map_it->second.lastSeqNum = std::numeric_limits<uint32_t>::max();
} else {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s Checkpoint State for VBucket %d Not Found",
logHeader(), i->vbucket);
}
}
addEvent_UNLOCKED(i->item);
}
break;
case TAP_OPAQUE:
{
uint32_t val = ntohl((uint32_t)i->state);
switch (val) {
case TAP_OPAQUE_ENABLE_AUTO_NACK:
case TAP_OPAQUE_ENABLE_CHECKPOINT_SYNC:
case TAP_OPAQUE_INITIAL_VBUCKET_STREAM:
case TAP_OPAQUE_CLOSE_BACKFILL:
case TAP_OPAQUE_OPEN_CHECKPOINT:
case TAP_OPAQUE_COMPLETE_VB_FILTER_CHANGE:
{
++opaque_msg_sent;
TapVBucketEvent e(i->event, i->vbucket, i->state);
addVBucketHighPriority_UNLOCKED(e);
}
break;
default:
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s Internal error in rollback()."
" Tap opaque value %d not implemented",
logHeader(), val);
abort();
}
}
break;
default:
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s Internal error in rollback()."
" Tap opcode value %d not implemented",
logHeader(), i->event);
abort();
}
tapLog.erase(i);
i = tapLog.begin();
++tapLogSize;
}
stats.memOverhead.decr(tapLogSize * sizeof(TapLogElement));
assert(stats.memOverhead.get() < GIGANTOR);
seqnoReceived = seqno - 1;
seqnoAckRequested = seqno - 1;
checkpointMsgCounter -= checkpoint_msg_sent;
opaqueMsgCounter -= opaque_msg_sent;
}
/**
* Dispatcher task to wake a tap connection.
*/
class TapResumeCallback : public DispatcherCallback {
public:
TapResumeCallback(EventuallyPersistentEngine &e, TapProducer &c)
: engine(e), connection(c) {
std::stringstream ss;
ss << "Resuming suspended tap connection: " << connection.getName();
descr = ss.str();
}
bool callback(Dispatcher &, TaskId) {
connection.setSuspended(false);
// The notify io thread will pick up this connection and resume it
// Since we was suspended I guess we can wait a little bit
// longer ;)
return false;
}
std::string description() {
return descr;
}
private:
EventuallyPersistentEngine &engine;
TapProducer &connection;
std::string descr;
};
bool TapProducer::isSuspended() const {
return suspended;
}
void TapProducer::setSuspended_UNLOCKED(bool value)
{
if (value) {
const TapConfig &config = engine.getTapConfig();
if (config.getBackoffSleepTime() > 0 && !suspended) {
Dispatcher *d = engine.getEpStore()->getNonIODispatcher();
d->schedule(shared_ptr<DispatcherCallback>
(new TapResumeCallback(engine, *this)),
NULL, Priority::TapResumePriority, config.getBackoffSleepTime(),
false);
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s Suspend for %.2f secs\n", logHeader(),
config.getBackoffSleepTime());
} else {
// backoff disabled, or already in a suspended state
return;
}
} else {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"%s Unlocked from the suspended state\n", logHeader());
}
suspended = value;
}
void TapProducer::setSuspended(bool value) {
LockHolder lh(queueLock);
setSuspended_UNLOCKED(value);
}
void TapProducer::reschedule_UNLOCKED(const std::list<TapLogElement>::iterator &iter)
{
switch (iter->event) {
case TAP_VBUCKET_SET:
{
TapVBucketEvent e(iter->event, iter->vbucket, iter->state);
if (iter->state == vbucket_state_pending) {
addVBucketHighPriority_UNLOCKED(e);
} else {
addVBucketLowPriority_UNLOCKED(e);
}
}
break;
case TAP_CHECKPOINT_START:
case TAP_CHECKPOINT_END:
--checkpointMsgCounter;
addCheckpointMessage_UNLOCKED(iter->item);
break;
case TAP_FLUSH:
addEvent_UNLOCKED(iter->item);
break;
case TAP_DELETION:
case TAP_MUTATION:
{
if (supportCheckpointSync) {
std::map<uint16_t, TapCheckpointState>::iterator map_it =
tapCheckpointState.find(iter->vbucket);
if (map_it != tapCheckpointState.end()) {
map_it->second.lastSeqNum = std::numeric_limits<uint32_t>::max();
}
}
addEvent_UNLOCKED(iter->item);
if (!isBackfillCompleted_UNLOCKED()) {
++totalBackfillBacklogs;
}
}
break;
case TAP_OPAQUE:
{
--opaqueMsgCounter;
TapVBucketEvent ev(iter->event, iter->vbucket,
(vbucket_state_t)iter->state);
addVBucketHighPriority_UNLOCKED(ev);
}
break;
default:
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s Internal error in reschedule_UNLOCKED()."
" Tap opcode value %d not implemented",
logHeader(), iter->event);
abort();
}
}
ENGINE_ERROR_CODE TapProducer::processAck(uint32_t s,
uint16_t status,
const std::string &msg)
{
LockHolder lh(queueLock);
std::list<TapLogElement>::iterator iter = tapLog.begin();
ENGINE_ERROR_CODE ret = ENGINE_SUCCESS;
const TapConfig &config = engine.getTapConfig();
rel_time_t ackGracePeriod = config.getAckGracePeriod();
expiryTime = ep_current_time() + ackGracePeriod;
if (isSeqNumRotated && s < seqnoReceived) {
// if the ack seq number is rotated, reset the last seq number of each vbucket to 0.
std::map<uint16_t, TapCheckpointState>::iterator it = tapCheckpointState.begin();
for (; it != tapCheckpointState.end(); ++it) {
it->second.lastSeqNum = 0;
}
isSeqNumRotated = false;
}
seqnoReceived = s;
isLastAckSucceed = false;
size_t num_logs = 0;
/* Implicit ack _every_ message up until this message */
while (iter != tapLog.end() && iter->seqno != s) {
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s Implicit ack (#%u)\n",
logHeader(), iter->seqno);
++iter;
++num_logs;
}
bool notifyTapNotificationThread = false;
switch (status) {
case PROTOCOL_BINARY_RESPONSE_SUCCESS:
/* And explicit ack this message! */
if (iter != tapLog.end()) {
// If this ACK is for TAP_CHECKPOINT messages, indicate that the checkpoint
// is synced between the master and slave nodes.
if ((iter->event == TAP_CHECKPOINT_START || iter->event == TAP_CHECKPOINT_END)
&& supportCheckpointSync) {
std::map<uint16_t, TapCheckpointState>::iterator map_it =
tapCheckpointState.find(iter->vbucket);
if (iter->event == TAP_CHECKPOINT_END && map_it != tapCheckpointState.end()) {
map_it->second.state = checkpoint_end_synced;
}
--checkpointMsgCounter;
notifyTapNotificationThread = true;
} else if (iter->event == TAP_OPAQUE) {
--opaqueMsgCounter;
notifyTapNotificationThread = true;
}
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s Explicit ack (#%u)\n",
logHeader(), iter->seqno);
++num_logs;
++iter;
tapLog.erase(tapLog.begin(), iter);
isLastAckSucceed = true;
} else {
num_logs = 0;
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s Explicit ack of nonexisting entry (#%u)\n",
logHeader(), s);
}
if (checkBackfillCompletion_UNLOCKED() || (doTakeOver && tapLog.empty())) {
notifyTapNotificationThread = true;
}
lh.unlock(); // Release the lock to avoid the deadlock with the notify thread
if (notifyTapNotificationThread) {
engine.notifyNotificationThread();
}
lh.lock();
if (mayCompleteDumpOrTakeover_UNLOCKED() && idle_UNLOCKED()) {
// We've got all of the ack's need, now we can shut down the
// stream
std::stringstream ss;
if (dumpQueue) {
ss << "TAP dump is completed. ";
} else if (doTakeOver) {
ss << "TAP takeover is completed. ";
}
ss << "Disconnecting tap stream <" << getName() << ">";
getLogger()->log(EXTENSION_LOG_WARNING, NULL, "%s\n",
ss.str().c_str());
setDisconnect(true);
expiryTime = 0;
ret = ENGINE_DISCONNECT;
}
break;
case PROTOCOL_BINARY_RESPONSE_EBUSY:
case PROTOCOL_BINARY_RESPONSE_ETMPFAIL:
if (!takeOverCompletionPhase) {
setSuspended_UNLOCKED(true);
}
++numTapNack;
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"%s Received temporary TAP nack (#%u): Code: %u (%s)\n",
logHeader(), seqnoReceived, status, msg.c_str());
// Reschedule _this_ sequence number..
if (iter != tapLog.end()) {
reschedule_UNLOCKED(iter);
++num_logs;
++iter;
}
tapLog.erase(tapLog.begin(), iter);
break;
default:
tapLog.erase(tapLog.begin(), iter);
++numTapNack;
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"%s Received negative TAP ack (#%u): Code: %u (%s)\n",
logHeader(), seqnoReceived, status, msg.c_str());
setDisconnect(true);