src/server.c C 8,824 lines View on github.com → Search inside
File is large — showing lines 1–2,000 of 8,824.
1/*2 * Copyright (c) 2009-Present, Redis Ltd.3 * All rights reserved.4 *5 * Copyright (c) 2024-present, Valkey contributors.6 * All rights reserved.7 *8 * Licensed under your choice of (a) the Redis Source Available License 2.09 * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the10 * GNU Affero General Public License v3 (AGPLv3).11 *12 * Portions of this file are available under BSD3 terms; see REDISCONTRIBUTIONS for more information.13 */1415#include "server.h"16#include "monotonic.h"17#include "cluster.h"18#include "cluster_slot_stats.h"19#include "slowlog.h"20#include "bio.h"21#include "latency.h"22#include "atomicvar.h"23#include "mt19937-64.h"24#include "functions.h"25#include "hdr_histogram.h"26#include "syscheck.h"27#include "threads_mngr.h"28#include "fmtargs.h"29#include "mstr.h"30#include "ebuckets.h"31#include "cluster_asm.h"32#include "fwtree.h"33#include "estore.h"34#include "chk.h"35#include "fast_float_strtod.h"36#include "bitroar.h"3738#include <time.h>39#include <signal.h>40#include <sys/wait.h>41#include <errno.h>42#include <ctype.h>43#include <stdarg.h>44#include <arpa/inet.h>45#include <sys/stat.h>46#include <fcntl.h>47#include <sys/file.h>48#include <sys/time.h>49#include <sys/resource.h>50#include <sys/uio.h>51#include <sys/un.h>52#include <limits.h>53#include <float.h>54#include <math.h>55#include <sys/utsname.h>56#include <locale.h>57#include <sys/socket.h>5859#ifdef __linux__60#include <sys/mman.h>61#endif6263#if defined(HAVE_SYSCTL_KIPC_SOMAXCONN) || defined(HAVE_SYSCTL_KERN_SOMAXCONN)64#include <sys/sysctl.h>65#endif6667#ifdef __GNUC__68#define GNUC_VERSION_STR STRINGIFY(__GNUC__) "." STRINGIFY(__GNUC_MINOR__) "." STRINGIFY(__GNUC_PATCHLEVEL__)69#else70#define GNUC_VERSION_STR "0.0.0"71#endif7273/* Our shared "common" objects */7475struct sharedObjectsStruct shared;7677/* Global vars that are actually used as constants. The following double78 * values are used for double on-disk serialization, and are initialized79 * at runtime to avoid strange compiler optimizations. */8081double R_Zero, R_PosInf, R_NegInf, R_Nan;8283/*================================= Globals ================================= */8485/* Global vars */86struct redisServer server; /* Server global state */8788/* Snapshot of server.stat_total_client_process_input_buff_events used in89 * beforeSleep() to detect event loop cycles where client input buffers90 * were processed. */91long long stat_prev_total_client_process_input_buff_events = 0;9293/*============================ Internal prototypes ========================== */9495static inline int isShutdownInitiated(void);96static inline int isCommandReusable(struct redisCommand *cmd, robj **argv, int argc);97int isReadyToShutdown(void);98int finishShutdown(void);99const char *replstateToString(int replstate);100101/*============================ Utility functions ============================ */102103/* Check if a given command can be reused without performing a lookup.104 * A command is reusable if:105 * - It is not NULL.106 * - It does not have subcommands (subcommands_dict == NULL).107 *   This preserves simplicity on the check and accounts for the majority of the use cases.108 * - For top-level commands, its full name matches argv[0].109 * - For subcommands, argv[0] matches the parent's full name and argv[1] matches110 *   the subcommand's declared name. */111static inline int isCommandReusable(struct redisCommand *cmd, robj **argv, int argc) {112    if (cmd == NULL || cmd->subcommands_dict != NULL) return 0;113    if (cmd->parent == NULL)114        return strcasecmp(cmd->fullname, argv[0]->ptr) == 0;115    return argc >= 2 &&116           strcasecmp(cmd->parent->fullname, argv[0]->ptr) == 0 &&117           strcasecmp(cmd->declared_name, argv[1]->ptr) == 0;118}119120/* This macro tells if we are in the context of loading an AOF. */121#define isAOFLoadingContext() \122    ((server.current_client && server.current_client->id == CLIENT_ID_AOF) ? 1 : 0)123124/* We use a private localtime implementation which is fork-safe. The logging125 * function of Redis may be called from other threads. */126void nolocks_localtime(struct tm *tmp, time_t t, time_t tz, int dst);127128static inline int shouldShutdownAsap(void) {129    int shutdown_asap;130    atomicGet(server.shutdown_asap, shutdown_asap);131    return shutdown_asap;132}133134/* Low level logging. To use only for very big messages, otherwise135 * serverLog() is to prefer. */136void serverLogRaw(int level, const char *msg) {137    const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING };138    const char *c = ".-*#";139    FILE *fp;140    char buf[64];141    int rawmode = (level & LL_RAW);142    int log_to_stdout = server.logfile[0] == '\0';143144    level &= 0xff; /* clear flags */145    if (level < server.verbosity) return;146147    fp = log_to_stdout ? stdout : fopen(server.logfile,"a");148    if (!fp) return;149150    if (rawmode) {151        fprintf(fp,"%s",msg);152    } else {153        int off;154        struct timeval tv;155        int role_char;156        int daylight_active = 0;157        pid_t pid = getpid();158159        gettimeofday(&tv,NULL);160        struct tm tm;161        atomicGet(server.daylight_active, daylight_active);162        nolocks_localtime(&tm,tv.tv_sec,server.timezone,daylight_active);163        off = strftime(buf,sizeof(buf),"%d %b %Y %H:%M:%S.",&tm);164        snprintf(buf+off,sizeof(buf)-off,"%03d",(int)tv.tv_usec/1000);165        if (server.sentinel_mode) {166            role_char = 'X'; /* Sentinel. */167        } else if (pid != server.pid) {168            role_char = 'C'; /* RDB / AOF writing child. */169        } else {170            role_char = (server.masterhost ? 'S':'M'); /* Slave or Master. */171        }172        fprintf(fp,"%d:%c %s %c %s\n",173            (int)getpid(),role_char, buf,c[level],msg);174    }175    fflush(fp);176177    if (!log_to_stdout) fclose(fp);178    if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg);179}180181/* Like serverLogRaw() but with printf-alike support. This is the function that182 * is used across the code. The raw version is only used in order to dump183 * the INFO output on crash. */184void _serverLog(int level, const char *fmt, ...) {185    va_list ap;186    char msg[LOG_MAX_LEN];187188    va_start(ap, fmt);189    vsnprintf(msg, sizeof(msg), fmt, ap);190    va_end(ap);191192    serverLogRaw(level,msg);193}194195/* Low level logging from signal handler. Should be used with pre-formatted strings. 196   See serverLogFromHandler. */197void serverLogRawFromHandler(int level, const char *msg) {198    int fd;199    int log_to_stdout = server.logfile[0] == '\0';200    char buf[64];201202    if ((level&0xff) < server.verbosity || (log_to_stdout && server.daemonize))203        return;204    fd = log_to_stdout ? STDOUT_FILENO :205                         open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644);206    if (fd == -1) return;207    if (level & LL_RAW) {208        if (write(fd,msg,strlen(msg)) == -1) goto err;209    }210    else {211        ll2string(buf,sizeof(buf),getpid());212        if (write(fd,buf,strlen(buf)) == -1) goto err;213        if (write(fd,":signal-handler (",17) == -1) goto err;214        ll2string(buf,sizeof(buf),time(NULL));215        if (write(fd,buf,strlen(buf)) == -1) goto err;216        if (write(fd,") ",2) == -1) goto err;217        if (write(fd,msg,strlen(msg)) == -1) goto err;218        if (write(fd,"\n",1) == -1) goto err;219    }220err:221    if (!log_to_stdout) close(fd);222}223224/* An async-signal-safe version of serverLog. if LL_RAW is not included in level flags,225 * The message format is: <pid>:signal-handler (<time>) <msg> \n226 * with LL_RAW flag only the msg is printed (with no new line at the end)227 *228 * We actually use this only for signals that are not fatal from the point229 * of view of Redis. Signals that are going to kill the server anyway and230 * where we need printf-alike features are served by serverLog(). */231void serverLogFromHandler(int level, const char *fmt, ...) {232    va_list ap;233    char msg[LOG_MAX_LEN];234235    va_start(ap, fmt);236    vsnprintf_async_signal_safe(msg, sizeof(msg), fmt, ap);237    va_end(ap);238239    serverLogRawFromHandler(level, msg);240}241242/* Return the UNIX time in microseconds */243long long ustime(void) {244    struct timeval tv;245    long long ust;246247    gettimeofday(&tv, NULL);248    ust = ((long long)tv.tv_sec)*1000000;249    ust += tv.tv_usec;250    return ust;251}252253/* Return the UNIX time in milliseconds */254mstime_t mstime(void) {255    return ustime()/1000;256}257258/* Return the command time snapshot in milliseconds.259 * The time the command started is the logical time it runs,260 * and all the time readings during the execution time should261 * reflect the same time.262 * More details can be found in the comments below. */263mstime_t commandTimeSnapshot(void) {264    /* When we are in the middle of a command execution, we want to use a265     * reference time that does not change: in that case we just use the266     * cached time, that we update before each call in the call() function.267     * This way we avoid that commands such as RPOPLPUSH or similar, that268     * may re-open the same key multiple times, can invalidate an already269     * open object in a next call, if the next call will see the key expired,270     * while the first did not.271     * This is specifically important in the context of scripts, where we272     * pretend that time freezes. This way a key can expire only the first time273     * it is accessed and not in the middle of the script execution, making274     * propagation to slaves / AOF consistent. See issue #1525 for more info.275     * Note that we cannot use the cached server.mstime because it can change276     * in processEventsWhileBlocked etc. */277    return server.cmd_time_snapshot;278}279280/* After an RDB dump or AOF rewrite we exit from children using _exit() instead of281 * exit(), because the latter may interact with the same file objects used by282 * the parent process. However if we are testing the coverage normal exit() is283 * used in order to obtain the right coverage information. 284 * There is a caveat for when we exit due to a signal.285 * In this case we want the function to be async signal safe, so we can't use exit()286 */287void exitFromChild(int retcode, int from_signal) {288#ifdef COVERAGE_TEST289    if (!from_signal) {290        exit(retcode);291    } else {292        _exit(retcode);293    }294#else295    UNUSED(from_signal);296    _exit(retcode);297#endif298}299300/*====================== Hash table type implementation  ==================== */301302/* This is a hash table type that uses the SDS dynamic strings library as303 * keys and redis objects as values (objects can hold SDS strings,304 * lists, sets). */305306void dictVanillaFree(dict *d, void *val)307{308    UNUSED(d);309    zfree(val);310}311312void dictListDestructor(dict *d, void *val)313{314    UNUSED(d);315    listRelease((list*)val);316}317318void dictDictDestructor(dict *d, void *val)319{320    UNUSED(d);321    dictRelease((dict*)val);322}323324size_t dictSdsKeyLen(dict *d, const void *key) {325    UNUSED(d);326    return sdslen((sds)key);327}328329static const void *kvGetKey(const void *kv) {330    sds sdsKey = kvobjGetKey((kvobj *) kv);331    return sdsKey;332}333334int dictSdsCompareKV(dictCmpCache *cache, const void *sdsKey1, const void *sdsKey2)335{336    /* is first cmp call of a new lookup */337    if (cache->useCache == 0) {338        cache->useCache = 1;339        cache->data[0].sz = sdslen((sds) sdsKey1);340    }341342    size_t l1 = cache->data[0].sz;343    size_t l2 = sdslen((sds)sdsKey2);344    if (l1 != l2) return 0;345    return memcmp(sdsKey1, sdsKey2, l1) == 0;346}347348static void dictDestructorKV(dict *d, void *key) {349    kvobj *kv = (kvobj *)key;350    if (kv == NULL) return;351    if (server.memory_tracking_enabled) {352        kvstore *kvs = d->type->userdata;353        kvstoreMetadata *kvstoreMeta = kvstoreGetMetadata(kvs);354        kvstoreDictMetadata *meta = (kvstoreDictMetadata *)dictMetadata(d);355        size_t alloc_size = kvobjAllocSize(kv);356        debugServerAssert(alloc_size <= meta->alloc_size);357        meta->alloc_size -= alloc_size;358        /* kvstoreMeta may be NULL when freeing kvstore created with kvstoreBaseType359         * (e.g. in lazy free context). */360        int64_t *hist = kvstoreMeta ? keysizesHistRow(kvstoreMeta->allocsizes_hist, kv->type) : NULL;361        if (hist) {362            /* we don't call kvsUpdateHistogram() because it contains debugServerAssert363             * that may fail in bg thread as kvstore might not being fully initialized */364            int old_bin = (alloc_size == 0) ? 0 :365                          min(log2ceil(alloc_size) + 1, MAX_KEYSIZES_BINS - 1);366            hist[old_bin]--;367        }368    }369    decrRefCount(kv);370}371372int dictSdsKeyCompare(dictCmpCache *cache, const void *key1,373        const void *key2)374{375    int l1,l2;376    UNUSED(cache);377378    l1 = sdslen((sds)key1);379    l2 = sdslen((sds)key2);380    if (l1 != l2) return 0;381    return memcmp(key1, key2, l1) == 0;382}383384/* A case insensitive version used for the command lookup table and other385 * places where case insensitive non binary-safe comparison is needed. */386int dictSdsKeyCaseCompare(dictCmpCache *cache, const void *key1,387        const void *key2)388{389    UNUSED(cache);390    return strcasecmp(key1, key2) == 0;391}392393void dictObjectDestructor(dict *d, void *val)394{395    UNUSED(d);396    if (val == NULL) return; /* Lazy freeing will set value to NULL. */397    decrRefCount(val);398}399400void dictSdsDestructor(dict *d, void *val)401{402    UNUSED(d);403    sdsfree(val);404}405406void *dictSdsDup(dict *d, const void *key) {407    UNUSED(d);408    return sdsdup((const sds) key);409}410411int dictObjKeyCompare(dictCmpCache *cache, const void *key1,412        const void *key2)413{414    const robj *o1 = key1, *o2 = key2;415    return dictSdsKeyCompare(cache, o1->ptr,o2->ptr);416}417418uint64_t dictObjHash(const void *key) {419    const robj *o = key;420    return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));421}422423uint64_t dictPtrHash(const void *key) {424    return dictGenHashFunction((unsigned char*)&key,sizeof(key));425}426427uint64_t dictSdsHash(const void *key) {428    return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));429}430431uint64_t dictSdsCaseHash(const void *key) {432    return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key));433}434435/* Dict hash function for null terminated string */436uint64_t dictCStrHash(const void *key) {437    return dictGenHashFunction((unsigned char*)key, strlen((char*)key));438}439440/* Dict hash function for null terminated string */441uint64_t dictCStrCaseHash(const void *key) {442    return dictGenCaseHashFunction((unsigned char*)key, strlen((char*)key));443}444445/* Dict hash function for client */446uint64_t dictClientHash(const void *key) {447    return ((client *)key)->id;448}449450/* Dict compare function for client */451int dictClientKeyCompare(dictCmpCache *cache, const void *key1, const void *key2) {452    UNUSED(cache);453    return ((client *)key1)->id == ((client *)key2)->id;454}455456/* Dict compare function for null terminated string */457int dictCStrKeyCompare(dictCmpCache *cache, const void *key1, const void *key2) {458    int l1,l2;459    UNUSED(cache);460461    l1 = strlen((char*)key1);462    l2 = strlen((char*)key2);463    if (l1 != l2) return 0;464    return memcmp(key1, key2, l1) == 0;465}466467/* Dict case insensitive compare function for null terminated string */468int dictCStrKeyCaseCompare(dictCmpCache *cache, const void *key1, const void *key2) {469    UNUSED(cache);470    return strcasecmp(key1, key2) == 0;471}472473int dictEncObjKeyCompare(dictCmpCache *cache, const void *key1, const void *key2)474{475    robj *o1 = (robj*) key1, *o2 = (robj*) key2;476    int cmp;477478    if (o1->encoding == OBJ_ENCODING_INT &&479        o2->encoding == OBJ_ENCODING_INT)480            return o1->ptr == o2->ptr;481482    /* Due to OBJ_STATIC_REFCOUNT, we avoid calling getDecodedObject() without483     * good reasons, because it would incrRefCount() the object, which484     * is invalid. So we check to make sure dictFind() works with static485     * objects as well. */486    if (o1->refcount != OBJ_STATIC_REFCOUNT) o1 = getDecodedObject(o1);487    if (o2->refcount != OBJ_STATIC_REFCOUNT) o2 = getDecodedObject(o2);488    cmp = dictSdsKeyCompare(cache,o1->ptr,o2->ptr);489    if (o1->refcount != OBJ_STATIC_REFCOUNT) decrRefCount(o1);490    if (o2->refcount != OBJ_STATIC_REFCOUNT) decrRefCount(o2);491    return cmp;492}493494uint64_t dictEncObjHash(const void *key) {495    robj *o = (robj*) key;496497    if (sdsEncodedObject(o)) {498        return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));499    } else if (o->encoding == OBJ_ENCODING_INT) {500        char buf[32];501        int len;502503        len = ll2string(buf,32,(long)o->ptr);504        return dictGenHashFunction((unsigned char*)buf, len);505    } else {506        serverPanic("Unknown string encoding");507    }508}509510static size_t kvstoreMetadataBytes(kvstore *kvs) {511    UNUSED(kvs);512    return sizeof(kvstoreMetadata);513}514515static size_t kvstoreDictMetaBytes(dict *d) {516    UNUSED(d);517    return sizeof(kvstoreDictMetadata);518}519520static int kvstoreCanFreeDict(kvstore *kvs, int didx) {521    kvstoreDictMetadata *meta = kvstoreGetDictMeta(kvs, didx, 0);522    debugServerAssert(meta->alloc_size == 0);523    /* Free if not in cluster */524    if (!server.cluster_enabled) return 1;525526    /* Don't free if we have stats for this slot and the relevant tracking is enabled. */527    int has_cpu_stats = (server.cluster_slot_stats_enabled & CLUSTER_SLOT_STATS_CPU) && meta->cpu_usec;528    int has_net_stats = (server.cluster_slot_stats_enabled & CLUSTER_SLOT_STATS_NET) &&529                        (meta->network_bytes_in || meta->network_bytes_out);530    if ((has_cpu_stats || has_net_stats) && clusterIsMySlot(didx)) {531        return 0;532    }533534    /* Otherwise, we can free */535    return 1;536}537538static void kvstoreOnEmpty(kvstore *kvs) {539    kvstoreMetadata *meta = kvstoreGetMetadata(kvs);540    serverAssert(meta); /* installed only for kvstores that carry metadata */541542    /* Nothing in an emptied kvstore holds a sample, so clear every histogram543     * and start a new generation: a slot-trim delta tallied against the old544     * contents is then discarded, not subtracted (asmBackgroundTrimDoneCB). */545    memset(&meta->keysizes_hist, 0, sizeof(meta->keysizes_hist));546    memset(&meta->allocsizes_hist, 0, sizeof(meta->allocsizes_hist));547    meta->keysizes_stats_epoch++;548    streamStatsResetMeta(meta);549}550551static void kvstoreOnDictEmpty(kvstore *kvs, int didx) {552    kvstoreDictMetadata *meta = kvstoreGetDictMeta(kvs, didx, 0);553    UNUSED(meta);554#ifdef DEBUG_ASSERTIONS555    dictEmpty(kvstoreGetDict(kvs, didx), NULL);556#endif557    debugServerAssert(meta->alloc_size == 0);558}559560/* Return 1 if currently we allow dict to expand. Dict may allocate huge561 * memory to contain hash buckets when dict expands, that may lead redis562 * rejects user's requests or evicts some keys, we can stop dict to expand563 * provisionally if used memory will be over maxmemory after dict expands,564 * but to guarantee the performance of redis, we still allow dict to expand565 * if dict load factor exceeds HASHTABLE_MAX_LOAD_FACTOR. */566int dictResizeAllowed(size_t moreMem, double usedRatio) {567    /* for debug purposes: dict is not allowed to be resized. */568    if (!server.dict_resizing) return 0;569570    if (usedRatio <= HASHTABLE_MAX_LOAD_FACTOR) {571        return !overMaxmemoryAfterAlloc(moreMem);572    } else {573        return 1;574    }575}576577/* dbDictType prefetch callbacks.578 * The main keyspace stores a kvobj as the entry's "stored key" (no_value=1).579 * The state machine in memory_prefetch.c calls these hooks to:580 *  - Bring the kvobj head into L1 before keyCompare runs (only useful when581 *    the entry holds an out-of-line pointer; embedded kvobjs are already582 *    in cache from the entry prefetch).583 *  - Bring kv->ptr into L1 when the value lives in its own allocation584 *    (RAW strings, listpacks, ...), since the caller reads it next. */585static void *dbDictPrefetchEntryKey(const dictEntry *de) {586    return dictEntryIsKey(de) ? NULL : dictGetKey(de);587}588589static void *dbDictPrefetchEntryValue(const dictEntry *de) {590    kvobj *kv = dictGetKey(de);591    if (inlineEncodedObject(kv)) return NULL;592    return kv->ptr;593}594595/* Generic hash table type where keys are Redis Objects, Values596 * dummy pointers. */597dictType objectKeyPointerValueDictType = {598    dictEncObjHash,            /* hash function */599    NULL,                      /* key dup */600    NULL,                      /* val dup */601    dictEncObjKeyCompare,      /* key compare */602    dictObjectDestructor,      /* key destructor */603    NULL,                      /* val destructor */604    NULL                       /* allow to expand */605};606607/* Dict type with robj pointer keys and no values. */608dictType objectKeyNoValueDictType = {609    dictEncObjHash,            /* hash function */610    NULL,                      /* key dup */611    NULL,                      /* val dup */612    dictEncObjKeyCompare,      /* key compare */613    dictObjectDestructor,      /* key destructor */614    NULL,                      /* val destructor */615    NULL,                      /* allow to expand */616    .no_value = 1,             /* no values in this dict */617    .keys_are_odd = 0,         /* robj pointers are not odd */618};619620/* Like objectKeyPointerValueDictType(), but values can be destroyed, if621 * not NULL, calling zfree(). */622dictType objectKeyHeapPointerValueDictType = {623    dictEncObjHash,            /* hash function */624    NULL,                      /* key dup */625    NULL,                      /* val dup */626    dictEncObjKeyCompare,      /* key compare */627    dictObjectDestructor,      /* key destructor */628    dictVanillaFree,           /* val destructor */629    NULL                       /* allow to expand */630};631632/* Db->dict, keys are of type kvobj, unification of key and value */633dictType dbDictType = {634    dictSdsHash,            /* hash function */635    NULL,                   /* key dup */636    NULL,                   /* val dup */637    dictSdsCompareKV,       /* lookup key compare */638    dictDestructorKV,       /* key destructor */639    NULL,                   /* val destructor */640    dictResizeAllowed,      /* allow to resize */641    .no_value = 1,          /* keys and values are unified (kvobj) */642    .keys_are_odd = 0,      /* simple kvobj (robj) struct */643    .keyFromStoredKey = kvGetKey,    /* get key from stored-key */644    .prefetchEntryKey = dbDictPrefetchEntryKey,645    .prefetchEntryValue = dbDictPrefetchEntryValue,646};647648/* Db->expires */649dictType dbExpiresDictType = {650    dictSdsHash,                /* hash function */651    NULL,                       /* key dup */652    NULL,                       /* val dup */653    dictSdsCompareKV,           /* key compare */654    NULL,                       /* key destructor */655    NULL,                       /* val destructor */656    dictResizeAllowed,          /* allow to resize */657    .no_value = 1,              /* keys and values are unified (kvobj) */658    .keys_are_odd = 0,          /* simple kvobj (robj) struct */659    .keyFromStoredKey = kvGetKey,   /* get key from stored-key */660};661662/* Command table. sds string -> command struct pointer. */663dictType commandTableDictType = {664    dictSdsCaseHash,            /* hash function */665    NULL,                       /* key dup */666    NULL,                       /* val dup */667    dictSdsKeyCaseCompare,      /* key compare */668    dictSdsDestructor,          /* key destructor */669    NULL,                       /* val destructor */670    NULL,                       /* allow to expand */671    .force_full_rehash = 1,     /* force full rehashing */672};673674/* Hash type hash table (note that small hashes are represented with listpacks) */675dictType hashDictType = {676    dictSdsHash,                /* hash function */677    NULL,                       /* key dup */678    NULL,                       /* val dup */679    dictSdsKeyCompare,          /* key compare */680    dictSdsDestructor,          /* key destructor */681    dictSdsDestructor,          /* val destructor */682    NULL,                       /* allow to expand */683};684685/* Dict type without destructor */686dictType sdsReplyDictType = {687    dictSdsHash,                /* hash function */688    NULL,                       /* key dup */689    NULL,                       /* val dup */690    dictSdsKeyCompare,          /* key compare */691    NULL,                       /* key destructor */692    NULL,                       /* val destructor */693    NULL                        /* allow to expand */694};695696/* Keylist hash table type has unencoded redis objects as keys and697 * lists as values. It's used for blocking operations (BLPOP) and to698 * map swapped keys to a list of clients waiting for this keys to be loaded. */699dictType keylistDictType = {700    dictObjHash,                /* hash function */701    NULL,                       /* key dup */702    NULL,                       /* val dup */703    dictObjKeyCompare,          /* key compare */704    dictObjectDestructor,       /* key destructor */705    dictListDestructor,         /* val destructor */706    NULL                        /* allow to expand */707};708709/* KeyDict hash table type has unencoded redis objects as keys and710 * dicts as values. It's used for PUBSUB command to track clients subscribing the channels. */711dictType objToDictDictType = {712    dictObjHash,                /* hash function */713    NULL,                       /* key dup */714    NULL,                       /* val dup */715    dictObjKeyCompare,          /* key compare */716    dictObjectDestructor,       /* key destructor */717    dictDictDestructor,         /* val destructor */718    NULL                        /* allow to expand */719};720721/* Modules system dictionary type. Keys are module name,722 * values are pointer to RedisModule struct. */723dictType modulesDictType = {724    dictSdsCaseHash,            /* hash function */725    NULL,                       /* key dup */726    NULL,                       /* val dup */727    dictSdsKeyCaseCompare,      /* key compare */728    dictSdsDestructor,          /* key destructor */729    NULL,                       /* val destructor */730    NULL                        /* allow to expand */731};732733/* Migrate cache dict type. */734dictType migrateCacheDictType = {735    dictSdsHash,                /* hash function */736    NULL,                       /* key dup */737    NULL,                       /* val dup */738    dictSdsKeyCompare,          /* key compare */739    dictSdsDestructor,          /* key destructor */740    NULL,                       /* val destructor */741    NULL                        /* allow to expand */742};743744/* Dict for for case-insensitive search using null terminated C strings.745 * The keys stored in dict are sds though. */746dictType stringSetDictType = {747    dictCStrCaseHash,           /* hash function */748    NULL,                       /* key dup */749    NULL,                       /* val dup */750    dictCStrKeyCaseCompare,     /* key compare */751    dictSdsDestructor,          /* key destructor */752    NULL,                       /* val destructor */753    NULL                        /* allow to expand */754};755756/* Dict for for case-insensitive search using null terminated C strings.757 * The key and value do not have a destructor. */758dictType externalStringType = {759    dictCStrCaseHash,           /* hash function */760    NULL,                       /* key dup */761    NULL,                       /* val dup */762    dictCStrKeyCaseCompare,     /* key compare */763    NULL,                       /* key destructor */764    NULL,                       /* val destructor */765    NULL                        /* allow to expand */766};767768/* Dict for case-insensitive search using sds objects with a zmalloc769 * allocated object as the value. */770dictType sdsHashDictType = {771    dictSdsCaseHash,            /* hash function */772    NULL,                       /* key dup */773    NULL,                       /* val dup */774    dictSdsKeyCaseCompare,      /* key compare */775    dictSdsDestructor,          /* key destructor */776    dictVanillaFree,            /* val destructor */777    NULL                        /* allow to expand */778};779780/* Client Set dictionary type. Keys are client, values are not used. */781dictType clientDictType = {782    dictClientHash,             /* hash function */783    NULL,                       /* key dup */784    NULL,                       /* val dup */785    dictClientKeyCompare,       /* key compare */786    .no_value = 1,              /* no values in this dict */787    .keys_are_odd = 0           /* a client pointer is not an odd pointer */            788};789790kvstoreType kvstoreBaseType = {791    NULL, /* kvstore metadata size */792    NULL, /* dict metadata size */793    NULL, /* can free dict */794    NULL, /* on kvstore empty */795    NULL, /* on dict empty */796};797798kvstoreType kvstoreExType = {799    kvstoreMetadataBytes, /* kvstore metadata size */800    kvstoreDictMetaBytes, /* dict metadata size */801    kvstoreCanFreeDict,   /* can free dict */802    kvstoreOnEmpty,       /* on kvstore empty */803    kvstoreOnDictEmpty,   /* on dict empty */804};805806/* This function is called once a background process of some kind terminates,807 * as we want to avoid resizing the hash tables when there is a child in order808 * to play well with copy-on-write (otherwise when a resize happens lots of809 * memory pages are copied). The goal of this function is to update the ability810 * for dict.c to resize or rehash the tables accordingly to the fact we have an811 * active fork child running. */812void updateDictResizePolicy(void) {813    if (server.in_fork_child != CHILD_TYPE_NONE)814        dictSetResizeEnabled(DICT_RESIZE_FORBID);815    else if (hasActiveChildProcess())816        dictSetResizeEnabled(DICT_RESIZE_AVOID);817    else818        dictSetResizeEnabled(DICT_RESIZE_ENABLE);819}820821const char *strChildType(int type) {822    switch(type) {823        case CHILD_TYPE_RDB: return "RDB";824        case CHILD_TYPE_AOF: return "AOF";825        case CHILD_TYPE_LDB: return "LDB";826        case CHILD_TYPE_MODULE: return "MODULE";827        default: return "Unknown";828    }829}830831/* Return true if there are active children processes doing RDB saving,832 * AOF rewriting, or some side process spawned by a loaded module. */833int hasActiveChildProcess(void) {834    return server.child_pid != -1;835}836837void resetChildState(void) {838    server.child_type = CHILD_TYPE_NONE;839    server.child_pid = -1;840    server.stat_current_cow_peak = 0;841    server.stat_current_cow_bytes = 0;842    server.stat_current_cow_updated = 0;843    server.stat_current_save_keys_processed = 0;844    server.stat_module_progress = 0;845    server.stat_current_save_keys_total = 0;846    updateDictResizePolicy();847    closeChildInfoPipe();848    moduleFireServerEvent(REDISMODULE_EVENT_FORK_CHILD,849                          REDISMODULE_SUBEVENT_FORK_CHILD_DIED,850                          NULL);851}852853/* Return if child type is mutually exclusive with other fork children */854int isMutuallyExclusiveChildType(int type) {855    return type == CHILD_TYPE_RDB || type == CHILD_TYPE_AOF || type == CHILD_TYPE_MODULE;856}857858/* Returns true when we're inside a long command that yielded to the event loop. */859int isInsideYieldingLongCommand(void) {860    return scriptIsTimedout() || server.busy_module_yield_flags;861}862863/* Return true if this instance has persistence completely turned off:864 * both RDB and AOF are disabled. */865int allPersistenceDisabled(void) {866    return server.saveparamslen == 0 && server.aof_state == AOF_OFF;867}868869/* ======================= Cron: called every 100 ms ======================== */870871/* Add a sample to the instantaneous metric. This function computes the quotient872 * of the increment of value and base, which is useful to record operation count873 * per second, or the average time consumption of an operation.874 *875 * current_value - The dividend876 * current_base - The divisor877 * */878void trackInstantaneousMetric(int metric, long long current_value, long long current_base, long long factor) {879    if (server.inst_metric[metric].last_sample_base > 0) {880        long long base = current_base - server.inst_metric[metric].last_sample_base;881        long long value = current_value - server.inst_metric[metric].last_sample_value;882        long long avg = base > 0 ? (value * factor / base) : 0;883        server.inst_metric[metric].samples[server.inst_metric[metric].idx] = avg;884        server.inst_metric[metric].idx++;885        server.inst_metric[metric].idx %= STATS_METRIC_SAMPLES;886    }887    server.inst_metric[metric].last_sample_base = current_base;888    server.inst_metric[metric].last_sample_value = current_value;889}890891/* Return the mean of all the samples. */892long long getInstantaneousMetric(int metric) {893    int j;894    long long sum = 0;895896    for (j = 0; j < STATS_METRIC_SAMPLES; j++)897        sum += server.inst_metric[metric].samples[j];898    return sum / STATS_METRIC_SAMPLES;899}900901/* The client query buffer is an sds.c string that can end with a lot of902 * free space not used, this function reclaims space if needed.903 *904 * The function always returns 0 as it never terminates the client. */905int clientsCronResizeQueryBuffer(client *c) {906    /* If the client query buffer is NULL, it is using the reusable query buffer and there is nothing to do. */907    if (c->querybuf == NULL) return 0;908    size_t querybuf_size = sdsalloc(c->querybuf);909    time_t idletime = server.unixtime - c->lastinteraction;910911    /* Only resize the query buffer if the buffer is actually wasting at least a912     * few kbytes */913    if (sdsavail(c->querybuf) > 1024*4) {914        /* There are two conditions to resize the query buffer: */915        if (idletime > 2) {916            /* 1) Query is idle for a long time. */917            size_t remaining = sdslen(c->querybuf) - c->qb_pos;918            if (!(c->flags & CLIENT_MASTER) && !remaining) {919                /* If the client is not a master and no data is pending,920                 * The client can safely use the reusable query buffer in the next read - free the client's querybuf. */921                sdsfree(c->querybuf);922                /* By setting the querybuf to NULL, the client will use the reusable query buffer in the next read.923                 * We don't move the client to the reusable query buffer immediately, because if we allocated a private924                 * query buffer for the client, it's likely that the client will use it again soon. */925                c->querybuf = NULL;926            } else {927                c->querybuf = sdsRemoveFreeSpace(c->querybuf, 1);928            }929        } else if (querybuf_size > PROTO_RESIZE_THRESHOLD && querybuf_size/2 > c->querybuf_peak) {930            /* 2) Query buffer is too big for latest peak and is larger than931             *    resize threshold. Trim excess space but only up to a limit,932             *    not below the recent peak and current c->querybuf (which will933             *    be soon get used). If we're in the middle of a bulk then make934             *    sure not to resize to less than the bulk length. */935            size_t resize = sdslen(c->querybuf);936            if (resize < c->querybuf_peak) resize = c->querybuf_peak;937            if (c->bulklen != -1 && resize < (size_t)c->bulklen + 2) resize = c->bulklen + 2;938            c->querybuf = sdsResize(c->querybuf, resize, 1);939        }940    }941942    /* Reset the peak again to capture the peak memory usage in the next943     * cycle. */944    c->querybuf_peak = c->querybuf ? sdslen(c->querybuf) : 0;945    /* We reset to either the current used, or currently processed bulk size,946     * which ever is bigger. */947    if (c->bulklen != -1 && (size_t)c->bulklen + 2 > c->querybuf_peak) c->querybuf_peak = c->bulklen + 2;948    return 0;949}950951/* The client output buffer can be adjusted to better fit the memory requirements.952 *953 * the logic is:954 * in case the last observed peak size of the buffer equals the buffer size - we double the size955 * in case the last observed peak size of the buffer is less than half the buffer size - we shrink by half.956 * The buffer peak will be reset back to the buffer position every server.reply_buffer_peak_reset_time milliseconds957 * The function always returns 0 as it never terminates the client. */958int clientsCronResizeOutputBuffer(client *c, mstime_t now_ms) {959960    size_t new_buffer_size = 0;961    char *oldbuf = NULL;962    const size_t buffer_target_shrink_size = c->buf_usable_size/2;963    const size_t buffer_target_expand_size = c->buf_usable_size*2;964965    /* in case the resizing is disabled return immediately */966    if(!server.reply_buffer_resizing_enabled)967        return 0;968969    /* Don't resize encoded buffers. When buf is encoded, we track the last970     * partially written payloadHeader pointer, so we can't971     * reallocate the buffer as it would invalidate this pointer. */972    if (c->buf_encoded) return 0;973974    if (buffer_target_shrink_size >= PROTO_REPLY_MIN_BYTES &&975        c->buf_peak < buffer_target_shrink_size )976    {977        new_buffer_size = max(PROTO_REPLY_MIN_BYTES,c->buf_peak+1);978        server.stat_reply_buffer_shrinks++;979    } else if (buffer_target_expand_size < PROTO_REPLY_CHUNK_BYTES*2 &&980        c->buf_peak == c->buf_usable_size)981    {982        new_buffer_size = min(PROTO_REPLY_CHUNK_BYTES,buffer_target_expand_size);983        server.stat_reply_buffer_expands++;984    }985986    serverAssertWithInfo(c, NULL, (!new_buffer_size) || (new_buffer_size >= (size_t)c->bufpos));987988    /* reset the peak value each server.reply_buffer_peak_reset_time seconds. in case the client will be idle989     * it will start to shrink.990     */991    if (server.reply_buffer_peak_reset_time >=0 &&992        now_ms - c->buf_peak_last_reset_time >= server.reply_buffer_peak_reset_time)993    {994        c->buf_peak = c->bufpos;995        c->buf_peak_last_reset_time = now_ms;996    }997998    if (new_buffer_size) {999        oldbuf = c->buf;1000        c->buf = zmalloc_usable(new_buffer_size, &c->buf_usable_size);1001        memcpy(c->buf,oldbuf,c->bufpos);1002        zfree(oldbuf);1003    }1004    return 0;1005}10061007/* This function is used in order to track clients using the biggest amount1008 * of memory in the latest few seconds. This way we can provide such information1009 * in the INFO output (clients section), without having to do an O(N) scan for1010 * all the clients.1011 *1012 * This is how it works. We have an array of CLIENTS_PEAK_MEM_USAGE_SLOTS slots1013 * where we track, for each, the biggest client output and input buffers we1014 * saw in that slot. Every slot corresponds to one of the latest seconds, since1015 * the array is indexed by doing UNIXTIME % CLIENTS_PEAK_MEM_USAGE_SLOTS.1016 *1017 * When we want to know what was recently the peak memory usage, we just scan1018 * such few slots searching for the maximum value. */1019#define CLIENTS_PEAK_MEM_USAGE_SLOTS 81020size_t ClientsPeakMemInput[CLIENTS_PEAK_MEM_USAGE_SLOTS] = {0};1021size_t ClientsPeakMemOutput[CLIENTS_PEAK_MEM_USAGE_SLOTS] = {0};1022int CurrentPeakMemUsageSlot = 0;10231024int clientsCronTrackExpansiveClients(client *c) {1025    size_t qb_size = c->querybuf ? sdsZmallocSize(c->querybuf) : 0;1026    size_t argv_size = c->argv ? zmalloc_size(c->argv) : 0;1027    size_t in_usage = qb_size + c->all_argv_len_sum + argv_size;1028    size_t out_usage = getClientOutputBufferMemoryUsage(c);10291030    /* Track the biggest values observed so far in this slot. */1031    if (in_usage > ClientsPeakMemInput[CurrentPeakMemUsageSlot])1032        ClientsPeakMemInput[CurrentPeakMemUsageSlot] = in_usage;1033    if (out_usage > ClientsPeakMemOutput[CurrentPeakMemUsageSlot])1034        ClientsPeakMemOutput[CurrentPeakMemUsageSlot] = out_usage;10351036    return 0; /* This function never terminates the client. */1037}10381039/* All normal clients are placed in one of the "mem usage buckets" according1040 * to how much memory they currently use. We use this function to find the1041 * appropriate bucket based on a given memory usage value. The algorithm simply1042 * does a log2(mem) to ge the bucket. This means, for examples, that if a1043 * client's memory usage doubles it's moved up to the next bucket, if it's1044 * halved we move it down a bucket.1045 * For more details see CLIENT_MEM_USAGE_BUCKETS documentation in server.h. */1046static inline clientMemUsageBucket *getMemUsageBucket(size_t mem) {1047    int size_in_bits = 8*(int)sizeof(mem);1048    int clz = mem > 0 ? __builtin_clzl(mem) : size_in_bits;1049    int bucket_idx = size_in_bits - clz;1050    if (bucket_idx > CLIENT_MEM_USAGE_BUCKET_MAX_LOG)1051        bucket_idx = CLIENT_MEM_USAGE_BUCKET_MAX_LOG;1052    else if (bucket_idx < CLIENT_MEM_USAGE_BUCKET_MIN_LOG)1053        bucket_idx = CLIENT_MEM_USAGE_BUCKET_MIN_LOG;1054    bucket_idx -= CLIENT_MEM_USAGE_BUCKET_MIN_LOG;1055    return &server.client_mem_usage_buckets[bucket_idx];1056}10571058/*1059 * This method updates the client memory usage and update the1060 * server stats for client type.1061 *1062 * This method is called from the clientsCron to have updated1063 * stats for non CLIENT_TYPE_NORMAL/PUBSUB clients to accurately1064 * provide information around clients memory usage.1065 *1066 * It is also used in updateClientMemUsageAndBucket to have latest1067 * client memory usage information to place it into appropriate client memory1068 * usage bucket.1069 */1070void updateClientMemoryUsage(client *c) {1071    serverAssert(c->conn);1072    size_t mem = getClientMemoryUsage(c);10731074    int type = getClientType(c);1075    /* Now that we have the memory used by the client, remove the old1076     * value from the old category, and add it back. */1077    server.stat_clients_type_memory[c->last_memory_type] -= c->last_memory_usage;1078    server.stat_clients_type_memory[type] += mem;1079    server.stat_clients_shared_memory -= c->last_memory_shared;1080    server.stat_clients_shared_memory += c->reply_bytes_shared;1081    server.stat_clients_unshared_memory -= c->last_memory_unshared;1082    server.stat_clients_unshared_memory += c->reply_bytes_unshared;1083    /* Remember what we added and where, to remove it next time. */1084    c->last_memory_type = type;1085    c->last_memory_usage = mem;1086    c->last_memory_shared = c->reply_bytes_shared;1087    c->last_memory_unshared = c->reply_bytes_unshared;1088    c->last_watch_pubsub_mem = c->watched_keys_mem + c->pubsub_names_mem;1089}10901091void updateClientWatchPubsubMemoryUsage(client *c) {1092    if (!c->conn) return;1093    size_t watch_pubsub_mem = c->watched_keys_mem + c->pubsub_names_mem;1094    if (watch_pubsub_mem == c->last_watch_pubsub_mem) return;1095    size_t mem = c->last_memory_usage - c->last_watch_pubsub_mem + watch_pubsub_mem;1096    server.stat_clients_type_memory[c->last_memory_type] =1097        server.stat_clients_type_memory[c->last_memory_type] - c->last_memory_usage + mem;1098    if (c->mem_usage_bucket) {1099        clientMemUsageBucket *bucket = getMemUsageBucket(mem);1100        c->mem_usage_bucket->mem_usage_sum -= c->last_memory_usage;1101        bucket->mem_usage_sum += mem;1102        if (bucket != c->mem_usage_bucket) {1103            listDelNode(c->mem_usage_bucket->clients, c->mem_usage_bucket_node);1104            c->mem_usage_bucket = bucket;1105            listAddNodeTail(bucket->clients, c);1106            c->mem_usage_bucket_node = listLast(bucket->clients);1107        }1108    }1109    c->last_memory_usage = mem;1110    c->last_watch_pubsub_mem = watch_pubsub_mem;1111}11121113int clientEvictionAllowed(client *c) {1114    if (server.maxmemory_clients == 0 || c->flags & CLIENT_NO_EVICT || !c->conn) {1115        return 0;1116    }1117    int type = getClientType(c);1118    return (type == CLIENT_TYPE_NORMAL || type == CLIENT_TYPE_PUBSUB);1119}112011211122/* This function is used to cleanup the client's previously tracked memory usage.1123 * This is called during incremental client memory usage tracking as well as1124 * used to reset when client to bucket allocation is not required when1125 * client eviction is disabled.  */1126void removeClientFromMemUsageBucket(client *c, int allow_eviction) {1127    if (c->mem_usage_bucket) {1128        c->mem_usage_bucket->mem_usage_sum -= c->last_memory_usage;1129        /* If this client can't be evicted then remove it from the mem usage1130         * buckets */1131        if (!allow_eviction) {1132            listDelNode(c->mem_usage_bucket->clients, c->mem_usage_bucket_node);1133            c->mem_usage_bucket = NULL;1134            c->mem_usage_bucket_node = NULL;1135        }1136    }1137}11381139/* This is called only if explicit clients when something changed their buffers,1140 * so we can track clients' memory and enforce clients' maxmemory in real time.1141 *1142 * This also adds the client to the correct memory usage bucket. Each bucket contains1143 * all clients with roughly the same amount of memory. This way we group1144 * together clients consuming about the same amount of memory and can quickly1145 * free them in case we reach maxmemory-clients (client eviction).1146 *1147 * Note: This function filters clients of type no-evict, master or replica regardless1148 * of whether the eviction is enabled or not, so the memory usage we get from these1149 * types of clients via the INFO command may be out of date.1150 *1151 * returns 1 if client eviction for this client is allowed, 0 otherwise.1152 */1153static int updateClientMemUsageAndBucketInternal(client *c, int unshared_refreshed) {1154    /* The unlikely case this function was called from a thread different1155     * than the main one is a module call from a spawned thread. This is safe1156     * since this call must have been made after calling1157     * RedisModule_ThreadSafeContextLock i.e the module is holding the GIL.1158     * Whoever the caller is, we assert that the updated client is running in1159     * the main thread, or that its IO-thread is paused, f.e see evictClients()1160     * and applyClientMaxMemoryUsage(). */1161    serverAssert((c->running_tid == IOTHREAD_MAIN_THREAD_ID ||1162                  isIOThreadPaused(c->tid)) && c->conn);1163    int allow_eviction = clientEvictionAllowed(c);1164    removeClientFromMemUsageBucket(c, allow_eviction);11651166    if (!allow_eviction) {1167        updateClientWatchPubsubMemoryUsage(c);1168        return 0;1169    }11701171    /* Include unshared reply bytes in the client's memory usage for eviction.1172     * Walking the reply buffer is costly, so skip the scan when its outcome1173     * cannot affect bucket placement: since 0 <= unshared <= shared, if both1174     * endpoints map to the same bucket the cached value is reused. */1175    if (!unshared_refreshed) {1176        if (c->reply_bytes_shared == 0) {1177            /* No shared bytes: clear any stale cached unshared. */1178            c->reply_bytes_unshared = 0;1179        } else {1180            size_t lower_bound = getClientMemoryUsage(c) - c->reply_bytes_unshared;1181            size_t upper_bound = lower_bound + c->reply_bytes_shared;1182            if (getMemUsageBucket(lower_bound) != getMemUsageBucket(upper_bound))1183                updateClientUnsharedReplyBytes(c);1184        }1185    }11861187    /* Update client memory usage. */1188    updateClientMemoryUsage(c);11891190    /* Update the client in the mem usage buckets */1191    clientMemUsageBucket *bucket = getMemUsageBucket(c->last_memory_usage);1192    bucket->mem_usage_sum += c->last_memory_usage;1193    if (bucket != c->mem_usage_bucket) {1194        if (c->mem_usage_bucket)1195            listDelNode(c->mem_usage_bucket->clients,1196                        c->mem_usage_bucket_node);1197        c->mem_usage_bucket = bucket;1198        listAddNodeTail(bucket->clients, c);1199        c->mem_usage_bucket_node = listLast(bucket->clients);1200    }1201    return 1;1202}12031204int updateClientMemUsageAndBucket(client *c) {1205    return updateClientMemUsageAndBucketInternal(c, 0);1206}12071208/* Return the max samples in the memory usage of clients tracked by1209 * the function clientsCronTrackExpansiveClients(). */1210void getExpansiveClientsInfo(size_t *in_usage, size_t *out_usage) {1211    size_t i = 0, o = 0;1212    for (int j = 0; j < CLIENTS_PEAK_MEM_USAGE_SLOTS; j++) {1213        if (ClientsPeakMemInput[j] > i) i = ClientsPeakMemInput[j];1214        if (ClientsPeakMemOutput[j] > o) o = ClientsPeakMemOutput[j];1215    }1216    *in_usage = i;1217    *out_usage = o;1218}12191220/* Run cron tasks for a single client. Return 1 if the client should1221 * be terminated, 0 otherwise. */1222int clientsCronRunClient(client *c) {1223    mstime_t now = server.mstime;1224    /* The following functions do different service checks on the client.1225     * The protocol is that they return non-zero if the client was1226     * terminated. */1227    if (clientsCronHandleTimeout(c,now)) return 1;1228    if (clientsCronResizeQueryBuffer(c)) return 1;1229    if (clientsCronResizeOutputBuffer(c,now)) return 1;12301231    if (clientsCronTrackExpansiveClients(c)) return 1;12321233    /* Refresh unshared reply memory roughly once per second for every client.1234     * Allow one cron tick of slack, otherwise a client visited slightly less1235     * than a second after its last refresh would wait for the next round,1236     * delaying the refresh to ~2s. */1237    int unshared_refreshed = c->last_unshared_refresh + 1000 - 1000/server.hz <= now;1238    if (unshared_refreshed) {1239        c->last_unshared_refresh = now;1240        updateClientUnsharedReplyBytes(c);1241    }12421243    /* Iterating all the clients in getMemoryOverheadData() is too slow and1244     * in turn would make the INFO command too slow. So we perform this1245     * computation incrementally and track the (not instantaneous but updated1246     * to the second) total memory used by clients using clientsCron() in1247     * a more incremental way (depending on server.hz).1248     * If client eviction is enabled, update the bucket as well. */1249    if (!updateClientMemUsageAndBucketInternal(c, unshared_refreshed))1250        updateClientMemoryUsage(c);12511252    if (closeClientOnOutputBufferLimitReached(c, 0)) return 1;1253    return 0;1254}12551256/* Periodic maintenance for the pending command pool.1257 * This function should be called from serverCron to manage pool size based on utilization patterns. */1258void pendingCommandPoolCron(void) {1259    /* Only shrink pool when IO threads are not active */1260    if (server.io_threads_active) return;12611262    /* Calculate utilization rate based on minimum pool size reached */1263    if (server.cmd_pool.capacity > PENDING_COMMAND_POOL_SIZE) {1264        /* If utilization is below threshold, shrink the pool */1265        double utilization_ratio = 1.0 - (double)server.cmd_pool.min_size / server.cmd_pool.capacity;1266        if (utilization_ratio < 0.5)1267            shrinkPendingCommandPool();1268    }12691270    /* Reset tracking for next interval */1271    server.cmd_pool.min_size = server.cmd_pool.size; /* Reset to current size */1272}12731274/* This function is called by serverCron() and is used in order to perform1275 * operations on clients that are important to perform constantly. For instance1276 * we use this function in order to disconnect clients after a timeout, including1277 * clients blocked in some blocking command with a non-zero timeout.1278 *1279 * The function makes some effort to process all the clients every second, even1280 * if this cannot be strictly guaranteed, since serverCron() may be called with1281 * an actual frequency lower than server.hz in case of latency events like slow1282 * commands.1283 *1284 * It is very important for this function, and the functions it calls, to be1285 * very fast: sometimes Redis has tens of hundreds of connected clients, and the1286 * default server.hz value is 10, so sometimes here we need to process thousands1287 * of clients per second, turning this function into a source of latency.1288 */1289void clientsCron(void) {1290    /* Try to process at least numclients/server.hz of clients1291     * per call. Since normally (if there are no big latency events) this1292     * function is called server.hz times per second, in the average case we1293     * process all the clients in 1 second. */1294    int numclients = listLength(server.clients);1295    int iterations = numclients/server.hz;12961297    /* Process at least a few clients while we are at it, even if we need1298     * to process less than CLIENTS_CRON_MIN_ITERATIONS to meet our contract1299     * of processing each client once per second. */1300    if (iterations < CLIENTS_CRON_MIN_ITERATIONS)1301        iterations = (numclients < CLIENTS_CRON_MIN_ITERATIONS) ?1302                     numclients : CLIENTS_CRON_MIN_ITERATIONS;130313041305    CurrentPeakMemUsageSlot = server.unixtime % CLIENTS_PEAK_MEM_USAGE_SLOTS;1306    /* Always zero the next sample, so that when we switch to that second, we'll1307     * only register samples that are greater in that second without considering1308     * the history of such slot.1309     *1310     * Note: our index may jump to any random position if serverCron() is not1311     * called for some reason with the normal frequency, for instance because1312     * some slow command is called taking multiple seconds to execute. In that1313     * case our array may end containing data which is potentially older1314     * than CLIENTS_PEAK_MEM_USAGE_SLOTS seconds: however this is not a problem1315     * since here we want just to track if "recently" there were very expansive1316     * clients from the POV of memory usage. */1317    int zeroidx = (CurrentPeakMemUsageSlot+1) % CLIENTS_PEAK_MEM_USAGE_SLOTS;1318    ClientsPeakMemInput[zeroidx] = 0;1319    ClientsPeakMemOutput[zeroidx] = 0;13201321    while(listLength(server.clients) && iterations--) {1322        client *c;1323        listNode *head;13241325        /* Take the current head, process, and then rotate the head to tail.1326         * This way we can fairly iterate all clients step by step. */1327        head = listFirst(server.clients);1328        c = listNodeValue(head);1329        listRotateHeadToTail(server.clients);13301331        /* Clients handled by IO threads will be processed by IOThreadClientsCron. */1332        if (c->tid != IOTHREAD_MAIN_THREAD_ID) continue;13331334        clientsCronRunClient(c);1335    }1336}13371338static int resizeShouldSkip(int didx) {1339    if (!server.cluster_enabled) return 0;13401341    /* ASM resizes importing slot dict using the size hint. Skip cron1342     * resizing until this node, or its master, owns the slot. */1343    return !clusterNodeCoversSlot(clusterNodeGetMaster(getMyClusterNode()), didx);1344}13451346/* This function handles 'background' operations we are required to do1347 * incrementally in Redis databases, such as active key expiring, resizing,1348 * rehashing. */1349void databasesCron(void) {1350    /* Expire keys by random sampling. Not required for slaves1351     * as master will synthesize DELs for us. */1352    if (server.active_expire_enabled) {1353        if (iAmMaster()) {1354            activeExpireCycle(ACTIVE_EXPIRE_CYCLE_SLOW);1355        } else {1356            expireSlaveKeys();1357        }1358    }13591360    /* Defrag keys gradually. */1361    activeDefragCycle();13621363    /* Handle active-trim */1364    if (server.cluster_enabled)1365        asmActiveTrimCycle();13661367    /* Perform hash tables rehashing if needed, but only if there are no1368     * other processes saving the DB on disk. Otherwise rehashing is bad1369     * as will cause a lot of copy-on-write of memory pages. */1370    if (!hasActiveChildProcess()) {1371        /* We use global counters so if we stop the computation at a given1372         * DB we'll be able to start from the successive in the next1373         * cron loop iteration. */1374        static unsigned int resize_db = 0;1375        static unsigned int rehash_db = 0;1376        int dbs_per_call = CRON_DBS_PER_CALL;1377        int j;13781379        /* Don't test more DBs than we have. */1380        if (dbs_per_call > server.dbnum) dbs_per_call = server.dbnum;13811382        for (j = 0; j < dbs_per_call; j++) {1383            redisDb *db = &server.db[resize_db % server.dbnum];1384            kvstoreTryResizeDicts(db->keys, CRON_DICTS_PER_DB, resizeShouldSkip);1385            kvstoreTryResizeDicts(db->expires, CRON_DICTS_PER_DB, resizeShouldSkip);1386            kvstoreTryResizeDicts(db->blessed_keys, CRON_DICTS_PER_DB, resizeShouldSkip);1387            resize_db++;1388        }13891390        /* Rehash */1391        if (server.activerehashing) {1392            uint64_t elapsed_us = 0;1393            for (j = 0; j < dbs_per_call; j++) {1394                redisDb *db = &server.db[rehash_db % server.dbnum];1395                elapsed_us += kvstoreIncrementallyRehash(db->keys, INCREMENTAL_REHASHING_THRESHOLD_US - elapsed_us);1396                if (elapsed_us >= INCREMENTAL_REHASHING_THRESHOLD_US)1397                    break;1398                elapsed_us += kvstoreIncrementallyRehash(db->expires, INCREMENTAL_REHASHING_THRESHOLD_US - elapsed_us);1399                if (elapsed_us >= INCREMENTAL_REHASHING_THRESHOLD_US)1400                    break;1401                elapsed_us += kvstoreIncrementallyRehash(db->blessed_keys, INCREMENTAL_REHASHING_THRESHOLD_US - elapsed_us);1402                if (elapsed_us >= INCREMENTAL_REHASHING_THRESHOLD_US)1403                    break;1404                rehash_db++;1405            }1406        }1407    }1408}14091410static inline void updateCachedTimeWithUs(int update_daylight_info, const long long ustime) {1411    server.ustime = ustime;1412    server.mstime = server.ustime / 1000;1413    time_t unixtime = server.mstime / 1000;1414    atomicSet(server.unixtime, unixtime);14151416    /* To get information about daylight saving time, we need to call1417     * localtime_r and cache the result. However calling localtime_r in this1418     * context is safe since we will never fork() while here, in the main1419     * thread. The logging function will call a thread safe version of1420     * localtime that has no locks. */1421    if (update_daylight_info) {1422        struct tm tm;1423        time_t ut = server.unixtime;1424        localtime_r(&ut,&tm);1425        atomicSet(server.daylight_active, tm.tm_isdst);1426    }1427}14281429/* We take a cached value of the unix time in the global state because with1430 * virtual memory and aging there is to store the current time in objects at1431 * every object access, and accuracy is not needed. To access a global var is1432 * a lot faster than calling time(NULL).1433 *1434 * This function should be fast because it is called at every command execution1435 * in call(), so it is possible to decide if to update the daylight saving1436 * info or not using the 'update_daylight_info' argument. Normally we update1437 * such info only when calling this function from serverCron() but not when1438 * calling it from call(). */1439void updateCachedTime(int update_daylight_info) {1440    const long long us = ustime();1441    updateCachedTimeWithUs(update_daylight_info, us);1442}14431444/* Performing required operations in order to enter an execution unit.1445 * In general, if we are already inside an execution unit then there is nothing to do,1446 * otherwise we need to update cache times so the same cached time will be used all over1447 * the execution unit.1448 * update_cached_time - if 0, will not update the cached time even if required.1449 * us - if not zero, use this time for cached time, otherwise get current time. */1450void enterExecutionUnit(int update_cached_time, long long us) {1451    if (server.execution_nesting++ == 0 && update_cached_time) {1452        if (us == 0) {1453            us = ustime();1454        }1455        updateCachedTimeWithUs(0, us);1456        server.cmd_time_snapshot = server.mstime;1457    }1458}14591460void exitExecutionUnit(void) {1461    --server.execution_nesting;1462}14631464void checkChildrenDone(void) {1465    int statloc = 0;1466    pid_t pid;14671468    if ((pid = waitpid(-1, &statloc, WNOHANG)) != 0) {1469        int exitcode = WIFEXITED(statloc) ? WEXITSTATUS(statloc) : -1;1470        int bysignal = 0;14711472        if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc);14731474        /* sigKillChildHandler catches the signal and calls exit(), but we1475         * must make sure not to flag lastbgsave_status, etc incorrectly.1476         * We could directly terminate the child process via SIGUSR11477         * without handling it */1478        if (exitcode == SERVER_CHILD_NOERROR_RETVAL) {1479            bysignal = SIGUSR1;1480            exitcode = 1;1481        }14821483        if (pid == -1) {1484            serverLog(LL_WARNING,"waitpid() returned an error: %s. "1485                "child_type: %s, child_pid = %d",1486                strerror(errno),1487                strChildType(server.child_type),1488                (int) server.child_pid);1489        } else if (pid == server.child_pid) {1490            if (server.child_type == CHILD_TYPE_RDB) {1491                backgroundSaveDoneHandler(exitcode, bysignal);1492            } else if (server.child_type == CHILD_TYPE_AOF) {1493                backgroundRewriteDoneHandler(exitcode, bysignal);1494            } else if (server.child_type == CHILD_TYPE_MODULE) {1495                ModuleForkDoneHandler(exitcode, bysignal);1496            } else {1497                serverPanic("Unknown child type %d for child pid %d", server.child_type, server.child_pid);1498                exit(1);1499            }1500            if (!bysignal && exitcode == 0) receiveChildInfo();1501            resetChildState();1502        } else {1503            if (!ldbRemoveChild(pid)) {1504                serverLog(LL_WARNING,1505                          "Warning, detected child with unmatched pid: %ld",1506                          (long) pid);1507            }1508        }15091510        /* start any pending forks immediately. */1511        replicationStartPendingFork();1512    }1513}15141515/* Record the max memory used since the server was started. */1516void updatePeakMemory(void) {1517    size_t zmalloc_used = zmalloc_used_memory();1518    if (zmalloc_used > server.stat_peak_memory) {1519        server.stat_peak_memory = zmalloc_used;1520        server.stat_peak_memory_time = server.unixtime;1521    }15221523    size_t zmalloc_peak = zmalloc_get_peak_memory();1524    if (zmalloc_peak > server.stat_peak_memory) {1525        server.stat_peak_memory = zmalloc_peak;1526        server.stat_peak_memory_time = zmalloc_get_peak_memory_time();1527    }1528}15291530/* Called from serverCron and cronUpdateMemoryStats to update cached memory metrics. */1531void cronUpdateMemoryStats(void) {1532    updatePeakMemory();15331534    run_with_period(100) {1535        /* Sample the RSS and other metrics here since this is a relatively slow call.1536         * We must sample the zmalloc_used at the same time we take the rss, otherwise1537         * the frag ratio calculate may be off (ratio of two samples at different times) */1538        server.cron_malloc_stats.process_rss = zmalloc_get_rss();1539        server.cron_malloc_stats.zmalloc_used = zmalloc_used_memory();1540        /* Sampling the allocator info can be slow too.1541         * The fragmentation ratio it'll show is potentially more accurate1542         * it excludes other RSS pages such as: shared libraries, LUA and other non-zmalloc1543         * allocations, and allocator reserved pages that can be pursed (all not actual frag) */1544        zmalloc_get_allocator_info(1,1545                                   &server.cron_malloc_stats.allocator_allocated,1546                                   &server.cron_malloc_stats.allocator_active,1547                                   &server.cron_malloc_stats.allocator_resident,1548                                   NULL,1549                                   &server.cron_malloc_stats.allocator_muzzy,1550                                   &server.cron_malloc_stats.allocator_frag_smallbins_bytes);1551        if (server.lua_arena != UINT_MAX) {1552            zmalloc_get_allocator_info_by_arena(server.lua_arena,1553                                                0,1554                                                &server.cron_malloc_stats.lua_allocator_allocated,1555                                                &server.cron_malloc_stats.lua_allocator_active,1556                                                &server.cron_malloc_stats.lua_allocator_resident,1557                                                &server.cron_malloc_stats.lua_allocator_frag_smallbins_bytes);1558        }1559        /* Publish the just-measured (Lua-arena-subtracted) fragmentation1560         * values into the defrag-side tick-local cache so1561         * computeDefragCycles() later this tick can skip its own1562         * duplicate jemalloc measurement. Mirrors1563         * getAllocatorFragmentation()'s Lua subtraction so the cached1564         * value matches the fall-through real measurement exactly.1565         * Publishing with allocated==0 leaves the cache invalid1566         * (sentinel set inside the publish) — defrag should decide on1567         * real data or none. */1568        size_t frag  = server.cron_malloc_stats.allocator_frag_smallbins_bytes;1569        size_t alloc = server.cron_malloc_stats.allocator_allocated;1570        if (alloc > 0 && server.lua_arena != UINT_MAX) {1571            frag  -= server.cron_malloc_stats.lua_allocator_frag_smallbins_bytes;1572            alloc -= server.cron_malloc_stats.lua_allocator_allocated;1573        }1574        defragFragCachePut(frag, alloc);1575        /* in case the allocator isn't providing these stats, fake them so that1576         * fragmentation info still shows some (inaccurate metrics) */1577        if (!server.cron_malloc_stats.allocator_resident)1578            server.cron_malloc_stats.allocator_resident = server.cron_malloc_stats.process_rss;1579        if (!server.cron_malloc_stats.allocator_active)1580            server.cron_malloc_stats.allocator_active = server.cron_malloc_stats.allocator_resident;1581        if (!server.cron_malloc_stats.allocator_allocated)1582            server.cron_malloc_stats.allocator_allocated = server.cron_malloc_stats.zmalloc_used;1583    }1584}15851586/* This is our timer interrupt, called server.hz times per second.1587 * Here is where we do a number of things that need to be done asynchronously.1588 * For instance:1589 *1590 * - Active expired keys collection (it is also performed in a lazy way on1591 *   lookup).1592 * - Software watchdog.1593 * - Update some statistic.1594 * - Incremental rehashing of the DBs hash tables.1595 * - Triggering BGSAVE / AOF rewrite, and handling of terminated children.1596 * - Clients timeout of different kinds.1597 * - Replication reconnection.1598 * - Many more...1599 *1600 * Everything directly called here will be called server.hz times per second,1601 * so in order to throttle execution of things we want to do less frequently1602 * a macro is used: run_with_period(milliseconds) { .... }1603 */16041605int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {1606    int j;1607    UNUSED(eventLoop);1608    UNUSED(id);1609    UNUSED(clientData);16101611    /* Software watchdog: deliver the SIGALRM that will reach the signal1612     * handler if we don't return here fast enough. */1613    if (server.watchdog_period) watchdogScheduleSignal(server.watchdog_period);16141615    server.hz = server.config_hz;1616    /* Adapt the server.hz value to the number of configured clients. If we have1617     * many clients, we want to call serverCron() with an higher frequency. */1618    if (server.dynamic_hz) {1619        while (listLength(server.clients) / server.hz >1620               MAX_CLIENTS_PER_CLOCK_TICK)1621        {1622            server.hz *= 2;1623            if (server.hz > CONFIG_MAX_HZ) {1624                server.hz = CONFIG_MAX_HZ;1625                break;1626            }1627        }1628    }16291630    /* for debug purposes: skip actual cron work if pause_cron is on */1631    if (server.pause_cron) return 1000/server.hz;16321633    monotime cron_start = getMonotonicUs();16341635    run_with_period(100) {1636        long long stat_net_input_bytes, stat_net_output_bytes;1637        long long stat_net_repl_input_bytes, stat_net_repl_output_bytes;1638        atomicGet(server.stat_net_input_bytes, stat_net_input_bytes);1639        atomicGet(server.stat_net_output_bytes, stat_net_output_bytes);1640        atomicGet(server.stat_net_repl_input_bytes, stat_net_repl_input_bytes);1641        atomicGet(server.stat_net_repl_output_bytes, stat_net_repl_output_bytes);1642        monotime current_time = getMonotonicUs();1643        long long factor = 1000000;  // us1644        trackInstantaneousMetric(STATS_METRIC_COMMAND, server.stat_numcommands, current_time, factor);1645        trackInstantaneousMetric(STATS_METRIC_NET_INPUT, stat_net_input_bytes + stat_net_repl_input_bytes,1646                                 current_time, factor);1647        trackInstantaneousMetric(STATS_METRIC_NET_OUTPUT, stat_net_output_bytes + stat_net_repl_output_bytes,1648                                 current_time, factor);1649        trackInstantaneousMetric(STATS_METRIC_NET_INPUT_REPLICATION, stat_net_repl_input_bytes, current_time,1650                                 factor);1651        trackInstantaneousMetric(STATS_METRIC_NET_OUTPUT_REPLICATION, stat_net_repl_output_bytes,1652                                 current_time, factor);1653        trackInstantaneousMetric(STATS_METRIC_EL_CYCLE, server.duration_stats[EL_DURATION_TYPE_EL].cnt,1654                                 current_time, factor);1655        trackInstantaneousMetric(STATS_METRIC_EL_DURATION, server.duration_stats[EL_DURATION_TYPE_EL].sum,1656                                 server.duration_stats[EL_DURATION_TYPE_EL].cnt, 1);16571658        /* Periodic cleanup of active clients sliding window to clear stale slots1659         * when no client activity occurs for extended periods */1660        statsUpdateActiveClients(NULL);1661    }16621663    /* We have just LRU_BITS bits per object for LRU information.1664     * So we use an (eventually wrapping) LRU clock.1665     *1666     * Note that even if the counter wraps it's not a big problem,1667     * everything will still work but some object will appear younger1668     * to Redis. However for this to happen a given object should never be1669     * touched for all the time needed to the counter to wrap, which is1670     * not likely.1671     *1672     * Note that you can change the resolution altering the1673     * LRU_CLOCK_RESOLUTION define. */1674    server.lruclock = getLRUClock();16751676    cronUpdateMemoryStats();16771678    /* We received a SIGTERM or SIGINT, shutting down here in a safe way, as it is1679     * not ok doing so inside the signal handler. */1680    if (shouldShutdownAsap() && !isShutdownInitiated()) {1681        int shutdownFlags = SHUTDOWN_NOFLAGS;1682        int last_sig_received;1683        atomicGet(server.last_sig_received, last_sig_received);1684        if (last_sig_received == SIGINT && server.shutdown_on_sigint)1685            shutdownFlags = server.shutdown_on_sigint;1686        else if (last_sig_received == SIGTERM && server.shutdown_on_sigterm)1687            shutdownFlags = server.shutdown_on_sigterm;16881689        if (prepareForShutdown(shutdownFlags) == C_OK) exit(0);1690    } else if (isShutdownInitiated()) {1691        if (server.mstime >= server.shutdown_mstime || isReadyToShutdown()) {1692            if (finishShutdown() == C_OK) exit(0);1693            /* Shutdown failed. Continue running. An error has been logged. */1694        }1695    }16961697    /* Show some info about non-empty databases */1698    if (server.verbosity <= LL_VERBOSE) {1699        run_with_period(5000) {1700            for (j = 0; j < server.dbnum; j++) {1701                long long size, used, vkeys;17021703                size = kvstoreBuckets(server.db[j].keys);1704                used = kvstoreSize(server.db[j].keys);1705                vkeys = kvstoreSize(server.db[j].expires);1706                if (used || vkeys) {1707                    serverLog(LL_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);1708                }1709            }1710        }1711    }17121713    /* Show information about connected clients */1714    if (!server.sentinel_mode) {1715        run_with_period(5000) {1716            serverLog(LL_DEBUG,1717                "%lu clients connected (%lu replicas), %zu bytes in use",1718                listLength(server.clients)-listLength(server.slaves),1719                replicationLogicalReplicaCount(),1720                zmalloc_used_memory());1721        }1722    }17231724    /* We need to do a few operations on clients asynchronously. */1725    clientsCron();17261727    /* Handle background operations on Redis databases. */1728    databasesCron();17291730    backupCron();17311732    /* Start a scheduled AOF rewrite if this was requested while another state1733     * prevented it earlier. */1734    if (!hasActiveChildProcess() &&1735        server.aof_rewrite_scheduled &&1736        !backupIsInProgress() &&1737        !aofRewriteLimited())1738    {1739        rewriteAppendOnlyFileBackground();1740    }17411742    /* Check if a background saving or AOF rewrite in progress terminated. */1743    if (hasActiveChildProcess() || ldbPendingChildren())1744    {1745        run_with_period(1000) receiveChildInfo();1746        checkChildrenDone();1747    } else {1748        /* If there is not a background saving/rewrite in progress check if1749         * we have to save/rewrite now. */1750        for (j = 0; j < server.saveparamslen; j++) {1751            struct saveparam *sp = server.saveparams+j;17521753            /* Save if we reached the given amount of changes,1754             * the given amount of seconds, and if the latest bgsave was1755             * successful or if, in case of an error, at least1756             * CONFIG_BGSAVE_RETRY_DELAY seconds already elapsed. */1757            if (server.dirty >= sp->changes &&1758                server.unixtime-server.lastsave > sp->seconds &&1759                (server.unixtime-server.lastbgsave_try >1760                 CONFIG_BGSAVE_RETRY_DELAY ||1761                 server.lastbgsave_status == C_OK))1762            {1763                serverLog(LL_NOTICE,"%d changes in %d seconds. Saving...",1764                    sp->changes, (int)sp->seconds);1765                rdbSaveInfo rsi, *rsiptr;1766                rsiptr = rdbPopulateSaveInfo(&rsi);1767                rdbSaveBackground(SLAVE_REQ_NONE,server.rdb_filename,rsiptr,RDBFLAGS_NONE);1768                break;1769            }1770        }17711772        /* Trigger an AOF rewrite if needed. */1773        if (server.aof_state == AOF_ON &&1774            !hasActiveChildProcess() &&1775            !backupIsInProgress() &&1776            server.aof_rewrite_perc &&1777            server.aof_current_size > server.aof_rewrite_min_size)1778        {1779            long long base = server.aof_rewrite_base_size ?1780                server.aof_rewrite_base_size : 1;1781            long long growth = (server.aof_current_size*100/base) - 100;1782            if (growth >= server.aof_rewrite_perc && !aofRewriteLimited()) {1783                serverLog(LL_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth);1784                rewriteAppendOnlyFileBackground();1785            }1786        }1787    }1788    /* Just for the sake of defensive programming, to avoid forgetting to1789     * call this function when needed. */1790    updateDictResizePolicy();17911792    /* AOF postponed flush: Try at every cron cycle if the slow fsync1793     * completed. */1794    if ((server.aof_state == AOF_ON || server.aof_state == AOF_WAIT_REWRITE) &&1795        server.aof_flush_postponed_start)1796    {1797        flushAppendOnlyFile(0);1798    }17991800    /* AOF write errors: in this case we have a buffer to flush as well and1801     * clear the AOF error in case of success to make the DB writable again,1802     * however to try every second is enough in case of 'hz' is set to1803     * a higher frequency. */1804    run_with_period(1000) {1805        if ((server.aof_state == AOF_ON || server.aof_state == AOF_WAIT_REWRITE) &&1806            server.aof_last_write_status == C_ERR) 1807            {1808                flushAppendOnlyFile(0);1809            }1810    }18111812    /* Clear the paused actions state if needed. */1813    updatePausedActions();18141815    /* Replication cron function -- used to reconnect to master,1816     * detect transfer failures, start background RDB transfers and so forth. 1817     * 1818     * If Redis is trying to failover then run the replication cron faster so1819     * progress on the handshake happens more quickly. */1820    if (server.failover_state != NO_FAILOVER) {1821        run_with_period(100) replicationCron();1822    } else {1823        run_with_period(1000) replicationCron();1824    }18251826    /* Run the Redis Cluster cron. */1827    run_with_period(100) {1828        if (server.cluster_enabled) {1829            clusterCron();1830            asmCron();1831        }1832    }18331834    /* Run the Sentinel timer if we are in sentinel mode. */1835    if (server.sentinel_mode) sentinelTimer();18361837    /* Cleanup expired MIGRATE cached sockets. */1838    run_with_period(1000) {1839        migrateCloseTimedoutSockets();1840    }18411842    /* Cleanup expired IDMP entries from tracked streams */1843    run_with_period(1000) {1844        handleExpiredIdmpEntries();1845    }18461847    /* Periodically shrink pending command reuse pool */1848    run_with_period(2000) {1849        pendingCommandPoolCron();1850    }18511852    /* Template registry maintenance. */1853    hashTemplatesCron();18541855    /* Resize tracking keys table if needed. This is also done at every1856     * command execution, but we want to be sure that if the last command1857     * executed changes the value via CONFIG SET, the server will perform1858     * the operation even if completely idle. */1859    if (server.tracking_clients) trackingLimitUsedSlots();18601861    /* Check if hotkey tracking duration has expired and auto-stop if needed */1862    if (server.hotkeys && server.hotkeys->active && server.hotkeys->duration > 0) {1863        mstime_t elapsed = (server.mstime - server.hotkeys->start);1864        if (elapsed >= server.hotkeys->duration) {1865            server.hotkeys->active = 0;1866            server.hotkeys->duration = elapsed;1867        }1868    }18691870    /* Start a scheduled BGSAVE if the corresponding flag is set. This is1871     * useful when we are forced to postpone a BGSAVE because an AOF1872     * rewrite is in progress.1873     *1874     * Note: this code must be after the replicationCron() call above so1875     * make sure when refactoring this file to keep this order. This is useful1876     * because we want to give priority to RDB savings for replication. */1877    if (!hasActiveChildProcess() &&1878        server.rdb_bgsave_scheduled &&1879        (server.unixtime-server.lastbgsave_try > CONFIG_BGSAVE_RETRY_DELAY ||1880         server.lastbgsave_status == C_OK))1881    {1882        rdbSaveInfo rsi, *rsiptr;1883        rsiptr = rdbPopulateSaveInfo(&rsi);1884        if (rdbSaveBackground(SLAVE_REQ_NONE,server.rdb_filename,rsiptr,RDBFLAGS_NONE) == C_OK)1885            server.rdb_bgsave_scheduled = 0;1886    }18871888    run_with_period(100) {1889        if (moduleCount()) modulesCron();1890    }18911892    /* Fire the cron loop modules event. */1893    RedisModuleCronLoopV1 ei = {REDISMODULE_CRON_LOOP_VERSION,server.hz};1894    moduleFireServerEvent(REDISMODULE_EVENT_CRON_LOOP,1895                          0,1896                          &ei);18971898    server.cronloops++;18991900    server.el_cron_duration = getMonotonicUs() - cron_start;19011902    return 1000/server.hz;1903}190419051906void blockingOperationStarts(void) {1907    if(!server.blocking_op_nesting++){1908        updateCachedTime(0);1909        server.blocked_last_cron = server.mstime;1910    }1911}19121913void blockingOperationEnds(void) {1914    if(!(--server.blocking_op_nesting)){1915        server.blocked_last_cron = 0;1916    }1917}19181919/* This function fills in the role of serverCron during RDB or AOF loading, and1920 * also during blocked scripts.1921 * It attempts to do its duties at a similar rate as the configured server.hz,1922 * and updates cronloops variable so that similarly to serverCron, the1923 * run_with_period can be used. */1924void whileBlockedCron(void) {1925    /* Here we may want to perform some cron jobs (normally done server.hz times1926     * per second). */19271928    /* Since this function depends on a call to blockingOperationStarts, let's1929     * make sure it was done. */1930    serverAssert(server.blocked_last_cron);19311932    /* In case we were called too soon, leave right away. This way one time1933     * jobs after the loop below don't need an if. and we don't bother to start1934     * latency monitor if this function is called too often. */1935    if (server.blocked_last_cron >= server.mstime)1936        return;19371938    /* Increment server.cronloops so that run_with_period works. */1939    long hz_ms = 1000 / server.hz;1940    int cronloops = (server.mstime - server.blocked_last_cron + (hz_ms - 1)) / hz_ms; /* rounding up */1941    server.blocked_last_cron += cronloops * hz_ms;1942    server.cronloops += cronloops;19431944    mstime_t latency;1945    latencyStartMonitor(latency);19461947    /* Only defragment during AOF loading. */1948    if (isAOFLoadingContext()) defragWhileBlocked();19491950    /* Update memory stats during loading (excluding blocked scripts) */1951    if (server.loading) cronUpdateMemoryStats();19521953    latencyEndMonitor(latency);1954    latencyAddSampleIfNeeded("while-blocked-cron",latency);19551956    /* We received a SIGTERM during loading, shutting down here in a safe way,1957     * as it isn't ok doing so inside the signal handler. */1958    if (shouldShutdownAsap() && server.loading) {1959        if (prepareForShutdown(SHUTDOWN_NOSAVE) == C_OK) exit(0);1960        serverLog(LL_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");1961        atomicSet(server.shutdown_asap, 0);1962        atomicSet(server.last_sig_received, 0);1963    }1964}19651966static void sendGetackToReplicas(void) {1967    robj *argv[3];1968    argv[0] = shared.replconf;1969    argv[1] = shared.getack;1970    argv[2] = shared.special_asterisk; /* Not used argument. */1971    replicationFeedSlaves(server.slaves, -1, argv, 3);1972}19731974extern int ProcessingEventsWhileBlocked;19751976/* This function gets called every time Redis is entering the1977 * main loop of the event driven library, that is, before to sleep1978 * for ready file descriptors.1979 *1980 * Note: This function is (currently) called from two functions:1981 * 1. aeMain - The main server loop1982 * 2. processEventsWhileBlocked - Process clients during RDB/AOF load1983 *1984 * If it was called from processEventsWhileBlocked we don't want1985 * to perform all actions (For example, we don't want to expire1986 * keys), but we do need to perform some actions.1987 *1988 * The most important is freeClientsInAsyncFreeQueue but we also1989 * call some other low-risk functions. */1990void beforeSleep(struct aeEventLoop *eventLoop) {1991    UNUSED(eventLoop);19921993    updatePeakMemory();19941995    /* Just call a subset of vital functions in case we are re-entering1996     * the event loop from processEventsWhileBlocked(). Note that in this1997     * case we keep track of the number of events we are processing, since1998     * processEventsWhileBlocked() wants to stop ASAP if there are no longer1999     * events to handle. */2000    if (ProcessingEventsWhileBlocked) {

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings