forked from agentic-review-benchmarks/redis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.c
More file actions
3689 lines (3259 loc) · 137 KB
/
db.c
File metadata and controls
3689 lines (3259 loc) · 137 KB
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 (c) 2009-Present, Redis Ltd.
* All rights reserved.
*
* Copyright (c) 2024-present, Valkey contributors.
* All rights reserved.
*
* Licensed under your choice of (a) the Redis Source Available License 2.0
* (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the
* GNU Affero General Public License v3 (AGPLv3).
*
* Portions of this file are available under BSD3 terms; see REDISCONTRIBUTIONS for more information.
*/
#include "server.h"
#include "cluster.h"
#include "atomicvar.h"
#include "latency.h"
#include "script.h"
#include "functions.h"
#include "cluster_asm.h"
#include "redisassert.h"
#include <signal.h>
#include <ctype.h>
#include "bio.h"
/*-----------------------------------------------------------------------------
* C-level DB API
*----------------------------------------------------------------------------*/
static_assert(MAX_KEYSIZES_TYPES == OBJ_TYPE_BASIC_MAX, "Must be equal");
/* Flags for expireIfNeeded */
#define EXPIRE_FORCE_DELETE_EXPIRED 1
#define EXPIRE_AVOID_DELETE_EXPIRED 2
#define EXPIRE_ALLOW_ACCESS_EXPIRED 4
/* Return values for expireIfNeeded */
typedef enum {
KEY_VALID = 0, /* Could be volatile and not yet expired, non-volatile, or even non-existing key. */
KEY_EXPIRED, /* Logically expired but not yet deleted. */
KEY_DELETED /* The key was deleted now. */
} keyStatus;
static keyStatus expireIfNeeded(redisDb *db, robj *key, kvobj *kv, int flags);
/* Update LFU when an object is accessed.
* Firstly, decrement the counter if the decrement time is reached.
* Then logarithmically increment the counter, and update the access time. */
void updateLFU(robj *val) {
unsigned long counter = LFUDecrAndReturn(val);
counter = LFULogIncr(counter);
val->lru = (LFUGetTimeInMinutes()<<8) | counter;
}
/*
* Update histogram of keys-sizes
*
* It is used to track the distribution of key sizes in the dataset. It is updated
* every time key's length is modified. Available to user via INFO command.
*
* The histogram is a base-2 logarithmic histogram, with 64 bins. The i'th bin
* represents the number of keys with a size in the range 2^i and 2^(i+1)
* exclusive. oldLen/newLen must be smaller than 2^48, and if their value
* equals -1, it means that the key is being created/deleted, respectively. Each
* data type has its own histogram and it is per database (In addition, there is
* histogram per slot for future cluster use).
*
* Example mapping of key lengths to bins:
* [1,2)->1 [2,4)->2 [4,8)->3 [8,16)->4 ...
*
* Since strings can be zero length, the histogram also tracks:
* [0,1)->0
*/
void updateKeysizesHist(redisDb *db, int didx, uint32_t type, int64_t oldLen, int64_t newLen) {
if(unlikely(type >= OBJ_TYPE_BASIC_MAX))
return;
kvstoreDictMetadata *dictMeta = kvstoreGetDictMetadata(db->keys, didx);
kvstoreMetadata *kvstoreMeta = kvstoreGetMetadata(db->keys);
if (oldLen > 0) {
int old_bin = log2ceil(oldLen) + 1;
debugServerAssert(old_bin < MAX_KEYSIZES_BINS);
/* If following a key deletion it is last one in slot's dict, then
* slot's dict might get released as well. Verify if metadata is not NULL. */
if(dictMeta) {
dictMeta->keysizes_hist[type][old_bin]--;
debugServerAssert(dictMeta->keysizes_hist[type][old_bin] >= 0);
}
kvstoreMeta->keysizes_hist[type][old_bin]--;
debugServerAssert(kvstoreMeta->keysizes_hist[type][old_bin] >= 0);
} else {
/* here, oldLen can be either 0 or -1 */
if (oldLen == 0) {
/* Only strings can be empty. Yet, a command flow might temporarily
* dbAdd() empty collection, and only after add elements. */
if (dictMeta) {
dictMeta->keysizes_hist[type][0]--;
debugServerAssert(dictMeta->keysizes_hist[type][0] >= 0);
}
kvstoreMeta->keysizes_hist[type][0]--;
debugServerAssert(kvstoreMeta->keysizes_hist[type][0] >= 0);
}
}
if (newLen > 0) {
int new_bin = log2ceil(newLen) + 1;
debugServerAssert(new_bin < MAX_KEYSIZES_BINS);
/* If following a key deletion it is last one in slot's dict, then
* slot's dict might get released as well. Verify if metadata is not NULL. */
if(dictMeta) dictMeta->keysizes_hist[type][new_bin]++;
kvstoreMeta->keysizes_hist[type][new_bin]++;
} else {
/* here, newLen can be either 0 or -1 */
if (newLen == 0) {
/* Only strings can be empty. Yet, a command flow might temporarily
* dbAdd() empty collection, and only after add elements. */
if (dictMeta) dictMeta->keysizes_hist[type][0]++;
kvstoreMeta->keysizes_hist[type][0]++;
}
}
}
void updateSlotAllocSize(redisDb *db, int didx, size_t oldsize, size_t newsize) {
debugServerAssert(server.memory_tracking_per_slot);
kvstoreDictMetadata *dictMeta = kvstoreGetDictMetadata(db->keys, didx);
if (!dictMeta) return;
#ifdef REDIS_TEST
serverAssert(oldsize <= dictMeta->alloc_size);
#endif
dictMeta->alloc_size -= oldsize;
dictMeta->alloc_size += newsize;
}
/* Assert keysizes histogram (For debugging only)
*
* Triggered by DEBUG KEYSIZES-HIST-ASSERT 1 and tested after each command.
*/
void dbgAssertKeysizesHist(redisDb *db) {
/* Scan DB and build expected histogram by scanning all keys */
int64_t scanHist[MAX_KEYSIZES_TYPES][MAX_KEYSIZES_BINS] = {{0}};
dictEntry *de;
kvstoreIterator *kvs_it = kvstoreIteratorInit(db->keys);
while ((de = kvstoreIteratorNext(kvs_it)) != NULL) {
kvobj *kv = dictGetKV(de);
if (kv->type < OBJ_TYPE_BASIC_MAX) {
int64_t len = getObjectLength(kv);
scanHist[kv->type][(len == 0) ? 0 : log2ceil(len) + 1]++;
}
}
kvstoreIteratorRelease(kvs_it);
for (int type = 0; type < OBJ_TYPE_BASIC_MAX; type++) {
volatile int64_t *keysizesHist = kvstoreGetMetadata(db->keys)->keysizes_hist[type];
for (int i = 0; i < MAX_KEYSIZES_BINS; i++) {
if (scanHist[type][i] == keysizesHist[i])
continue;
/* print scanStr vs. expected histograms for debugging */
char scanStr[500], keysizesStr[500];
int l1 = 0, l2 = 0;
for (int j = 0; (j < MAX_KEYSIZES_BINS) && (l1 < 500) && (l2 < 500); j++) {
if (scanHist[type][j])
l1 += snprintf(scanStr + l1, sizeof(scanStr) - l1,
"[%d]=%"PRId64" ", j, scanHist[type][j]);
if (keysizesHist[j])
l2 += snprintf(keysizesStr + l2, sizeof(keysizesStr) - l2,
"[%d]=%"PRId64" ", j, keysizesHist[j]);
}
serverPanic("dbgAssertKeysizesHist: type=%d\nscanStr=%s\nkeysizes=%s\n",
type, scanStr, keysizesStr);
}
}
}
/* Assert per-slot alloc_size (For debugging only)
*
* Triggered by DEBUG ALLOCSIZE-SLOTS-ASSERT 1 and tested after each command.
*/
void dbgAssertAllocSizePerSlot(redisDb *db) {
if (!server.memory_tracking_per_slot) return;
size_t slot_sizes[CLUSTER_SLOTS] = {0};
dictEntry *de;
kvstoreIterator *kvs_it = kvstoreIteratorInit(db->keys);
while ((de = kvstoreIteratorNext(kvs_it)) != NULL) {
int slot = kvstoreIteratorGetCurrentDictIndex(kvs_it);
kvobj *kv = dictGetKV(de);
slot_sizes[slot] += kvobjAllocSize(kv);
}
kvstoreIteratorRelease(kvs_it);
int num_slots = kvstoreNumDicts(db->keys);
for (int slot = 0; slot < num_slots; slot++) {
kvstoreDictMetadata *dictMeta = kvstoreGetDictMetadata(db->keys, slot);
size_t want = slot_sizes[slot];
size_t have = dictMeta ? dictMeta->alloc_size : 0;
if (have == want) continue;
serverPanic("dbgAssertAllocSizePerSlot: slot=%d expected=%zu actual=%zu",
slot, want, have);
}
}
/* Lookup a kvobj for read or write operations, or return NULL if the it is not
* found in the specified DB. This function implements the functionality of
* lookupKeyRead(), lookupKeyWrite() and their ...WithFlags() variants.
*
* link - If key found, return the link of the key.
* If key not found, return the bucket link, where the key should be added.
* Or NULL if dict wasn't allocated yet.
*
* Side-effects of calling this function:
*
* 1. A key gets expired if it reached it's TTL.
* 2. The key's last access time is updated.
* 3. The global keys hits/misses stats are updated (reported in INFO).
* 4. If keyspace notifications are enabled, a "keymiss" notification is fired.
*
* Flags change the behavior of this command:
*
* LOOKUP_NONE (or zero): No special flags are passed.
* LOOKUP_NOTOUCH: Don't alter the last access time of the key.
* LOOKUP_NONOTIFY: Don't trigger keyspace event on key miss.
* LOOKUP_NOSTATS: Don't increment key hits/misses counters.
* LOOKUP_WRITE: Prepare the key for writing (delete expired keys even on
* replicas, use separate keyspace stats and events (TODO)).
* LOOKUP_NOEXPIRE: Perform expiration check, but avoid deleting the key,
* so that we don't have to propagate the deletion.
*
* Note: this function also returns NULL if the key is logically expired but
* still existing, in case this is a replica and the LOOKUP_WRITE is not set.
* Even if the key expiry is master-driven, we can correctly report a key is
* expired on replicas even if the master is lagging expiring our key via DELs
* in the replication link. */
kvobj *lookupKey(redisDb *db, robj *key, int flags, dictEntryLink *link) {
kvobj *val = dbFindByLink(db, key->ptr, link);
if (val) {
/* Forcing deletion of expired keys on a replica makes the replica
* inconsistent with the master. We forbid it on readonly replicas, but
* we have to allow it on writable replicas to make write commands
* behave consistently.
*
* It's possible that the WRITE flag is set even during a readonly
* command, since the command may trigger events that cause modules to
* perform additional writes. */
int is_ro_replica = server.masterhost && server.repl_slave_ro;
int expire_flags = 0;
if (flags & LOOKUP_WRITE && !is_ro_replica)
expire_flags |= EXPIRE_FORCE_DELETE_EXPIRED;
if (flags & LOOKUP_NOEXPIRE)
expire_flags |= EXPIRE_AVOID_DELETE_EXPIRED;
if (flags & LOOKUP_ACCESS_EXPIRED)
expire_flags |= EXPIRE_ALLOW_ACCESS_EXPIRED;
if (expireIfNeeded(db, key, val, expire_flags) != KEY_VALID) {
/* The key is no longer valid. */
val = NULL;
if (link) *link = NULL;
}
}
if (val) {
/* Update the access time for the ageing algorithm.
* Don't do it if we have a saving child, as this will trigger
* a copy on write madness. */
if (((flags & LOOKUP_NOTOUCH) == 0) &&
(server.current_client && server.current_client->flags & CLIENT_NO_TOUCH) &&
(server.executing_client && server.executing_client->cmd->proc != touchCommand))
flags |= LOOKUP_NOTOUCH;
if (!hasActiveChildProcess() && !(flags & LOOKUP_NOTOUCH)){
if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
updateLFU(val);
} else {
val->lru = LRU_CLOCK();
}
}
if (!(flags & (LOOKUP_NOSTATS | LOOKUP_WRITE)))
server.stat_keyspace_hits++;
/* TODO: Use separate hits stats for WRITE */
} else {
if (!(flags & (LOOKUP_NONOTIFY | LOOKUP_WRITE)))
notifyKeyspaceEvent(NOTIFY_KEY_MISS, "keymiss", key, db->id);
if (!(flags & (LOOKUP_NOSTATS | LOOKUP_WRITE)))
server.stat_keyspace_misses++;
/* TODO: Use separate misses stats and notify event for WRITE */
}
return val;
}
/* Lookup a key for read operations, or return NULL if the key is not found
* in the specified DB.
*
* This API should not be used when we write to the key after obtaining
* the object linked to the key, but only for read only operations.
*
* This function is equivalent to lookupKey(). The point of using this function
* rather than lookupKey() directly is to indicate that the purpose is to read
* the key. */
kvobj *lookupKeyReadWithFlags(redisDb *db, robj *key, int flags) {
serverAssert(!(flags & LOOKUP_WRITE));
return lookupKey(db, key, flags, NULL);
}
/* Like lookupKeyReadWithFlags(), but does not use any flag, which is the
* common case. */
kvobj *lookupKeyRead(redisDb *db, robj *key) {
return lookupKeyReadWithFlags(db,key,LOOKUP_NONE);
}
/* Lookup a key for write operations, and as a side effect, if needed, expires
* the key if its TTL is reached. It's equivalent to lookupKey() with the
* LOOKUP_WRITE flag added.
*
* Returns the linked value object if the key exists or NULL if the key
* does not exist in the specified DB. */
kvobj *lookupKeyWriteWithFlags(redisDb *db, robj *key, int flags) {
return lookupKey(db, key, flags | LOOKUP_WRITE, NULL);
}
kvobj *lookupKeyWrite(redisDb *db, robj *key) {
return lookupKeyWriteWithFlags(db, key, LOOKUP_NONE);
}
/* Like lookupKeyWrite(), but accepts ref to optional `link`
*
* link - If key found, updated to link the key.
* If key not found, updated to the bucket where the key should be added.
* If key not found and dict is empty, it is set to NULL
*/
kvobj *lookupKeyWriteWithLink(redisDb *db, robj *key, dictEntryLink *link) {
return lookupKey(db, key, LOOKUP_NONE | LOOKUP_WRITE, link);
}
kvobj *lookupKeyReadOrReply(client *c, robj *key, robj *reply) {
kvobj *kv = lookupKeyRead(c->db, key);
if (!kv) addReplyOrErrorObject(c, reply);
return kv;
}
kvobj *lookupKeyWriteOrReply(client *c, robj *key, robj *reply) {
kvobj *kv = lookupKeyWrite(c->db, key);
if (!kv) addReplyOrErrorObject(c, reply);
return kv;
}
/* Add a key-value entry to the DB.
*
* A copy of 'key' is stored in the database. The caller must ensure the
* `key` is properly freed by calling decrRefcount(key).
*
* The value may (if its reference counter == 1) be reallocated and become
* invalid after a call to this function. The (possibly reallocated) value is
* stored in the database and the 'valref' pointer is updated to point to the
* new allocation.
*
* The reference counter of the value pointed to by valref is not incremented,
* so the caller should not free the value using decrRefcount after calling this
* function.
*
* link - Optional link to bucket where the key should be added.
* On return, get updated, by need, to the inserted key.
*
* expire - Set expiry of the key. -1 for no expiry.
*/
kvobj *dbAddInternal(redisDb *db, robj *key, robj **valref, dictEntryLink *link, long long expire) {
int slot = getKeySlot(key->ptr);
dictEntryLink tmp = NULL;
if (link == NULL) link = &tmp;
robj *val = *valref;
int hasExpire = expire != -1;
kvobj *kv = kvobjSet(key->ptr, val, hasExpire);
initObjectLRUOrLFU(kv);
kvstoreDictSetAtLink(db->keys, slot, kv, link, 1);
/* Add to expires. Leverage setExpireByLink() to reuse the key link. */
if (hasExpire) kv = setExpireByLink(NULL, db, key->ptr, expire, *link);
signalKeyAsReady(db, key, kv->type);
notifyKeyspaceEvent(NOTIFY_NEW,"new",key,db->id);
updateKeysizesHist(db, slot, kv->type, -1, getObjectLength(kv)); /* add hist */
if (server.memory_tracking_per_slot)
updateSlotAllocSize(db, slot, 0, kvobjAllocSize(kv));
*valref = kv;
return kv;
}
/* Read dbAddInternal() comment */
kvobj *dbAdd(redisDb *db, robj *key, robj **valref) {
return dbAddInternal(db, key, valref, NULL, -1);
}
kvobj *dbAddByLink(redisDb *db, robj *key, robj **valref, dictEntryLink *link) {
return dbAddInternal(db, key, valref, link, -1);
}
/* Returns key's hash slot when cluster mode is enabled, or 0 when disabled.
* The only difference between this function and getKeySlot, is that it's not using cached key slot from the current_client
* and always calculates CRC hash.
* This is useful when slot needs to be calculated for a key that user didn't request for, such as in case of eviction. */
int calculateKeySlot(sds key) {
return server.cluster_enabled ? keyHashSlot(key, (int) sdslen(key)) : 0;
}
/* Return slot-specific dictionary for key based on key's hash slot when cluster mode is enabled, else 0.*/
int getKeySlot(sds key) {
if (!server.cluster_enabled) return 0;
/* This is performance optimization that uses pre-set slot id from the current command,
* in order to avoid calculation of the key hash.
*
* This optimization is only used when current_client flag `CLIENT_EXECUTING_COMMAND` is set.
* It only gets set during the execution of command under `call` method. Other flows requesting
* the key slot would fallback to calculateKeySlot.
*/
if (server.current_client && server.current_client->slot >= 0 && server.current_client->flags & CLIENT_EXECUTING_COMMAND) {
debugServerAssertWithInfo(server.current_client, NULL,
(int)keyHashSlot(key, (int)sdslen(key)) == server.current_client->slot);
return server.current_client->slot;
}
int slot = keyHashSlot(key, (int)sdslen(key));
return slot;
}
/* Return the slot of the key in the command.
* INVALID_CLUSTER_SLOT if no keys, CLUSTER_CROSSSLOT if cross slot, otherwise the slot number. */
int getSlotFromCommand(struct redisCommand *cmd, robj **argv, int argc) {
if (!cmd || !server.cluster_enabled) return INVALID_CLUSTER_SLOT;
/* Get the keys from the command */
getKeysResult result = GETKEYS_RESULT_INIT;
getKeysFromCommand(cmd, argv, argc, &result);
/* Extract slot from the keys result. */
int slot = extractSlotFromKeysResult(argv, &result);
getKeysFreeResult(&result);
return slot;
}
/* This is a special version of dbAdd() that is used only when loading
* keys from the RDB file: the key is passed as an SDS string that is
* copied by the function and freed by the caller.
*
* Moreover this function will not abort if the key is already busy, to
* give more control to the caller, nor will signal the key as ready
* since it is not useful in this context.
*
* If added to db, returns pointer to the object, Otherwise NULL is returned.
*/
kvobj *dbAddRDBLoad(redisDb *db, sds key, robj **valref, long long expire) {
/* Add new kvobj to the db. */
int slot = getKeySlot(key);
dictEntryLink link, bucket;
link = kvstoreDictFindLink(db->keys, slot, key, &bucket);
/* If already exists, return NULL */
if (link != NULL)
return NULL;
/* prepare kvobj for insertion. Pass expire to reserve space for it */
kvobj *kv = kvobjSet(key, *valref, expire != -1);
initObjectLRUOrLFU(kv);
kvstoreDictSetAtLink(db->keys, slot, kv, &bucket, 1);
/* Set the expire time if needed */
if (expire != -1)
kv = setExpireByLink(NULL, db, key, expire, bucket);
updateKeysizesHist(db, slot, kv->type, -1, (int64_t) getObjectLength(kv));
if (server.memory_tracking_per_slot)
updateSlotAllocSize(db, slot, 0, kvobjAllocSize(kv));
return *valref = kv;
}
/**
* Overwrite an existing key's value in db with a new value.
*
* - If the reference count of 'valref' is 1 the ownership of the value is
* transferred to this function. The value may be reallocated, potentially
* invalidating any external references to it. The (potentially reallocated)
* value is stored in the database, and the 'valref' pointer is updated to
* reflect the new allocation, if one occurs.
* - The reference counter of the value referenced by 'valref' is not incremented
* so the caller must refrain from releasing it using decrRefCount after this
* function is called.
* - This function does not modify the expire time of the existing key.
* - The 'overwrite' flag is an indication whether this is done as part of a
* complete replacement of their key, which can be thought as a deletion and
* replacement (in which case we need to emit deletion signals), or just an
* update of a value of an existing key (when false).
* - The `link` is optional, can save lookup, if provided.
*/
static void dbSetValue(redisDb *db, robj *key, robj **valref, dictEntryLink link,
int overwrite, int updateKeySizes, int keepTTL) {
robj *val = *valref;
int slot = getKeySlot(key->ptr);
size_t oldsize = 0;
if (!link) {
link = kvstoreDictFindLink(db->keys, slot, key->ptr, NULL);
serverAssertWithInfo(NULL, key, link != NULL); /* expected to exist */
}
kvobj *old = dictGetKV(*link);
kvobj *kvNew;
int64_t oldlen = (int64_t) getObjectLength(old);
int oldtype = old->type;
/* if hash with HFEs, take care to remove from global HFE DS before attempting
* to manipulate and maybe free kvOld object */
if (old->type == OBJ_HASH)
estoreRemove(db->subexpires, slot, old);
if (overwrite) {
/* RM_StringDMA may call dbUnshareStringValue which may free val, so we
* need to incr to retain old */
incrRefCount(old);
/* Although the key is not really deleted from the database, we regard
* overwrite as two steps of unlink+add, so we still need to call the unlink
* callback of the module. */
moduleNotifyKeyUnlink(key,old,db->id,DB_FLAG_KEY_OVERWRITE);
/* We want to try to unblock any module clients or clients using a blocking XREADGROUP */
signalDeletedKeyAsReady(db,key,old->type);
decrRefCount(old);
/* Because of RM_StringDMA, old may be changed, so we need get old again */
old = dictGetKV(*link);
}
if (server.memory_tracking_per_slot)
oldsize = kvobjAllocSize(old);
if ((old->refcount == 1 && old->encoding != OBJ_ENCODING_EMBSTR) &&
(val->refcount == 1 && val->encoding != OBJ_ENCODING_EMBSTR)) {
/* Keep old object in the database. Just swap it's ptr, type and
* encoding with the content of val. */
robj tmp = *old;
old->type = val->type;
old->encoding = val->encoding;
old->ptr = val->ptr;
val->type = tmp.type;
val->encoding = tmp.encoding;
val->ptr = tmp.ptr;
/* Set new to old to keep the old object. Set old to val to be freed below. */
kvNew = old;
old = val;
/* Handle TTL in the optimization path */
if ((!keepTTL) && (getExpire(db, key->ptr, kvNew) >= 0))
removeExpire(db, key);
} else {
/* Replace the old value at its location in the key space. */
val->lru = old->lru;
/* Update expire reference if needed */
long long expire = getExpire(db, key->ptr, old);
int hasExpire = keepTTL && (expire != -1);
kvNew = kvobjSet(key->ptr, val, hasExpire);
kvstoreDictSetAtLink(db->keys, slot, kvNew, &link, 0);
/* Replace the old value at its location in the expire space. */
if (expire >= 0) {
if (keepTTL) {
kvobjSetExpire(kvNew, expire); /* kvNew not reallocated here */
dictEntryLink exLink = kvstoreDictFindLink(db->expires, slot,
key->ptr, NULL);
serverAssertWithInfo(NULL, key, exLink != NULL);
kvstoreDictSetAtLink(db->expires, slot, kvNew, &exLink, 0);
} else {
kvstoreDictDelete(db->expires, slot, key->ptr);
}
}
}
/* Remove old key and add new key to KEYSIZES histogram */
int64_t newlen = (int64_t) getObjectLength(kvNew);
if (updateKeySizes) {
/* Save one call if old and new are the same type */
if (oldtype == kvNew->type) {
updateKeysizesHist(db, slot, oldtype, oldlen, newlen);
} else {
updateKeysizesHist(db, slot, oldtype, oldlen, -1);
updateKeysizesHist(db, slot, kvNew->type, -1, newlen);
}
}
if (server.memory_tracking_per_slot)
updateSlotAllocSize(db, slot, oldsize, kvobjAllocSize(kvNew));
if (server.io_threads_num > 1 && old->encoding == OBJ_ENCODING_RAW) {
/* In multi-threaded mode, the OBJ_ENCODING_RAW string object usually is
* allocated in the IO thread, so we defer the free to the IO thread.
* Besides, we never free a string object in BIO threads, so, even with
* lazyfree-lazy-server-del enabled, a fallback to main thread freeing
* due to defer free failure doesn't go against the config intention. */
tryDeferFreeClientObject(server.current_client, DEFERRED_OBJECT_TYPE_ROBJ, old);
} else if (server.lazyfree_lazy_server_del) {
freeObjAsync(key, old, db->id);
} else {
decrRefCount(old);
}
*valref = kvNew;
}
/* Replace an existing key with a new value, we just replace value and don't
* emit any events */
void dbReplaceValue(redisDb *db, robj *key, robj **valref, int updateKeySizes) {
dbSetValue(db, key, valref, NULL, 0, updateKeySizes, 1);
}
/* Replace an existing key with a new value (don't emit any events)
*
* parameter 'link' is optional. If provided, saves lookup.
*/
void dbReplaceValueWithLink(redisDb *db, robj *key, robj **val, dictEntryLink link) {
dbSetValue(db, key, val, link, 0, 1, 1);
}
/* High level Set operation. This function can be used in order to set
* a key, whatever it was existing or not, to a new object.
*
* 1) The value may be reallocated when adding it to the database. The value
* pointer 'valref' is updated to point to the reallocated object. The
* reference count of the value object is *not* incremented.
* 2) clients WATCHing for the destination key notified.
* 3) The expire time of the key is reset (the key is made persistent),
* unless 'SETKEY_KEEPTTL' is enabled in flags.
* 4) The key lookup can take place outside this interface outcome will be
* delivered with 'SETKEY_ALREADY_EXIST' or 'SETKEY_DOESNT_EXIST'
*
* All the new keys in the database should be created via this interface.
* The client 'c' argument may be set to NULL if the operation is performed
* in a context where there is no clear client performing the operation. */
void setKey(client *c, redisDb *db, robj *key, robj **valref, int flags) {
setKeyByLink(c, db, key, valref, flags, NULL);
}
/* Like setKey(), but accepts an optional link
*
* - If flags is set with SETKEY_ALREADY_EXIST, then `link` must be provided
* - If flags is set with SETKEY_DOESNT_EXIST, then `link` is optional. If
* provided, it will point to the bucket where the key should be added.
* - If flag is not set (0) then add or update key, and `link` must be NULL
* On return, link get updated, by need, to the inserted kvobj.
*/
void setKeyByLink(client *c, redisDb *db, robj *key, robj **valref, int flags, dictEntryLink *plink) {
dictEntryLink dummy = NULL, *link = plink ? plink : &dummy;
int exists;
kvobj *oldval = NULL;
if (flags & SETKEY_ALREADY_EXIST) {
debugServerAssert((*link) != NULL);
oldval = dictGetKV(**link);
exists = 1;
} else if (flags & SETKEY_DOESNT_EXIST) {
/* link is optional */
exists = 0;
} else {
/* Add or update key */
oldval = lookupKeyWriteWithLink(db, key, link);
exists = oldval != NULL;
}
if (exists) {
int oldtype = oldval->type;
int newtype = (*valref)->type;
/* Update the value of an existing key */
dbSetValue(db, key, valref, *link, 1, 1, flags & SETKEY_KEEPTTL);
/* Notify keyspace events for override and type change */
notifyKeyspaceEvent(NOTIFY_OVERWRITTEN, "overwritten", key, db->id);
if (oldtype != newtype)
notifyKeyspaceEvent(NOTIFY_TYPE_CHANGED, "type_changed", key, db->id);
} else {
/* Add the new key to the database */
dbAddByLink(db, key, valref, link);
}
if (!(flags & SETKEY_NO_SIGNAL))
signalModifiedKey(c,db,key);
}
/* During atomic slot migration, keys that are being imported are in an
* intermediate state. we cannot access them and therefore skip them.
*
* This callback function now is used by:
* - dbRandomKey
* - keysCommand
* - scanCommand
*/
static int accessKeysShouldSkipDictIndex(int didx) {
return !clusterCanAccessKeysInSlot(didx);
}
/* Return a random key, in form of a Redis object.
* If there are no keys, NULL is returned.
*
* The function makes sure to return keys not already expired. */
robj *dbRandomKey(redisDb *db) {
dictEntry *de;
int maxtries = 100;
int allvolatile = kvstoreSize(db->keys) == kvstoreSize(db->expires);
while(1) {
robj *keyobj;
int randomSlot = kvstoreGetFairRandomDictIndex(db->keys, accessKeysShouldSkipDictIndex, 16, 1);
if (randomSlot == -1) return NULL;
de = kvstoreDictGetFairRandomKey(db->keys, randomSlot);
if (de == NULL) return NULL;
kvobj *kv = dictGetKV(de);
sds key = kvobjGetKey(kv);
keyobj = createStringObject(key,sdslen(key));
if (allvolatile && (server.masterhost || isPausedActions(PAUSE_ACTION_EXPIRE)) && --maxtries == 0) {
/* If the DB is composed only of keys with an expire set,
* it could happen that all the keys are already logically
* expired in the slave, so the function cannot stop because
* expireIfNeeded() is false, nor it can stop because
* dictGetFairRandomKey() returns NULL (there are keys to return).
* To prevent the infinite loop we do some tries, but if there
* are the conditions for an infinite loop, eventually we
* return a key name that may be already expired. */
return keyobj;
}
if (expireIfNeeded(db, keyobj, kv, 0) != KEY_VALID) {
decrRefCount(keyobj);
continue; /* search for another key. This expired. */
}
return keyobj;
}
}
/* Helper for sync and async delete. */
int dbGenericDelete(redisDb *db, robj *key, int async, int flags) {
dictEntryLink link;
int table;
int slot = getKeySlot(key->ptr);
link = kvstoreDictTwoPhaseUnlinkFind(db->keys, slot, key->ptr, &table);
if (link) {
kvobj *kv = dictGetKV(*link);
int64_t oldlen = (int64_t) getObjectLength(kv);
int type = kv->type;
/* If hash object with expiry on fields, remove it from HFE DS of DB */
if (type == OBJ_HASH)
estoreRemove(db->subexpires, slot, kv);
/* RM_StringDMA may call dbUnshareStringValue which may free kv, so we
* need to incr to retain kv */
incrRefCount(kv); /* refcnt=1->2 */
/* Tells the module that the key has been unlinked from the database. */
moduleNotifyKeyUnlink(key, kv, db->id, flags);
/* We want to try to unblock any module clients or clients using a blocking XREADGROUP */
signalDeletedKeyAsReady(db,key,type);
/* We should call decr before freeObjAsync. If not, the refcount may be
* greater than 1, so freeObjAsync doesn't work */
decrRefCount(kv);
/* Because of dbUnshareStringValue, the val in db may change. */
kv = dictGetKV(*link);
/* if expirable, delete an entry from the expires dict is not decrRefCount of kvobj */
if (kvobjGetExpire(kv) != -1)
kvstoreDictDelete(db->expires, slot, key->ptr);
if (async) {
if (server.memory_tracking_per_slot)
updateSlotAllocSize(db, slot, kvobjAllocSize(kv), 0);
freeObjAsync(key, kv, db->id);
/* Set the key to NULL in the main dictionary. */
kvstoreDictSetAtLink(db->keys, slot, NULL, &link, 0);
}
kvstoreDictTwoPhaseUnlinkFree(db->keys, slot, link, table);
/* remove key from histogram */
if(!(flags & DB_FLAG_NO_UPDATE_KEYSIZES))
updateKeysizesHist(db, slot, type, oldlen, -1);
return 1;
} else {
return 0;
}
}
/* Delete a key, value, and associated expiration entry if any, from the DB */
int dbSyncDelete(redisDb *db, robj *key) {
return dbGenericDelete(db, key, 0, DB_FLAG_KEY_DELETED);
}
/* Delete a key, value, and associated expiration entry if any, from the DB. If
* the value consists of many allocations, it may be freed asynchronously. */
int dbAsyncDelete(redisDb *db, robj *key) {
return dbGenericDelete(db, key, 1, DB_FLAG_KEY_DELETED);
}
/* This is a wrapper whose behavior depends on the Redis lazy free
* configuration. Deletes the key synchronously or asynchronously. */
int dbDelete(redisDb *db, robj *key) {
return dbGenericDelete(db, key, server.lazyfree_lazy_server_del, DB_FLAG_KEY_DELETED);
}
/* Similar to dbDelete(), but does not update the keysizes histogram.
* This is used when we want to delete a key without affecting the histogram,
* typically in cases where a command flow deletes elements from a collection
* and then deletes the collection itself. In such cases, using dbDelete()
* would incorrectly decrement bin #0. A corresponding test should be added
* to `info-keysizes.tcl`. */
int dbDeleteSkipKeysizesUpdate(redisDb *db, robj *key) {
return dbGenericDelete(db, key, server.lazyfree_lazy_server_del,
DB_FLAG_KEY_DELETED | DB_FLAG_NO_UPDATE_KEYSIZES);
}
/* Prepare the string object stored at 'key' to be modified destructively
* to implement commands like SETBIT or APPEND.
*
* An object is usually ready to be modified unless one of the two conditions
* are true:
*
* 1) The object 'o' is shared (refcount > 1), we don't want to affect
* other users.
* 2) The object encoding is not "RAW".
*
* If the object is found in one of the above conditions (or both) by the
* function, an unshared / not-encoded copy of the string object is stored
* at 'key' in the specified 'db'. Otherwise the object 'o' itself is
* returned.
*
* USAGE:
*
* The object 'o' is what the caller already obtained by looking up 'key'
* in 'db', the usage pattern looks like this:
*
* o = lookupKeyWrite(db,key);
* if (checkType(c,o,OBJ_STRING)) return;
* o = dbUnshareStringValue(db,key,o);
*
* At this point the caller is ready to modify the object, for example
* using an sdscat() call to append some data, or anything else.
*/
kvobj *dbUnshareStringValue(redisDb *db, robj *key, kvobj *kv) {
return dbUnshareStringValueByLink(db,key,kv,NULL);
}
/* Like dbUnshareStringValue(), but accepts a optional link,
* which can be used if we already have one, thus saving the dbFind call. */
kvobj *dbUnshareStringValueByLink(redisDb *db, robj *key, kvobj *o, dictEntryLink link) {
serverAssert(o->type == OBJ_STRING);
if (o->refcount != 1 || o->encoding != OBJ_ENCODING_RAW) {
robj *decoded = getDecodedObject(o);
o = createRawStringObject(decoded->ptr, sdslen(decoded->ptr));
decrRefCount(decoded);
dbReplaceValueWithLink(db, key, &o, link);
}
return o;
}
/* Remove all keys from the database(s) structure. The dbarray argument
* may not be the server main DBs (could be a temporary DB).
*
* The dbnum can be -1 if all the DBs should be emptied, or the specified
* DB index if we want to empty only a single database.
* The function returns the number of keys removed from the database(s). */
long long emptyDbStructure(redisDb *dbarray, int dbnum, int async,
void(callback)(dict*))
{
long long removed = 0;
int startdb, enddb;
if (dbnum == -1) {
startdb = 0;
enddb = server.dbnum-1;
} else {
startdb = enddb = dbnum;
}
for (int j = startdb; j <= enddb; j++) {
removed += kvstoreSize(dbarray[j].keys);
if (async) {
emptyDbAsync(&dbarray[j]);
} else {
/* Destroy sub-expires before deleting the kv-objects since ebuckets
* data structure is embedded in the stored kv-objects. */
estoreEmpty(dbarray[j].subexpires);
kvstoreEmpty(dbarray[j].keys, callback);
kvstoreEmpty(dbarray[j].expires, callback);
}
/* Because all keys of database are removed, reset average ttl. */
dbarray[j].avg_ttl = 0;
dbarray[j].expires_cursor = 0;
}
return removed;
}
/* Remove all data (keys and functions) from all the databases in a
* Redis server. If callback is given the function is called from
* time to time to signal that work is in progress.
*
* The dbnum can be -1 if all the DBs should be flushed, or the specified
* DB number if we want to flush only a single Redis database number.
*
* Flags are be EMPTYDB_NO_FLAGS if no special flags are specified or
* EMPTYDB_ASYNC if we want the memory to be freed in a different thread
* and the function to return ASAP. EMPTYDB_NOFUNCTIONS can also be set
* to specify that we do not want to delete the functions.
*
* On success the function returns the number of keys removed from the
* database(s). Otherwise -1 is returned in the specific case the
* DB number is out of range, and errno is set to EINVAL. */
long long emptyData(int dbnum, int flags, void(callback)(dict*)) {
int async = (flags & EMPTYDB_ASYNC);
int with_functions = !(flags & EMPTYDB_NOFUNCTIONS);
RedisModuleFlushInfoV1 fi = {REDISMODULE_FLUSHINFO_VERSION,!async,dbnum};
long long removed = 0;
if (dbnum < -1 || dbnum >= server.dbnum) {
errno = EINVAL;
return -1;
}
if (dbnum == -1 || dbnum == 0)
asmCancelTrimJobs();
/* Fire the flushdb modules event. */
moduleFireServerEvent(REDISMODULE_EVENT_FLUSHDB,
REDISMODULE_SUBEVENT_FLUSHDB_START,
&fi);
/* Make sure the WATCHed keys are affected by the FLUSH* commands.
* Note that we need to call the function while the keys are still
* there. */
signalFlushedDb(dbnum, async, NULL);
/* Empty redis database structure. */
removed = emptyDbStructure(server.db, dbnum, async, callback);
if (dbnum == -1) flushSlaveKeysWithExpireList();
if (with_functions) {
serverAssert(dbnum == -1);
functionsLibCtxClearCurrent(async);
}
/* Also fire the end event. Note that this event will fire almost
* immediately after the start event if the flush is asynchronous. */
moduleFireServerEvent(REDISMODULE_EVENT_FLUSHDB,
REDISMODULE_SUBEVENT_FLUSHDB_END,
&fi);
return removed;
}
/* Initialize temporary db on replica for use during diskless replication. */
redisDb *initTempDb(void) {
int slot_count_bits = 0;
int flags = KVSTORE_ALLOCATE_DICTS_ON_DEMAND;
if (server.cluster_enabled) {
slot_count_bits = CLUSTER_SLOT_MASK_BITS;
flags |= KVSTORE_FREE_EMPTY_DICTS;
}
redisDb *tempDb = zcalloc(sizeof(redisDb)*server.dbnum);
for (int i=0; i<server.dbnum; i++) {
tempDb[i].id = i;
tempDb[i].keys = kvstoreCreate(&dbDictType, slot_count_bits,
flags | KVSTORE_ALLOC_META_KEYS_HIST);
tempDb[i].expires = kvstoreCreate(&dbExpiresDictType, slot_count_bits, flags);
tempDb[i].subexpires = estoreCreate(&subexpiresBucketsType, slot_count_bits);
}
return tempDb;
}
/* Discard tempDb, this can be slow (similar to FLUSHALL), but it's always async. */
void discardTempDb(redisDb *tempDb) {
int async = 1;
/* Release temp DBs. */
emptyDbStructure(tempDb, -1, async, NULL);
for (int i=0; i<server.dbnum; i++) {
/* Destroy sub-expires before deleting the kv-objects since ebuckets
* data structure is embedded in the stored kv-objects. */
estoreRelease(tempDb[i].subexpires);
kvstoreRelease(tempDb[i].keys);
kvstoreRelease(tempDb[i].expires);
}
zfree(tempDb);
}
int selectDb(client *c, int id) {
if (id < 0 || id >= server.dbnum)
return C_ERR;
c->db = &server.db[id];
return C_OK;
}
long long dbTotalServerKeyCount(void) {