-
Notifications
You must be signed in to change notification settings - Fork 60
/
couch-kvstore.cc
4325 lines (3809 loc) · 160 KB
/
couch-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 2015-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 "couch-kvstore/couch-kvstore.h"
#include "bucket_logger.h"
#include "collections/collection_persisted_stats.h"
#include "couch-kvstore-config.h"
#include "couch-kvstore-db-holder.h"
#include "diskdockey.h"
#include "ep_time.h"
#include "getkeys.h"
#include "item.h"
#include "kvstore_config.h"
#include "persistence_callback.h"
#include "rollback_result.h"
#include "vb_commit.h"
#include "vbucket.h"
#include "vbucket_bgfetch_item.h"
#include "vbucket_state.h"
#include <JSON_checker.h>
#include <mcbp/protocol/unsigned_leb128.h>
#include <memcached/isotime.h>
#include <nlohmann/json.hpp>
#include <phosphor/phosphor.h>
#include <platform/compress.h>
#include <platform/dirutils.h>
#include <gsl/gsl>
#include <memory>
#include <shared_mutex>
#include <utility>
static int bySeqnoScanCallback(Db* db, DocInfo* docinfo, void* ctx);
static int byIdScanCallback(Db* db, DocInfo* docinfo, void* ctx);
static int getMultiCallback(Db* db, DocInfo* docinfo, void* ctx);
static bool endWithCompact(const std::string &filename) {
const std::string suffix{".compact"};
const auto pos = filename.rfind(suffix);
return pos != std::string::npos && (pos + suffix.size()) == filename.size();
}
static std::vector<std::string> discoverDbFiles(const std::string& dir) {
auto files = cb::io::findFilesContaining(dir, ".couch.");
std::vector<std::string>::iterator ii;
std::vector<std::string> filenames;
for (ii = files.begin(); ii != files.end(); ++ii) {
if (!endWithCompact(*ii)) {
filenames.push_back(*ii);
}
}
return filenames;
}
static bool allDigit(const std::string& input) {
size_t numchar = input.length();
for(size_t i = 0; i < numchar; ++i) {
if (!isdigit(input[i])) {
return false;
}
}
return !input.empty();
}
static std::string couchkvstore_strerrno(Db *db, couchstore_error_t err) {
std::array<char, 256> msg;
switch (err) {
case COUCHSTORE_ERROR_OPEN_FILE:
case COUCHSTORE_ERROR_READ:
case COUCHSTORE_ERROR_WRITE:
case COUCHSTORE_ERROR_FILE_CLOSE:
if (couchstore_last_os_error(db, msg.data(), msg.size()) ==
COUCHSTORE_SUCCESS) {
return {msg.data()};
}
return {"<error retrieving last_os_error>"};
case COUCHSTORE_ERROR_CORRUPT:
case COUCHSTORE_ERROR_CHECKSUM_FAIL:
if (couchstore_last_internal_error(db, msg.data(), msg.size()) ==
COUCHSTORE_SUCCESS) {
return {msg.data()};
}
return {"<error retrieving last_internal_error>"};
default:
return {"none"};
}
}
static DiskDocKey makeDiskDocKey(sized_buf buf) {
return DiskDocKey{buf.buf, buf.size};
}
static sized_buf to_sized_buf(const DiskDocKey& key) {
return {const_cast<char*>(reinterpret_cast<const char*>(key.data())),
key.size()};
}
static std::pair<couchstore_error_t, nlohmann::json> getLocalVbState(Db& db) {
auto [status, doc] =
cb::couchstore::openLocalDocument(db, "_local/vbstate");
if (status == COUCHSTORE_SUCCESS) {
try {
auto view = std::string_view{doc->json.buf, doc->json.size};
return {status, nlohmann::json::parse(view)};
} catch (const std::exception& e) {
return {COUCHSTORE_ERROR_CORRUPT, {}};
}
}
return {status, {}};
}
/**
* Helper function to create an Item from couchstore DocInfo & related types.
*/
static std::unique_ptr<Item> makeItemFromDocInfo(Vbid vbid,
const DocInfo& docinfo,
const MetaData& metadata,
sized_buf value,
bool fetchedCompressed) {
auto datatype = metadata.getDataType();
// If document was fetched compressed, then set SNAPPY flag for non-zero
// length documents.
if (fetchedCompressed && (value.size > 0)) {
datatype |= PROTOCOL_BINARY_DATATYPE_SNAPPY;
}
// Strip off the DurabilityPrepare namespace (if present) from the persisted
// dockey before we create the in-memory item.
auto item = std::make_unique<Item>(makeDiskDocKey(docinfo.id).getDocKey(),
metadata.getFlags(),
metadata.getExptime(),
value.buf,
value.size,
datatype,
metadata.getCas(),
docinfo.db_seq,
vbid,
docinfo.rev_seq);
if (docinfo.deleted) {
item->setDeleted(metadata.getDeleteSource());
}
if (metadata.getVersionInitialisedFrom() == MetaData::Version::V3) {
// Metadata is from a SyncWrite - update the Item appropriately.
switch (metadata.getDurabilityOp()) {
case queue_op::pending_sync_write:
// From disk we return an infinite timeout; as this could
// refer to an already-committed SyncWrite and hence timeout
// must be ignored.
item->setPendingSyncWrite({metadata.getDurabilityLevel(),
cb::durability::Timeout::Infinity()});
if (metadata.isPreparedSyncDelete()) {
item->setDeleted(DeleteSource::Explicit);
}
break;
case queue_op::commit_sync_write:
item->setCommittedviaPrepareSyncWrite();
item->setPrepareSeqno(metadata.getPrepareSeqno());
break;
case queue_op::abort_sync_write:
item->setAbortSyncWrite();
item->setPrepareSeqno(metadata.getPrepareSeqno());
break;
default:
throw std::logic_error("makeItemFromDocInfo: Invalid queue_op:" +
to_string(metadata.getDurabilityOp()));
}
}
return item;
}
static std::string getDBFileName(const std::string& dbname,
Vbid vbid,
uint64_t rev) {
return dbname + "/" + std::to_string(vbid.get()) + ".couch." +
std::to_string(rev);
}
/// @returns the document ID used to store cid
std::string CouchKVStore::getCollectionStatsLocalDocId(CollectionID cid) {
return fmt::format("|{:#x}|", uint32_t(cid));
}
/// @returns the cid from a document-ID (see getCollectionStatsLocalDocId)
CollectionID CouchKVStore::getCollectionIdFromStatsDocId(std::string_view id) {
// id is expected to be "|0x<id>|" min size is 5, i.e. "|0x0|"
if (id.size() < 5) {
throw std::logic_error(
"getCollectionIdFromStatsDocId: cannot convert id:" +
std::string(id));
}
id.remove_prefix(1); // |0x.. becomes 0x..
std::string tmp{id};
// @todo: switch to using from_chars which avoids the tmp std::string.
// this is dependent on compiler upgrade MB-45044
return std::stoul(tmp, nullptr, 16);
}
struct GetMultiCbCtx {
GetMultiCbCtx(CouchKVStore& c, Vbid v, vb_bgfetch_queue_t& f)
: cks(c), vbId(v), fetches(f) {
}
CouchKVStore &cks;
Vbid vbId;
vb_bgfetch_queue_t &fetches;
};
struct AllKeysCtx {
AllKeysCtx(std::shared_ptr<StatusCallback<const DiskDocKey&>> callback,
uint32_t cnt)
: cb(std::move(callback)), count(cnt) {
}
std::shared_ptr<StatusCallback<const DiskDocKey&>> cb;
uint32_t count;
};
class CouchKVFileHandle : public ::KVFileHandle {
public:
explicit CouchKVFileHandle(CouchKVStore& kvstore) : db(kvstore) {
}
~CouchKVFileHandle() override = default;
DbHolder& getDbHolder() {
return db;
}
Db* getDb() const {
return db.getDb();
}
private:
DbHolder db;
};
couchstore_content_meta_flags CouchRequest::getContentMeta(const Item& it) {
couchstore_content_meta_flags rval;
if (mcbp::datatype::is_json(it.getDataType())) {
rval = COUCH_DOC_IS_JSON;
} else {
rval = COUCH_DOC_NON_JSON_MODE;
}
if (it.getNBytes() > 0 && !mcbp::datatype::is_snappy(it.getDataType())) {
//Compress only if a value exists and is not already compressed
rval |= COUCH_DOC_IS_COMPRESSED;
}
return rval;
}
CouchRequest::CouchRequest(queued_item it)
: IORequest(std::move(it)), value(item->getValue()) {
dbDoc.id = to_sized_buf(getKey());
if (item->getNBytes()) {
dbDoc.data.buf = const_cast<char *>(value->getData());
dbDoc.data.size = item->getNBytes();
} else {
dbDoc.data.buf = nullptr;
dbDoc.data.size = 0;
}
meta.setCas(item->getCas());
meta.setFlags(item->getFlags());
meta.setExptime(item->getExptime());
meta.setDataType(item->getDataType());
const auto isDurabilityOp =
(item->getOperation() == queue_op::pending_sync_write ||
item->getOperation() == queue_op::commit_sync_write ||
item->getOperation() == queue_op::abort_sync_write);
if (isDurabilityOp) {
meta.setDurabilityOp(item->getOperation());
}
if (item->isPending()) {
// Note: durability timeout /isn't/ persisted as part of a pending
// SyncWrite. This is because if we ever read it back from disk
// during warmup (i.e. the commit_sync_write was never persisted), we
// don't know if the SyncWrite was actually already committed; as such
// to ensure consistency the pending SyncWrite *must* eventually commit
// (or sit in pending forever).
const auto level = item->getDurabilityReqs().getLevel();
meta.setPrepareProperties(level, item->isDeleted());
}
if (item->isCommitSyncWrite() || item->isAbort()) {
meta.setCompletedProperties(item->getPrepareSeqno());
}
dbDocInfo.db_seq = item->getBySeqno();
// Now allocate space to hold the meta and get it ready for storage
dbDocInfo.rev_meta.size = MetaData::getMetaDataSize(
isDurabilityOp ? MetaData::Version::V3 : MetaData::Version::V1);
dbDocInfo.rev_meta.buf = meta.prepareAndGetForPersistence();
dbDocInfo.rev_seq = item->getRevSeqno();
if (item->isDeleted() && !item->isPending()) {
// Prepared SyncDeletes are not marked as deleted.
dbDocInfo.deleted = 1;
meta.setDeleteSource(item->deletionSource());
} else {
dbDocInfo.deleted = 0;
}
dbDocInfo.id = dbDoc.id;
dbDocInfo.content_meta = getContentMeta(*item);
}
CouchRequest::~CouchRequest() = default;
namespace Collections {
static constexpr const char* manifestName = "_local/collections/manifest";
static constexpr const char* openCollectionsName = "_local/collections/open";
static constexpr const char* scopesName = "_local/scope/open";
static constexpr const char* droppedCollectionsName =
"_local/collections/dropped";
} // namespace Collections
CouchKVStore::CouchKVStore(const CouchKVStoreConfig& config)
: CouchKVStore(config, *couchstore_get_default_file_ops()) {
}
CouchKVStore::CouchKVStore(const CouchKVStoreConfig& config,
FileOpsInterface& ops,
bool readOnly,
std::shared_ptr<RevisionMap> revMap)
: KVStore(readOnly),
configuration(config),
dbname(config.getDBName()),
dbFileRevMap(std::move(revMap)),
logger(config.getLogger()),
base_ops(ops) {
if (!readOnly) {
vbCompactionRunning =
std::vector<std::atomic_bool>(configuration.getMaxVBuckets());
vbAbortCompaction =
std::vector<std::atomic_bool>(configuration.getMaxVBuckets());
}
statCollectingFileOps = getCouchstoreStatsOps(st.fsStats, base_ops);
statCollectingFileOpsCompaction = getCouchstoreStatsOps(
st.fsStatsCompaction, base_ops);
// init db file map with default revision number, 1
auto numDbFiles = configuration.getMaxVBuckets();
// pre-allocate lookup maps (vectors) given we have a relatively
// small, fixed number of vBuckets.
cachedDocCount.assign(numDbFiles, cb::RelaxedAtomic<size_t>(0));
cachedDeleteCount.assign(numDbFiles, cb::RelaxedAtomic<size_t>(0));
cachedFileSize.assign(numDbFiles, cb::RelaxedAtomic<uint64_t>(0));
cachedSpaceUsed.assign(numDbFiles, cb::RelaxedAtomic<uint64_t>(0));
cachedOnDiskPrepareSize.assign(numDbFiles, 0);
cachedVBStates.resize(numDbFiles);
}
// Helper function to create and resize the 'locked' vector
std::shared_ptr<CouchKVStore::RevisionMap> CouchKVStore::makeRevisionMap(
size_t vbucketCount) {
auto map = std::make_shared<RevisionMap>();
(*map->wlock()).resize(vbucketCount);
return map;
}
CouchKVStore::CouchKVStore(CreateReadWrite,
const CouchKVStoreConfig& config,
FileOpsInterface& ops)
: CouchKVStore(
config, ops, false, makeRevisionMap(config.getMaxVBuckets())) {
// 1) Create the data directory
createDataDir(dbname);
// 2) populate the dbFileRevMap which can remove old revisions, this returns
// a map, which the keys (vbid) will be needed for step 3 and 4.
auto map = populateRevMapAndRemoveStaleFiles();
// 3) clean up any .compact files
for (const auto& id : map) {
maybeRemoveCompactFile(dbname, id.first);
}
// 4) continue to intialise the store (reads vbstate etc...)
initialize(map);
}
CouchKVStore::CouchKVStore(CreateReadOnly,
const CouchKVStoreConfig& config,
FileOpsInterface& ops,
std::shared_ptr<RevisionMap> dbFileRevMap)
: CouchKVStore(config, ops, true, dbFileRevMap) {
// intialise the store (reads vbstate etc...)
initialize(getVbucketRevisions(discoverDbFiles(dbname)));
}
CouchKVStore::CouchKVStore(const CouchKVStoreConfig& config,
FileOpsInterface& ops)
: CouchKVStore(CreateReadWrite{}, config, ops) {
}
// Make a read-only CouchKVStore from this object
std::unique_ptr<CouchKVStore> CouchKVStore::makeReadOnlyStore() const {
// Can only make the RO store from an RW store
Expects(isReadWrite());
// Not using make_unique due to the private constructor we're calling
return std::unique_ptr<CouchKVStore>(
new CouchKVStore(CreateReadOnly{},
configuration,
*couchstore_get_default_file_ops(),
dbFileRevMap));
}
void CouchKVStore::initialize(
const std::unordered_map<Vbid, std::unordered_set<uint64_t>>& map) {
for (const auto& [vbid, revisions] : map) {
(void)revisions;
DbHolder db(*this);
const auto openRes = openDB(vbid, db, COUCHSTORE_OPEN_FLAG_RDONLY);
if (openRes != COUCHSTORE_SUCCESS) {
const auto msg = "CouchKVStore::initialize: openDB error:" +
std::string(couchstore_strerror(openRes)) +
", file_name:" +
getDBFileName(dbname, vbid, db.getFileRev());
throw std::runtime_error(msg);
}
const auto readRes = readVBStateAndUpdateCache(db, vbid).status;
if (readRes != ReadVBStateStatus::Success) {
const auto msg = "CouchKVStore::initialize: readVBState error:" +
to_string(readRes) + ", file_name:" +
getDBFileName(dbname, vbid, db.getFileRev());
// Note: The CorruptSnapshot error is a special case. That is
// generated for replica/pending vbuckets only and we want to
// continue as if the vbucket does not exist so it gets rebuilt from
// the active.
if (readRes == ReadVBStateStatus::CorruptSnapshot) {
logger.warn(msg);
continue;
}
logger.error(msg);
throw std::runtime_error(msg);
}
// Success, update stats
++st.numLoadedVb;
cachedDeleteCount[vbid.get()] =
cb::couchstore::getHeader(*db.getDb()).deletedCount;
cachedDocCount[vbid.get()] =
cb::couchstore::getHeader(*db.getDb()).docCount;
}
}
CouchKVStore::~CouchKVStore() {
close();
}
void CouchKVStore::set(queued_item item) {
if (isReadOnly()) {
throw std::logic_error("CouchKVStore::set: Not valid on a read-only "
"object.");
}
if (!inTransaction) {
throw std::invalid_argument(
"CouchKVStore::set: inTransaction must be "
"true to perform a set operation.");
}
// each req will be de-allocated after commit
pendingReqsQ.emplace_back(std::move(item));
}
GetValue CouchKVStore::get(const DiskDocKey& key, Vbid vb, ValueFilter filter) {
DbHolder db(*this);
couchstore_error_t errCode = openDB(vb, db, COUCHSTORE_OPEN_FLAG_RDONLY);
if (errCode != COUCHSTORE_SUCCESS) {
++st.numGetFailure;
logger.warn("CouchKVStore::get: openDB error:{}, {}",
couchstore_strerror(errCode),
vb);
return GetValue(nullptr, couchErr2EngineErr(errCode));
}
GetValue gv = getWithHeader(db, key, vb, filter);
return gv;
}
GetValue CouchKVStore::getWithHeader(const KVFileHandle& kvFileHandle,
const DiskDocKey& key,
Vbid vb,
ValueFilter filter) {
// const_cast away here, the lower level couchstore does not use const
auto& couchKvHandle = static_cast<CouchKVFileHandle&>(
const_cast<KVFileHandle&>(kvFileHandle));
return getWithHeader(couchKvHandle.getDbHolder(), key, vb, filter);
}
GetValue CouchKVStore::getWithHeader(DbHolder& db,
const DiskDocKey& key,
Vbid vb,
ValueFilter filter) {
auto start = std::chrono::steady_clock::now();
DocInfo *docInfo = nullptr;
GetValue rv;
sized_buf id = to_sized_buf(key);
couchstore_error_t errCode = couchstore_docinfo_by_id(db, (uint8_t *)id.buf,
id.size, &docInfo);
if (errCode != COUCHSTORE_SUCCESS) {
if (filter != ValueFilter::KEYS_ONLY) {
// log error only if this is non-xdcr case
logger.warn(
"CouchKVStore::getWithHeader: couchstore_docinfo_by_id "
"error:{} [{}], {}",
couchstore_strerror(errCode),
couchkvstore_strerrno(db, errCode),
vb);
}
} else {
if (docInfo == nullptr) {
throw std::logic_error("CouchKVStore::getWithHeader: "
"couchstore_docinfo_by_id returned success but docInfo "
"is NULL");
}
errCode = fetchDoc(db, docInfo, rv, vb, filter);
if (errCode != COUCHSTORE_SUCCESS) {
logger.warn(
"CouchKVStore::getWithHeader: fetchDoc error:{} [{}],"
" {}, deleted:{}",
couchstore_strerror(errCode),
couchkvstore_strerrno(db, errCode),
vb,
docInfo->deleted ? "yes" : "no");
}
// record stats
st.readTimeHisto.add(
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - start));
if (errCode == COUCHSTORE_SUCCESS) {
st.readSizeHisto.add(key.size() + rv.item->getNBytes());
}
}
if(errCode != COUCHSTORE_SUCCESS) {
++st.numGetFailure;
}
couchstore_free_docinfo(docInfo);
rv.setStatus(couchErr2EngineErr(errCode));
return rv;
}
void CouchKVStore::getMulti(Vbid vb, vb_bgfetch_queue_t& itms) {
if (itms.empty()) {
return;
}
int numItems = itms.size();
DbHolder db(*this);
couchstore_error_t errCode = openDB(vb, db, COUCHSTORE_OPEN_FLAG_RDONLY);
if (errCode != COUCHSTORE_SUCCESS) {
logger.warn(
"CouchKVStore::getMulti: openDB error:{}, "
"{}, numDocs:{}",
couchstore_strerror(errCode),
vb,
numItems);
st.numGetFailure += numItems;
for (auto& item : itms) {
item.second.value.setStatus(cb::engine_errc::not_my_vbucket);
}
return;
}
size_t idx = 0;
std::vector<sized_buf> ids(itms.size());
for (auto& item : itms) {
ids[idx] = to_sized_buf(item.first);
++idx;
}
GetMultiCbCtx ctx(*this, vb, itms);
errCode = couchstore_docinfos_by_id(
db, ids.data(), itms.size(), 0, getMultiCallback, &ctx);
if (errCode != COUCHSTORE_SUCCESS) {
st.numGetFailure += numItems;
logger.warn(
"CouchKVStore::getMulti: "
"couchstore_docinfos_by_id error {} [{}], {}",
couchstore_strerror(errCode),
couchkvstore_strerrno(db, errCode),
vb);
for (auto& item : itms) {
item.second.value.setStatus(couchErr2EngineErr(errCode));
}
}
// If available, record how many reads() we did for this getMulti;
// and the average reads per document.
auto* stats = couchstore_get_db_filestats(db);
if (stats != nullptr) {
const auto readCount = stats->getReadCount();
st.getMultiFsReadCount += readCount;
st.getMultiFsReadHisto.add(readCount);
st.getMultiFsReadPerDocHisto.add(readCount / itms.size());
}
}
void CouchKVStore::getRange(Vbid vb,
const DiskDocKey& startKey,
const DiskDocKey& endKey,
ValueFilter filter,
const KVStore::GetRangeCb& cb) {
DbHolder db(*this);
auto errCode = openDB(vb, db, COUCHSTORE_OPEN_FLAG_RDONLY);
if (errCode != COUCHSTORE_SUCCESS) {
throw std::runtime_error("CouchKVStore::getRange: openDB error for " +
vb.to_string() +
" - couchstore returned error: " +
couchstore_strerror(errCode));
}
// Trampoine's state. Cannot use lambda capture as couchstore expects a
// C-style callback.
struct TrampolineState {
Vbid vb;
const ValueFilter filter;
const DiskDocKey& endKey;
const KVStore::GetRangeCb& userFunc;
};
TrampolineState trampoline_state{vb, filter, endKey, cb};
// Trampoline to fetch the document value, and map C++ std::function to
// C-style callback expected by couchstore.
auto callback_trampoline = [](Db* db, DocInfo* docinfo, void* ctx) -> int {
auto& state = *reinterpret_cast<TrampolineState*>(ctx);
// Filter out (skip) any deleted items (couchstore_docinfos_by_id()
// returns both alive and deleted items).
if (docinfo->deleted) {
return COUCHSTORE_SUCCESS;
}
// Note: Unfortunately couchstore compares the endKey *inclusively* -
// i.e. it will return a document which has the key endKey. We only
// want to perform an exclusive search [start, end).
// Therefore, skip the last document if it's the same as the specified
// end key.
if (makeDiskDocKey(docinfo->id) == state.endKey) {
return COUCHSTORE_SUCCESS;
}
// Create metadata from the rev_meta.
std::unique_ptr<MetaData> metadata;
try {
metadata = MetaDataFactory::createMetaData(docinfo->rev_meta);
} catch (std::logic_error&) {
return COUCHSTORE_ERROR_DB_NO_LONGER_VALID;
}
// Fetch document value if requested.
const bool fetchCompressed =
(state.filter == ValueFilter::VALUES_COMPRESSED);
Doc* doc = nullptr;
if (state.filter != ValueFilter::KEYS_ONLY) {
const couchstore_open_options openOptions =
fetchCompressed ? 0 : DECOMPRESS_DOC_BODIES;
auto errCode = couchstore_open_doc_with_docinfo(
db, docinfo, &doc, openOptions);
if (errCode != COUCHSTORE_SUCCESS) {
// Failed to fetch document - cancel couchstore_docinfos_by_id
// scan.
return errCode;
}
}
auto value = doc ? doc->data : sized_buf{nullptr, 0};
state.userFunc(GetValue{makeItemFromDocInfo(
state.vb, *docinfo, *metadata, value, fetchCompressed)});
if (doc) {
couchstore_free_document(doc);
}
return COUCHSTORE_SUCCESS;
};
const std::array<sized_buf, 2> range = {
{to_sized_buf(startKey), to_sized_buf(endKey)}};
errCode = couchstore_docinfos_by_id(db.getDb(),
range.data(),
range.size(),
RANGES,
callback_trampoline,
&trampoline_state);
if (errCode != COUCHSTORE_SUCCESS) {
throw std::runtime_error(
"CouchKVStore::getRange: docinfos_by_id failed for " +
vb.to_string() + " - couchstore returned error: " +
couchstore_strerror(errCode));
}
}
void CouchKVStore::del(queued_item item) {
if (isReadOnly()) {
throw std::logic_error("CouchKVStore::del: Not valid on a read-only "
"object.");
}
if (!inTransaction) {
throw std::invalid_argument(
"CouchKVStore::del: inTransaction must be "
"true to perform a delete operation.");
}
pendingReqsQ.emplace_back(std::move(item));
}
void CouchKVStore::delVBucket(Vbid vbucket, uint64_t fileRev) {
if (isReadOnly()) {
throw std::logic_error("CouchKVStore::delVBucket: Not valid on a "
"read-only object.");
}
unlinkCouchFile(vbucket, fileRev);
}
std::vector<vbucket_state *> CouchKVStore::listPersistedVbuckets() {
std::vector<vbucket_state*> result;
for (const auto& vb : cachedVBStates) {
result.emplace_back(vb.get());
}
return result;
}
/**
* Notify the expiry callback that a document has expired
*
* @param info document information for the expired item
* @param metadata metadata of the document
* @param item buffer containing data and size
* @param ctx context for compaction
* @param currtime current time
*/
static int notify_expired_item(DocInfo& info,
MetaData& metadata,
sized_buf item,
CompactionContext& ctx,
time_t currtime) {
sized_buf data{nullptr, 0};
cb::compression::Buffer inflated;
if (mcbp::datatype::is_xattr(metadata.getDataType())) {
if (item.buf == nullptr) {
// We need to pass on the entire document to the callback
return COUCHSTORE_COMPACT_NEED_BODY;
}
// A document on disk is marked snappy in two ways.
// 1) info.content_meta if the document was compressed by couchstore
// 2) datatype snappy if the document was already compressed when stored
if ((info.content_meta & COUCH_DOC_IS_COMPRESSED) ||
mcbp::datatype::is_snappy(metadata.getDataType())) {
using namespace cb::compression;
if (!inflate(Algorithm::Snappy, {item.buf, item.size}, inflated)) {
EP_LOG_WARN(
"notify_expired_item: failed to inflate document with "
"seqno {} revno: {}",
info.db_seq,
info.rev_seq);
return COUCHSTORE_ERROR_CORRUPT;
}
// Now remove snappy bit
metadata.setDataType(metadata.getDataType() &
~PROTOCOL_BINARY_DATATYPE_SNAPPY);
data = {inflated.data(), inflated.size()};
}
}
auto it = makeItemFromDocInfo(ctx.vbid, info, metadata, data, false);
ctx.expiryCallback->callback(*it, currtime);
return COUCHSTORE_SUCCESS;
}
static int time_purge_hook(Db* d,
DocInfo* info,
sized_buf item,
CompactionContext* ctx) {
if (info == nullptr) {
// Compaction finished
return couchstore_set_purge_seq(d, ctx->max_purged_seq);
}
auto metadata = MetaDataFactory::createMetaData(info->rev_meta);
uint32_t exptime = metadata->getExptime();
// 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(info->id);
const auto& docKey = diskKey.getDocKey();
// Define a helper function for updating the collection sizes
auto maybeAccountForPurgedCollectionData = [ctx, docKey, info] {
if (!docKey.isInSystemCollection()) {
auto itr = ctx->stats.collectionSizeUpdates.emplace(
docKey.getCollectionID(), 0);
itr.first->second += info->getTotalSize();
}
};
if (ctx->eraserContext->isLogicallyDeleted(docKey, int64_t(info->db_seq))) {
// Inform vb that the key@seqno is dropped
try {
ctx->droppedKeyCb(diskKey,
int64_t(info->db_seq),
metadata->isAbort(),
ctx->highCompletedSeqno);
} catch (const std::exception& e) {
EP_LOG_WARN("time_purge_hook: droppedKeyCb exception: {}",
e.what());
return COUCHSTORE_ERROR_INVALID_ARGUMENTS;
}
if (metadata->isPrepare()) {
ctx->stats.preparesPurged++;
ctx->stats.prepareBytesPurged += info->getTotalSize();
// Track nothing for the individual collection as the stats doc has
// already been deleted.
} else {
if (!info->deleted) {
ctx->stats.collectionsItemsPurged++;
} else {
ctx->stats.collectionsDeletedItemsPurged++;
}
}
// No need to make 'disk-size' changes here as the collection has gone.
return COUCHSTORE_COMPACT_DROP_ITEM;
} else if (docKey.isInSystemCollection()) {
ctx->eraserContext->processSystemEvent(
docKey, SystemEvent(metadata->getFlags()));
}
if (info->deleted) {
const auto infoDb = cb::couchstore::getHeader(*d);
if (info->db_seq != infoDb.updateSeqNum) {
bool purgeItem = ctx->compactConfig.drop_deletes;
/**
* MB-30015: Found a tombstone whose expiry time is 0. Log this
* message because tombstones are expected to have a non-zero
* expiry time
*/
if (!exptime) {
EP_LOG_WARN(
"time_purge_hook: tombstone found with an"
" expiry time of 0");
}
if (exptime < ctx->compactConfig.purge_before_ts &&
(exptime || !ctx->compactConfig.retain_erroneous_tombstones) &&
(!ctx->compactConfig.purge_before_seq ||
info->db_seq <= ctx->compactConfig.purge_before_seq)) {
purgeItem = true;
}
if (purgeItem) {
// Maybe update purge seqno
if (ctx->max_purged_seq < info->db_seq) {
ctx->max_purged_seq = info->db_seq;
}
// Update stats and return
ctx->stats.tombstonesPurged++;
maybeAccountForPurgedCollectionData();
return COUCHSTORE_COMPACT_DROP_ITEM;
}
}
} 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 (metadata->isPrepare()) {
if (info->db_seq <= ctx->highCompletedSeqno) {
ctx->stats.preparesPurged++;
ctx->stats.prepareBytesPurged += info->getTotalSize();
// Decrement individual collection disk sizes as we track
// prepares in the value. We don't do this at collection drop
// as the stat doc will have already been deleted (for
// couchstore)
maybeAccountForPurgedCollectionData();
return COUCHSTORE_COMPACT_DROP_ITEM;
}
// Just keep the item if not complete. We should not attempt to
// expire a prepare and we do not want to update the bloom
// filter for a prepare either as that could cause us to run
// unnecessary BGFetches.
return COUCHSTORE_COMPACT_KEEP_ITEM;
}
time_t currtime = ep_real_time();
if (exptime && exptime < currtime && metadata->isCommit()) {
int ret;
metadata->setDeleteSource(DeleteSource::TTL);
try {
ret = notify_expired_item(
*info, *metadata, item, *ctx, currtime);
} catch (const std::bad_alloc&) {
EP_LOG_WARN("time_purge_hook: memory allocation failed");
return COUCHSTORE_ERROR_ALLOC_FAIL;
} catch (const std::exception& ex) {
EP_LOG_WARN("time_purge_hook: exception: {}", ex.what());
return COUCHSTORE_ERROR_INVALID_ARGUMENTS;
}
if (ret != COUCHSTORE_SUCCESS) {
return ret;
}
}
}
if (ctx->bloomFilterCallback) {
bool deleted = info->deleted;
auto key = makeDiskDocKey(info->id);
try {
ctx->bloomFilterCallback->callback(
ctx->vbid, key.getDocKey(), deleted);
} catch (std::runtime_error& re) {
EP_LOG_WARN(
"time_purge_hook: exception occurred when invoking the "
"bloomfilter callback on {}"
" - Details: {}",
ctx->vbid,
re.what());
}
}
return COUCHSTORE_COMPACT_KEEP_ITEM;
}
bool CouchKVStore::compactDB(std::unique_lock<std::mutex>& vbLock,
std::shared_ptr<CompactionContext> hook_ctx) {
if (isReadOnly()) {
throw std::logic_error(
"CouchKVStore::compactDB() can't be called on read only "
"instance");
}
if (!hook_ctx->droppedKeyCb) {
throw std::runtime_error(
"CouchKVStore::compactDB: droppedKeyCb must be set ");
}
auto vbid = hook_ctx->vbid.get();
// Note that this isn't racy as we'll hold the vbucket lock when we're
// calling the method for doing the check and when we'll set it to
// true
if (vbCompactionRunning[vbid]) {
EP_LOG_INFO(
"CouchKVStore::compactDB: compaction already running for {}",
vbid);
// The API don't let me tell the caller that a compaction is
// already running so I just have to fail it..
return false;
}
// Open the source VBucket database file
DbHolder sourceDb(*this);
auto errCode = openDB(hook_ctx->vbid,
sourceDb,
(uint64_t)COUCHSTORE_OPEN_FLAG_RDONLY,
statCollectingFileOpsCompaction.get());
if (errCode != COUCHSTORE_SUCCESS) {