/
ep_bucket.cc
2483 lines (2163 loc) · 92.8 KB
/
ep_bucket.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 2018-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#include "ep_bucket.h"
#include "bgfetcher.h"
#include "bucket_logger.h"
#include "checkpoint_manager.h"
#include "collections/manager.h"
#include "collections/persist_manifest_task.h"
#include "collections/vbucket_manifest_handles.h"
#include "dcp/dcpconnmap.h"
#include "ep_engine.h"
#include "ep_time.h"
#include "ep_vb.h"
#include "failover-table.h"
#include "flusher.h"
#include "item.h"
#include "kvstore/kvstore.h"
#include "kvstore/kvstore_transaction_context.h"
#include "kvstore/persistence_callback.h"
#include "range_scans/range_scan_callbacks.h"
#include "replicationthrottle.h"
#include "rollback_result.h"
#include "tasks.h"
#include "vb_commit.h"
#include "vb_visitors.h"
#include "vbucket_state.h"
#include "warmup.h"
#include <executor/executorpool.h>
#include <fmt/ostream.h>
#include <hdrhistogram/hdrhistogram.h>
#include <memcached/range_scan_optional_configuration.h>
#include <memcached/server_document_iface.h>
#include <platform/timeutils.h>
#include <statistics/cbstat_collector.h>
#include <statistics/collector.h>
#include <statistics/labelled_collector.h>
#include <utilities/logtags.h>
#include <gsl/gsl-lite.hpp>
#include <utility>
/**
* Callback class used by EpStore, for adding relevant keys
* to bloomfilter during compaction.
*/
class BloomFilterCallback : public Callback<Vbid&, const DocKey&, bool&> {
public:
explicit BloomFilterCallback(KVBucket& eps) : store(eps) {
}
void callback(Vbid& vbucketId,
const DocKey& key,
bool& isDeleted) override {
VBucketPtr vb = store.getVBucket(vbucketId);
if (vb) {
/* Check if a temporary filter has been initialized. If not,
* initialize it. If initialization fails, throw an exception
* to the caller and let the caller deal with it.
*/
bool tempFilterInitialized = vb->isTempFilterAvailable();
if (!tempFilterInitialized) {
tempFilterInitialized = initTempFilter(vbucketId);
}
if (!tempFilterInitialized) {
throw std::runtime_error(
"BloomFilterCallback::callback: Failed "
"to initialize temporary filter for " +
vbucketId.to_string());
}
if (store.getItemEvictionPolicy() == EvictionPolicy::Value) {
/**
* VALUE-ONLY EVICTION POLICY
* Consider deleted items only.
*/
if (isDeleted) {
vb->addToTempFilter(key);
}
} else {
/**
* FULL EVICTION POLICY
* If vbucket's resident ratio is found to be less than
* the residency threshold, consider all items, otherwise
* consider deleted and non-resident items only.
*/
bool residentRatioLessThanThreshold =
vb->isResidentRatioUnderThreshold(
store.getBfiltersResidencyThreshold());
if (residentRatioLessThanThreshold) {
vb->addToTempFilter(key);
} else {
if (isDeleted || !store.isMetaDataResident(vb, key)) {
vb->addToTempFilter(key);
}
}
}
}
}
private:
bool initTempFilter(Vbid vbucketId);
KVBucket& store;
};
bool BloomFilterCallback::initTempFilter(Vbid vbucketId) {
Configuration& config = store.getEPEngine().getConfiguration();
VBucketPtr vb = store.getVBucket(vbucketId);
if (!vb) {
return false;
}
size_t initial_estimation = config.getBfilterKeyCount();
size_t estimated_count;
size_t num_deletes = 0;
try {
num_deletes = store.getRWUnderlying(vbucketId)->getNumPersistedDeletes(
vbucketId);
} catch (std::runtime_error& re) {
EP_LOG_WARN(
"BloomFilterCallback::initTempFilter: runtime error while "
"getting "
"number of persisted deletes for {} Details: {}",
vbucketId,
re.what());
return false;
}
EvictionPolicy eviction_policy = store.getItemEvictionPolicy();
if (eviction_policy == EvictionPolicy::Value) {
/**
* VALUE-ONLY EVICTION POLICY
* Obtain number of persisted deletes from underlying kvstore.
* Bloomfilter's estimated_key_count = 1.25 * deletes
*/
estimated_count = round(1.25 * num_deletes);
} else {
/**
* FULL EVICTION POLICY
* First determine if the resident ratio of vbucket is less than
* the threshold from configuration.
*/
bool residentRatioAlert = vb->isResidentRatioUnderThreshold(
store.getBfiltersResidencyThreshold());
/**
* Based on resident ratio against threshold, estimate count.
*
* 1. If resident ratio is greater than the threshold:
* Obtain number of persisted deletes from underlying kvstore.
* Obtain number of non-resident-items for vbucket.
* Bloomfilter's estimated_key_count =
* 1.25 * (deletes + non-resident)
*
* 2. Otherwise:
* Obtain number of items for vbucket.
* Bloomfilter's estimated_key_count =
* 1.25 * (num_items)
*/
if (residentRatioAlert) {
estimated_count = round(1.25 * vb->getNumItems());
} else {
estimated_count =
round(1.25 * (num_deletes + vb->getNumNonResidentItems()));
}
}
if (estimated_count < initial_estimation) {
estimated_count = initial_estimation;
}
vb->initTempFilter(estimated_count, config.getBfilterFpProb());
return true;
}
class ExpiredItemsCallback : public Callback<Item&, time_t&> {
public:
explicit ExpiredItemsCallback(KVBucket& store) : epstore(store) {
}
void callback(Item& item, time_t& startTime) override {
epstore.processExpiredItem(item, startTime, ExpireBy::Compactor);
}
private:
KVBucket& epstore;
};
void NotifyFlusherCB::callback(Vbid& vbid) {
auto vb = shard->getBucket(vbid);
if (vb) {
vb->getFlusher()->notifyFlushEvent(vb);
}
}
class EPBucket::ValueChangedListener : public ::ValueChangedListener {
public:
explicit ValueChangedListener(EPBucket& bucket) : bucket(bucket) {
}
void sizeValueChanged(const std::string& key, size_t value) override {
if (key == "flusher_total_batch_limit") {
bucket.setFlusherBatchSplitTrigger(value);
} else if (key == "alog_sleep_time") {
bucket.setAccessScannerSleeptime(value, false);
} else if (key == "alog_task_time") {
bucket.resetAccessScannerStartTime();
} else {
EP_LOG_WARN("Failed to change value for unknown variable, {}", key);
}
}
void booleanValueChanged(const std::string& key, bool value) override {
if (key == "access_scanner_enabled") {
if (value) {
bucket.enableAccessScannerTask();
} else {
bucket.disableAccessScannerTask();
}
} else if (key == "retain_erroneous_tombstones") {
bucket.setRetainErroneousTombstones(value);
} else {
EP_LOG_WARN("Failed to change value for unknown variable, {}", key);
}
}
private:
EPBucket& bucket;
};
EPBucket::EPBucket(EventuallyPersistentEngine& theEngine)
: KVBucket(theEngine), rangeScans(engine.getConfiguration()) {
auto& config = engine.getConfiguration();
const std::string& policy = config.getItemEvictionPolicy();
if (policy.compare("value_only") == 0) {
eviction_policy = EvictionPolicy::Value;
} else {
eviction_policy = EvictionPolicy::Full;
}
replicationThrottle = std::make_unique<ReplicationThrottleEP>(
engine.getConfiguration(), stats);
// Pre 7.0.0 Flushers were a part of KVShard so keep the same default
// scaling.
auto configFlusherLimit = config.getMaxNumFlushers();
auto flusherLimit =
configFlusherLimit == 0 ? vbMap.getNumShards() : configFlusherLimit;
for (size_t i = 0; i < flusherLimit; i++) {
flushers.emplace_back(std::make_unique<Flusher>(this, i));
}
// Pre-7.0.0 BgFetchers were a part of KVShard so keep the same default
// scaling.
auto configBgFetcherLimit = config.getMaxNumBgfetchers();
auto bgFetcherLimit = configBgFetcherLimit == 0 ? vbMap.getNumShards()
: configBgFetcherLimit;
// Limit BgFetchers by the number of vBuckets as any more would be useless.
bgFetcherLimit = std::min(bgFetcherLimit, config.getMaxVbuckets());
for (size_t i = 0; i < bgFetcherLimit; i++) {
bgFetchers.emplace_back(std::make_unique<BgFetcher>(*this));
}
setFlusherBatchSplitTrigger(config.getFlusherTotalBatchLimit());
config.addValueChangedListener(
"flusher_total_batch_limit",
std::make_unique<ValueChangedListener>(*this));
retainErroneousTombstones = config.isRetainErroneousTombstones();
config.addValueChangedListener(
"retain_erroneous_tombstones",
std::make_unique<ValueChangedListener>(*this));
// create the semaphore with a default capacity of 1. This will be
// updated when a compaction is scheduled.
compactionSemaphore = std::make_unique<cb::AwaitableSemaphore>();
initializeWarmupTask();
}
EPBucket::~EPBucket() = default;
bool EPBucket::initialize() {
KVBucket::initialize();
startWarmupTask();
enableItemPager();
if (!startBgFetcher()) {
EP_LOG_CRITICAL_RAW(
"EPBucket::initialize: Failed to create and start "
"bgFetchers");
return false;
}
return true;
}
void EPBucket::initializeShards() {
vbMap.forEachShard([this](KVShard& shard) {
shard.getRWUnderlying()->setMakeCompactionContextCallback(
[this](Vbid vbid,
CompactionConfig& config,
uint64_t purgeSeqno) {
return makeCompactionContext(vbid, config, purgeSeqno);
});
});
}
void EPBucket::deinitialize() {
stopFlusher();
stopBgFetcher();
KVBucket::deinitialize();
// Persist the type of shutdown (stats.forceShutdown), and consequently
// on the next warmup can determine is there was a clean shutdown - see
// Warmup::cleanShutdown.
persistShutdownContext();
// Now that we've stopped all of our tasks, stop any tasks the storage
// layer may have created.
vbMap.forEachShard([](KVShard& shard) {
shard.getRWUnderlying()->deinitialize();
});
}
/**
* @returns true if the item `candidate` can be de-duplicated (skipped) because
* `lastFlushed` already supercedes it.
*/
static bool canDeDuplicate(Item* lastFlushed, Item& candidate) {
if (!lastFlushed) {
// Nothing to de-duplicate against.
return false;
}
if (lastFlushed->getKey() != candidate.getKey()) {
// Keys differ - cannot de-dupe.
return false;
}
if (lastFlushed->isCommitted() != candidate.isCommitted()) {
// Committed / pending namespace differs - cannot de-dupe.
return false;
}
// items match - the candidate must have a lower seqno.
Expects(lastFlushed->getBySeqno() > candidate.getBySeqno());
// Otherwise - valid to de-dupe.
return true;
}
EPBucket::FlushResult EPBucket::flushVBucket(Vbid vbid) {
auto vb = getLockedVBucket(vbid, std::try_to_lock);
if (!vb.owns_lock()) {
// Try another bucket if this one is locked to avoid blocking flusher.
return {MoreAvailable::Yes, 0};
}
if (!vb) {
return {MoreAvailable::No, 0};
}
return flushVBucket_UNLOCKED(std::move(vb));
}
EPBucket::FlushResult EPBucket::flushVBucket_UNLOCKED(LockedVBucketPtr vb) {
if (!vb || !vb.owns_lock()) {
// should never really hit this code, if we do you're using the method
// incorrectly
std::logic_error(fmt::format(
"EPBucket::flushVBucket_UNLOCKED(): should always be called "
"with a valid LockedVBucketPtr: VbucketPtr:{} owns_lock:{}",
bool{vb},
vb.owns_lock()));
}
const auto vbid = vb->getId();
const auto flushStart = std::chrono::steady_clock::now();
// Obtain the set of items to flush, up to the maximum allowed for
// a single flush.
auto toFlush = vb->getItemsToPersist(flusherBatchSplitTrigger);
// Callback must be initialized at persistence
Expects(toFlush.flushHandle.get());
const auto moreAvailable =
toFlush.moreAvailable ? MoreAvailable::Yes : MoreAvailable::No;
if (toFlush.items.empty()) {
return {moreAvailable, 0};
}
// The range becomes initialised only when an item is flushed
std::optional<snapshot_range_t> range;
auto* rwUnderlying = getRWUnderlying(vb->getId());
auto ctx = rwUnderlying->begin(
vbid, std::make_unique<EPPersistenceCallback>(stats, *vb));
while (!ctx) {
++stats.beginFailed;
EP_LOG_WARN(
"EPBucket::flushVBucket_UNLOCKED: () Failed to start a "
"transaction. "
"Retry in 1 second.",
vb->getId());
std::this_thread::sleep_for(std::chrono::seconds(1));
ctx = rwUnderlying->begin(
vbid, std::make_unique<EPPersistenceCallback>(stats, *vb));
}
bool mustDedupe =
!rwUnderlying->getStorageProperties().hasAutomaticDeduplication();
if (mustDedupe) {
rwUnderlying->prepareForDeduplication(toFlush.items);
}
Item* prev = nullptr;
// Read the vbucket_state from disk as many values from the
// in-memory vbucket_state may be ahead of what we are flushing.
const auto* persistedVbState =
rwUnderlying->getCachedVBucketState(vb->getId());
// The first flush we do populates the cachedVBStates of the KVStore
// so we may not (if this is the first flush) have a state returned
// from the KVStore.
vbucket_state vbstate;
if (persistedVbState) {
vbstate = *persistedVbState;
}
// Callback executed at KVStore::commit.
bool logged = false;
const auto callback = [this, &logged, vbid](const std::system_error& err) {
if (!logged) {
EP_LOG_WARN(
"EPBucket::flushVBucket_UNLOCKED: {} {}", vbid, err.what());
logged = true;
}
// MB-42224: sync-header failure callback increments
// ep_data_write_failed, which is what ns_server uses for
// detecting a high rate of disk-write failures and failing the
// node if the user enabled auto-failover.
++(this->stats.commitFailed);
// Return true to let couchstore re-try the operation
return true;
};
WriteOperation writeOp = WriteOperation::Upsert;
// A disk snapshot has unique items and if we're receiving a vbucket from
// the start (seqno 0), we can issue Insert operations. This benefits some
// KVStore implementations since a lookup isn't needed. This scenario
// commonly occurs in rebalance where a vbucket is taken over by a new node.
if (toFlush.ranges.size() == 1 &&
toFlush.checkpointType == CheckpointType::InitialDisk) {
writeOp = WriteOperation::Insert;
}
VB::Commit commitData(vb->getManifest(), writeOp, vbstate, callback);
vbucket_state& proposedVBState = commitData.proposedVBState;
// We need to set a few values from the in-memory state.
uint64_t maxSeqno = 0;
uint64_t maxVbStateOpCas = 0;
auto minSeqno = std::numeric_limits<uint64_t>::max();
// Stores the number of items added to the flush-batch in KVStore.
// Note:
// - Does not carry any information on whether the flush-batch is
// successfully persisted or not
// - Does not account set-vbstate items
size_t flushBatchSize = 0;
// Set if we process an explicit set-vbstate item, which requires a flush
// to disk regardless of whether we have any other item to flush or not
bool mustPersistVBState = false;
// HCS is optional because we have to update it on disk only if some
// Commit/Abort SyncWrite is found in the flush-batch. If we're
// flushing Disk checkpoints then the toFlush value may be
// supplied. In this case, this should be the HCS received from the
// Active node and should be greater than or equal to the HCS for
// any other item in this flush batch. This is required because we
// send mutations instead of a commits and would not otherwise
// update the HCS on disk.
std::optional<uint64_t> hcs;
// HPS is optional because we have to update it on disk only if a
// prepare is found in the flush-batch
// This value is read at warmup to determine what seqno to stop
// loading prepares at (there will not be any prepares after this
// point) but cannot be used to initialise a PassiveDM after warmup
// as this value will advance into snapshots immediately, without
// the entire snapshot needing to be persisted.
std::optional<uint64_t> hps;
// We always maintain the maxVisibleSeqno at the current value
// and only change it to a higher-seqno when a flush of a visible
// item is seen. This value must be tracked to provide a correct
// snapshot range for non-sync write aware consumers during backfill
// (the snapshot should not end on a prepare or an abort, as these
// items will not be sent). This value is also used at warmup so
// that vbuckets can resume with the same visible seqno as before
// the restart.
Monotonic<uint64_t> maxVisibleSeqno{proposedVBState.maxVisibleSeqno};
if (toFlush.maxDeletedRevSeqno) {
proposedVBState.maxDeletedSeqno = toFlush.maxDeletedRevSeqno.value();
}
AggregatedFlushStats aggStats;
// Iterate through items, checking if we (a) can skip persisting,
// (b) can de-duplicate as the previous key was the same, or (c)
// actually need to persist.
// Note: This assumes items have been sorted by key and then by
// seqno (see prepareForDeduplication() above) such that duplicate keys are
// adjacent but with the highest seqno first.
// Note(2): The de-duplication here is an optimization to save
// creating and enqueuing multiple set() operations on the
// underlying KVStore - however the KVStore itself only stores a
// single value per key, and so even if we don't de-dupe here the
// KVStore will eventually - just potentialy after unnecessary work.
for (const auto& item : toFlush.items) {
if (!item->shouldPersist()) {
continue;
}
const auto op = item->getOperation();
if ((op == queue_op::commit_sync_write ||
op == queue_op::abort_sync_write) &&
!isDiskCheckpointType(toFlush.checkpointType)) {
// If we are receiving a disk snapshot then we want to skip
// the HCS update as we will persist a correct one when we
// flush the last item. If we were to persist an incorrect
// HCS then we would have to backtrack the start seqno of
// our warmup to ensure that we do warmup prepares that may
// not have been completed if they were completed out of
// order.
hcs = std::max(hcs.value_or(0), item->getPrepareSeqno());
}
if (item->isVisible() &&
static_cast<uint64_t>(item->getBySeqno()) > maxVisibleSeqno) {
maxVisibleSeqno = static_cast<uint64_t>(item->getBySeqno());
}
if (op == queue_op::pending_sync_write) {
Expects(item->getBySeqno() > 0);
hps = std::max(hps.value_or(0),
static_cast<uint64_t>(item->getBySeqno()));
}
if (item->isSystemEvent()) {
commitData.collections.recordSystemEvent(*item);
}
if (op == queue_op::set_vbucket_state) {
// Only process vbstate if it's sequenced higher (by cas).
// We use the cas instead of the seqno here because a
// set_vbucket_state does not increment the lastBySeqno in
// the CheckpointManager when it is created. This means that
// it is possible to have two set_vbucket_state items that
// follow one another with the same seqno. The cas will be
// bumped for every item so it can be used to distinguish
// which item is the latest and should be flushed.
if (item->getCas() > maxVbStateOpCas) {
// Should only bump the stat once for the latest state
// change that we want to flush
if (maxVbStateOpCas == 0) {
// There is at least a commit to be done, so
// increase todo
++stats.flusher_todo;
}
maxVbStateOpCas = item->getCas();
// It could be the case that the set_vbucket_state is
// alone, i.e. no mutations are being flushed, we must
// trigger an update of the vbstate, which will always
// happen when we set this.
mustPersistVBState = true;
// Process the Item's value into the transition struct
proposedVBState.transition.fromItem(*item);
}
} else if (!mustDedupe || !canDeDuplicate(prev, *item)) {
// This is an item we must persist.
prev = item.get();
++flushBatchSize;
if (mcbp::datatype::is_xattr(item->getDataType())) {
proposedVBState.mightContainXattrs = true;
}
flushOneDelOrSet(*ctx, item, vb.getVB());
maxSeqno = std::max(maxSeqno, (uint64_t)item->getBySeqno());
// Track the lowest seqno, so we can set the HLC epoch
minSeqno = std::min(minSeqno, (uint64_t)item->getBySeqno());
proposedVBState.maxCas =
std::max(proposedVBState.maxCas, item->getCas());
++stats.flusher_todo;
if (!range.has_value()) {
range = snapshot_range_t{
proposedVBState.lastSnapStart,
toFlush.ranges.empty()
? proposedVBState.lastSnapEnd
: toFlush.ranges.back().getEnd()};
}
// Is the item the end item of one of the ranges we're
// flushing? Note all the work here only affects replica VBs
auto itr = std::find_if(toFlush.ranges.begin(),
toFlush.ranges.end(),
[&item](auto& range) {
return uint64_t(item->getBySeqno()) ==
range.getEnd();
});
// If this is the end item, we can adjust the start of our
// flushed range, which would be used for failure purposes.
// Primarily by bringing the start to be a consistent point
// allows for promotion to active to set the fail-over table
// to a consistent point.
if (itr != toFlush.ranges.end()) {
// Use std::max as the flusher is not visiting in seqno
// order.
range->setStart(
std::max(range->getStart(), itr->range.getEnd()));
// HCS may be weakly monotonic when received via a disk
// snapshot so we special case this for the disk
// snapshot instead of relaxing the general constraint.
if (isDiskCheckpointType(toFlush.checkpointType) &&
itr->highCompletedSeqno !=
proposedVBState.persistedCompletedSeqno) {
hcs = itr->highCompletedSeqno;
}
// Now that the end of a snapshot has been reached,
// store the hps tracked by the checkpoint to disk
switch (toFlush.checkpointType) {
case CheckpointType::Memory:
if (itr->highPreparedSeqno) {
proposedVBState.highPreparedSeqno =
std::max(proposedVBState.highPreparedSeqno,
*(itr->highPreparedSeqno));
}
break;
case CheckpointType::InitialDisk:
case CheckpointType::Disk:
// MB-51639: We need to set the HPS value to the snapshot
// end regardless of whether we have a prepare or not
// because whilst the active does not complete prepares we
// are about to persist their logical completions and so
// we can move the HPS.
proposedVBState.highPreparedSeqno = std::max(
proposedVBState.highPreparedSeqno, itr->getEnd());
break;
}
}
} else {
// Item is the same key as the previous[1] one - don't need
// to flush to disk.
// [1] Previous here really means 'next' - prepareForDeduplication()
// above has actually re-ordered items such that items
// with the same key are ordered from high->low seqno.
// This means we only write the highest (i.e. newest)
// item for a given key, and discard any duplicate,
// older items.
}
// Register the item for deferred (flush success only) stats update.
aggStats.accountItem(*item);
}
// Just return if nothing to flush
if (!mustPersistVBState && flushBatchSize == 0) {
return {moreAvailable, 0};
}
if (proposedVBState.transition.state == vbucket_state_active) {
if (maxSeqno) {
range = snapshot_range_t(maxSeqno, maxSeqno);
}
}
// Update VBstate based on the changes we have just made,
// then tell the rwUnderlying the 'new' state
// (which will persisted as part of the commit() below).
// only update the snapshot range if items were flushed, i.e.
// don't appear to be in a snapshot when you have no data for it
// We also update the checkpointType here as this should only
// change with snapshots.
if (range) {
proposedVBState.lastSnapStart = range->getStart();
proposedVBState.lastSnapEnd = range->getEnd();
proposedVBState.checkpointType = toFlush.checkpointType;
}
// Track the lowest seqno written in spock and record it as
// the HLC epoch, a seqno which we can be sure the value has a
// HLC CAS.
proposedVBState.hlcCasEpochSeqno = vb->getHLCEpochSeqno();
if (proposedVBState.hlcCasEpochSeqno == HlcCasSeqnoUninitialised &&
minSeqno != std::numeric_limits<uint64_t>::max()) {
proposedVBState.hlcCasEpochSeqno = minSeqno;
// @todo MB-37692: Defer this call at flush-success only or reset
// the value if flush fails.
vb->setHLCEpochSeqno(proposedVBState.hlcCasEpochSeqno);
}
if (hcs) {
if (hcs <= proposedVBState.persistedCompletedSeqno) {
throw std::logic_error(fmt::format(
"EPBucket::flushVBucket_UNLOCKED: {} Trying to set PCS to "
"{} but "
"the current value is {} and the PCS must be monotonic. "
"The current checkpoint type is {}. Flush's seqno "
"range:[{},{}], proposedVBState:'{}'.",
vbid,
*hcs,
proposedVBState.persistedCompletedSeqno,
to_string(toFlush.checkpointType),
minSeqno,
maxSeqno,
proposedVBState));
}
proposedVBState.persistedCompletedSeqno = *hcs;
}
if (hps) {
if (hps <= proposedVBState.persistedPreparedSeqno) {
throw std::logic_error(fmt::format(
"EPBucket::flushVBucket_UNLOCKED: {} Trying to set PPS to "
"{} but "
"the current value is {} and the PPS must be monotonic. "
"The current checkpoint type is {}. Flush's seqno "
"range:[{},{}], proposedVBState:'{}'.",
vbid,
*hps,
proposedVBState.persistedPreparedSeqno,
to_string(toFlush.checkpointType),
minSeqno,
maxSeqno,
proposedVBState));
}
proposedVBState.persistedPreparedSeqno = *hps;
}
proposedVBState.maxVisibleSeqno = maxVisibleSeqno;
// Are we flushing only a new vbstate?
if (mustPersistVBState && (flushBatchSize == 0)) {
if (!rwUnderlying->snapshotVBucket(vbid, commitData.proposedVBState)) {
flushFailureEpilogue(*vb, toFlush);
return {MoreAvailable::Yes, 0};
}
// The new vbstate was the only thing to flush. All done.
flushSuccessEpilogue(*vb,
flushStart,
0 /*itemsFlushed*/,
aggStats,
commitData.collections);
return {moreAvailable, 0};
}
// The flush-batch must be non-empty by logic at this point.
Expects(flushBatchSize > 0);
// Release the memory allocated for vectors in toFlush before we call
// into KVStore::commit. This reduces memory peaks (every queued_item in
// toFlush.items is a pointer (8 bytes); also, having a big
// toFlush.ranges is not likely but may happen).
//
// Note:
// - std::vector::clear() leaves the capacity of vector unchanged,
// so memory is not released.
// - we cannot rely on clear() + shrink_to_fit() as the latter is a
// non-binding request to reduce capacity() to size(), it depends on
// the implementation whether the request is fulfilled.
{
const auto itemsToRelease = std::move(toFlush.items);
const auto rangesToRelease = std::move(toFlush.ranges);
}
// Persist the flush-batch.
if (!commit(*rwUnderlying, std::move(ctx), commitData)) {
flushFailureEpilogue(*vb, toFlush);
return {MoreAvailable::Yes, 0};
}
// Note: We want to update the snap-range only if we have flushed at least
// one item. I.e. don't appear to be in a snap when you have no data for it
Expects(range.has_value());
vb->setPersistedSnapshot(*range);
uint64_t highSeqno = rwUnderlying->getLastPersistedSeqno(vbid);
if (highSeqno > 0 && highSeqno != vb->getPersistenceSeqno()) {
vb->setPersistenceSeqno(highSeqno);
}
// Notify the local DM that the Flusher has run. Persistence
// could unblock some pending Prepares in the DM.
// If it is the case, this call updates the High Prepared Seqno
// for this node.
// In the case of a Replica node, that could trigger a SeqnoAck
// to the Active.
//
// Note: This is a NOP if the there's no Prepare queued in DM.
// We could notify the DM only if strictly required (i.e.,
// only when the Flusher has persisted up to the snap-end
// mutation of an in-memory snapshot, see HPS comments in
// PassiveDM for details), but that requires further work.
// The main problem is that in general a flush-batch does
// not coincide with in-memory snapshots (ie, we don't
// persist at snapshot boundaries). So, the Flusher could
// split a single in-memory snapshot into multiple
// flush-batches. That may happen at Replica, e.g.:
//
// 1) received snap-marker [1, 2]
// 2) received 1:PRE
// 3) flush-batch {1:PRE}
// 4) received 2:mutation
// 5) flush-batch {2:mutation}
//
// In theory we need to notify the DM only at step (5) and
// only if the the snapshot contains at least 1 Prepare
// (which is the case in our example), but the problem is
// that the Flusher doesn't know about 1:PRE at step (5).
//
// So, given that here we are executing in a slow bg-thread
// (write+sync to disk), then we can just afford to calling
// back to the DM unconditionally.
vb->notifyPersistenceToDurabilityMonitor();
flushSuccessEpilogue(*vb,
flushStart,
flushBatchSize /*itemsFlushed*/,
aggStats,
commitData.collections);
// Handle Seqno Persistence requests
vb->notifyHighPriorityRequests(engine, vb->getPersistenceSeqno());
return {moreAvailable, flushBatchSize};
}
void EPBucket::flushSuccessEpilogue(
VBucket& vb,
const std::chrono::steady_clock::time_point flushStart,
size_t itemsFlushed,
const AggregatedFlushStats& aggStats,
Collections::VB::Flush& collectionFlush) {
// Clear the flag if set (ie, only at vbucket creation)
if (vb.setBucketCreation(false)) {
EP_LOG_DEBUG("EPBucket::flushSuccessEpilogue: {} created", vb.getId());
}
// Update flush stats
const auto flushEnd = std::chrono::steady_clock::now();
const auto transTime =
std::chrono::duration_cast<std::chrono::milliseconds>(flushEnd -
flushStart)
.count();
const auto transTimePerItem =
itemsFlushed ? static_cast<double>(transTime) / itemsFlushed : 0;
lastTransTimePerItem.store(transTimePerItem);
stats.cumulativeFlushTime.fetch_add(transTime);
stats.flusher_todo.store(0);
stats.totalPersistVBState++;
++stats.flusherCommits;
vb.doAggregatedFlushStats(aggStats);
// By definition, does not need to be called if no flush performed or
// if flush failed.
collectionFlush.flushSuccess(vb.getId(), *this);
// By definition, this function is called after persisting a batch of
// data, so it can be safely skipped if no flush performed or if flush
// failed.
getRWUnderlying(vb.getId())->pendingTasks();
}
void EPBucket::flushFailureEpilogue(VBucket& vb, ItemsToFlush& flush) {
// Flush failed, we need to reset the pcursor to the original
// position. At the next run the flusher will re-attempt by retrieving
// all the items from the disk queue again.
flush.flushHandle->markFlushFailed(vb);
++stats.commitFailed;
}
void EPBucket::setFlusherBatchSplitTrigger(size_t limit) {
// If limit is lower than the number of writers then we should run with a
// limit of 1 as a 0 limit could cause us to fail to flush anything.
flusherBatchSplitTrigger =
std::max(size_t(1), limit / ExecutorPool::get()->getNumWriters());
}
size_t EPBucket::getFlusherBatchSplitTrigger() {
return flusherBatchSplitTrigger;
}
bool EPBucket::commit(KVStoreIface& kvstore,
std::unique_ptr<TransactionContext> txnCtx,
VB::Commit& commitData) {
HdrMicroSecBlockTimer timer(
&stats.diskCommitHisto, "disk_commit", stats.timingLog.get());
const auto commit_start = std::chrono::steady_clock::now();
auto vbid = txnCtx->vbid;
const auto res = kvstore.commit(std::move(txnCtx), commitData);
if (!res) {
EP_LOG_WARN("KVBucket::commit: kvstore.commit failed {}", vbid);
}
const auto commit_time =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - commit_start)
.count();
stats.commit_time.store(commit_time);
stats.cumulativeCommitTime.fetch_add(commit_time);
return res;
}
void EPBucket::startFlusher() {
for (const auto& flusher : flushers) {
flusher->start();
}
}
void EPBucket::stopFlusher() {
for (const auto& flusher : flushers) {
EP_LOG_INFO("Attempting to stop flusher:{}", flusher->getId());
bool rv = flusher->stop(stats.forceShutdown);
if (rv && !stats.forceShutdown) {
flusher->wait();
}
}
}
bool EPBucket::pauseFlusher() {
bool rv = true;
for (const auto& flusher : flushers) {
if (!flusher->pause()) {
EP_LOG_WARN(
"Attempted to pause flusher in state "
"[{}], flusher = {}",
flusher->stateName(),
flusher->getId());
rv = false;
}
}
return rv;
}
bool EPBucket::resumeFlusher() {
bool rv = true;
for (const auto& flusher : flushers) {
if (!flusher->resume()) {
EP_LOG_WARN(
"Attempted to resume flusher in state [{}], "
"flusher = {}",
flusher->stateName(),
flusher->getId());