-
Notifications
You must be signed in to change notification settings - Fork 716
/
Copy pathserver.c
7130 lines (6337 loc) · 299 KB
/
server.c
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-2016, Redis Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "server.h"
#include "monotonic.h"
#include "cluster.h"
#include "cluster_slot_stats.h"
#include "slowlog.h"
#include "bio.h"
#include "latency.h"
#include "mt19937-64.h"
#include "functions.h"
#include "hdr_histogram.h"
#include "syscheck.h"
#include "threads_mngr.h"
#include "fmtargs.h"
#include "io_threads.h"
#include "sds.h"
#include <time.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <ctype.h>
#include <stdarg.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <limits.h>
#include <float.h>
#include <math.h>
#include <sys/utsname.h>
#include <locale.h>
#include <sys/socket.h>
#ifdef __linux__
#include <sys/mman.h>
#endif
#if defined(HAVE_SYSCTL_KIPC_SOMAXCONN) || defined(HAVE_SYSCTL_KERN_SOMAXCONN)
#include <sys/sysctl.h>
#endif
#ifdef __GNUC__
#define GNUC_VERSION_STR STRINGIFY(__GNUC__) "." STRINGIFY(__GNUC_MINOR__) "." STRINGIFY(__GNUC_PATCHLEVEL__)
#else
#define GNUC_VERSION_STR "0.0.0"
#endif
/* Our shared "common" objects */
struct sharedObjectsStruct shared;
/* Global vars that are actually used as constants. The following double
* values are used for double on-disk serialization, and are initialized
* at runtime to avoid strange compiler optimizations. */
double R_Zero, R_PosInf, R_NegInf, R_Nan;
/*================================= Globals ================================= */
/* Global vars */
struct valkeyServer server; /* Server global state */
/*============================ Internal prototypes ========================== */
static inline int isShutdownInitiated(void);
int isReadyToShutdown(void);
int finishShutdown(void);
const char *replstateToString(int replstate);
/*============================ Utility functions ============================ */
/* This macro tells if we are in the context of loading an AOF. */
#define isAOFLoadingContext() ((server.current_client && server.current_client->id == CLIENT_ID_AOF) ? 1 : 0)
/* We use a private localtime implementation which is fork-safe. The logging
* function of the server may be called from other threads. */
void nolocks_localtime(struct tm *tmp, time_t t, time_t tz, int dst);
/* Formats the timezone offset into a string. daylight_active indicates whether dst is active (1)
* or not (0). */
void formatTimezone(char *buf, size_t buflen, int timezone, int daylight_active) {
serverAssert(buflen >= 7);
serverAssert(timezone >= -50400 && timezone <= 43200);
// Adjust the timezone for daylight saving, if active
int total_offset = (-1) * timezone + 3600 * daylight_active;
int hours = abs(total_offset / 3600);
int minutes = abs(total_offset % 3600) / 60;
buf[0] = total_offset >= 0 ? '+' : '-';
buf[1] = '0' + hours / 10;
buf[2] = '0' + hours % 10;
buf[3] = ':';
buf[4] = '0' + minutes / 10;
buf[5] = '0' + minutes % 10;
buf[6] = '\0';
}
bool hasInvalidLogfmtChar(const char *msg) {
if (msg == NULL) return false;
for (int i = 0; msg[i] != '\0'; i++) {
if (msg[i] == '"' || msg[i] == '\n' || msg[i] == '\r') {
return true;
}
}
return false;
}
/* Modifies the input string by:
* replacing \r and \n with whitespace
* replacing " with '
*
* Parameters:
* safemsg - A char pointer where the modified message will be stored
* safemsglen - size of safemsg
* msg - The original message */
void filterInvalidLogfmtChar(char *safemsg, size_t safemsglen, const char *msg) {
serverAssert(safemsglen == LOG_MAX_LEN);
if (msg == NULL) return;
size_t index = 0;
while (index < safemsglen - 1 && msg[index] != '\0') {
if (msg[index] == '"') {
safemsg[index] = '\'';
} else if (msg[index] == '\n' || msg[index] == '\r') {
safemsg[index] = ' ';
} else {
safemsg[index] = msg[index];
}
index++;
}
safemsg[index] = '\0';
}
/* Low level logging. To use only for very big messages, otherwise
* serverLog() is to prefer. */
void serverLogRaw(int level, const char *msg) {
const int syslogLevelMap[] = {LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING};
const char *c = ".-*#";
const char *verbose_level[] = {"debug", "info", "notice", "warning"};
const char *roles[] = {"sentinel", "RDB/AOF", "replica", "primary"};
const char *role_chars = "XCSM";
FILE *fp;
char buf[64];
int rawmode = (level & LL_RAW);
int log_to_stdout = server.logfile[0] == '\0';
level &= 0xff; /* clear flags */
if (level < server.verbosity) return;
/* We open and close the log file in every call to support log rotation.
* This allows external processes to move or truncate the log file without
* disrupting logging. */
fp = log_to_stdout ? stdout : fopen(server.logfile, "a");
if (!fp) return;
if (rawmode) {
fprintf(fp, "%s", msg);
} else {
int off;
struct timeval tv;
pid_t pid = getpid();
int daylight_active = atomic_load_explicit(&server.daylight_active, memory_order_relaxed);
gettimeofday(&tv, NULL);
struct tm tm;
nolocks_localtime(&tm, tv.tv_sec, server.timezone, daylight_active);
switch (server.log_timestamp_format) {
case LOG_TIMESTAMP_LEGACY:
off = strftime(buf, sizeof(buf), "%d %b %Y %H:%M:%S.", &tm);
snprintf(buf + off, sizeof(buf) - off, "%03d", (int)tv.tv_usec / 1000);
break;
case LOG_TIMESTAMP_ISO8601:
off = strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.", &tm);
char tzbuf[7];
formatTimezone(tzbuf, sizeof(tzbuf), server.timezone, server.daylight_active);
snprintf(buf + off, sizeof(buf) - off, "%03d%s", (int)tv.tv_usec / 1000, tzbuf);
break;
case LOG_TIMESTAMP_MILLISECONDS:
snprintf(buf, sizeof(buf), "%lld", (long long)tv.tv_sec * 1000 + (long long)tv.tv_usec / 1000);
break;
}
int role_index;
if (server.sentinel_mode) {
role_index = 0; /* Sentinel. */
} else if (pid != server.pid) {
role_index = 1; /* RDB / AOF writing child. */
} else {
role_index = (server.primary_host ? 2 : 3); /* Replica or Primary. */
}
switch (server.log_format) {
case LOG_FORMAT_LOGFMT:
if (hasInvalidLogfmtChar(msg)) {
char safemsg[LOG_MAX_LEN];
filterInvalidLogfmtChar(safemsg, LOG_MAX_LEN, msg);
fprintf(fp, "pid=%d role=%s timestamp=\"%s\" level=%s message=\"%s\"\n", (int)getpid(), roles[role_index],
buf, verbose_level[level], safemsg);
} else {
fprintf(fp, "pid=%d role=%s timestamp=\"%s\" level=%s message=\"%s\"\n", (int)getpid(), roles[role_index],
buf, verbose_level[level], msg);
}
break;
case LOG_FORMAT_LEGACY:
fprintf(fp, "%d:%c %s %c %s\n", (int)getpid(), role_chars[role_index], buf, c[level], msg);
break;
}
}
fflush(fp);
if (!log_to_stdout) fclose(fp);
if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg);
}
/* Like serverLogRaw() but with printf-alike support. This is the function that
* is used across the code. The raw version is only used in order to dump
* the INFO output on crash. */
void _serverLog(int level, const char *fmt, ...) {
va_list ap;
char msg[LOG_MAX_LEN];
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
serverLogRaw(level, msg);
}
/* Low level logging from signal handler. Should be used with pre-formatted strings.
See serverLogFromHandler. */
void serverLogRawFromHandler(int level, const char *msg) {
int fd;
int log_to_stdout = server.logfile[0] == '\0';
char buf[64];
if ((level & 0xff) < server.verbosity || (log_to_stdout && server.daemonize)) return;
fd = log_to_stdout ? STDOUT_FILENO : open(server.logfile, O_APPEND | O_CREAT | O_WRONLY, 0644);
if (fd == -1) return;
if (level & LL_RAW) {
if (write(fd, msg, strlen(msg)) == -1) goto err;
} else {
ll2string(buf, sizeof(buf), getpid());
if (write(fd, buf, strlen(buf)) == -1) goto err;
if (write(fd, ":signal-handler (", 17) == -1) goto err;
ll2string(buf, sizeof(buf), time(NULL));
if (write(fd, buf, strlen(buf)) == -1) goto err;
if (write(fd, ") ", 2) == -1) goto err;
if (write(fd, msg, strlen(msg)) == -1) goto err;
if (write(fd, "\n", 1) == -1) goto err;
}
err:
if (!log_to_stdout) close(fd);
}
/* An async-signal-safe version of serverLog. if LL_RAW is not included in level flags,
* The message format is: <pid>:signal-handler (<time>) <msg> \n
* with LL_RAW flag only the msg is printed (with no new line at the end)
*
* We actually use this only for signals that are not fatal from the point
* of view of the server. Signals that are going to kill the server anyway and
* where we need printf-alike features are served by serverLog(). */
void serverLogFromHandler(int level, const char *fmt, ...) {
va_list ap;
char msg[LOG_MAX_LEN];
va_start(ap, fmt);
vsnprintf_async_signal_safe(msg, sizeof(msg), fmt, ap);
va_end(ap);
serverLogRawFromHandler(level, msg);
}
/* Return the UNIX time in microseconds */
long long ustime(void) {
struct timeval tv;
long long ust;
gettimeofday(&tv, NULL);
ust = ((long long)tv.tv_sec) * 1000000;
ust += tv.tv_usec;
return ust;
}
/* Return the UNIX time in milliseconds */
mstime_t mstime(void) {
return ustime() / 1000;
}
/* Return the command time snapshot in milliseconds.
* The time the command started is the logical time it runs,
* and all the time readings during the execution time should
* reflect the same time.
* More details can be found in the comments below. */
mstime_t commandTimeSnapshot(void) {
/* When we are in the middle of a command execution, we want to use a
* reference time that does not change: in that case we just use the
* cached time, that we update before each call in the call() function.
* This way we avoid that commands such as RPOPLPUSH or similar, that
* may re-open the same key multiple times, can invalidate an already
* open object in a next call, if the next call will see the key expired,
* while the first did not.
* This is specifically important in the context of scripts, where we
* pretend that time freezes. This way a key can expire only the first time
* it is accessed and not in the middle of the script execution, making
* propagation to replicas / AOF consistent. See issue #1525 for more info.
* Note that we cannot use the cached server.mstime because it can change
* in processEventsWhileBlocked etc. */
return server.cmd_time_snapshot;
}
/* After an RDB dump or AOF rewrite we exit from children using _exit() instead of
* exit(), because the latter may interact with the same file objects used by
* the parent process. However if we are testing the coverage normal exit() is
* used in order to obtain the right coverage information. */
void exitFromChild(int retcode) {
#ifdef COVERAGE_TEST
exit(retcode);
#else
_exit(retcode);
#endif
}
/*====================== Hash table type implementation ==================== */
/* This is a hash table type that uses the SDS dynamic strings library as
* keys and Objects as values (Objects can hold SDS strings,
* lists, sets). */
void dictVanillaFree(void *val) {
zfree(val);
}
void dictListDestructor(void *val) {
listRelease((list *)val);
}
void dictDictDestructor(void *val) {
dictRelease((dict *)val);
}
/* Returns 1 when keys match */
int dictSdsKeyCompare(const void *key1, const void *key2) {
int l1, l2;
l1 = sdslen((sds)key1);
l2 = sdslen((sds)key2);
if (l1 != l2) return 0;
return memcmp(key1, key2, l1) == 0;
}
/* Returns 0 when keys match */
int hashtableSdsKeyCompare(const void *key1, const void *key2) {
const sds sds1 = (const sds)key1, sds2 = (const sds)key2;
return sdslen(sds1) != sdslen(sds2) || sdscmp(sds1, sds2);
}
size_t dictSdsEmbedKey(unsigned char *buf, size_t buf_len, const void *key, uint8_t *key_offset) {
return sdscopytobuffer(buf, buf_len, (sds)key, key_offset);
}
/* A case insensitive version used for the command lookup table and other
* places where case insensitive non binary-safe comparison is needed. */
int dictSdsKeyCaseCompare(const void *key1, const void *key2) {
return strcasecmp(key1, key2) == 0;
}
/* Case insensitive key comparison */
int hashtableStringKeyCaseCompare(const void *key1, const void *key2) {
return strcasecmp(key1, key2);
}
void dictObjectDestructor(void *val) {
if (val == NULL) return; /* Lazy freeing will set value to NULL. */
decrRefCount(val);
}
void dictSdsDestructor(void *val) {
sdsfree(val);
}
void *dictSdsDup(const void *key) {
return sdsdup((const sds)key);
}
int dictObjKeyCompare(const void *key1, const void *key2) {
const robj *o1 = key1, *o2 = key2;
return dictSdsKeyCompare(o1->ptr, o2->ptr);
}
uint64_t dictObjHash(const void *key) {
const robj *o = key;
return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
}
uint64_t dictSdsHash(const void *key) {
return dictGenHashFunction((unsigned char *)key, sdslen((char *)key));
}
uint64_t dictSdsCaseHash(const void *key) {
return dictGenCaseHashFunction((unsigned char *)key, sdslen((char *)key));
}
/* Dict hash function for null terminated string */
uint64_t dictCStrHash(const void *key) {
return dictGenHashFunction((unsigned char *)key, strlen((char *)key));
}
/* Dict hash function for null terminated string */
uint64_t dictCStrCaseHash(const void *key) {
return dictGenCaseHashFunction((unsigned char *)key, strlen((char *)key));
}
/* Dict hash function for client */
uint64_t dictClientHash(const void *key) {
return ((client *)key)->id;
}
/* Dict compare function for client */
int dictClientKeyCompare(const void *key1, const void *key2) {
return ((client *)key1)->id == ((client *)key2)->id;
}
/* Dict compare function for null terminated string */
int dictCStrKeyCompare(const void *key1, const void *key2) {
int l1, l2;
l1 = strlen((char *)key1);
l2 = strlen((char *)key2);
if (l1 != l2) return 0;
return memcmp(key1, key2, l1) == 0;
}
/* Dict case insensitive compare function for null terminated string */
int dictCStrKeyCaseCompare(const void *key1, const void *key2) {
return strcasecmp(key1, key2) == 0;
}
int dictEncObjKeyCompare(const void *key1, const void *key2) {
robj *o1 = (robj *)key1, *o2 = (robj *)key2;
int cmp;
if (o1->encoding == OBJ_ENCODING_INT && o2->encoding == OBJ_ENCODING_INT) return o1->ptr == o2->ptr;
/* Due to OBJ_STATIC_REFCOUNT, we avoid calling getDecodedObject() without
* good reasons, because it would incrRefCount() the object, which
* is invalid. So we check to make sure dictFind() works with static
* objects as well. */
if (o1->refcount != OBJ_STATIC_REFCOUNT) o1 = getDecodedObject(o1);
if (o2->refcount != OBJ_STATIC_REFCOUNT) o2 = getDecodedObject(o2);
cmp = dictSdsKeyCompare(o1->ptr, o2->ptr);
if (o1->refcount != OBJ_STATIC_REFCOUNT) decrRefCount(o1);
if (o2->refcount != OBJ_STATIC_REFCOUNT) decrRefCount(o2);
return cmp;
}
uint64_t dictEncObjHash(const void *key) {
robj *o = (robj *)key;
if (sdsEncodedObject(o)) {
return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
} else if (o->encoding == OBJ_ENCODING_INT) {
char buf[32];
int len;
len = ll2string(buf, 32, (long)o->ptr);
return dictGenHashFunction((unsigned char *)buf, len);
} else {
serverPanic("Unknown string encoding");
}
}
/* Return 1 if we allow a hash table to expand. It may allocate a huge amount of
* memory to contain hash buckets when it expands, that may lead the server to
* reject user's requests or evict some keys. We can prevent expansion
* provisionally if used memory will be over maxmemory after it expands,
* but to guarantee the performance of the server, we still allow it to expand
* if the load factor exceeds the hard limit defined in hashtable.c. */
int hashtableResizeAllowed(size_t moreMem, double usedRatio) {
UNUSED(usedRatio);
/* For debug purposes, not allowed to be resized. */
if (!server.dict_resizing) return 0;
/* Avoid resizing over max memory. */
return !overMaxmemoryAfterAlloc(moreMem);
}
const void *hashtableCommandGetKey(const void *element) {
struct serverCommand *command = (struct serverCommand *)element;
return command->fullname;
}
const void *hashtableSubcommandGetKey(const void *element) {
struct serverCommand *command = (struct serverCommand *)element;
return command->declared_name;
}
/* Generic hash table type where keys are Objects, Values
* dummy pointers. */
dictType objectKeyPointerValueDictType = {
dictEncObjHash, /* hash function */
NULL, /* key dup */
dictEncObjKeyCompare, /* key compare */
dictObjectDestructor, /* key destructor */
NULL, /* val destructor */
NULL /* allow to expand */
};
/* Like objectKeyPointerValueDictType(), but values can be destroyed, if
* not NULL, calling zfree(). */
dictType objectKeyHeapPointerValueDictType = {
dictEncObjHash, /* hash function */
NULL, /* key dup */
dictEncObjKeyCompare, /* key compare */
dictObjectDestructor, /* key destructor */
dictVanillaFree, /* val destructor */
NULL /* allow to expand */
};
/* Set hashtable type. Items are SDS strings */
hashtableType setHashtableType = {
.hashFunction = dictSdsHash,
.keyCompare = hashtableSdsKeyCompare,
.entryDestructor = dictSdsDestructor};
/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
dictType zsetDictType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
dictSdsKeyCompare, /* key compare */
NULL, /* Note: SDS string shared & freed by skiplist */
NULL, /* val destructor */
NULL, /* allow to expand */
};
uint64_t hashtableSdsHash(const void *key) {
return hashtableGenHashFunction((const char *)key, sdslen((char *)key));
}
const void *hashtableObjectGetKey(const void *entry) {
return objectGetKey(entry);
}
int hashtableObjKeyCompare(const void *key1, const void *key2) {
const robj *o1 = key1, *o2 = key2;
return hashtableSdsKeyCompare(o1->ptr, o2->ptr);
}
void hashtableObjectDestructor(void *val) {
if (val == NULL) return; /* Lazy freeing will set value to NULL. */
decrRefCount(val);
}
/* Kvstore->keys, keys are sds strings, vals are Objects. */
hashtableType kvstoreKeysHashtableType = {
.entryGetKey = hashtableObjectGetKey,
.hashFunction = hashtableSdsHash,
.keyCompare = hashtableSdsKeyCompare,
.entryDestructor = hashtableObjectDestructor,
.resizeAllowed = hashtableResizeAllowed,
.rehashingStarted = kvstoreHashtableRehashingStarted,
.rehashingCompleted = kvstoreHashtableRehashingCompleted,
.trackMemUsage = kvstoreHashtableTrackMemUsage,
.getMetadataSize = kvstoreHashtableMetadataSize,
};
/* Kvstore->expires */
hashtableType kvstoreExpiresHashtableType = {
.entryGetKey = hashtableObjectGetKey,
.hashFunction = hashtableSdsHash,
.keyCompare = hashtableSdsKeyCompare,
.entryDestructor = NULL, /* shared with keyspace table */
.resizeAllowed = hashtableResizeAllowed,
.rehashingStarted = kvstoreHashtableRehashingStarted,
.rehashingCompleted = kvstoreHashtableRehashingCompleted,
.trackMemUsage = kvstoreHashtableTrackMemUsage,
.getMetadataSize = kvstoreHashtableMetadataSize,
};
/* Command set, hashed by sds string, stores serverCommand structs. */
hashtableType commandSetType = {.entryGetKey = hashtableCommandGetKey,
.hashFunction = dictSdsCaseHash,
.keyCompare = hashtableStringKeyCaseCompare,
.instant_rehashing = 1};
/* Sub-command set, hashed by char* string, stores serverCommand structs. */
hashtableType subcommandSetType = {.entryGetKey = hashtableSubcommandGetKey,
.hashFunction = dictCStrCaseHash,
.keyCompare = hashtableStringKeyCaseCompare,
.instant_rehashing = 1};
/* Hash type hash table (note that small hashes are represented with listpacks) */
dictType hashDictType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
dictSdsKeyCompare, /* key compare */
dictSdsDestructor, /* key destructor */
dictSdsDestructor, /* val destructor */
NULL, /* allow to expand */
};
/* Dict type without destructor */
dictType sdsReplyDictType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
dictSdsKeyCompare, /* key compare */
NULL, /* key destructor */
NULL, /* val destructor */
NULL /* allow to expand */
};
/* Hashtable type without destructor */
hashtableType sdsReplyHashtableType = {
.hashFunction = dictSdsCaseHash,
.keyCompare = hashtableSdsKeyCompare};
/* Keylist hash table type has unencoded Objects as keys and
* lists as values. It's used for blocking operations (BLPOP) and to
* map swapped keys to a list of clients waiting for this keys to be loaded. */
dictType keylistDictType = {
dictObjHash, /* hash function */
NULL, /* key dup */
dictObjKeyCompare, /* key compare */
dictObjectDestructor, /* key destructor */
dictListDestructor, /* val destructor */
NULL /* allow to expand */
};
/* KeyDict hash table type has unencoded Objects as keys and
* dicts as values. It's used for PUBSUB command to track clients subscribing the patterns. */
dictType objToDictDictType = {
dictObjHash, /* hash function */
NULL, /* key dup */
dictObjKeyCompare, /* key compare */
dictObjectDestructor, /* key destructor */
dictDictDestructor, /* val destructor */
NULL /* allow to expand */
};
/* Callback used for hash tables where the entries are dicts and the key
* (channel name) is stored in each dict's metadata. */
const void *hashtableChannelsDictGetKey(const void *entry) {
const dict *d = entry;
return *((const void **)dictMetadata(d));
}
void hashtableChannelsDictDestructor(void *entry) {
dict *d = entry;
robj *channel = *((void **)dictMetadata(d));
decrRefCount(channel);
dictRelease(d);
}
/* Similar to objToDictDictType, but changed to hashtable and added some kvstore
* callbacks, it's used for PUBSUB command to track clients subscribing the
* channels. The elements are dicts where the keys are clients. The metadata in
* each dict stores a pointer to the channel name. */
hashtableType kvstoreChannelHashtableType = {
.entryGetKey = hashtableChannelsDictGetKey,
.hashFunction = dictObjHash,
.keyCompare = hashtableObjKeyCompare,
.entryDestructor = hashtableChannelsDictDestructor,
.rehashingStarted = kvstoreHashtableRehashingStarted,
.rehashingCompleted = kvstoreHashtableRehashingCompleted,
.trackMemUsage = kvstoreHashtableTrackMemUsage,
.getMetadataSize = kvstoreHashtableMetadataSize,
};
/* Modules system dictionary type. Keys are module name,
* values are pointer to ValkeyModule struct. */
dictType modulesDictType = {
dictSdsCaseHash, /* hash function */
NULL, /* key dup */
dictSdsKeyCaseCompare, /* key compare */
dictSdsDestructor, /* key destructor */
NULL, /* val destructor */
NULL /* allow to expand */
};
/* Migrate cache dict type. */
dictType migrateCacheDictType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
dictSdsKeyCompare, /* key compare */
dictSdsDestructor, /* key destructor */
NULL, /* val destructor */
NULL /* allow to expand */
};
/* Dict for for case-insensitive search using null terminated C strings.
* The keys stored in dict are sds though. */
dictType stringSetDictType = {
dictCStrCaseHash, /* hash function */
NULL, /* key dup */
dictCStrKeyCaseCompare, /* key compare */
dictSdsDestructor, /* key destructor */
NULL, /* val destructor */
NULL /* allow to expand */
};
/* Dict for for case-insensitive search using null terminated C strings.
* The key and value do not have a destructor. */
dictType externalStringType = {
dictCStrCaseHash, /* hash function */
NULL, /* key dup */
dictCStrKeyCaseCompare, /* key compare */
NULL, /* key destructor */
NULL, /* val destructor */
NULL /* allow to expand */
};
/* Dict for case-insensitive search using sds objects with a zmalloc
* allocated object as the value. */
dictType sdsHashDictType = {
dictSdsCaseHash, /* hash function */
NULL, /* key dup */
dictSdsKeyCaseCompare, /* key compare */
dictSdsDestructor, /* key destructor */
dictVanillaFree, /* val destructor */
NULL /* allow to expand */
};
size_t clientSetDictTypeMetadataBytes(dict *d) {
UNUSED(d);
return sizeof(void *);
}
/* Client Set dictionary type. Keys are client, values are not used. */
dictType clientDictType = {
dictClientHash, /* hash function */
NULL, /* key dup */
dictClientKeyCompare, /* key compare */
.dictMetadataBytes = clientSetDictTypeMetadataBytes,
.no_value = 1 /* no values in this dict */
};
/* This function is called once a background process of some kind terminates,
* as we want to avoid resizing the hash tables when there is a child in order
* to play well with copy-on-write (otherwise when a resize happens lots of
* memory pages are copied). The goal of this function is to update the ability
* for dict.c to resize or rehash the tables accordingly to the fact we have an
* active fork child running. */
void updateDictResizePolicy(void) {
if (server.in_fork_child != CHILD_TYPE_NONE) {
dictSetResizeEnabled(DICT_RESIZE_FORBID);
hashtableSetResizePolicy(HASHTABLE_RESIZE_FORBID);
} else if (hasActiveChildProcess()) {
dictSetResizeEnabled(DICT_RESIZE_AVOID);
hashtableSetResizePolicy(HASHTABLE_RESIZE_AVOID);
} else {
dictSetResizeEnabled(DICT_RESIZE_ENABLE);
hashtableSetResizePolicy(HASHTABLE_RESIZE_ALLOW);
}
}
const char *strChildType(int type) {
switch (type) {
case CHILD_TYPE_RDB: return "RDB";
case CHILD_TYPE_AOF: return "AOF";
case CHILD_TYPE_LDB: return "LDB";
case CHILD_TYPE_MODULE: return "MODULE";
default: return "Unknown";
}
}
/* Return true if there are active children processes doing RDB saving,
* AOF rewriting, or some side process spawned by a loaded module. */
int hasActiveChildProcess(void) {
return server.child_pid != -1;
}
void resetChildState(void) {
server.child_type = CHILD_TYPE_NONE;
server.child_pid = -1;
server.stat_current_cow_peak = 0;
server.stat_current_cow_bytes = 0;
server.stat_current_cow_updated = 0;
server.stat_current_save_keys_processed = 0;
server.stat_module_progress = 0;
server.stat_current_save_keys_total = 0;
updateDictResizePolicy();
closeChildInfoPipe();
moduleFireServerEvent(VALKEYMODULE_EVENT_FORK_CHILD, VALKEYMODULE_SUBEVENT_FORK_CHILD_DIED, NULL);
}
/* Return if child type is mutually exclusive with other fork children */
int isMutuallyExclusiveChildType(int type) {
return type == CHILD_TYPE_RDB || type == CHILD_TYPE_AOF || type == CHILD_TYPE_MODULE;
}
/* Returns true when we're inside a long command that yielded to the event loop. */
int isInsideYieldingLongCommand(void) {
return scriptIsTimedout() || server.busy_module_yield_flags;
}
/* Return true if this instance has persistence completely turned off:
* both RDB and AOF are disabled. */
int allPersistenceDisabled(void) {
return server.saveparamslen == 0 && server.aof_state == AOF_OFF;
}
/* ======================= Cron: called every 100 ms ======================== */
/* Add a sample to the instantaneous metric. This function computes the quotient
* of the increment of value and base, which is useful to record operation count
* per second, or the average time consumption of an operation.
*
* current_value - The dividend
* current_base - The divisor
* */
void trackInstantaneousMetric(int metric, long long current_value, long long current_base, long long factor) {
if (server.inst_metric[metric].last_sample_base > 0) {
long long base = current_base - server.inst_metric[metric].last_sample_base;
long long value = current_value - server.inst_metric[metric].last_sample_value;
long long avg = base > 0 ? (value * factor / base) : 0;
server.inst_metric[metric].samples[server.inst_metric[metric].idx] = avg;
server.inst_metric[metric].idx++;
server.inst_metric[metric].idx %= STATS_METRIC_SAMPLES;
}
server.inst_metric[metric].last_sample_base = current_base;
server.inst_metric[metric].last_sample_value = current_value;
}
/* Return the mean of all the samples. */
long long getInstantaneousMetric(int metric) {
int j;
long long sum = 0;
for (j = 0; j < STATS_METRIC_SAMPLES; j++) sum += server.inst_metric[metric].samples[j];
return sum / STATS_METRIC_SAMPLES;
}
/* The client query buffer is an sds.c string that can end with a lot of
* free space not used, this function reclaims space if needed.
*
* The function always returns 0 as it never terminates the client. */
int clientsCronResizeQueryBuffer(client *c) {
/* If the client query buffer is NULL, it is using the shared query buffer and there is nothing to do. */
if (c->querybuf == NULL) return 0;
size_t querybuf_size = sdsalloc(c->querybuf);
time_t idletime = server.unixtime - c->last_interaction;
/* Only resize the query buffer if the buffer is actually wasting at least a
* few kbytes */
if (sdsavail(c->querybuf) > 1024 * 4) {
/* There are two conditions to resize the query buffer: */
if (idletime > 2) {
/* 1) Query is idle for a long time. */
size_t remaining = sdslen(c->querybuf) - c->qb_pos;
if (!c->flag.primary && !remaining) {
/* If the client is not a primary and no data is pending,
* The client can safely use the shared query buffer in the next read - free the client's querybuf. */
sdsfree(c->querybuf);
/* By setting the querybuf to NULL, the client will use the shared query buffer in the next read.
* We don't move the client to the shared query buffer immediately, because if we allocated a private
* query buffer for the client, it's likely that the client will use it again soon. */
c->querybuf = NULL;
} else {
c->querybuf = sdsRemoveFreeSpace(c->querybuf, 1);
}
} else if (querybuf_size > PROTO_RESIZE_THRESHOLD && querybuf_size / 2 > c->querybuf_peak) {
/* 2) Query buffer is too big for latest peak and is larger than
* resize threshold. Trim excess space but only up to a limit,
* not below the recent peak and current c->querybuf (which will
* be soon get used). If we're in the middle of a bulk then make
* sure not to resize to less than the bulk length. */
size_t resize = sdslen(c->querybuf);
if (resize < c->querybuf_peak) resize = c->querybuf_peak;
if (c->bulklen != -1 && resize < (size_t)c->bulklen + 2) resize = c->bulklen + 2;
c->querybuf = sdsResize(c->querybuf, resize, 1);
}
}
/* Reset the peak again to capture the peak memory usage in the next
* cycle. */
c->querybuf_peak = c->querybuf ? sdslen(c->querybuf) : 0;
/* We reset to either the current used, or currently processed bulk size,
* which ever is bigger. */
if (c->bulklen != -1 && (size_t)c->bulklen + 2 > c->querybuf_peak) c->querybuf_peak = c->bulklen + 2;
return 0;
}
/* The client output buffer can be adjusted to better fit the memory requirements.
*
* the logic is:
* in case the last observed peak size of the buffer equals the buffer size - we double the size
* in case the last observed peak size of the buffer is less than half the buffer size - we shrink by half.
* The buffer peak will be reset back to the buffer position every server.reply_buffer_peak_reset_time milliseconds
* The function always returns 0 as it never terminates the client. */
int clientsCronResizeOutputBuffer(client *c, mstime_t now_ms) {
if (c->io_write_state != CLIENT_IDLE) return 0;
size_t new_buffer_size = 0;
char *oldbuf = NULL;
const size_t buffer_target_shrink_size = c->buf_usable_size / 2;
const size_t buffer_target_expand_size = c->buf_usable_size * 2;
/* in case the resizing is disabled return immediately */
if (!server.reply_buffer_resizing_enabled) return 0;
if (buffer_target_shrink_size >= PROTO_REPLY_MIN_BYTES && c->buf_peak < buffer_target_shrink_size) {
new_buffer_size = max(PROTO_REPLY_MIN_BYTES, c->buf_peak + 1);
server.stat_reply_buffer_shrinks++;
} else if (buffer_target_expand_size < PROTO_REPLY_CHUNK_BYTES * 2 && c->buf_peak == c->buf_usable_size) {
new_buffer_size = min(PROTO_REPLY_CHUNK_BYTES, buffer_target_expand_size);
server.stat_reply_buffer_expands++;
}
serverAssertWithInfo(c, NULL, (!new_buffer_size) || (new_buffer_size >= (size_t)c->bufpos));
/* reset the peak value each server.reply_buffer_peak_reset_time seconds. in case the client will be idle
* it will start to shrink.
*/
if (server.reply_buffer_peak_reset_time >= 0 &&
now_ms - c->buf_peak_last_reset_time >= server.reply_buffer_peak_reset_time) {
c->buf_peak = c->bufpos;
c->buf_peak_last_reset_time = now_ms;
}
if (new_buffer_size) {
oldbuf = c->buf;
size_t oldbuf_size = c->buf_usable_size;
c->buf = zmalloc_usable(new_buffer_size, &c->buf_usable_size);
memcpy(c->buf, oldbuf, c->bufpos);
zfree_with_size(oldbuf, oldbuf_size);
}
return 0;
}
/* This function is used in order to track clients using the biggest amount
* of memory in the latest few seconds. This way we can provide such information
* in the INFO output (clients section), without having to do an O(N) scan for
* all the clients.
*
* This is how it works. We have an array of CLIENTS_PEAK_MEM_USAGE_SLOTS slots
* where we track, for each, the biggest client output and input buffers we
* saw in that slot. Every slot corresponds to one of the latest seconds, since
* the array is indexed by doing UNIXTIME % CLIENTS_PEAK_MEM_USAGE_SLOTS.
*
* When we want to know what was recently the peak memory usage, we just scan
* such few slots searching for the maximum value. */
#define CLIENTS_PEAK_MEM_USAGE_SLOTS 8
size_t ClientsPeakMemInput[CLIENTS_PEAK_MEM_USAGE_SLOTS] = {0};
size_t ClientsPeakMemOutput[CLIENTS_PEAK_MEM_USAGE_SLOTS] = {0};
int clientsCronTrackExpansiveClients(client *c, int time_idx) {
size_t qb_size = c->querybuf ? sdsAllocSize(c->querybuf) : 0;
size_t argv_size = c->argv ? zmalloc_size(c->argv) : 0;
size_t in_usage = qb_size + c->argv_len_sum + argv_size;
size_t out_usage = getClientOutputBufferMemoryUsage(c);
/* Track the biggest values observed so far in this slot. */
if (in_usage > ClientsPeakMemInput[time_idx]) ClientsPeakMemInput[time_idx] = in_usage;
if (out_usage > ClientsPeakMemOutput[time_idx]) ClientsPeakMemOutput[time_idx] = out_usage;
return 0; /* This function never terminates the client. */
}
/* All normal clients are placed in one of the "mem usage buckets" according
* to how much memory they currently use. We use this function to find the
* appropriate bucket based on a given memory usage value. The algorithm simply
* does a log2(mem) to ge the bucket. This means, for examples, that if a
* client's memory usage doubles it's moved up to the next bucket, if it's
* halved we move it down a bucket.
* For more details see CLIENT_MEM_USAGE_BUCKETS documentation in server.h. */
static inline clientMemUsageBucket *getMemUsageBucket(size_t mem) {
int size_in_bits = 8 * (int)sizeof(mem);
int clz = mem > 0 ? __builtin_clzl(mem) : size_in_bits;