/
consumer.cc
1927 lines (1704 loc) · 68.2 KB
/
consumer.cc
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 2015 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.
*/
#include "dcp/consumer.h"
#include "bucket_logger.h"
#include "checkpoint_manager.h"
#include "collections/vbucket_manifest_handles.h"
#include "connhandler_impl.h"
#include "dcp/dcpconnmap.h"
#include "dcp/passive_stream.h"
#include "dcp/response.h"
#include "ep_engine.h"
#include "ep_time.h"
#include "executorpool.h"
#include "failover-table.h"
#include "kv_bucket.h"
#include "replicationthrottle.h"
#include <memcached/server_cookie_iface.h>
#include <phosphor/phosphor.h>
#include <xattr/utils.h>
#include <utility>
const std::string DcpConsumer::noopCtrlMsg = "enable_noop";
const std::string DcpConsumer::noopIntervalCtrlMsg = "set_noop_interval";
const std::string DcpConsumer::connBufferCtrlMsg = "connection_buffer_size";
const std::string DcpConsumer::priorityCtrlMsg = "set_priority";
const std::string DcpConsumer::extMetadataCtrlMsg = "enable_ext_metadata";
// from vulcan onwards we only use the _vulcan control message
const std::string DcpConsumer::cursorDroppingCtrlMsg =
"supports_cursor_dropping_vulcan";
const std::string DcpConsumer::sendStreamEndOnClientStreamCloseCtrlMsg =
"send_stream_end_on_client_close_stream";
const std::string DcpConsumer::hifiMFUCtrlMsg = "supports_hifi_MFU";
const std::string DcpConsumer::enableOpcodeExpiryCtrlMsg =
"enable_expiry_opcode";
class DcpConsumerTask : public GlobalTask {
public:
DcpConsumerTask(EventuallyPersistentEngine* e,
std::shared_ptr<DcpConsumer> c,
double sleeptime = 1,
bool completeBeforeShutdown = true)
: GlobalTask(e,
TaskId::DcpConsumerTask,
sleeptime,
completeBeforeShutdown),
consumerPtr(c),
description("DcpConsumerTask, processing buffered items for " +
c->getName()) {
}
~DcpConsumerTask() override {
auto consumer = consumerPtr.lock();
if (consumer) {
consumer->taskCancelled();
}
}
bool run() override {
TRACE_EVENT0("ep-engine/task", "DcpConsumerTask");
auto consumer = consumerPtr.lock();
if (!consumer) {
return false;
}
if (consumer->doDisconnect()) {
return false;
}
double sleepFor = 0.0;
enum process_items_error_t state = consumer->processBufferedItems();
switch (state) {
case all_processed:
sleepFor = INT_MAX;
break;
case more_to_process:
sleepFor = 0.0;
break;
case cannot_process:
sleepFor = 5.0;
break;
case stop_processing:
return false;
}
// Check if we've been notified of more work to do - if not then sleep;
// if so then wakeup and re-run the task.
// Note: The order of the wakeUp / snooze here is *critical* - another
// thread may concurrently notify us (set processorNotification=true)
// while we are performing the checks, so we need to ensure we don't
// loose a wakeup as that would result in this Task sleeping forever
// (and DCP hanging).
// To prevent this, we perform an initial check of notifiedProcessor(),
// which if false we initially sleep, and then check a second time.
// We could race if the other actor sets processorNotification=true
// between the second `if(consumer->notifiedProcessor)` and us calling
// `wakeUp()`; but that's essentially a benign race as it will just
// result in wakeUp() being called twice which is benign.
if (consumer->notifiedProcessor(false)) {
wakeUp();
state = more_to_process;
} else {
snooze(sleepFor);
// Check if the processor was notified again,
// in which case the task should wake immediately.
if (consumer->notifiedProcessor(false)) {
wakeUp();
state = more_to_process;
}
}
consumer->setProcessorTaskState(state);
return true;
}
std::string getDescription() override {
return description;
}
std::chrono::microseconds maxExpectedDuration() override {
// This should be a very fast operation (p50 under 10us), however we
// have observed long tails: p99.9 of 20ms; so use a threshold of 100ms.
return std::chrono::milliseconds(100);
}
private:
/* we have one task per consumer. the task only needs a reference to the
consumer object and does not own it. Hence std::weak_ptr should be used*/
const std::weak_ptr<DcpConsumer> consumerPtr;
const std::string description;
};
DcpConsumer::DcpConsumer(EventuallyPersistentEngine& engine,
const void* cookie,
const std::string& name,
std::string consumerName_)
: ConnHandler(engine, cookie, name),
lastMessageTime(ep_current_time()),
opaqueCounter(0),
processorTaskId(0),
processorTaskState(all_processed),
processorNotification(false),
backoffs(0),
dcpNoopTxInterval(engine.getConfiguration().getDcpNoopTxInterval()),
pendingSendStreamEndOnClientStreamClose(true),
consumerName(std::move(consumerName_)),
producerIsVersion5orHigher(false),
processorTaskRunning(false),
flowControl(engine, this),
processBufferedMessagesYieldThreshold(
engine.getConfiguration()
.getDcpConsumerProcessBufferedMessagesYieldLimit()),
processBufferedMessagesBatchSize(
engine.getConfiguration()
.getDcpConsumerProcessBufferedMessagesBatchSize()) {
Configuration& config = engine.getConfiguration();
setSupportAck(false);
setLogHeader("DCP (Consumer) " + getName() + " -");
setReserved(true);
pendingEnableNoop = config.isDcpEnableNoop();
getErrorMapState = pendingEnableNoop ? GetErrorMapState::PendingRequest
: GetErrorMapState::Skip;
pendingSendNoopInterval = config.isDcpEnableNoop();
pendingSetPriority = true;
pendingEnableExtMetaData = true;
pendingSupportCursorDropping = true;
pendingSupportHifiMFU = true;
pendingEnableExpiryOpcode = true;
// If a consumer_name was provided then tell the producer about it. Having
// a consumer name determines if we should support SyncReplication. If we
// have not yet received a consumer name then the cluster is in a mixed mode
// state and ns_server will not have set the topology on any producer nodes.
// We should NOT attempt to enable SyncReplication if this is the case. When
// the cluster is fully upgraded to MadHatter+, ns_server will tear down DCP
// connections and recreate them with the consumer name.
pendingSendConsumerName = !consumerName.empty();
syncReplNegotiation.state =
pendingSendConsumerName
? BlockingDcpControlNegotiation::State::PendingRequest
: BlockingDcpControlNegotiation::State::Completed;
// Consumer needs to know if the Producer supports IncludeDeletedUserXattrs
deletedUserXattrsNegotiation.state =
BlockingDcpControlNegotiation::State::PendingRequest;
// Consumer need to know if the Producer supports v7 DCP status codes
v7DcpStatusCodesNegotiation.state =
BlockingDcpControlNegotiation::State::PendingRequest;
allowSanitizeValueInDeletion.store(config.isAllowSanitizeValueInDeletion());
}
DcpConsumer::~DcpConsumer() {
cancelTask();
}
void DcpConsumer::cancelTask() {
bool exp = true;
if (processorTaskRunning.compare_exchange_strong(exp, false)) {
ExecutorPool::get()->cancel(processorTaskId);
}
}
void DcpConsumer::taskCancelled() {
processorTaskRunning.store(false);
}
std::shared_ptr<PassiveStream> DcpConsumer::makePassiveStream(
EventuallyPersistentEngine& e,
std::shared_ptr<DcpConsumer> consumer,
const std::string& name,
uint32_t flags,
uint32_t opaque,
Vbid vb,
uint64_t start_seqno,
uint64_t end_seqno,
uint64_t vb_uuid,
uint64_t snap_start_seqno,
uint64_t snap_end_seqno,
uint64_t vb_high_seqno,
const Collections::ManifestUid vb_manifest_uid) {
return std::make_shared<PassiveStream>(&e,
consumer,
name,
flags,
opaque,
vb,
start_seqno,
end_seqno,
vb_uuid,
snap_start_seqno,
snap_end_seqno,
vb_high_seqno,
vb_manifest_uid);
}
ENGINE_ERROR_CODE DcpConsumer::addStream(uint32_t opaque,
Vbid vbucket,
uint32_t flags) {
TRACE_EVENT2(
"DcpConsumer", "addStream", "vbid", vbucket.get(), "flags", flags);
lastMessageTime = ep_current_time();
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
VBucketPtr vb = engine_.getVBucket(vbucket);
if (!vb) {
logger->warn(
"({}) Add stream failed because this vbucket doesn't exist",
vbucket);
return ENGINE_NOT_MY_VBUCKET;
}
if (vb->getState() == vbucket_state_active) {
logger->warn(
"({}) Add stream failed because this vbucket happens to "
"be in active state",
vbucket);
return ENGINE_NOT_MY_VBUCKET;
}
snapshot_info_t info = vb->checkpointManager->getSnapshotInfo();
if (info.range.getEnd() == info.start) {
info.range.setStart(info.start);
}
uint32_t new_opaque = ++opaqueCounter;
failover_entry_t entry = vb->failovers->getLatestEntry();
uint64_t start_seqno = info.start;
uint64_t end_seqno = std::numeric_limits<uint64_t>::max();
uint64_t vbucket_uuid = entry.vb_uuid;
uint64_t snap_start_seqno = info.range.getStart();
uint64_t snap_end_seqno = info.range.getEnd();
uint64_t high_seqno = vb->getHighSeqno();
const Collections::ManifestUid vb_manifest_uid =
vb->lockCollections().getManifestUid();
auto stream = findStream(vbucket);
if (stream) {
if(stream->isActive()) {
logger->warn("({}) Cannot add stream because one already exists",
vbucket);
return ENGINE_KEY_EEXISTS;
} else {
removeStream(vbucket);
}
}
/* We need 'Processor' task only when we have a stream. Hence create it
only once when the first stream is added */
bool exp = false;
if (processorTaskRunning.compare_exchange_strong(exp, true)) {
ExTask task = std::make_shared<DcpConsumerTask>(
&engine_, shared_from_this(), 1);
processorTaskId = ExecutorPool::get()->schedule(task);
}
stream = makePassiveStream(engine_,
shared_from_this(),
getName(),
flags,
new_opaque,
vbucket,
start_seqno,
end_seqno,
vbucket_uuid,
snap_start_seqno,
snap_end_seqno,
high_seqno,
vb_manifest_uid);
registerStream(stream);
LockHolder lh(readyMutex);
ready.push_back(vbucket);
opaqueMap_[new_opaque] = std::make_pair(opaque, vbucket);
pendingAddStream = false;
return ENGINE_SUCCESS;
}
ENGINE_ERROR_CODE DcpConsumer::closeStream(uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpStreamId sid) {
TRACE_EVENT2("DcpConsumer",
"closeStream",
"opaque",
opaque,
"vbid",
vbucket.get());
lastMessageTime = ep_current_time();
if (doDisconnect()) {
removeStream(vbucket);
return ENGINE_DISCONNECT;
}
auto oitr = opaqueMap_.find(opaque);
if (oitr != opaqueMap_.end()) {
opaqueMap_.erase(oitr);
}
auto stream = findStream(vbucket);
if (!stream) {
logger->warn(
"({}) Cannot close stream because no "
"stream exists for this vbucket",
vbucket);
return getNoStreamFoundErrorCode();
}
uint32_t bytesCleared =
stream->setDead(cb::mcbp::DcpStreamEndStatus::Closed);
flowControl.incrFreedBytes(bytesCleared);
// Note the stream is not yet removed from the `streams` map; as we need to
// handle (but ignore) any in-flight messages from the Producer until
// STREAM_END is received.
scheduleNotifyIfNecessary();
return ENGINE_SUCCESS;
}
ENGINE_ERROR_CODE DcpConsumer::streamEnd(uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpStreamEndStatus status) {
TRACE_EVENT2("DcpConsumer",
"streamEnd",
"vbid",
vbucket.get(),
"status",
uint32_t(status));
lastMessageTime = ep_current_time();
UpdateFlowControl ufc(*this, StreamEndResponse::baseMsgBytes);
auto stream = findStream(vbucket);
if (!stream) {
logger->warn(
"({}) End stream received with opaque:{} but no such stream "
"for this "
"vBucket",
vbucket,
opaque);
return getNoStreamFoundErrorCode();
}
if (stream->getOpaque() != opaque) {
// MB-34951: By the time the DcpConsumer receives the StreamEnd from
// the DcpProducer it is possible that ns_server has already started
// a new Stream (with updated opaque) for this vbucket.
// In which case just ignore this StreamEnd message, returning SUCCESS.
logger->info(
"({}) End stream received with opaque {} but current opaque "
"for that vb is {} - ignoring",
vbucket,
opaque,
stream->getOpaque());
return ENGINE_SUCCESS;
}
logger->info("({}) End stream received with reason {}",
vbucket,
cb::mcbp::to_string(status));
auto msg = std::make_unique<StreamEndResponse>(
opaque, status, vbucket, cb::mcbp::DcpStreamId{});
auto res = lookupStreamAndDispatchMessage(
ufc, vbucket, opaque, std::move(msg));
if (res == ENGINE_SUCCESS) {
// Stream End message successfully passed to stream. Can now remove
// the stream from the streams map as it has completed its lifetime.
removeStream(vbucket);
}
return res;
}
ENGINE_ERROR_CODE DcpConsumer::processMutationOrPrepare(
Vbid vbucket,
uint32_t opaque,
const DocKey& key,
queued_item item,
cb::const_byte_buffer meta,
size_t msgBytes) {
UpdateFlowControl ufc(*this, msgBytes);
std::unique_ptr<ExtendedMetaData> emd;
if (!meta.empty()) {
emd = std::make_unique<ExtendedMetaData>(meta.data(), meta.size());
if (emd->getStatus() == ENGINE_EINVAL) {
return ENGINE_EINVAL;
}
}
auto msg = std::make_unique<MutationConsumerMessage>(
std::move(item),
opaque,
IncludeValue::Yes,
IncludeXattrs::Yes,
IncludeDeleteTime::No,
IncludeDeletedUserXattrs::Yes,
key.getEncoding(),
emd.release(),
cb::mcbp::DcpStreamId{});
return lookupStreamAndDispatchMessage(ufc, vbucket, opaque, std::move(msg));
}
ENGINE_ERROR_CODE DcpConsumer::mutation(uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint32_t flags,
uint64_t bySeqno,
uint64_t revSeqno,
uint32_t exptime,
uint32_t lock_time,
cb::const_byte_buffer meta,
uint8_t nru) {
lastMessageTime = ep_current_time();
if (bySeqno == 0) {
logger->warn("({}) Invalid sequence number(0) for mutation!", vbucket);
return ENGINE_EINVAL;
}
queued_item item(new Item(key,
flags,
exptime,
value.data(),
value.size(),
datatype,
cas,
bySeqno,
vbucket,
revSeqno,
nru /*freqCounter */));
return processMutationOrPrepare(vbucket,
opaque,
key,
std::move(item),
meta,
MutationResponse::mutationBaseMsgBytes +
key.size() + meta.size() +
value.size());
}
ENGINE_ERROR_CODE DcpConsumer::deletion(uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t bySeqno,
uint64_t revSeqno,
cb::const_byte_buffer meta) {
return toMainDeletion(DeleteType::Deletion,
opaque,
key,
value,
datatype,
cas,
vbucket,
bySeqno,
revSeqno,
meta,
0);
}
ENGINE_ERROR_CODE DcpConsumer::deletionV2(uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t bySeqno,
uint64_t revSeqno,
uint32_t deleteTime) {
return toMainDeletion(DeleteType::DeletionV2,
opaque,
key,
value,
datatype,
cas,
vbucket,
bySeqno,
revSeqno,
{},
deleteTime);
}
ENGINE_ERROR_CODE DcpConsumer::deletion(uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t bySeqno,
uint64_t revSeqno,
cb::const_byte_buffer meta,
uint32_t deleteTime,
IncludeDeleteTime includeDeleteTime,
DeleteSource deletionCause) {
lastMessageTime = ep_current_time();
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
if (bySeqno == 0) {
logger->warn("({}) Invalid sequence number(0) for deletion!", vbucket);
return ENGINE_EINVAL;
}
auto stream = findStream(vbucket);
if (!stream) {
return getNoStreamFoundErrorCode();
}
if (stream->getOpaque() != opaque) {
return getOpaqueMissMatchErrorCode();
}
queued_item item(Item::makeDeletedItem(deletionCause,
key,
0,
deleteTime,
value.data(),
value.size(),
datatype,
cas,
bySeqno,
vbucket,
revSeqno));
if (includeDeletedUserXattrs == IncludeDeletedUserXattrs::No) {
// Case pre-6.6 connection: Body and UserXattrs are invalid in deletion
// MB-29040: Producer may send deleted doc with value that still has
// the user xattrs and the body. Fix up that mistake by running the
// expiry hook which will correctly process the document
if (value.size() > 0) {
if (mcbp::datatype::is_xattr(datatype)) {
auto vb = engine_.getVBucket(vbucket);
if (vb) {
engine_.getKVBucket()->runPreExpiryHook(*vb, *item);
}
} else {
// MB-31141: Deletes cannot have a value
item->replaceValue(TaggedPtr<Blob>(Blob::New(0),
TaggedPtrBase::NoTagValue));
item->setDataType(PROTOCOL_BINARY_RAW_BYTES);
}
}
} else {
// Case 6.6 connection: UserXattrs in deletion is legal since MB-37374,
// Body still invalid.
if (cb::xattr::get_body_size(
datatype,
{reinterpret_cast<const char*>(value.data()),
value.size()}) > 0) {
// MB-43205 shows that we cannot unconditionally fail here as 6.6
// connections may still see Body in deletions (generated by pre-6.6
// nodes) after an offline upgrade.
// Note: (allowSanitizeValueInDeletion = true) by default, disabling
// the sanitizer is left only for test purpose.
if (!allowSanitizeValueInDeletion) {
logger->error(
"DcpConsumer::deletion: ({}) Value cannot contain a "
"body",
vbucket);
return ENGINE_EINVAL;
}
item->removeBody();
}
}
ENGINE_ERROR_CODE err;
std::unique_ptr<ExtendedMetaData> emd;
if (!meta.empty()) {
emd = std::make_unique<ExtendedMetaData>(meta.data(), meta.size());
if (emd->getStatus() == ENGINE_EINVAL) {
err = ENGINE_EINVAL;
}
}
try {
err = stream->messageReceived(std::make_unique<MutationConsumerMessage>(
item,
opaque,
IncludeValue::Yes,
IncludeXattrs::Yes,
includeDeleteTime,
IncludeDeletedUserXattrs::Yes,
key.getEncoding(),
emd.release(),
cb::mcbp::DcpStreamId{}));
} catch (const std::bad_alloc&) {
err = ENGINE_ENOMEM;
}
// The item was buffered and will be processed later
if (err == ENGINE_TMPFAIL) {
notifyVbucketReady(vbucket);
}
return err;
}
ENGINE_ERROR_CODE DcpConsumer::expiration(uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
size_t priv_bytes,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t bySeqno,
uint64_t revSeqno,
uint32_t deleteTime) {
return toMainDeletion(DeleteType::Expiration,
opaque,
key,
value,
datatype,
cas,
vbucket,
bySeqno,
revSeqno,
{},
deleteTime);
}
ENGINE_ERROR_CODE DcpConsumer::toMainDeletion(DeleteType origin,
uint32_t opaque,
const DocKey& key,
cb::const_byte_buffer value,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t bySeqno,
uint64_t revSeqno,
cb::const_byte_buffer meta,
uint32_t deleteTime) {
IncludeDeleteTime includeDeleteTime;
uint32_t bytes = 0;
DeleteSource deleteSource;
switch (origin) {
case DeleteType::Deletion: {
includeDeleteTime = IncludeDeleteTime::No;
deleteTime = 0;
deleteSource = DeleteSource::Explicit;
bytes = MutationResponse::deletionBaseMsgBytes + key.size() +
meta.size() + value.size();
break;
}
case DeleteType::DeletionV2: {
meta = {};
includeDeleteTime = IncludeDeleteTime::Yes;
deleteSource = DeleteSource::Explicit;
bytes = MutationResponse::deletionV2BaseMsgBytes + key.size() +
value.size();
break;
}
case DeleteType::Expiration: {
meta = {};
includeDeleteTime = IncludeDeleteTime::Yes;
deleteSource = DeleteSource::TTL;
bytes = MutationResponse::expirationBaseMsgBytes + key.size() +
value.size();
break;
}
}
if (bytes == 0) {
throw std::logic_error(std::string("DcpConsumer::toMainDeletion: ") +
logHeader() +
" is using an unexpected deletion type, as bytes"
" is uninitialized!");
}
UpdateFlowControl ufc(*this, bytes);
auto err = deletion(opaque,
key,
value,
datatype,
cas,
vbucket,
bySeqno,
revSeqno,
meta,
deleteTime,
includeDeleteTime,
deleteSource);
// TMPFAIL means the stream has buffered the message for later processing
// so skip flowControl, success or any other error, we still need to ack
if (err == ENGINE_TMPFAIL) {
ufc.release();
// Mask the TMPFAIL
return ENGINE_SUCCESS;
}
return err;
}
ENGINE_ERROR_CODE DcpConsumer::snapshotMarker(
uint32_t opaque,
Vbid vbucket,
uint64_t start_seqno,
uint64_t end_seqno,
uint32_t flags,
std::optional<uint64_t> high_completed_seqno,
std::optional<uint64_t> max_visible_seqno) {
lastMessageTime = ep_current_time();
uint32_t bytes = SnapshotMarker::baseMsgBytes;
if (high_completed_seqno || max_visible_seqno) {
bytes += sizeof(cb::mcbp::request::DcpSnapshotMarkerV2xPayload) +
sizeof(cb::mcbp::request::DcpSnapshotMarkerV2_0Value);
} else {
bytes += sizeof(cb::mcbp::request::DcpSnapshotMarkerV1Payload);
}
UpdateFlowControl ufc(*this, bytes);
if (start_seqno > end_seqno) {
logger->warn(
"({}) Invalid snapshot marker "
"received, snap_start ({}) <= snap_end ({})",
vbucket,
start_seqno,
end_seqno);
return ENGINE_EINVAL;
}
auto msg = std::make_unique<SnapshotMarker>(
opaque,
vbucket,
start_seqno,
end_seqno,
flags,
high_completed_seqno,
max_visible_seqno,
std::optional<uint64_t>{}, // @todo MB-37319
cb::mcbp::DcpStreamId{});
return lookupStreamAndDispatchMessage(ufc, vbucket, opaque, std::move(msg));
}
ENGINE_ERROR_CODE DcpConsumer::noop(uint32_t opaque) {
lastMessageTime = ep_current_time();
return ENGINE_SUCCESS;
}
ENGINE_ERROR_CODE DcpConsumer::setVBucketState(uint32_t opaque,
Vbid vbucket,
vbucket_state_t state) {
TRACE_EVENT2("DcpConsumer",
"setVBucketState",
"vbid",
vbucket.get(),
"state",
int(state));
lastMessageTime = ep_current_time();
UpdateFlowControl ufc(*this, SetVBucketState::baseMsgBytes);
auto msg = std::make_unique<SetVBucketState>(opaque, vbucket, state);
return lookupStreamAndDispatchMessage(ufc, vbucket, opaque, std::move(msg));
}
ENGINE_ERROR_CODE DcpConsumer::step(DcpMessageProducersIface& producers) {
if (doDisconnect()) {
return ENGINE_DISCONNECT;
}
if (pendingAddStream) {
return ENGINE_EWOULDBLOCK;
}
ENGINE_ERROR_CODE ret;
if ((ret = flowControl.handleFlowCtl(producers)) != ENGINE_FAILED) {
return ret;
}
// MB-29441: Send a GetErrorMap to the producer to determine if it
// is a pre-5.0.0 node. The consumer will set the producer's noop-interval
// accordingly in 'handleNoop()', so 'handleGetErrorMap()' *must* execute
// before 'handleNoop()'.
if ((ret = handleGetErrorMap(producers)) != ENGINE_FAILED) {
return ret;
}
if ((ret = handleNoop(producers)) != ENGINE_FAILED) {
return ret;
}
if ((ret = handlePriority(producers)) != ENGINE_FAILED) {
return ret;
}
if ((ret = handleExtMetaData(producers)) != ENGINE_FAILED) {
return ret;
}
if ((ret = supportCursorDropping(producers)) != ENGINE_FAILED) {
return ret;
}
if ((ret = supportHifiMFU(producers)) != ENGINE_FAILED) {
return ret;
}
if ((ret = sendStreamEndOnClientStreamClose(producers)) != ENGINE_FAILED) {
return ret;
}
if ((ret = enableExpiryOpcode(producers)) != ENGINE_FAILED) {
return ret;
}
if ((ret = enableSynchronousReplication(producers)) != ENGINE_FAILED) {
return ret;
}
if ((ret = handleDeletedUserXattrs(producers)) != ENGINE_FAILED) {
return ret;
}
if ((ret = enableV7DcpStatus(producers)) != ENGINE_FAILED) {
return ret;
}
auto resp = getNextItem();
if (resp == nullptr) {
return ENGINE_EWOULDBLOCK;
}
switch (resp->getEvent()) {
case DcpResponse::Event::AddStream:
{
auto* as = static_cast<AddStreamResponse*>(resp.get());
ret = producers.add_stream_rsp(
as->getOpaque(), as->getStreamOpaque(), as->getStatus());
break;
}
case DcpResponse::Event::StreamReq:
{
auto* sr = static_cast<StreamRequest*>(resp.get());
ret = producers.stream_req(sr->getOpaque(),
sr->getVBucket(),
sr->getFlags(),
sr->getStartSeqno(),
sr->getEndSeqno(),
sr->getVBucketUUID(),
sr->getSnapStartSeqno(),
sr->getSnapEndSeqno(),
sr->getRequestValue());
break;
}
case DcpResponse::Event::SetVbucket:
{
auto* vs =
static_cast<SetVBucketStateResponse*>(resp.get());
ret = producers.set_vbucket_state_rsp(vs->getOpaque(),
vs->getStatus());
break;
}
case DcpResponse::Event::SnapshotMarker: {
auto* mr =
static_cast<SnapshotMarkerResponse*>(resp.get());
ret = producers.marker_rsp(mr->getOpaque(), mr->getStatus());
break;
}
case DcpResponse::Event::SeqnoAcknowledgement: {
auto* ack = static_cast<SeqnoAcknowledgement*>(resp.get());
ret = producers.seqno_acknowledged(ack->getOpaque(),
ack->getVbucket(),
ack->getPreparedSeqno());
break;
}
default:
logger->warn("Unknown consumer event ({}), disconnecting",
int(resp->getEvent()));
ret = ENGINE_DISCONNECT;
}
return ret;
}
bool RollbackTask::run() {
TRACE_EVENT0("ep-engine/task", "RollbackTask");
if (cons->doDisconnect()) {
return false;
}
if (cons->doRollback(opaque, vbid, rollbackSeqno)) {
return true;
}
++(engine->getEpStats().rollbackCount);
return false;
}
bool DcpConsumer::handleResponse(const cb::mcbp::Response& response) {
if (doDisconnect()) {
return false;
}
const auto opcode = response.getClientOpcode();
const auto opaque = response.getOpaque();
if (opcode == cb::mcbp::ClientOpcode::DcpStreamReq) {
auto oitr = opaqueMap_.find(opaque);
if (oitr == opaqueMap_.end()) {
EP_LOG_WARN(
"Received response with opaque {} and that opaque "
"does not exist in opaqueMap",
opaque);
return false;
} else if (!isValidOpaque(opaque, oitr->second.second)) {
EP_LOG_WARN(
"Received response with opaque {} and that stream does not "
"exist for {}",
opaque,
Vbid(oitr->second.second));
return false;
}
Vbid vbid = oitr->second.second;
const auto status = response.getStatus();
const auto value = response.getValue();
TRACE_EVENT2("DcpConsumer",
"dcp_stream_req response",