/
magma-kvstore.cc
2629 lines (2310 loc) · 94.9 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 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 "magma-kvstore.h"
#include "bucket_logger.h"
#include "ep_time.h"
#include "item.h"
#include "magma-kvstore_config.h"
#include "magma-kvstore_iorequest.h"
#include "magma-kvstore_metadata.h"
#include "objectregistry.h"
#include "vb_commit.h"
#include "vbucket.h"
#include "vbucket_state.h"
#include <mcbp/protocol/request.h>
#include <nlohmann/json.hpp>
#include <statistics/cbstat_collector.h>
#include <utilities/logtags.h>
#include <string.h>
#include <algorithm>
#include <limits>
#include <utility>
#include <mcbp/protocol/unsigned_leb128.h>
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::MetaData(const Item& it)
: metaDataVersion(0),
bySeqno(it.getBySeqno()),
cas(it.getCas()),
revSeqno(it.getRevSeqno()),
exptime(it.getExptime()),
flags(it.getFlags()),
valueSize(it.getNBytes()),
vbid(it.getVBucketId().get()),
datatype(it.getDataType()),
prepareSeqno(it.getPrepareSeqno()) {
if (it.isDeleted()) {
deleted = 1;
deleteSource = static_cast<uint8_t>(it.deletionSource());
} else {
deleted = 0;
deleteSource = 0;
}
operation = static_cast<uint8_t>(toOperation(it.getOperation()));
durabilityLevel = static_cast<uint8_t>(it.getDurabilityReqs().getLevel());
}
MetaData::MetaData(bool isDeleted, uint32_t valueSize, int64_t seqno, Vbid vbid)
: metaDataVersion(0),
bySeqno(seqno),
cas(0),
revSeqno(0),
exptime(0),
flags(0),
valueSize(valueSize),
vbid(vbid.get()),
datatype(0),
operation(0),
durabilityLevel(0),
prepareSeqno(0) {
if (isDeleted) {
deleted = 1;
deleteSource = static_cast<uint8_t>(DeleteSource::Explicit);
} else {
deleted = 0;
deleteSource = 0;
}
}
cb::durability::Level MetaData::getDurabilityLevel() const {
return static_cast<cb::durability::Level>(durabilityLevel);
}
std::string MetaData::to_string(Operation op) const {
switch (op) {
case Operation::Mutation:
return "Mutation";
case Operation::PreparedSyncWrite:
return "PreparedSyncWrite";
case Operation::CommittedSyncWrite:
return "CommittedSyncWrite";
case Operation::Abort:
return "Abort";
}
return std::string{"Unknown:" + std::to_string(static_cast<uint8_t>(op))};
}
std::string MetaData::to_string() const {
std::stringstream ss;
int vers = metaDataVersion;
int dt = datatype;
cb::durability::Requirements req(getDurabilityLevel(), {});
ss << "bySeqno:" << bySeqno << " cas:" << cas << " exptime:" << exptime
<< " revSeqno:" << revSeqno << " flags:" << flags
<< " valueSize:" << valueSize << " vbid:" << vbid
<< " deleted:" << (deleted == 0 ? "false" : "true") << " deleteSource:"
<< (deleted == 0 ? " " : deleteSource == 0 ? "Explicit" : "TTL")
<< " version:" << vers << " datatype:" << dt
<< " operation:" << to_string(getOperation())
<< " durabilityLevel:" << cb::durability::to_string(req);
return ss.str();
}
MetaData::Operation MetaData::toOperation(queue_op op) {
switch (op) {
case queue_op::mutation:
case queue_op::system_event:
return Operation::Mutation;
case queue_op::pending_sync_write:
return Operation::PreparedSyncWrite;
case queue_op::commit_sync_write:
return Operation::CommittedSyncWrite;
case queue_op::abort_sync_write:
return Operation::Abort;
case queue_op::flush:
case queue_op::empty:
case queue_op::checkpoint_start:
case queue_op::checkpoint_end:
case queue_op::set_vbucket_state:
break;
}
throw std::invalid_argument(
"magma::MetaData::toOperation: Unsupported op " +
std::to_string(static_cast<uint8_t>(op)));
}
/**
* 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(const Slice& metaSlice) {
const auto* docMeta =
reinterpret_cast<MetaData*>(const_cast<char*>(metaSlice.Data()));
return *docMeta;
}
static uint64_t getSeqNum(const Slice& metaSlice) {
return getDocMeta(metaSlice).bySeqno;
}
static size_t getValueSize(const Slice& metaSlice) {
return getDocMeta(metaSlice).valueSize;
}
static uint32_t getExpiryTime(const Slice& metaSlice) {
return getDocMeta(metaSlice).exptime;
}
static bool isDeleted(const Slice& metaSlice) {
return getDocMeta(metaSlice).deleted > 0;
}
static bool isCompressed(const Slice& metaSlice) {
return mcbp::datatype::is_snappy(getDocMeta(metaSlice).datatype);
}
static Vbid getVbid(const Slice& metaSlice) {
return Vbid(getDocMeta(metaSlice).vbid);
}
static bool isPrepared(const Slice& metaSlice) {
return static_cast<MetaData::Operation>(getDocMeta(metaSlice).operation) ==
MetaData::Operation::PreparedSyncWrite;
}
static bool isAbort(const Slice& metaSlice) {
return static_cast<MetaData::Operation>(getDocMeta(metaSlice).operation) ==
MetaData::Operation::Abort;
}
} // namespace magmakv
MagmaRequest::MagmaRequest(queued_item it, std::shared_ptr<BucketLogger> logger)
: IORequest(std::move(it)),
docMeta(magmakv::MetaData(*item)),
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:" << docMeta.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, std::shared_ptr<CompactionContext> ctx)
: magmaKVStore(magmaKVStore), ctx(std::move(ctx)) {
magmaKVStore.logger->TRACE("MagmaCompactionCB constructor");
}
MagmaKVStore::MagmaCompactionCB::~MagmaCompactionCB() {
magmaKVStore.logger->debug("MagmaCompactionCB destructor");
}
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 = magmakv::getVbid(metaSlice);
auto& itemString = cbCtx.itemKeyBuf;
if (logger->should_log(spdlog::level::TRACE)) {
itemString.str(std::string());
itemString << "key:"
<< cb::UserData{makeDiskDocKey(keySlice).to_string()};
itemString << " ";
itemString << magmakv::getDocMeta(metaSlice).to_string();
logger->TRACE("MagmaCompactionCB: {} {}",
vbid,
cb::UserData(itemString.str()));
}
if (!cbCtx.ctx) {
// Don't already have a compaction context (i.e. this is the first
// key for an implicit compaction) - atempt 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 beforew 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);
}
auto seqno = magmakv::getSeqNum(metaSlice);
auto exptime = magmakv::getExpiryTime(metaSlice);
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(metaSlice), cbCtx.ctx->highCompletedSeqno);
{ // Locking scope for magmaDbStats
auto dbStats = cbCtx.magmaDbStats.stats.wlock();
if (magmakv::isPrepared(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 "
"{}",
itemString.str());
}
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,
cb::UserData(itemString.str()));
}
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,
cb::UserData(itemString.str()));
}
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.stats.wlock();
if (dbStats->purgeSeqno < seqno) {
dbStats->purgeSeqno = seqno;
}
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(metaSlice)) {
if (seqno <= cbCtx.ctx->highCompletedSeqno) {
cbCtx.ctx->stats.preparesPurged++;
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE(
"MagmaKVStore::MagmaCompactionCallback: "
"DROP prepare {}",
itemString.str());
}
return true;
}
}
time_t currTime = ep_real_time();
if (exptime && exptime < currTime) {
auto docMeta = magmakv::getDocMeta(metaSlice);
auto itm =
std::make_unique<Item>(makeDiskDocKey(keySlice).getDocKey(),
docMeta.flags,
docMeta.exptime,
valueSlice.Data(),
valueSlice.Len(),
docMeta.datatype,
docMeta.cas,
docMeta.bySeqno,
vbid,
docMeta.revSeqno);
if (magmakv::isCompressed(metaSlice)) {
itm->decompressValue();
}
itm->setDeleted(DeleteSource::TTL);
cbCtx.ctx->expiryCallback->callback(*(itm.get()), currTime);
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE("MagmaCompactionCB: {} expiry callback {}",
vbid,
cb::UserData(itemString.str()));
}
}
}
if (logger->should_log(spdlog::level::TRACE)) {
logger->TRACE("MagmaCompactionCB: {} KEEP {}",
vbid,
cb::UserData(itemString.str()));
}
return false;
}
MagmaKVStore::MagmaKVStore(MagmaKVStoreConfig& configuration)
: KVStore(),
configuration(configuration),
pendingReqs(std::make_unique<PendingRequestQueue>()),
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.WALSyncTime = 0ms;
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.setStore(this);
magma::SetMaxOpenFiles(configuration.getMaxFileDescriptors());
cachedVBStates.resize(configuration.getMaxVBuckets());
kvstoreRevList.resize(configuration.getMaxVBuckets(),
Monotonic<uint64_t>(0));
useUpsertForSet = configuration.getMagmaEnableUpsert();
if (useUpsertForSet) {
configuration.magmaCfg.EnableUpdateStatusForSet = false;
} else {
configuration.magmaCfg.EnableUpdateStatusForSet = true;
}
doCheckpointEveryBatch = configuration.getMagmaCheckpointEveryBatch();
// Set up thread and memory tracking.
// Please note... SetupThreadContext and ResetThreadContext
// will being removed once magma tracking is complete.
configuration.magmaCfg.SetupThreadContext = [this]() {
ObjectRegistry::onSwitchThread(currEngine, false);
};
configuration.magmaCfg.ResetThreadContext = []() {
ObjectRegistry::onSwitchThread(nullptr);
};
// 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);
};
configuration.magmaCfg.MakeCompactionCallback = [&]() {
return std::make_unique<MagmaKVStore::MagmaCompactionCB>(*this);
};
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 use this logger.
std::string loggerName =
"magma_" + std::to_string(configuration.getShardId());
logger = BucketLogger::createBucketLogger(loggerName, loggerName);
configuration.magmaCfg.LogContext = logger;
configuration.magmaCfg.UID = loggerName;
// Open the magma instance for this shard and populate the vbstate.
magma = std::make_unique<Magma>(configuration.magmaCfg);
auto 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();
auto kvstoreList = magma->GetKVStoreList();
for (auto& kvid : kvstoreList) {
// While loading the vbstate cache, set the kvstoreRev.
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() {
}
void MagmaKVStore::deinitialize() {
logger->debug("MagmaKVStore deinitialize");
if (!inTransaction) {
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();
}
std::string MagmaKVStore::getVBDBSubdir(Vbid vbid) {
return magmaPath + std::to_string(vbid.get());
}
bool MagmaKVStore::commit(VB::Commit& commitData) {
// This behaviour is to replicate the one in Couchstore.
// If `commit` is called when not in transaction, just return true.
if (!inTransaction) {
logger->warn("MagmaKVStore::commit called not in transaction");
return true;
}
if (pendingReqs->size() == 0) {
inTransaction = false;
return true;
}
kvstats_ctx kvctx(commitData);
bool success = true;
// Flush all documents to disk
auto errCode = saveDocs(commitData, kvctx);
if (errCode != ENGINE_SUCCESS) {
logger->warn("MagmaKVStore::commit: saveDocs {} errCode:{}",
pendingReqs->front().getVbID(),
errCode);
success = false;
}
if (postFlushHook) {
postFlushHook();
}
commitCallback(errCode, kvctx);
// This behaviour is to replicate the one in Couchstore.
// Set `in_transanction = false` only if `commit` is successful.
if (success) {
inTransaction = false;
transactionCtx.reset();
}
pendingReqs->clear();
logger->TRACE("MagmaKVStore::commit success:{}", success);
return success;
}
void MagmaKVStore::commitCallback(int errCode, kvstats_ctx&) {
const auto flushSuccess = (errCode == Status::Code::Ok);
for (const auto& req : *pendingReqs) {
size_t mutationSize =
req.getRawKeyLen() + req.getBodySize() + req.getMetaSize();
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;
}
logger->TRACE(
"MagmaKVStore::commitCallback(Delete) {} key:{} errCode:{} "
"deleteState:{}",
pendingReqs->front().getVbID(),
cb::UserData(req.getKey().to_string()),
errCode,
to_string(state));
transactionCtx->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;
}
logger->TRACE(
"MagmaKVStore::commitCallback(Set) {} key:{} errCode:{} "
"setState:{}",
pendingReqs->front().getVbID(),
cb::UserData(req.getKey().to_string()),
errCode,
to_string(state));
transactionCtx->setCallback(req.getItem(), state);
}
}
}
void MagmaKVStore::rollback() {
if (inTransaction) {
inTransaction = false;
transactionCtx.reset();
}
}
StorageProperties MagmaKVStore::getStorageProperties() {
StorageProperties rv(StorageProperties::EfficientVBDump::Yes,
StorageProperties::EfficientVBDeletion::Yes,
StorageProperties::PersistedDeletion::No,
StorageProperties::EfficientGet::Yes,
StorageProperties::ConcurrentWriteCompact::Yes,
StorageProperties::ByIdScan::No);
return rv;
}
void MagmaKVStore::setMaxDataSize(size_t 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(queued_item item) {
if (!inTransaction) {
throw std::logic_error(
"MagmaKVStore::set: inTransaction must be true to perform a "
"set operation.");
}
pendingReqs->emplace_back(std::move(item), logger);
}
GetValue MagmaKVStore::get(const DiskDocKey& key, Vbid vb, ValueFilter filter) {
return getWithHeader(key, vb, filter);
}
GetValue MagmaKVStore::getWithHeader(const KVFileHandle& kvFileHandle,
const DiskDocKey& key,
Vbid vbid,
ValueFilter filter) {
return getWithHeader(key, vbid, filter);
}
GetValue MagmaKVStore::getWithHeader(const DiskDocKey& key,
Vbid vbid,
ValueFilter filter) {
Slice keySlice = {reinterpret_cast<const char*>(key.data()), key.size()};
Slice metaSlice;
Slice valueSlice;
Magma::FetchBuffer idxBuf;
Magma::FetchBuffer 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{NULL, 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{NULL, ENGINE_KEY_ENOENT};
}
// 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) {
// 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,
const GetRangeCb& cb) {
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,
ValueFilter::VALUES_DECOMPRESSED);
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, true);
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::reset(Vbid vbid) {
auto vbstate = getVBucketState(vbid);
if (!vbstate) {
throw std::invalid_argument(
"MagmaKVStore::reset: No entry in cached "
"states for " +
vbid.to_string());
}
Status status;
Magma::KVStoreRevision kvsRev;
std::tie(status, kvsRev) = magma->GetKVStoreRevision(vbid.get());
if (!status) {
logger->critical(
"MagmaKVStore::reset GetKVStoreRevision failed. {} "
"status:{}",
vbid.to_string(),
status.String());
// Magma doesn't think the kvstore exists. We need to use
// the kvstore revision from kv engine and assume its
// the latest revision. This will allow DeleteKVStore to
// remove the kvstore path.
kvsRev = kvstoreRevList[vbid.get()];
}
status = magma->DeleteKVStore(vbid.get(), kvsRev);
if (!status) {
logger->critical(
"MagmaKVStore::reset DeleteKVStore {} failed. status:{}",
vbid,
status.String());
}
vbstate->reset();
status = writeVBStateToDisk(vbid, *vbstate);
if (!status) {
throw std::runtime_error("MagmaKVStore::reset writeVBStateToDisk " +
vbid.to_string() +
" failed. Status:" + status.String());
}
}
void MagmaKVStore::del(queued_item item) {
if (!inTransaction) {
throw std::logic_error(
"MagmaKVStore::del: inTransaction must be true to perform a "
"delete operation.");
}
pendingReqs->emplace_back(std::move(item), logger);
}
void MagmaKVStore::delVBucket(Vbid vbid, uint64_t vb_version) {
auto status = magma->DeleteKVStore(
vbid.get(), static_cast<Magma::KVStoreRevision>(vb_version));
logger->info("MagmaKVStore::delVBucket DeleteKVStore {} {}. status:{}",
vbid,
vb_version,
status.String());
}
void MagmaKVStore::prepareToCreateImpl(Vbid vbid) {
auto vbstate = getVBucketState(vbid);
if (vbstate) {
vbstate->reset();
}
kvstoreRevList[vbid.get()]++;
logger->info("MagmaKVStore::prepareToCreateImpl {} kvstoreRev:{}",
vbid,
kvstoreRevList[vbid.get()]);
}
uint64_t MagmaKVStore::prepareToDeleteImpl(Vbid vbid) {
Status status;