-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathdb_slice.cc
1752 lines (1444 loc) · 55.7 KB
/
db_slice.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
// Copyright 2022, DragonflyDB authors. All rights reserved.
// See LICENSE for licensing terms.
//
#include "server/db_slice.h"
extern "C" {
#include "redis/hyperloglog.h"
}
#include <absl/cleanup/cleanup.h>
#include "base/flags.h"
#include "base/logging.h"
#include "core/top_keys.h"
#include "search/doc_index.h"
#include "server/channel_store.h"
#include "server/cluster/slot_set.h"
#include "server/engine_shard_set.h"
#include "server/error.h"
#include "server/journal/journal.h"
#include "server/server_state.h"
#include "server/tiered_storage.h"
#include "strings/human_readable.h"
#include "util/fibers/fibers.h"
#include "util/fibers/stacktrace.h"
ABSL_FLAG(uint32_t, max_eviction_per_heartbeat, 100,
"The maximum number of key-value pairs that will be deleted in each eviction "
"when heartbeat based eviction is triggered under memory pressure.");
ABSL_FLAG(uint32_t, max_segment_to_consider, 4,
"The maximum number of dashtable segments to scan in each eviction "
"when heartbeat based eviction is triggered under memory pressure.");
ABSL_FLAG(double, table_growth_margin, 0.4,
"Prevents table from growing if number of free slots x average object size x this ratio "
"is larger than memory budget.");
ABSL_FLAG(std::string, notify_keyspace_events, "",
"notify-keyspace-events. Only Ex is supported for now");
namespace dfly {
using namespace std;
using namespace util;
using absl::GetFlag;
using namespace facade;
using Payload = journal::Entry::Payload;
namespace {
constexpr auto kPrimeSegmentSize = PrimeTable::kSegBytes;
constexpr auto kExpireSegmentSize = ExpireTable::kSegBytes;
// mi_malloc good size is 32768. i.e. we have malloc waste of 1.5%.
static_assert(kPrimeSegmentSize == 32288);
// 20480 is the next goodsize so we are loosing ~300 bytes or 1.5%.
// 24576
static_assert(kExpireSegmentSize == 23528);
void AccountObjectMemory(string_view key, unsigned type, int64_t size, DbTable* db) {
DCHECK_NE(db, nullptr);
if (size == 0)
return;
DbTableStats& stats = db->stats;
DCHECK_GE(static_cast<int64_t>(stats.obj_memory_usage) + size, 0)
<< "Can't decrease " << size << " from " << stats.obj_memory_usage;
stats.AddTypeMemoryUsage(type, size);
if (db->slots_stats) {
db->slots_stats[KeySlot(key)].memory_bytes += size;
}
}
class PrimeEvictionPolicy {
public:
static constexpr bool can_evict = true; // we implement eviction functionality.
static constexpr bool can_gc = true;
// mem_offset - memory_offset that we should account for in addition to DbSlice::memory_budget.
// May be negative.
PrimeEvictionPolicy(const DbContext& cntx, bool can_evict, ssize_t mem_offset, ssize_t soft_limit,
DbSlice* db_slice, bool apply_memory_limit)
: db_slice_(db_slice),
mem_offset_(mem_offset),
soft_limit_(soft_limit),
cntx_(cntx),
can_evict_(can_evict),
apply_memory_limit_(apply_memory_limit) {
}
// A hook function that is called every time a segment is full and requires splitting.
void RecordSplit(PrimeTable::Segment_t* segment) {
DVLOG(2) << "split: " << segment->SlowSize() << "/" << segment->capacity();
}
bool CanGrow(const PrimeTable& tbl) const;
unsigned GarbageCollect(const PrimeTable::HotspotBuckets& eb, PrimeTable* me);
unsigned Evict(const PrimeTable::HotspotBuckets& eb, PrimeTable* me);
unsigned evicted() const {
return evicted_;
}
unsigned checked() const {
return checked_;
}
private:
DbSlice* db_slice_;
ssize_t mem_offset_;
ssize_t soft_limit_ = 0;
const DbContext cntx_;
unsigned evicted_ = 0;
unsigned checked_ = 0;
// unlike static constexpr can_evict, this parameter tells whether we can evict
// items in runtime.
const bool can_evict_;
const bool apply_memory_limit_;
};
bool PrimeEvictionPolicy::CanGrow(const PrimeTable& tbl) const {
ssize_t mem_available = db_slice_->memory_budget() + mem_offset_;
if (!apply_memory_limit_ || mem_available > soft_limit_)
return true;
DCHECK_LE(tbl.size(), tbl.capacity());
// We take a conservative stance here -
// we estimate how much memory we will take with the current capacity
// even though we may currently use less memory.
// see https://github.com/dragonflydb/dragonfly/issues/256#issuecomment-1227095503
size_t table_free_items = ((tbl.capacity() - tbl.size()) + PrimeTable::kSegCapacity) *
GetFlag(FLAGS_table_growth_margin);
size_t obj_bytes_estimation = db_slice_->bytes_per_object() * table_free_items;
bool res = mem_available > int64_t(PrimeTable::kSegBytes + obj_bytes_estimation);
if (res) {
VLOG(1) << "free_items: " << table_free_items
<< ", obj_bytes: " << db_slice_->bytes_per_object() << " "
<< " mem_available: " << mem_available;
} else {
LOG_EVERY_T(INFO, 1) << "Can't grow, free_items " << table_free_items
<< ", obj_bytes: " << db_slice_->bytes_per_object() << " "
<< " mem_available: " << mem_available;
}
return res;
}
unsigned PrimeEvictionPolicy::GarbageCollect(const PrimeTable::HotspotBuckets& eb, PrimeTable* me) {
unsigned res = 0;
if (db_slice_->WillBlockOnJournalWrite()) {
return res;
}
// Disable flush journal changes to prevent preemtion in GarbageCollect.
journal::JournalFlushGuard journal_flush_guard(db_slice_->shard_owner()->journal());
// bool should_print = (eb.key_hash % 128) == 0;
// based on tests - it's more efficient to pass regular buckets to gc.
// stash buckets are filled last so much smaller change they have expired items.
string scratch;
unsigned num_buckets =
std::min<unsigned>(PrimeTable::HotspotBuckets::kRegularBuckets, eb.num_buckets);
for (unsigned i = 0; i < num_buckets; ++i) {
auto bucket_it = eb.at(i);
for (; !bucket_it.is_done(); ++bucket_it) {
if (bucket_it->second.HasExpire()) {
string_view key = bucket_it->first.GetSlice(&scratch);
++checked_;
auto [prime_it, exp_it] = db_slice_->ExpireIfNeeded(
cntx_, DbSlice::Iterator(bucket_it, StringOrView::FromView(key)));
if (prime_it.is_done())
++res;
}
}
}
return res;
}
unsigned PrimeEvictionPolicy::Evict(const PrimeTable::HotspotBuckets& eb, PrimeTable* me) {
if (!can_evict_ || db_slice_->WillBlockOnJournalWrite())
return 0;
// Disable flush journal changes to prevent preemtion in evict.
journal::JournalFlushGuard journal_flush_guard(db_slice_->shard_owner()->journal());
constexpr size_t kNumStashBuckets = ABSL_ARRAYSIZE(eb.probes.by_type.stash_buckets);
// choose "randomly" a stash bucket to evict an item.
auto bucket_it = eb.probes.by_type.stash_buckets[eb.key_hash % kNumStashBuckets];
auto last_slot_it = bucket_it;
last_slot_it += (PrimeTable::kSlotNum - 1);
if (!last_slot_it.is_done()) {
// don't evict sticky items
if (last_slot_it->first.IsSticky()) {
return 0;
}
DbTable* table = db_slice_->GetDBTable(cntx_.db_index);
auto& lt = table->trans_locks;
string scratch;
string_view key = last_slot_it->first.GetSlice(&scratch);
// do not evict locked keys
if (lt.Find(LockTag(key)).has_value())
return 0;
// log the evicted keys to journal.
if (auto journal = db_slice_->shard_owner()->journal(); journal) {
RecordExpiryBlocking(cntx_.db_index, key);
}
db_slice_->PerformDeletion(DbSlice::Iterator(last_slot_it, StringOrView::FromView(key)), table);
++evicted_;
}
me->ShiftRight(bucket_it);
return 1;
}
class AsyncDeleter {
public:
static void EnqueDeletion(uint32_t next, DenseSet* ds);
static void Shutdown();
private:
static constexpr uint32_t kClearStepSize = 1024;
struct ClearNode {
DenseSet* ds;
uint32_t cursor;
ClearNode* next;
ClearNode(DenseSet* d, uint32_t c, ClearNode* n) : ds(d), cursor(c), next(n) {
}
};
// Asynchronously deletes entries during the cpu-idle time.
static int32_t IdleCb();
// We add async deletion requests to a linked list and process them asynchronously
// in each thread.
static __thread ClearNode* head_;
};
__thread AsyncDeleter::ClearNode* AsyncDeleter::head_ = nullptr;
void AsyncDeleter::EnqueDeletion(uint32_t next, DenseSet* ds) {
bool launch_task = (head_ == nullptr);
// register ds
head_ = new ClearNode{ds, next, head_};
ProactorBase* pb = ProactorBase::me();
DCHECK(pb);
DVLOG(2) << "Adding async deletion task, thread " << pb->GetPoolIndex() << " " << launch_task;
if (launch_task) {
pb->AddOnIdleTask(&IdleCb);
}
}
void AsyncDeleter::Shutdown() {
// we do not bother with deleting objects scheduled for asynchronous deletion
// during the shutdown. this should work well because we destroy mimalloc heap anyways.
while (head_) {
auto* next = head_->next;
delete head_;
head_ = next;
}
}
int32_t AsyncDeleter::IdleCb() {
if (head_ == nullptr)
return -1; // unregister itself.
auto* current = head_;
DVLOG(2) << "IdleCb " << current->cursor;
uint32_t next = current->ds->ClearStep(current->cursor, kClearStepSize);
if (next == current->ds->BucketCount()) { // reached the end.
CompactObj::DeleteMR<DenseSet>(current->ds);
head_ = current->next;
delete current;
} else {
current->cursor = next;
}
return ProactorBase::kOnIdleMaxLevel;
};
inline void TouchTopKeysIfNeeded(string_view key, TopKeys* top_keys) {
if (top_keys) {
top_keys->Touch(key);
}
}
inline void TouchHllIfNeeded(string_view key, uint8_t* hll) {
if (hll) {
HllBufferPtr hll_buf;
hll_buf.size = getDenseHllSize();
hll_buf.hll = hll;
pfadd_dense(hll_buf, reinterpret_cast<const uint8_t*>(key.data()), key.size());
}
}
} // namespace
#define ADD(x) (x) += o.x
DbStats& DbStats::operator+=(const DbStats& o) {
constexpr size_t kDbSz = sizeof(DbStats) - sizeof(DbTableStats);
static_assert(kDbSz == 32);
DbTableStats::operator+=(o);
ADD(key_count);
ADD(expire_count);
ADD(bucket_count);
ADD(table_mem_usage);
return *this;
}
SliceEvents& SliceEvents::operator+=(const SliceEvents& o) {
static_assert(sizeof(SliceEvents) == 120, "You should update this function with new fields");
ADD(evicted_keys);
ADD(hard_evictions);
ADD(expired_keys);
ADD(garbage_collected);
ADD(stash_unloaded);
ADD(bumpups);
ADD(garbage_checked);
ADD(hits);
ADD(misses);
ADD(mutations);
ADD(insertion_rejections);
ADD(update);
ADD(ram_hits);
ADD(ram_cool_hits);
ADD(ram_misses);
return *this;
}
#undef ADD
class DbSlice::PrimeBumpPolicy {
public:
PrimeBumpPolicy(absl::flat_hash_set<uint64_t, FpHasher>* items) : fetched_items_(items) {
}
// returns true if we can change the object location in dash table.
bool CanBump(const CompactObj& obj) const {
if (obj.IsSticky()) {
return false;
}
auto hc = obj.HashCode();
return fetched_items_->insert(hc).second;
}
private:
mutable absl::flat_hash_set<uint64_t, FpHasher>* fetched_items_;
};
DbSlice::DbSlice(uint32_t index, bool cache_mode, EngineShard* owner)
: shard_id_(index),
cache_mode_(cache_mode),
owner_(owner),
client_tracking_map_(owner->memory_resource()) {
db_arr_.emplace_back();
CreateDb(0);
expire_base_[0] = expire_base_[1] = 0;
soft_budget_limit_ = (0.3 * max_memory_limit / shard_set->size());
std::string keyspace_events = GetFlag(FLAGS_notify_keyspace_events);
if (!keyspace_events.empty() && keyspace_events != "Ex") {
LOG(ERROR) << "Only Ex is currently supported";
exit(0);
}
expired_keys_events_recording_ = !keyspace_events.empty();
}
DbSlice::~DbSlice() {
// we do not need this code but it's easier to debug in case we encounter
// memory allocation bugs during delete operations.
for (auto& db : db_arr_) {
if (!db)
continue;
db.reset();
}
AsyncDeleter::Shutdown();
}
auto DbSlice::GetStats() const -> Stats {
Stats s;
s.events = events_;
s.db_stats.resize(db_arr_.size());
for (size_t i = 0; i < db_arr_.size(); ++i) {
if (!db_arr_[i])
continue;
const auto& db_wrap = *db_arr_[i];
DbStats& stats = s.db_stats[i];
stats = db_wrap.stats;
stats.key_count = db_wrap.prime.size();
stats.bucket_count = db_wrap.prime.bucket_count();
stats.expire_count = db_wrap.expire.size();
stats.table_mem_usage = db_wrap.table_memory();
}
s.small_string_bytes = CompactObj::GetStats().small_string_bytes;
return s;
}
SlotStats DbSlice::GetSlotStats(SlotId sid) const {
CHECK(db_arr_[0]);
return db_arr_[0]->slots_stats[sid];
}
void DbSlice::Reserve(DbIndex db_ind, size_t key_size) {
ActivateDb(db_ind);
auto& db = db_arr_[db_ind];
DCHECK(db);
db->prime.Reserve(key_size);
}
DbSlice::AutoUpdater::AutoUpdater() {
}
DbSlice::AutoUpdater::AutoUpdater(AutoUpdater&& o) {
*this = std::move(o);
}
DbSlice::AutoUpdater& DbSlice::AutoUpdater::operator=(AutoUpdater&& o) {
Run();
fields_ = o.fields_;
o.Cancel();
return *this;
}
DbSlice::AutoUpdater::~AutoUpdater() {
Run();
}
void DbSlice::AutoUpdater::Run() {
if (fields_.action == DestructorAction::kDoNothing) {
return;
}
// Check that AutoUpdater does not run after a key was removed.
// If this CHECK() failed for you, it probably means that you deleted a key while having an auto
// updater in scope. You'll probably want to call Run() (or Cancel() - but be careful).
DCHECK(IsValid(fields_.db_slice->db_arr_[fields_.db_ind]->prime.Find(fields_.key)));
DCHECK(fields_.action == DestructorAction::kRun);
CHECK_NE(fields_.db_slice, nullptr);
fields_.db_slice->PostUpdate(fields_.db_ind, fields_.it, fields_.key, fields_.orig_heap_size);
Cancel(); // Reset to not run again
}
void DbSlice::AutoUpdater::Cancel() {
this->fields_ = {};
}
DbSlice::AutoUpdater::AutoUpdater(const Fields& fields) : fields_(fields) {
DCHECK(fields_.action == DestructorAction::kRun);
DCHECK(IsValid(fields.it));
fields_.orig_heap_size = fields.it->second.MallocUsed();
}
DbSlice::ItAndUpdater DbSlice::FindMutable(const Context& cntx, string_view key) {
return std::move(FindMutableInternal(cntx, key, std::nullopt).value());
}
OpResult<DbSlice::ItAndUpdater> DbSlice::FindMutable(const Context& cntx, string_view key,
unsigned req_obj_type) {
return FindMutableInternal(cntx, key, req_obj_type);
}
OpResult<DbSlice::ItAndUpdater> DbSlice::FindMutableInternal(const Context& cntx, string_view key,
std::optional<unsigned> req_obj_type) {
auto res = FindInternal(cntx, key, req_obj_type, UpdateStatsMode::kMutableStats);
if (!res.ok()) {
return res.status();
}
auto it = Iterator(res->it, StringOrView::FromView(key));
auto exp_it = ExpIterator(res->exp_it, StringOrView::FromView(key));
PreUpdateBlocking(cntx.db_index, it, key);
// PreUpdate() might have caused a deletion of `it`
if (res->it.IsOccupied()) {
DCHECK_GE(db_arr_[cntx.db_index]->stats.obj_memory_usage, res->it->second.MallocUsed());
return {{it, exp_it,
AutoUpdater({.action = AutoUpdater::DestructorAction::kRun,
.db_slice = this,
.db_ind = cntx.db_index,
.it = it,
.key = key})}};
} else {
return OpStatus::KEY_NOTFOUND;
}
}
DbSlice::ItAndExpConst DbSlice::FindReadOnly(const Context& cntx, std::string_view key) const {
auto res = FindInternal(cntx, key, std::nullopt, UpdateStatsMode::kReadStats);
return {ConstIterator(res->it, StringOrView::FromView(key)),
ExpConstIterator(res->exp_it, StringOrView::FromView(key))};
}
OpResult<DbSlice::ConstIterator> DbSlice::FindReadOnly(const Context& cntx, string_view key,
unsigned req_obj_type) const {
auto res = FindInternal(cntx, key, req_obj_type, UpdateStatsMode::kReadStats);
if (res.ok()) {
return ConstIterator(res->it, StringOrView::FromView(key));
}
return res.status();
}
auto DbSlice::FindInternal(const Context& cntx, string_view key, optional<unsigned> req_obj_type,
UpdateStatsMode stats_mode) const -> OpResult<PrimeItAndExp> {
if (!IsDbValid(cntx.db_index)) { // Can it even happen?
LOG(DFATAL) << "Invalid db index " << cntx.db_index;
return OpStatus::KEY_NOTFOUND;
}
auto& db = *db_arr_[cntx.db_index];
PrimeItAndExp res;
res.it = db.prime.Find(key);
int miss_weight = (stats_mode == UpdateStatsMode::kReadStats);
if (!IsValid(res.it)) {
events_.misses += miss_weight;
return OpStatus::KEY_NOTFOUND;
}
TouchTopKeysIfNeeded(key, db.top_keys);
TouchHllIfNeeded(key, db.dense_hll);
if (req_obj_type.has_value() && res.it->second.ObjType() != req_obj_type.value()) {
events_.misses += miss_weight;
return OpStatus::WRONG_TYPE;
}
if (res.it->second.HasExpire()) { // check expiry state
res = ExpireIfNeeded(cntx, res.it);
if (!IsValid(res.it)) {
events_.misses += miss_weight;
return OpStatus::KEY_NOTFOUND;
}
}
DCHECK(IsValid(res.it));
if (IsCacheMode()) {
if (!change_cb_.empty()) {
auto bump_cb = [&](PrimeTable::bucket_iterator bit) {
CallChangeCallbacks(cntx.db_index, key, bit);
};
db.prime.CVCUponBump(change_cb_.back().first, res.it, bump_cb);
}
// We must not change the bucket's internal order during serialization
serialization_latch_.Wait();
auto bump_it = db.prime.BumpUp(res.it, PrimeBumpPolicy{&fetched_items_});
if (bump_it != res.it) { // the item was bumped
res.it = bump_it;
++events_.bumpups;
}
}
switch (stats_mode) {
case UpdateStatsMode::kMutableStats:
events_.mutations++;
break;
case UpdateStatsMode::kReadStats:
events_.hits++;
if (db.slots_stats) {
db.slots_stats[KeySlot(key)].total_reads++;
}
if (res.it->second.IsExternal()) {
if (res.it->second.IsCool())
events_.ram_cool_hits++;
else
events_.ram_misses++;
} else {
events_.ram_hits++;
}
break;
}
auto& pv = res.it->second;
// Cancel any pending stashes of looked up values
// Rationale: we either look it up for reads - and then it's hot, or alternatively,
// we follow up with modifications, so the pending stash becomes outdated.
if (pv.HasStashPending()) {
owner_->tiered_storage()->CancelStash(cntx.db_index, key, &pv);
}
// Fetch back cool items
if (pv.IsExternal() && pv.IsCool()) {
pv = owner_->tiered_storage()->Warmup(cntx.db_index, pv.GetCool());
}
// Mark this entry as being looked up. We use key (first) deliberately to preserve the hotness
// attribute of the entry in case of value overrides.
res.it->first.SetTouched(true);
return res;
}
OpResult<DbSlice::ItAndUpdater> DbSlice::AddOrFind(const Context& cntx, string_view key) {
return AddOrFindInternal(cntx, key);
}
OpResult<DbSlice::ItAndUpdater> DbSlice::AddOrFindInternal(const Context& cntx, string_view key) {
DCHECK(IsDbValid(cntx.db_index));
DbTable& db = *db_arr_[cntx.db_index];
auto res = FindInternal(cntx, key, std::nullopt, UpdateStatsMode::kMutableStats);
if (res.ok()) {
Iterator it(res->it, StringOrView::FromView(key));
ExpIterator exp_it(res->exp_it, StringOrView::FromView(key));
PreUpdateBlocking(cntx.db_index, it, key);
// PreUpdate() might have caused a deletion of `it`
if (res->it.IsOccupied()) {
return ItAndUpdater{
.it = it,
.exp_it = exp_it,
.post_updater = AutoUpdater({.action = AutoUpdater::DestructorAction::kRun,
.db_slice = this,
.db_ind = cntx.db_index,
.it = it,
.key = key}),
.is_new = false};
} else {
res = OpStatus::KEY_NOTFOUND;
}
}
auto status = res.status();
CHECK(status == OpStatus::KEY_NOTFOUND || status == OpStatus::OUT_OF_MEMORY) << status;
// It's a new entry.
CallChangeCallbacks(cntx.db_index, key, {key});
ssize_t memory_offset = -key.size();
size_t reclaimed = 0;
// If we are low on memory due to cold storage, free some memory.
if (owner_->tiered_storage()) {
// At least 40KB bytes to cover potential segment split.
ssize_t red_line = std::max<size_t>(key.size() * 2, 40_KB);
if (memory_budget_ < red_line) {
size_t goal = red_line - memory_budget_;
reclaimed = owner_->tiered_storage()->ReclaimMemory(goal);
memory_budget_ += reclaimed;
}
// CoolMemoryUsage is the memory that we can always reclaim, like in the block above,
// therefore we include it for PrimeEvictionPolicy considerations.
memory_offset += owner_->tiered_storage()->CoolMemoryUsage();
}
// In case we are loading from rdb file or replicating we want to disable conservative memory
// checks (inside PrimeEvictionPolicy::CanGrow) and reject insertions only after we pass max
// memory limit. When loading a snapshot created by the same server configuration (memory and
// number of shards) we will create a different dash table segment directory tree, because the
// tree shape is related to the order of entries insertion. Therefore when loading data from
// snapshot or from replication the conservative memory checks might fail as the new tree might
// have more segments. Because we dont want to fail loading a snapshot from the same server
// configuration we disable this checks on loading and replication.
bool apply_memory_limit =
!owner_->IsReplica() && !(ServerState::tlocal()->gstate() == GlobalState::LOADING);
// If we are over limit in non-cache scenario, just be conservative and throw.
if (apply_memory_limit && !IsCacheMode() && memory_budget_ + memory_offset < 0) {
LOG_EVERY_T(WARNING, 1) << "AddOrFind: over limit, budget: " << memory_budget_
<< " reclaimed: " << reclaimed << " offset: " << memory_offset;
events_.insertion_rejections++;
return OpStatus::OUT_OF_MEMORY;
}
PrimeEvictionPolicy evp{cntx, (IsCacheMode() && !owner_->IsReplica()),
memory_offset, ssize_t(soft_budget_limit_),
this, apply_memory_limit};
// Fast-path if change_cb_ is empty so we Find or Add using
// the insert operation: twice more efficient.
CompactObj co_key{key};
PrimeIterator it;
ssize_t table_before = db.prime.mem_usage();
try {
it = db.prime.InsertNew(std::move(co_key), PrimeValue{}, evp);
} catch (bad_alloc& e) {
LOG_EVERY_T(WARNING, 1) << "AddOrFind: InsertNew failed, budget: " << memory_budget_
<< " reclaimed: " << reclaimed << " offset: " << memory_offset;
events_.insertion_rejections++;
return OpStatus::OUT_OF_MEMORY;
}
events_.mutations++;
ssize_t table_increase = db.prime.mem_usage() - table_before;
memory_budget_ -= table_increase;
if (memory_budget_ < 0 && apply_memory_limit) {
// We may reach the state when our memory usage is below the limit even if we
// do not add new segments. For example, we have half full segments
// and we add new objects or update the existing ones and our memory usage grows.
// We do not require for a single operation to unload the whole negative debt.
// Instead, we create a positive, converging force that should help with freeing enough memory.
// Free at least K bytes or 3% of the total debt.
// TODO: to reenable and optimize this - this call significantly slows down server
// when evictions are running.
#if 0
size_t evict_goal = std::max<size_t>(512, (-evp.mem_budget()) / 32);
auto [items, bytes] = FreeMemWithEvictionStep(cntx.db_index, it.segment_id(), evict_goal);
events_.hard_evictions += items;
#endif
}
table_memory_ += table_increase;
entries_count_++;
db.stats.inline_keys += it->first.IsInline();
AccountObjectMemory(key, it->first.ObjType(), it->first.MallocUsed(), &db); // Account for key
DCHECK_EQ(it->second.MallocUsed(), 0UL); // Make sure accounting is no-op
it.SetVersion(NextVersion());
TouchTopKeysIfNeeded(key, db.top_keys);
TouchHllIfNeeded(key, db.dense_hll);
events_.garbage_collected = db.prime.garbage_collected();
events_.stash_unloaded = db.prime.stash_unloaded();
events_.evicted_keys += evp.evicted();
events_.garbage_checked += evp.checked();
if (db.slots_stats) {
SlotId sid = KeySlot(key);
db.slots_stats[sid].key_count += 1;
}
return ItAndUpdater{.it = Iterator(it, StringOrView::FromView(key)),
.exp_it = ExpIterator{},
.post_updater = AutoUpdater({.action = AutoUpdater::DestructorAction::kRun,
.db_slice = this,
.db_ind = cntx.db_index,
.it = Iterator(it, StringOrView::FromView(key)),
.key = key}),
.is_new = true};
}
void DbSlice::ActivateDb(DbIndex db_ind) {
if (db_arr_.size() <= db_ind)
db_arr_.resize(db_ind + 1);
CreateDb(db_ind);
}
void DbSlice::Del(Context cntx, Iterator it) {
CHECK(IsValid(it));
auto& db = db_arr_[cntx.db_index];
auto obj_type = it->second.ObjType();
if (doc_del_cb_ && (obj_type == OBJ_JSON || obj_type == OBJ_HASH)) {
string tmp;
string_view key = it->first.GetSlice(&tmp);
doc_del_cb_(key, cntx, it->second);
}
PerformDeletion(it, db.get());
}
void DbSlice::FlushSlotsFb(const cluster::SlotSet& slot_ids) {
// Slot deletion can take time as it traverses all the database, hence it runs in fiber.
// We want to flush all the data of a slot that was added till the time the call to FlushSlotsFb
// was made. Therefore we delete slots entries with version < next_version
uint64_t next_version = 0;
std::string tmp;
auto del_entry_cb = [&](PrimeTable::iterator it) {
std::string_view key = it->first.GetSlice(&tmp);
SlotId sid = KeySlot(key);
if (slot_ids.Contains(sid) && it.GetVersion() < next_version) {
PerformDeletion(Iterator::FromPrime(it), db_arr_[0].get());
}
return true;
};
auto on_change = [&](DbIndex db_index, const ChangeReq& req) {
FiberAtomicGuard fg;
PrimeTable* table = GetTables(db_index).first;
auto iterate_bucket = [&](DbIndex db_index, PrimeTable::bucket_iterator it) {
it.AdvanceIfNotOccupied();
while (!it.is_done()) {
del_entry_cb(it);
++it;
}
};
if (const PrimeTable::bucket_iterator* bit = req.update()) {
if (!bit->is_done() && bit->GetVersion() < next_version) {
iterate_bucket(db_index, *bit);
}
} else {
string_view key = get<string_view>(req.change);
table->CVCUponInsert(
next_version, key,
[db_index, next_version, iterate_bucket](PrimeTable::bucket_iterator it) {
DCHECK_LT(it.GetVersion(), next_version);
iterate_bucket(db_index, it);
});
}
};
next_version = RegisterOnChange(std::move(on_change));
ServerState& etl = *ServerState::tlocal();
PrimeTable* pt = &db_arr_[0]->prime;
PrimeTable::Cursor cursor;
uint64_t i = 0;
do {
PrimeTable::Cursor next = pt->Traverse(cursor, del_entry_cb);
++i;
cursor = next;
if (i % 100 == 0) {
ThisFiber::Yield();
}
} while (cursor && etl.gstate() != GlobalState::SHUTTING_DOWN);
UnregisterOnChange(next_version);
etl.DecommitMemory(ServerState::kDataHeap);
}
void DbSlice::FlushSlots(const cluster::SlotRanges& slot_ranges) {
cluster::SlotSet slot_set(slot_ranges);
InvalidateSlotWatches(slot_set);
fb2::Fiber("flush_slots", [this, slot_set = std::move(slot_set)]() mutable {
FlushSlotsFb(slot_set);
}).Detach();
}
void DbSlice::FlushDbIndexes(const std::vector<DbIndex>& indexes) {
bool clear_tiered = owner_->tiered_storage() != nullptr;
if (clear_tiered)
ClearOffloadedEntries(indexes, db_arr_);
DbTableArray flush_db_arr(db_arr_.size());
for (DbIndex index : indexes) {
if (!index) {
owner_->search_indices()->DropAllIndices();
}
table_memory_ -= db_arr_[index]->table_memory();
entries_count_ -= db_arr_[index]->prime.size();
InvalidateDbWatches(index);
flush_db_arr[index] = std::move(db_arr_[index]);
CreateDb(index);
std::swap(db_arr_[index]->trans_locks, flush_db_arr[index]->trans_locks);
}
LOG_IF(DFATAL, !fetched_items_.empty())
<< "Some operation might bumped up items outside of a transaction";
auto cb = [indexes, flush_db_arr = std::move(flush_db_arr)]() mutable {
flush_db_arr.clear();
ServerState::tlocal()->DecommitMemory(ServerState::kDataHeap | ServerState::kBackingHeap |
ServerState::kGlibcmalloc);
};
fb2::Fiber("flush_dbs", std::move(cb)).Detach();
}
void DbSlice::FlushDb(DbIndex db_ind) {
DVLOG(1) << "Flushing db " << db_ind;
// clear client tracking map.
client_tracking_map_.clear();
if (db_ind != kDbAll) {
// Flush a single database if a specific index is provided
FlushDbIndexes({db_ind});
return;
}
std::vector<DbIndex> indexes;
indexes.reserve(db_arr_.size());
for (DbIndex i = 0; i < db_arr_.size(); ++i) {
if (db_arr_[i]) {
indexes.push_back(i);
}
}
FlushDbIndexes(indexes);
}
void DbSlice::AddExpire(DbIndex db_ind, Iterator main_it, uint64_t at) {
uint64_t delta = at - expire_base_[0]; // TODO: employ multigen expire updates.
auto& db = *db_arr_[db_ind];
size_t table_before = db.expire.mem_usage();
CHECK(db.expire.Insert(main_it->first.AsRef(), ExpirePeriod(delta)).second);
table_memory_ += (db.expire.mem_usage() - table_before);
main_it->second.SetExpire(true);
}
bool DbSlice::RemoveExpire(DbIndex db_ind, Iterator main_it) {
if (main_it->second.HasExpire()) {
auto& db = *db_arr_[db_ind];
size_t table_before = db.expire.mem_usage();
CHECK_EQ(1u, db.expire.Erase(main_it->first));
main_it->second.SetExpire(false);
table_memory_ += (db.expire.mem_usage() - table_before);
return true;
}
return false;
}
// Returns true if a state has changed, false otherwise.
bool DbSlice::UpdateExpire(DbIndex db_ind, Iterator it, uint64_t at) {
if (at == 0) {
return RemoveExpire(db_ind, it);
}
if (!it->second.HasExpire() && at) {
AddExpire(db_ind, it, at);
return true;
}
return false;
}
void DbSlice::SetMCFlag(DbIndex db_ind, PrimeKey key, uint32_t flag) {
auto& db = *db_arr_[db_ind];
if (flag == 0) {
db.mcflag.Erase(key);
} else {
auto [it, _] = db.mcflag.Insert(std::move(key), flag);
it->second = flag;
}
}
uint32_t DbSlice::GetMCFlag(DbIndex db_ind, const PrimeKey& key) const {
auto& db = *db_arr_[db_ind];
auto it = db.mcflag.Find(key);
if (it.is_done()) {
LOG(DFATAL) << "Internal error, inconsistent state, mcflag should be present but not found "
<< key.ToString();
return 0;
}
return it->second;
}
OpResult<DbSlice::ItAndUpdater> DbSlice::AddNew(const Context& cntx, string_view key,
PrimeValue obj, uint64_t expire_at_ms) {
auto op_result = AddOrUpdateInternal(cntx, key, std::move(obj), expire_at_ms, false);
RETURN_ON_BAD_STATUS(op_result);
auto& res = *op_result;
CHECK(res.is_new);
return DbSlice::ItAndUpdater{
.it = res.it, .exp_it = res.exp_it, .post_updater = std::move(res.post_updater)};
}
int64_t DbSlice::ExpireParams::Cap(int64_t value, TimeUnit unit) {
return unit == TimeUnit::SEC ? min(value, kMaxExpireDeadlineSec)
: min(value, kMaxExpireDeadlineMs);
}
pair<int64_t, int64_t> DbSlice::ExpireParams::Calculate(uint64_t now_ms, bool cap) const {
if (persist)
return {0, 0};
// return a negative absolute time if we overflow.
if (unit == TimeUnit::SEC && value > INT64_MAX / 1000) {
return {0, -1};
}
int64_t msec = (unit == TimeUnit::SEC) ? value * 1000 : value;
int64_t rel_msec = absolute ? msec - now_ms : msec;