/
magma-kvstore.cc
3022 lines (2651 loc) · 114 KB
/
magma-kvstore.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 "magma-kvstore.h"
#include "bucket_logger.h"
#include "collections/collection_persisted_stats.h"
#include "ep_engine.h"
#include "ep_time.h"
#include "item.h"
#include "kv_magma_common/magma-kvstore_metadata.h"
#include "kvstore/kvstore_transaction_context.h"
#include "magma-kvstore_config.h"
#include "magma-kvstore_iorequest.h"
#include "magma-memory-tracking-proxy.h"
#include "objectregistry.h"
#include "vb_commit.h"
#include "vbucket.h"
#include "vbucket_state.h"
#include <executor/executorpool.h>
#include <mcbp/protocol/unsigned_leb128.h>
#include <nlohmann/json.hpp>
#include <platform/cb_arena_malloc.h>
#include <statistics/cbstat_collector.h>
#include <utilities/logtags.h>
#include <algorithm>
#include <cstring>
#include <limits>
#include <utility>
class Snapshot;
using namespace magma;
using namespace std::chrono_literals;
// Keys to localdb docs
static const std::string vbstateKey = "_vbstate";
static const std::string manifestKey = "_collections/manifest";
static const std::string openCollectionsKey = "_collections/open";
static const std::string openScopesKey = "_scopes/open";
static const std::string droppedCollectionsKey = "_collections/dropped";
// Unfortunately, turning on logging for the tests is limited to debug
// mode. While we are in the midst of dropping in magma, this provides
// a simple way to change all the logging->trace calls to logging->debug
// by changing trace to debug..
// Once magma has been completed, we can remove this #define and change
// all the logging calls back to trace.
#define TRACE trace
namespace magmakv {
MetaData makeMetaData(const Item& it) {
auto metadata = MetaData();
if (it.isPending() || it.isAbort()) {
metadata.setVersion(MetaData::Version::V1);
} else {
metadata.setVersion(MetaData::Version::V0);
}
metadata.setBySeqno(it.getBySeqno());
metadata.setCas(it.getCas());
metadata.setRevSeqno(it.getRevSeqno());
metadata.setExptime(it.getExptime());
metadata.setFlags(it.getFlags());
metadata.setValueSize(it.getNBytes());
metadata.setDataType(it.getDataType());
if (it.isDeleted() && !it.isPending()) {
metadata.setDeleted(true, static_cast<bool>(it.deletionSource()));
}
if (it.isPending()) {
metadata.setDurabilityDetailsForPrepare(
it.isDeleted(),
static_cast<uint8_t>(it.getDurabilityReqs().getLevel()));
}
if (it.isAbort()) {
metadata.setDurabilityDetailsForAbort(it.getPrepareSeqno());
}
return metadata;
}
std::string MetaData::to_string() const {
std::stringstream ss;
auto level = static_cast<cb::durability::Level>(getDurabilityLevel());
cb::durability::Requirements req(level, {});
ss << "bySeqno:" << allMeta.v0.bySeqno << " cas:" << allMeta.v0.cas
<< " exptime:" << allMeta.v0.exptime
<< " revSeqno:" << allMeta.v0.revSeqno << " flags:" << allMeta.v0.flags
<< " valueSize:" << allMeta.v0.valueSize
<< " deleted:" << (allMeta.v0.bits.deleted == 0 ? "false" : "true")
<< " deleteSource:"
<< (allMeta.v0.bits.deleted == 0 ? " "
: allMeta.v0.bits.deleteSource == 0 ? "Explicit"
: "TTL")
<< " version:" << static_cast<uint8_t>(getVersion())
<< " datatype:" << allMeta.v0.datatype;
if (getVersion() == Version::V1) {
if (allMeta.v0.bits.deleted) {
// abort
ss << " prepareSeqno:"
<< allMeta.v1.durabilityDetails.completed.prepareSeqno;
} else {
// prepare
ss << " durabilityLevel:"
<< allMeta.v1.durabilityDetails.pending.level;
ss << " syncDelete:"
<< allMeta.v1.durabilityDetails.pending.isDelete;
}
}
return ss.str();
}
/**
* Magma stores an item in 3 slices... key, metadata, value
* See libmagma/slice.h for more info on slices.
*
* Helper functions to pull metadata stuff out of the metadata slice.
* The are used down in magma and are passed in as part of the configuration.
*/
static const MetaData getDocMeta(std::string_view meta) {
return MetaData(meta);
}
static const MetaData getDocMeta(const Slice& metaSlice) {
return getDocMeta(std::string_view{metaSlice.Data(), metaSlice.Len()});
}
static uint64_t getSeqNum(const Slice& metaSlice) {
return getDocMeta(metaSlice).getBySeqno();
}
static size_t getValueSize(const Slice& metaSlice) {
return getDocMeta(metaSlice).getValueSize();
}
static uint32_t getExpiryTime(const Slice& metaSlice) {
return getDocMeta(metaSlice).getExptime();
}
static bool isDeleted(const Slice& metaSlice) {
return getDocMeta(metaSlice).isDeleted();
}
static bool isCompressed(const Slice& metaSlice) {
return mcbp::datatype::is_snappy(getDocMeta(metaSlice).getDatatype());
}
static bool isPrepared(const Slice& keySlice, const Slice& metaSlice) {
return DiskDocKey(keySlice.Data(), keySlice.Len()).isPrepared() &&
!getDocMeta(metaSlice).isDeleted();
}
static bool isAbort(const Slice& keySlice, const Slice& metaSlice) {
return DiskDocKey(keySlice.Data(), keySlice.Len()).isPrepared() &&
getDocMeta(metaSlice).isDeleted();
}
} // namespace magmakv
MagmaRequest::MagmaRequest(queued_item it, std::shared_ptr<BucketLogger> logger)
: IORequest(std::move(it)),
docMeta(magmakv::makeMetaData(*item).encode()),
docBody(item->getValue()) {
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE("MagmaRequest:{}", to_string());
}
}
std::string MagmaRequest::to_string() {
std::stringstream ss;
ss << "Key:" << key.to_string()
<< " docMeta:" << magmakv::getDocMeta(getDocMeta()).to_string()
<< " itemOldExists:" << (itemOldExists ? "true" : "false")
<< " itemOldIsDelete:" << (itemOldIsDelete ? "true" : "false");
return ss.str();
}
static DiskDocKey makeDiskDocKey(const Slice& key) {
return DiskDocKey{key.Data(), key.Len()};
}
MagmaKVStore::MagmaCompactionCB::MagmaCompactionCB(
MagmaKVStore& magmaKVStore,
Vbid vbid,
std::shared_ptr<CompactionContext> ctx)
: magmaKVStore(magmaKVStore), vbid(vbid), ctx(std::move(ctx)) {
magmaKVStore.logger->TRACE("MagmaCompactionCB constructor");
}
MagmaKVStore::MagmaCompactionCB::~MagmaCompactionCB() {
magmaKVStore.logger->debug("MagmaCompactionCB destructor");
}
struct MagmaKVStoreTransactionContext : public TransactionContext {
MagmaKVStoreTransactionContext(KVStore& kvstore,
Vbid vbid,
std::unique_ptr<PersistenceCallback> cb)
: TransactionContext(kvstore, vbid, std::move(cb)) {
}
/**
* Container for pending Magma requests.
*
* Using deque as as the expansion behaviour is less aggressive compared to
* std::vector (MagmaRequest objects are ~176 bytes in size).
*/
using PendingRequestQueue = std::deque<MagmaRequest>;
PendingRequestQueue pendingReqs;
};
bool MagmaKVStore::compactionCallBack(MagmaKVStore::MagmaCompactionCB& cbCtx,
const magma::Slice& keySlice,
const magma::Slice& metaSlice,
const magma::Slice& valueSlice) {
Expects(currEngine == ObjectRegistry::getCurrentEngine());
// If we are compacting the localDb, items don't have metadata so
// we always keep everything.
if (metaSlice.Len() == 0) {
return false;
}
auto vbid = cbCtx.vbid;
std::string userSanitizedItemStr;
if (logger->should_log(spdlog::level::TRACE)) {
userSanitizedItemStr =
"key:" +
cb::UserData{makeDiskDocKey(keySlice).to_string()}
.getSanitizedValue() +
" " + magmakv::getDocMeta(metaSlice).to_string();
logger->TRACE("MagmaCompactionCB: {} {}", vbid, userSanitizedItemStr);
}
if (!cbCtx.ctx) {
// Don't already have a compaction context (i.e. this is the first
// key for an implicit compaction) - attempt to create one.
// Note that Magma implicit (internal) compactions can start _as soon
// as_ the Magma instance is Open()'d, which means this method can be
// called before Warmup has completed - and hence before
// makeCompactionContextCallback is assigned to a non-empty value.
// Until warmup *does* complete it isn't possible for us to know how
// to correctly deal with those keys - for example need to have
// initialised document counters during warmup to be able to update
// counter on TTL expiry. As such, until we have a non-empty
// makeCompactionContextCallback, simply return false.
if (!makeCompactionContextCallback) {
return false;
}
cbCtx.ctx = makeCompactionContext(vbid);
cbCtx.implicitCompaction = true;
}
auto seqno = magmakv::getSeqNum(metaSlice);
auto exptime = magmakv::getExpiryTime(metaSlice);
// function to update the purge seqno when we're dropping a document if this
// method is being called for implicit compaction
auto maybeUpdatePurgeSeqno = [&cbCtx, &seqno]() -> void {
if (cbCtx.implicitCompaction) {
cbCtx.ctx->maybeUpdatePurgeSeqno(seqno);
}
};
if (cbCtx.ctx->droppedKeyCb) {
// We need to check both committed and prepared documents - if the
// collection has been logically deleted then we need to discard
// both types of keys.
// As such use the docKey (i.e. without any DurabilityPrepare
// namespace) when checking if logically deleted;
auto diskKey = makeDiskDocKey(keySlice);
if (cbCtx.ctx->eraserContext->isLogicallyDeleted(diskKey.getDocKey(),
seqno)) {
// Inform vb that the key@seqno is dropped
cbCtx.ctx->droppedKeyCb(diskKey,
seqno,
magmakv::isAbort(keySlice, metaSlice),
cbCtx.ctx->highCompletedSeqno);
if (magmakv::isPrepared(keySlice, metaSlice)) {
cbCtx.ctx->stats.preparesPurged++;
} else {
if (magmakv::isDeleted(metaSlice)) {
cbCtx.ctx->stats.collectionsDeletedItemsPurged++;
}
}
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE(
"MagmaKVStore::MagmaCompactionCallback: DROP "
"collections "
"{}",
userSanitizedItemStr);
}
maybeUpdatePurgeSeqno();
return true;
}
}
if (magmakv::isDeleted(metaSlice)) {
uint64_t maxSeqno;
auto status = magma->GetMaxSeqno(vbid.get(), maxSeqno);
if (!status) {
throw std::runtime_error("MagmaCompactionCallback: Failed : " +
vbid.to_string() + " " + status.String());
}
// A bunch of DCP code relies on us keeping the last item (it may be a
// tombstone) so we can't purge the item at maxSeqno.
if (seqno != maxSeqno) {
bool drop = false;
if (cbCtx.ctx->compactConfig.drop_deletes) {
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE("MagmaCompactionCB: {} DROP drop_deletes {}",
vbid,
userSanitizedItemStr);
}
drop = true;
}
if (exptime && exptime < cbCtx.ctx->compactConfig.purge_before_ts) {
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE(
"MagmaCompactionCB: {} DROP expired tombstone {}",
vbid,
userSanitizedItemStr);
}
drop = true;
}
if (drop) {
cbCtx.ctx->stats.tombstonesPurged++;
if (cbCtx.ctx->max_purged_seq < seqno) {
cbCtx.ctx->max_purged_seq = seqno;
}
auto& dbStats = cbCtx.magmaDbStats;
if (dbStats.purgeSeqno < seqno) {
dbStats.purgeSeqno = seqno;
}
maybeUpdatePurgeSeqno();
return true;
}
}
} else {
// We can remove any prepares that have been completed. This works
// because we send Mutations instead of Commits when streaming from
// Disk so we do not need to send a Prepare message to keep things
// consistent on a replica.
if (magmakv::isPrepared(keySlice, metaSlice)) {
if (seqno <= cbCtx.ctx->highCompletedSeqno) {
cbCtx.ctx->stats.preparesPurged++;
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE(
"MagmaKVStore::MagmaCompactionCallback: "
"DROP prepare {}",
userSanitizedItemStr);
}
maybeUpdatePurgeSeqno();
return true;
}
}
time_t timeToExpireFrom;
if (cbCtx.ctx->timeToExpireFrom) {
timeToExpireFrom = cbCtx.ctx->timeToExpireFrom.value();
} else {
timeToExpireFrom = ep_real_time();
}
if (exptime && exptime < timeToExpireFrom &&
!magmakv::isPrepared(keySlice, metaSlice)) {
auto docMeta = magmakv::getDocMeta(metaSlice);
auto itm =
std::make_unique<Item>(makeDiskDocKey(keySlice).getDocKey(),
docMeta.getFlags(),
docMeta.getExptime(),
valueSlice.Data(),
valueSlice.Len(),
docMeta.getDatatype(),
docMeta.getCas(),
docMeta.getBySeqno(),
vbid,
docMeta.getRevSeqno());
if (magmakv::isCompressed(metaSlice)) {
itm->decompressValue();
}
itm->setDeleted(DeleteSource::TTL);
cbCtx.ctx->expiryCallback->callback(*(itm.get()), timeToExpireFrom);
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE("MagmaCompactionCB: {} expiry callback {}",
vbid,
userSanitizedItemStr);
}
}
}
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE(
"MagmaCompactionCB: {} KEEP {}", vbid, userSanitizedItemStr);
}
return false;
}
MagmaKVStore::MagmaKVStore(MagmaKVStoreConfig& configuration)
: KVStore(),
configuration(configuration),
magmaPath(configuration.getDBName() + "/magma." +
std::to_string(configuration.getShardId())),
scanCounter(0),
currEngine(ObjectRegistry::getCurrentEngine()) {
configuration.magmaCfg.Path = magmaPath;
configuration.magmaCfg.MaxKVStores = configuration.getMaxVBuckets();
configuration.magmaCfg.MaxKVStoreLSDBufferSize =
configuration.getMagmaDeleteMemtableWritecache();
configuration.magmaCfg.LSDFragmentationRatio =
configuration.getMagmaDeleteFragRatio();
configuration.magmaCfg.MaxCheckpoints =
configuration.getMagmaMaxCheckpoints();
configuration.magmaCfg.CheckpointCreationInterval =
configuration.getMagmaCheckpointInterval();
configuration.magmaCfg.CheckpointCreationThreshold =
configuration.getMagmaCheckpointThreshold();
configuration.magmaCfg.HeartbeatInterval =
configuration.getMagmaHeartbeatInterval();
configuration.magmaCfg.MinValueSize =
configuration.getMagmaValueSeparationSize();
configuration.magmaCfg.MaxWriteCacheSize =
configuration.getMagmaMaxWriteCache();
configuration.magmaCfg.WALBufferSize =
configuration.getMagmaInitialWalBufferSize();
configuration.magmaCfg.EnableWAL = configuration.getMagmaEnableWAL();
configuration.magmaCfg.EnableGroupCommit =
configuration.getMagmaEnableGroupCommit();
configuration.magmaCfg.GroupCommitMaxSyncWaitDuration =
configuration.getMagmaGroupCommitMaxSyncWaitDuration();
configuration.magmaCfg.GroupCommitMaxTransactionCount =
configuration.getMagmaGroupCommitMaxTransactionCount();
configuration.magmaCfg.ExpiryFragThreshold =
configuration.getMagmaExpiryFragThreshold();
configuration.magmaCfg.KVStorePurgerInterval =
configuration.getMagmaExpiryPurgerInterval();
configuration.magmaCfg.GetSeqNum = magmakv::getSeqNum;
configuration.magmaCfg.GetExpiryTime = [this](const magma::Slice& slice) {
return getExpiryOrPurgeTime(slice);
};
configuration.magmaCfg.GetValueSize = magmakv::getValueSize;
configuration.magmaCfg.IsTombstone = magmakv::isDeleted;
configuration.magmaCfg.EnableDirectIO =
configuration.getMagmaEnableDirectIo();
configuration.magmaCfg.EnableBlockCache =
configuration.getMagmaEnableBlockCache();
configuration.magmaCfg.WriteCacheRatio =
configuration.getMagmaWriteCacheRatio();
configuration.magmaCfg.MaxRecoveryBytes =
configuration.getMagmaMaxRecoveryBytes();
configuration.magmaCfg.LSMMaxLevel0CompactionTTL =
configuration.getMagmaMaxLevel0TTL();
configuration.magmaCfg.BloomFilterAccuracy =
configuration.getMagmaBloomFilterAccuracy();
configuration.magmaCfg.BloomFilterAccuracyForBottomLevel =
configuration.getMagmaBloomFilterAccuracyForBottomLevel();
configuration.setStore(this);
magma::SetMaxOpenFiles(configuration.getMaxFileDescriptors());
// To save memory only allocate counters for the number of vBuckets that
// this shard will have to deal with
auto cacheSize = getCacheSize();
cachedVBStates.resize(cacheSize);
inTransaction = std::vector<std::atomic_bool>(cacheSize);
kvstoreRevList.resize(cacheSize, Monotonic<uint64_t>(0));
useUpsertForSet = configuration.getMagmaEnableUpsert();
if (useUpsertForSet) {
configuration.magmaCfg.EnableUpdateStatusForSet = false;
} else {
configuration.magmaCfg.EnableUpdateStatusForSet = true;
}
doCheckpointEveryBatch = configuration.getMagmaCheckpointEveryBatch();
// If currEngine is null, which can happen with some tests,
// that is ok because a null currEngine means we are operating
// in a global environment.
configuration.magmaCfg.ExecutionEnv = currEngine;
configuration.magmaCfg.SwitchExecutionEnvFunc =
[](void* env) -> EventuallyPersistentEngine* {
auto eng = static_cast<EventuallyPersistentEngine*>(env);
return ObjectRegistry::onSwitchThread(
eng,
true,
eng ? cb::MemoryDomain::Secondary : cb::MemoryDomain::Primary);
};
configuration.magmaCfg.MakeCompactionCallback =
[&](const Magma::KVStoreID kvID) {
return std::make_unique<MagmaKVStore::MagmaCompactionCB>(
*this, Vbid(kvID));
};
configuration.magmaCfg.MakeUserStats = []() {
return std::make_unique<MagmaDbStats>();
};
// Create the data directory.
createDataDir(configuration.magmaCfg.Path);
// Create a logger that is prefixed with magma so that all code from
// wrapper down through magma uses this logger. As the spdlog API does not
// set their log functions to virtual and magma needs to maintain some
// separation from KV it does not use the BucketLogger log functions which
// prefix the engine name. As such we have to manually add the prefix to the
// logger name/prefix here.
EventuallyPersistentEngine* engine = ObjectRegistry::getCurrentEngine();
// Some tests may not have an engine.
std::string loggerName;
if (engine) {
loggerName += '(' + engine->getName() + ") ";
}
loggerName += "magma_" + std::to_string(configuration.getShardId());
logger = BucketLogger::createBucketLogger(loggerName);
configuration.magmaCfg.LogContext = logger;
configuration.magmaCfg.UID = loggerName;
// Open the magma instance for this shard and populate the vbstate.
magma = std::make_unique<MagmaMemoryTrackingProxy>(configuration.magmaCfg);
auto status = magma->Open();
if (status.ErrorCode() == Status::Code::DiskFull) {
// Magma construction needs to recover and replay all WAL ops to provide
// us a consistent state. Magma may require disk space to do so. We
// are required to provide a read only view of the data for recovery
// should a disk become unwriteable. To accomplish this magma has a
// read only mode that be constructed to give us a consistent view of
// data without performing recovery. This read only instance cannot be
// written to so it can only be used in an emergency should the disk be
// full.
//
// It is worth noting that nothing in kv_engine will modify this magma
// instance to make it writeable should the disk stop being full. A
// restart is required. We /could/ write code to swap the instance but
// it's probably not going to be trivial and we don't expect to run out
// of disk space very often so it's of questionable worth.
logger->warn(
"MagmaKVStore::MagmaKVStore: opening in read only mode as "
"magma reported a disk full error");
configuration.setReadOnly(true);
magma = std::make_unique<MagmaMemoryTrackingProxy>(
configuration.magmaCfg);
status = magma->Open();
}
if (!status) {
std::string err =
"MagmaKVStore Magma open failed. Status:" + status.String();
logger->critical(err);
throw std::logic_error(err);
}
setMaxDataSize(configuration.getBucketQuota());
setMagmaFragmentationPercentage(
configuration.getMagmaFragmentationPercentage());
calculateAndSetMagmaThreads();
magma->executeOnKVStoreList(
[this](const std::vector<magma::Magma::KVStoreID>& kvstores) {
cb::UseArenaMallocPrimaryDomain domainGuard;
for (auto kvid : kvstores) {
auto status = loadVBStateCache(Vbid(kvid), true);
++st.numLoadedVb;
if (!status) {
throw std::logic_error("MagmaKVStore vbstate vbid:" +
std::to_string(kvid) +
" not found."
" Status:" +
status.String());
}
}
});
}
MagmaKVStore::~MagmaKVStore() {
logger->unregister();
}
void MagmaKVStore::deinitialize() {
logger->info("MagmaKVStore: {} deinitializing", configuration.getShardId());
magma->Sync(true);
// Close shuts down all of the magma background threads (compaction is the
// one that we care about here). The compaction callbacks require the magma
// instance to exist so we must do this before we reset it.
magma->Close();
// Flusher should have already been stopped so it should be safe to destroy
// the magma instance now
magma.reset();
logger->info("MagmaKVStore: {} deinitialized", configuration.getShardId());
}
std::string MagmaKVStore::getVBDBSubdir(Vbid vbid) {
return magmaPath + std::to_string(vbid.get());
}
bool MagmaKVStore::commit(std::unique_ptr<TransactionContext> txnCtx,
VB::Commit& commitData) {
checkIfInTransaction(txnCtx->vbid, "MagmaKVStore::commit");
auto& ctx = dynamic_cast<MagmaKVStoreTransactionContext&>(*txnCtx);
if (ctx.pendingReqs.size() == 0) {
return true;
}
kvstats_ctx kvctx(commitData);
bool success = true;
// Flush all documents to disk
auto errCode = saveDocs(ctx, commitData, kvctx);
if (errCode != static_cast<int>(cb::engine_errc::success)) {
logger->warn("MagmaKVStore::commit: saveDocs {} errCode:{}",
txnCtx->vbid,
errCode);
success = false;
}
postFlushHook();
commitCallback(ctx, errCode, kvctx);
// This behaviour is to replicate the one in Couchstore.
// Set `in_transanction = false` only if `commit` is successful.
if (success) {
updateCachedVBState(txnCtx->vbid, commitData.proposedVBState);
}
logger->TRACE("MagmaKVStore::commit success:{}", success);
return success;
}
void MagmaKVStore::commitCallback(MagmaKVStoreTransactionContext& txnCtx,
int errCode,
kvstats_ctx&) {
const auto flushSuccess = (errCode == Status::Code::Ok);
for (const auto& req : txnCtx.pendingReqs) {
size_t mutationSize = req.getRawKeyLen() + req.getBodySize() +
req.getDocMeta().size();
st.io_num_write++;
st.io_document_write_bytes += mutationSize;
if (req.isDelete()) {
FlushStateDeletion state;
if (flushSuccess) {
if (req.oldItemExists() && !req.oldItemIsDelete()) {
// Deletion is for an existing item on disk
state = FlushStateDeletion::Delete;
} else {
// Deletion is for a non-existing item on disk
state = FlushStateDeletion::DocNotFound;
}
st.delTimeHisto.add(req.getDelta());
} else {
state = FlushStateDeletion::Failed;
++st.numDelFailure;
}
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE(
"MagmaKVStore::commitCallback(Delete) {} key:{} "
"errCode:{} "
"deleteState:{}",
txnCtx.vbid,
cb::UserData(req.getKey().to_string()),
errCode,
to_string(state));
}
txnCtx.deleteCallback(req.getItem(), state);
} else {
FlushStateMutation state;
if (flushSuccess) {
if (req.oldItemExists() && !req.oldItemIsDelete()) {
// Mutation is for an existing item on disk
state = FlushStateMutation::Update;
} else {
// Mutation is for a non-existing item on disk
state = FlushStateMutation::Insert;
}
st.writeTimeHisto.add(req.getDelta());
st.writeSizeHisto.add(mutationSize);
} else {
state = FlushStateMutation::Failed;
++st.numSetFailure;
}
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE(
"MagmaKVStore::commitCallback(Set) {} key:{} "
"errCode:{} "
"setState:{}",
txnCtx.vbid,
cb::UserData(req.getKey().to_string()),
errCode,
to_string(state));
}
txnCtx.setCallback(req.getItem(), state);
}
}
}
StorageProperties MagmaKVStore::getStorageProperties() const {
StorageProperties rv(StorageProperties::ByIdScan::No,
// @TODO MB-33784: Enable auto de-dupe if/when magma
// supports it
StorageProperties::AutomaticDeduplication::No,
StorageProperties::PrepareCounting::No,
StorageProperties::CompactionStaleItemCallbacks::Yes);
return rv;
}
void MagmaKVStore::setMaxDataSize(size_t size) {
configuration.setBucketQuota(size);
const size_t memoryQuota = (size / configuration.getMaxShards()) *
configuration.getMagmaMemQuotaRatio();
magma->SetMemoryQuota(memoryQuota);
}
// Note: This routine is only called during warmup. The caller
// can not make changes to the vbstate or it would cause race conditions.
std::vector<vbucket_state*> MagmaKVStore::listPersistedVbuckets() {
std::vector<vbucket_state*> result;
Vbid vbid(0);
for (const auto& vb : cachedVBStates) {
if (vb) {
mergeMagmaDbStatsIntoVBState(*vb, vbid);
}
result.emplace_back(vb.get());
vbid++;
}
return result;
}
void MagmaKVStore::set(TransactionContext& txnCtx, queued_item item) {
checkIfInTransaction(txnCtx.vbid, "MagmaKVStore::set");
auto& ctx = static_cast<MagmaKVStoreTransactionContext&>(txnCtx);
ctx.pendingReqs.emplace_back(std::move(item), logger);
}
GetValue MagmaKVStore::get(const DiskDocKey& key,
Vbid vb,
ValueFilter filter) const {
return getWithHeader(key, vb, filter);
}
GetValue MagmaKVStore::getWithHeader(const KVFileHandle& kvFileHandle,
const DiskDocKey& key,
Vbid vbid,
ValueFilter filter) const {
return getWithHeader(key, vbid, filter);
}
GetValue MagmaKVStore::getWithHeader(const DiskDocKey& key,
Vbid vbid,
ValueFilter filter) const {
Slice keySlice = {reinterpret_cast<const char*>(key.data()), key.size()};
Slice metaSlice;
Slice valueSlice;
DomainAwareFetchBuffer idxBuf;
DomainAwareFetchBuffer seqBuf;
bool found;
auto start = std::chrono::steady_clock::now();
Status status = magma->Get(
vbid.get(), keySlice, idxBuf, seqBuf, metaSlice, valueSlice, found);
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE(
"MagmaKVStore::getWithHeader {} key:{} status:{} found:{} "
"deleted:{}",
vbid,
cb::UserData{key.to_string()},
status.String(),
found,
found ? magmakv::isDeleted(metaSlice) : false);
}
if (!status) {
logger->warn("MagmaKVStore::getWithHeader {} key:{} status:{}",
vbid,
cb::UserData{makeDiskDocKey(keySlice).to_string()},
status.String());
st.numGetFailure++;
return GetValue{nullptr, magmaErr2EngineErr(status.ErrorCode())};
}
if (!found) {
// Whilst this isn't strictly a failure if we're running full eviction
// it could be considered one for value eviction.
st.numGetFailure++;
return GetValue{nullptr, cb::engine_errc::no_such_key};
}
// record stats
st.readTimeHisto.add(std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - start));
st.readSizeHisto.add(keySlice.Len() + metaSlice.Len() + valueSlice.Len());
++st.io_bg_fetch_docs_read;
st.io_bgfetch_doc_bytes +=
keySlice.Len() + metaSlice.Len() + valueSlice.Len();
return makeGetValue(vbid, keySlice, metaSlice, valueSlice, filter);
}
using GetOperations = magma::OperationsList<Magma::GetOperation>;
void MagmaKVStore::getMulti(Vbid vbid, vb_bgfetch_queue_t& itms) const {
// Convert the vb_bgfetch_queue_t (which is a std::unordered_map
// under the covers) to a vector of GetOperations.
// Note: We can't pass vb_bgfetch_queue_t to GetDocs because GetDocs
// requires a list type which can be broken up for use by coroutines
// and a std::map doesn't support a numeric 'at' index.
GetOperations getOps;
for (auto& it : itms) {
auto& key = it.first;
getOps.Add(Magma::GetOperation(
{reinterpret_cast<const char*>(key.data()), key.size()},
&it.second));
}
auto cb = [this, &vbid](bool found,
Status status,
const Magma::GetOperation& op,
const Slice& metaSlice,
const Slice& valueSlice) {
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE(
"MagmaKVStore::getMulti {} key:{} status:{} found:{} "
"deleted:{}",
vbid,
cb::UserData{makeDiskDocKey(op.Key).to_string()},
status.String(),
found,
found ? magmakv::isDeleted(metaSlice) : false);
}
auto errCode = magmaErr2EngineErr(status.ErrorCode(), found);
auto* bg_itm_ctx =
reinterpret_cast<vb_bgfetch_item_ctx_t*>(op.UserContext);
bg_itm_ctx->value.setStatus(errCode);
if (found) {
bg_itm_ctx->value = makeGetValue(vbid,
op.Key,
metaSlice,
valueSlice,
bg_itm_ctx->getValueFilter());
GetValue* rv = &bg_itm_ctx->value;
for (auto& fetch : bg_itm_ctx->getRequests()) {
fetch->value = rv;
st.readTimeHisto.add(
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() -
fetch->initTime));
st.readSizeHisto.add(bg_itm_ctx->value.item->getKey().size() +
bg_itm_ctx->value.item->getNBytes());
}
++st.io_bg_fetch_docs_read;
st.io_bgfetch_doc_bytes +=
op.Key.Len() + metaSlice.Len() + valueSlice.Len();
} else {
if (!status) {
logger->critical(
"MagmaKVStore::getMulti::GetDocs {} key:{} status:{}, ",
vbid,
cb::UserData{makeDiskDocKey(op.Key).to_string()},
status.String());
st.numGetFailure++;
}
}
};
auto status = magma->GetDocs(vbid.get(), getOps, cb);
if (!status) {
logger->warn("MagmaKVStore::getMulti::GetDocs {} failed. Status:{}",
vbid,
status.String());
}
}
void MagmaKVStore::getRange(Vbid vbid,
const DiskDocKey& startKey,
const DiskDocKey& endKey,
ValueFilter filter,
const GetRangeCb& cb) const {
Slice startKeySlice = {reinterpret_cast<const char*>(startKey.data()),
startKey.size()};
Slice endKeySlice = {reinterpret_cast<const char*>(endKey.data()),
endKey.size()};
auto callback = [&](Slice& keySlice, Slice& metaSlice, Slice& valueSlice) {
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE(
"MagmaKVStore::getRange callback {} key:{} seqno:{} "
"deleted:{}",
vbid,
cb::UserData{makeDiskDocKey(keySlice).to_string()},
magmakv::getSeqNum(metaSlice),
magmakv::isDeleted(metaSlice));
}
if (magmakv::isDeleted(metaSlice)) {
return;
}
auto rv = makeGetValue(vbid, keySlice, metaSlice, valueSlice, filter);
cb(std::move(rv));
};
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE("MagmaKVStore::getRange {} start:{} end:{}",
vbid,
cb::UserData{makeDiskDocKey(startKeySlice).to_string()},
cb::UserData{makeDiskDocKey(endKeySlice).to_string()});
}
auto status = magma->GetRange(vbid.get(),
startKeySlice,
endKeySlice,
callback,
filter != ValueFilter::KEYS_ONLY);
if (!status) {
logger->critical(
"MagmaKVStore::getRange {} start:{} end:{} status:{}",
vbid,
cb::UserData{makeDiskDocKey(startKeySlice).to_string()},
cb::UserData{makeDiskDocKey(endKeySlice).to_string()},
status.String());
st.numGetFailure++;
}
}
void MagmaKVStore::del(TransactionContext& txnCtx, queued_item item) {
checkIfInTransaction(txnCtx.vbid, "MagmaKVStore::del");
auto& ctx = dynamic_cast<MagmaKVStoreTransactionContext&>(txnCtx);
ctx.pendingReqs.emplace_back(std::move(item), logger);
}
void MagmaKVStore::delVBucket(Vbid vbid, uint64_t kvstoreRev) {
auto status = magma->DeleteKVStore(
vbid.get(), static_cast<Magma::KVStoreRevision>(kvstoreRev));
logger->info(
"MagmaKVStore::delVBucket DeleteKVStore {} kvstoreRev:{}. "
"status:{}",
vbid,
kvstoreRev,
status.String());
}
void MagmaKVStore::prepareToCreateImpl(Vbid vbid) {
auto vbstate = getCachedVBucketState(vbid);
if (vbstate) {
vbstate->reset();
}
kvstoreRevList[getCacheSlot(vbid)]++;
logger->info("MagmaKVStore::prepareToCreateImpl {} kvstoreRev:{}",
vbid,
kvstoreRevList[getCacheSlot(vbid)]);
}
uint64_t MagmaKVStore::prepareToDeleteImpl(Vbid vbid) {
Status status;
Magma::KVStoreRevision kvsRev;
std::tie(status, kvsRev) = magma->GetKVStoreRevision(vbid.get());
if (!status) {
logger->critical(
"MagmaKVStore::prepareToDeleteImpl {} "
"GetKVStoreRevision failed. Status:{}",