xref: /f-stack/app/redis-5.0.5/src/server.h (revision 572c4311)
1 /*
2  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *   * Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *   * Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  *   * Neither the name of Redis nor the names of its contributors may be used
14  *     to endorse or promote products derived from this software without
15  *     specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #ifndef __REDIS_H
31 #define __REDIS_H
32 
33 #include "fmacros.h"
34 #include "config.h"
35 #include "solarisfixes.h"
36 #include "rio.h"
37 
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <time.h>
42 #include <limits.h>
43 #include <unistd.h>
44 #include <errno.h>
45 #include <inttypes.h>
46 #define _GNU_SOURCE
47 #include <pthread.h>
48 #include <syslog.h>
49 #include <netinet/in.h>
50 #include <lua.h>
51 #include <signal.h>
52 
53 typedef long long mstime_t; /* millisecond time type. */
54 
55 #include "ae.h"      /* Event driven programming library */
56 #include "sds.h"     /* Dynamic safe strings */
57 #include "dict.h"    /* Hash tables */
58 #include "adlist.h"  /* Linked lists */
59 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
60 #include "anet.h"    /* Networking the easy way */
61 #include "ziplist.h" /* Compact list data structure */
62 #include "intset.h"  /* Compact integer set structure */
63 #include "version.h" /* Version macro */
64 #include "util.h"    /* Misc functions useful in many places */
65 #include "latency.h" /* Latency monitor API */
66 #include "sparkline.h" /* ASCII graphs API */
67 #include "quicklist.h"  /* Lists are encoded as linked lists of
68                            N-elements flat arrays */
69 #include "rax.h"     /* Radix tree */
70 
71 /* Following includes allow test functions to be called from Redis main() */
72 #include "zipmap.h"
73 #include "sha1.h"
74 #include "endianconv.h"
75 #include "crc64.h"
76 
77 /* Error codes */
78 #define C_OK                    0
79 #define C_ERR                   -1
80 
81 /* Static server configuration */
82 #define CONFIG_DEFAULT_DYNAMIC_HZ 1             /* Adapt hz to # of clients.*/
83 #define CONFIG_DEFAULT_HZ        10             /* Time interrupt calls/sec. */
84 #define CONFIG_MIN_HZ            1
85 #define CONFIG_MAX_HZ            500
86 #define MAX_CLIENTS_PER_CLOCK_TICK 200          /* HZ is adapted based on that. */
87 #define CONFIG_DEFAULT_SERVER_PORT        6379  /* TCP port. */
88 #define CONFIG_DEFAULT_TCP_BACKLOG       511    /* TCP listen backlog. */
89 #define CONFIG_DEFAULT_CLIENT_TIMEOUT       0   /* Default client timeout: infinite */
90 #define CONFIG_DEFAULT_DBNUM     16
91 #define CONFIG_MAX_LINE    1024
92 #define CRON_DBS_PER_CALL 16
93 #define NET_MAX_WRITES_PER_EVENT (1024*64)
94 #define PROTO_SHARED_SELECT_CMDS 10
95 #define OBJ_SHARED_INTEGERS 10000
96 #define OBJ_SHARED_BULKHDR_LEN 32
97 #define LOG_MAX_LEN    1024 /* Default maximum length of syslog messages.*/
98 #define AOF_REWRITE_PERC  100
99 #define AOF_REWRITE_MIN_SIZE (64*1024*1024)
100 #define AOF_REWRITE_ITEMS_PER_CMD 64
101 #define AOF_READ_DIFF_INTERVAL_BYTES (1024*10)
102 #define CONFIG_DEFAULT_SLOWLOG_LOG_SLOWER_THAN 10000
103 #define CONFIG_DEFAULT_SLOWLOG_MAX_LEN 128
104 #define CONFIG_DEFAULT_MAX_CLIENTS 10000
105 #define CONFIG_AUTHPASS_MAX_LEN 512
106 #define CONFIG_DEFAULT_SLAVE_PRIORITY 100
107 #define CONFIG_DEFAULT_REPL_TIMEOUT 60
108 #define CONFIG_DEFAULT_REPL_PING_SLAVE_PERIOD 10
109 #define CONFIG_RUN_ID_SIZE 40
110 #define RDB_EOF_MARK_SIZE 40
111 #define CONFIG_DEFAULT_REPL_BACKLOG_SIZE (1024*1024)    /* 1mb */
112 #define CONFIG_DEFAULT_REPL_BACKLOG_TIME_LIMIT (60*60)  /* 1 hour */
113 #define CONFIG_REPL_BACKLOG_MIN_SIZE (1024*16)          /* 16k */
114 #define CONFIG_BGSAVE_RETRY_DELAY 5 /* Wait a few secs before trying again. */
115 #define CONFIG_DEFAULT_PID_FILE "/var/run/redis.pid"
116 #define CONFIG_DEFAULT_SYSLOG_IDENT "redis"
117 #define CONFIG_DEFAULT_CLUSTER_CONFIG_FILE "nodes.conf"
118 #define CONFIG_DEFAULT_CLUSTER_ANNOUNCE_IP NULL         /* Auto detect. */
119 #define CONFIG_DEFAULT_CLUSTER_ANNOUNCE_PORT 0          /* Use server.port */
120 #define CONFIG_DEFAULT_CLUSTER_ANNOUNCE_BUS_PORT 0      /* Use +10000 offset. */
121 #define CONFIG_DEFAULT_DAEMONIZE 0
122 #define CONFIG_DEFAULT_UNIX_SOCKET_PERM 0
123 #define CONFIG_DEFAULT_TCP_KEEPALIVE 300
124 #define CONFIG_DEFAULT_PROTECTED_MODE 1
125 #define CONFIG_DEFAULT_LOGFILE ""
126 #define CONFIG_DEFAULT_SYSLOG_ENABLED 0
127 #define CONFIG_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR 1
128 #define CONFIG_DEFAULT_RDB_COMPRESSION 1
129 #define CONFIG_DEFAULT_RDB_CHECKSUM 1
130 #define CONFIG_DEFAULT_RDB_FILENAME "dump.rdb"
131 #define CONFIG_DEFAULT_REPL_DISKLESS_SYNC 0
132 #define CONFIG_DEFAULT_REPL_DISKLESS_SYNC_DELAY 5
133 #define CONFIG_DEFAULT_SLAVE_SERVE_STALE_DATA 1
134 #define CONFIG_DEFAULT_SLAVE_READ_ONLY 1
135 #define CONFIG_DEFAULT_SLAVE_IGNORE_MAXMEMORY 1
136 #define CONFIG_DEFAULT_SLAVE_ANNOUNCE_IP NULL
137 #define CONFIG_DEFAULT_SLAVE_ANNOUNCE_PORT 0
138 #define CONFIG_DEFAULT_REPL_DISABLE_TCP_NODELAY 0
139 #define CONFIG_DEFAULT_MAXMEMORY 0
140 #define CONFIG_DEFAULT_MAXMEMORY_SAMPLES 5
141 #define CONFIG_DEFAULT_LFU_LOG_FACTOR 10
142 #define CONFIG_DEFAULT_LFU_DECAY_TIME 1
143 #define CONFIG_DEFAULT_AOF_FILENAME "appendonly.aof"
144 #define CONFIG_DEFAULT_AOF_NO_FSYNC_ON_REWRITE 0
145 #define CONFIG_DEFAULT_AOF_LOAD_TRUNCATED 1
146 #define CONFIG_DEFAULT_AOF_USE_RDB_PREAMBLE 1
147 #define CONFIG_DEFAULT_ACTIVE_REHASHING 1
148 #define CONFIG_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC 1
149 #define CONFIG_DEFAULT_RDB_SAVE_INCREMENTAL_FSYNC 1
150 #define CONFIG_DEFAULT_MIN_SLAVES_TO_WRITE 0
151 #define CONFIG_DEFAULT_MIN_SLAVES_MAX_LAG 10
152 #define NET_IP_STR_LEN 46 /* INET6_ADDRSTRLEN is 46, but we need to be sure */
153 #define NET_PEER_ID_LEN (NET_IP_STR_LEN+32) /* Must be enough for ip:port */
154 #define CONFIG_BINDADDR_MAX 16
155 #define CONFIG_MIN_RESERVED_FDS 32
156 #define CONFIG_DEFAULT_LATENCY_MONITOR_THRESHOLD 0
157 #define CONFIG_DEFAULT_SLAVE_LAZY_FLUSH 0
158 #define CONFIG_DEFAULT_LAZYFREE_LAZY_EVICTION 0
159 #define CONFIG_DEFAULT_LAZYFREE_LAZY_EXPIRE 0
160 #define CONFIG_DEFAULT_LAZYFREE_LAZY_SERVER_DEL 0
161 #define CONFIG_DEFAULT_ALWAYS_SHOW_LOGO 0
162 #define CONFIG_DEFAULT_ACTIVE_DEFRAG 0
163 #define CONFIG_DEFAULT_DEFRAG_THRESHOLD_LOWER 10 /* don't defrag when fragmentation is below 10% */
164 #define CONFIG_DEFAULT_DEFRAG_THRESHOLD_UPPER 100 /* maximum defrag force at 100% fragmentation */
165 #define CONFIG_DEFAULT_DEFRAG_IGNORE_BYTES (100<<20) /* don't defrag if frag overhead is below 100mb */
166 #define CONFIG_DEFAULT_DEFRAG_CYCLE_MIN 5 /* 5% CPU min (at lower threshold) */
167 #define CONFIG_DEFAULT_DEFRAG_CYCLE_MAX 75 /* 75% CPU max (at upper threshold) */
168 #define CONFIG_DEFAULT_DEFRAG_MAX_SCAN_FIELDS 1000 /* keys with more than 1000 fields will be processed separately */
169 #define CONFIG_DEFAULT_PROTO_MAX_BULK_LEN (512ll*1024*1024) /* Bulk request max size */
170 
171 #define ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP 20 /* Loopkups per loop. */
172 #define ACTIVE_EXPIRE_CYCLE_FAST_DURATION 1000 /* Microseconds */
173 #define ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC 25 /* CPU max % for keys collection */
174 #define ACTIVE_EXPIRE_CYCLE_SLOW 0
175 #define ACTIVE_EXPIRE_CYCLE_FAST 1
176 
177 /* Instantaneous metrics tracking. */
178 #define STATS_METRIC_SAMPLES 16     /* Number of samples per metric. */
179 #define STATS_METRIC_COMMAND 0      /* Number of commands executed. */
180 #define STATS_METRIC_NET_INPUT 1    /* Bytes read to network .*/
181 #define STATS_METRIC_NET_OUTPUT 2   /* Bytes written to network. */
182 #define STATS_METRIC_COUNT 3
183 
184 /* Protocol and I/O related defines */
185 #define PROTO_MAX_QUERYBUF_LEN  (1024*1024*1024) /* 1GB max query buffer. */
186 #define PROTO_IOBUF_LEN         (1024*16)  /* Generic I/O buffer size */
187 #define PROTO_REPLY_CHUNK_BYTES (16*1024) /* 16k output buffer */
188 #define PROTO_INLINE_MAX_SIZE   (1024*64) /* Max size of inline reads */
189 #define PROTO_MBULK_BIG_ARG     (1024*32)
190 #define LONG_STR_SIZE      21          /* Bytes needed for long -> str + '\0' */
191 #define REDIS_AUTOSYNC_BYTES (1024*1024*32) /* fdatasync every 32MB */
192 
193 #define LIMIT_PENDING_QUERYBUF (4*1024*1024) /* 4mb */
194 
195 /* When configuring the server eventloop, we setup it so that the total number
196  * of file descriptors we can handle are server.maxclients + RESERVED_FDS +
197  * a few more to stay safe. Since RESERVED_FDS defaults to 32, we add 96
198  * in order to make sure of not over provisioning more than 128 fds. */
199 #define CONFIG_FDSET_INCR (CONFIG_MIN_RESERVED_FDS+96)
200 
201 /* Hash table parameters */
202 #define HASHTABLE_MIN_FILL        10      /* Minimal hash table fill 10% */
203 
204 /* Command flags. Please check the command table defined in the redis.c file
205  * for more information about the meaning of every flag. */
206 #define CMD_WRITE (1<<0)            /* "w" flag */
207 #define CMD_READONLY (1<<1)         /* "r" flag */
208 #define CMD_DENYOOM (1<<2)          /* "m" flag */
209 #define CMD_MODULE (1<<3)           /* Command exported by module. */
210 #define CMD_ADMIN (1<<4)            /* "a" flag */
211 #define CMD_PUBSUB (1<<5)           /* "p" flag */
212 #define CMD_NOSCRIPT (1<<6)         /* "s" flag */
213 #define CMD_RANDOM (1<<7)           /* "R" flag */
214 #define CMD_SORT_FOR_SCRIPT (1<<8)  /* "S" flag */
215 #define CMD_LOADING (1<<9)          /* "l" flag */
216 #define CMD_STALE (1<<10)           /* "t" flag */
217 #define CMD_SKIP_MONITOR (1<<11)    /* "M" flag */
218 #define CMD_ASKING (1<<12)          /* "k" flag */
219 #define CMD_FAST (1<<13)            /* "F" flag */
220 #define CMD_MODULE_GETKEYS (1<<14)  /* Use the modules getkeys interface. */
221 #define CMD_MODULE_NO_CLUSTER (1<<15) /* Deny on Redis Cluster. */
222 
223 /* AOF states */
224 #define AOF_OFF 0             /* AOF is off */
225 #define AOF_ON 1              /* AOF is on */
226 #define AOF_WAIT_REWRITE 2    /* AOF waits rewrite to start appending */
227 
228 /* Client flags */
229 #define CLIENT_SLAVE (1<<0)   /* This client is a slave server */
230 #define CLIENT_MASTER (1<<1)  /* This client is a master server */
231 #define CLIENT_MONITOR (1<<2) /* This client is a slave monitor, see MONITOR */
232 #define CLIENT_MULTI (1<<3)   /* This client is in a MULTI context */
233 #define CLIENT_BLOCKED (1<<4) /* The client is waiting in a blocking operation */
234 #define CLIENT_DIRTY_CAS (1<<5) /* Watched keys modified. EXEC will fail. */
235 #define CLIENT_CLOSE_AFTER_REPLY (1<<6) /* Close after writing entire reply. */
236 #define CLIENT_UNBLOCKED (1<<7) /* This client was unblocked and is stored in
237                                   server.unblocked_clients */
238 #define CLIENT_LUA (1<<8) /* This is a non connected client used by Lua */
239 #define CLIENT_ASKING (1<<9)     /* Client issued the ASKING command */
240 #define CLIENT_CLOSE_ASAP (1<<10)/* Close this client ASAP */
241 #define CLIENT_UNIX_SOCKET (1<<11) /* Client connected via Unix domain socket */
242 #define CLIENT_DIRTY_EXEC (1<<12)  /* EXEC will fail for errors while queueing */
243 #define CLIENT_MASTER_FORCE_REPLY (1<<13)  /* Queue replies even if is master */
244 #define CLIENT_FORCE_AOF (1<<14)   /* Force AOF propagation of current cmd. */
245 #define CLIENT_FORCE_REPL (1<<15)  /* Force replication of current cmd. */
246 #define CLIENT_PRE_PSYNC (1<<16)   /* Instance don't understand PSYNC. */
247 #define CLIENT_READONLY (1<<17)    /* Cluster client is in read-only state. */
248 #define CLIENT_PUBSUB (1<<18)      /* Client is in Pub/Sub mode. */
249 #define CLIENT_PREVENT_AOF_PROP (1<<19)  /* Don't propagate to AOF. */
250 #define CLIENT_PREVENT_REPL_PROP (1<<20)  /* Don't propagate to slaves. */
251 #define CLIENT_PREVENT_PROP (CLIENT_PREVENT_AOF_PROP|CLIENT_PREVENT_REPL_PROP)
252 #define CLIENT_PENDING_WRITE (1<<21) /* Client has output to send but a write
253                                         handler is yet not installed. */
254 #define CLIENT_REPLY_OFF (1<<22)   /* Don't send replies to client. */
255 #define CLIENT_REPLY_SKIP_NEXT (1<<23)  /* Set CLIENT_REPLY_SKIP for next cmd */
256 #define CLIENT_REPLY_SKIP (1<<24)  /* Don't send just this reply. */
257 #define CLIENT_LUA_DEBUG (1<<25)  /* Run EVAL in debug mode. */
258 #define CLIENT_LUA_DEBUG_SYNC (1<<26)  /* EVAL debugging without fork() */
259 #define CLIENT_MODULE (1<<27) /* Non connected client used by some module. */
260 #define CLIENT_PROTECTED (1<<28) /* Client should not be freed for now. */
261 
262 /* Client block type (btype field in client structure)
263  * if CLIENT_BLOCKED flag is set. */
264 #define BLOCKED_NONE 0    /* Not blocked, no CLIENT_BLOCKED flag set. */
265 #define BLOCKED_LIST 1    /* BLPOP & co. */
266 #define BLOCKED_WAIT 2    /* WAIT for synchronous replication. */
267 #define BLOCKED_MODULE 3  /* Blocked by a loadable module. */
268 #define BLOCKED_STREAM 4  /* XREAD. */
269 #define BLOCKED_ZSET 5    /* BZPOP et al. */
270 #define BLOCKED_NUM 6     /* Number of blocked states. */
271 
272 /* Client request types */
273 #define PROTO_REQ_INLINE 1
274 #define PROTO_REQ_MULTIBULK 2
275 
276 /* Client classes for client limits, currently used only for
277  * the max-client-output-buffer limit implementation. */
278 #define CLIENT_TYPE_NORMAL 0 /* Normal req-reply clients + MONITORs */
279 #define CLIENT_TYPE_SLAVE 1  /* Slaves. */
280 #define CLIENT_TYPE_PUBSUB 2 /* Clients subscribed to PubSub channels. */
281 #define CLIENT_TYPE_MASTER 3 /* Master. */
282 #define CLIENT_TYPE_OBUF_COUNT 3 /* Number of clients to expose to output
283                                     buffer configuration. Just the first
284                                     three: normal, slave, pubsub. */
285 
286 /* Slave replication state. Used in server.repl_state for slaves to remember
287  * what to do next. */
288 #define REPL_STATE_NONE 0 /* No active replication */
289 #define REPL_STATE_CONNECT 1 /* Must connect to master */
290 #define REPL_STATE_CONNECTING 2 /* Connecting to master */
291 /* --- Handshake states, must be ordered --- */
292 #define REPL_STATE_RECEIVE_PONG 3 /* Wait for PING reply */
293 #define REPL_STATE_SEND_AUTH 4 /* Send AUTH to master */
294 #define REPL_STATE_RECEIVE_AUTH 5 /* Wait for AUTH reply */
295 #define REPL_STATE_SEND_PORT 6 /* Send REPLCONF listening-port */
296 #define REPL_STATE_RECEIVE_PORT 7 /* Wait for REPLCONF reply */
297 #define REPL_STATE_SEND_IP 8 /* Send REPLCONF ip-address */
298 #define REPL_STATE_RECEIVE_IP 9 /* Wait for REPLCONF reply */
299 #define REPL_STATE_SEND_CAPA 10 /* Send REPLCONF capa */
300 #define REPL_STATE_RECEIVE_CAPA 11 /* Wait for REPLCONF reply */
301 #define REPL_STATE_SEND_PSYNC 12 /* Send PSYNC */
302 #define REPL_STATE_RECEIVE_PSYNC 13 /* Wait for PSYNC reply */
303 /* --- End of handshake states --- */
304 #define REPL_STATE_TRANSFER 14 /* Receiving .rdb from master */
305 #define REPL_STATE_CONNECTED 15 /* Connected to master */
306 
307 /* State of slaves from the POV of the master. Used in client->replstate.
308  * In SEND_BULK and ONLINE state the slave receives new updates
309  * in its output queue. In the WAIT_BGSAVE states instead the server is waiting
310  * to start the next background saving in order to send updates to it. */
311 #define SLAVE_STATE_WAIT_BGSAVE_START 6 /* We need to produce a new RDB file. */
312 #define SLAVE_STATE_WAIT_BGSAVE_END 7 /* Waiting RDB file creation to finish. */
313 #define SLAVE_STATE_SEND_BULK 8 /* Sending RDB file to slave. */
314 #define SLAVE_STATE_ONLINE 9 /* RDB file transmitted, sending just updates. */
315 
316 /* Slave capabilities. */
317 #define SLAVE_CAPA_NONE 0
318 #define SLAVE_CAPA_EOF (1<<0)    /* Can parse the RDB EOF streaming format. */
319 #define SLAVE_CAPA_PSYNC2 (1<<1) /* Supports PSYNC2 protocol. */
320 
321 /* Synchronous read timeout - slave side */
322 #define CONFIG_REPL_SYNCIO_TIMEOUT 5
323 
324 /* List related stuff */
325 #define LIST_HEAD 0
326 #define LIST_TAIL 1
327 #define ZSET_MIN 0
328 #define ZSET_MAX 1
329 
330 /* Sort operations */
331 #define SORT_OP_GET 0
332 
333 /* Log levels */
334 #define LL_DEBUG 0
335 #define LL_VERBOSE 1
336 #define LL_NOTICE 2
337 #define LL_WARNING 3
338 #define LL_RAW (1<<10) /* Modifier to log without timestamp */
339 #define CONFIG_DEFAULT_VERBOSITY LL_NOTICE
340 
341 /* Supervision options */
342 #define SUPERVISED_NONE 0
343 #define SUPERVISED_AUTODETECT 1
344 #define SUPERVISED_SYSTEMD 2
345 #define SUPERVISED_UPSTART 3
346 
347 /* Anti-warning macro... */
348 #define UNUSED(V) ((void) V)
349 
350 #define ZSKIPLIST_MAXLEVEL 64 /* Should be enough for 2^64 elements */
351 #define ZSKIPLIST_P 0.25      /* Skiplist P = 1/4 */
352 
353 /* Append only defines */
354 #define AOF_FSYNC_NO 0
355 #define AOF_FSYNC_ALWAYS 1
356 #define AOF_FSYNC_EVERYSEC 2
357 #define CONFIG_DEFAULT_AOF_FSYNC AOF_FSYNC_EVERYSEC
358 
359 /* Zipped structures related defaults */
360 #define OBJ_HASH_MAX_ZIPLIST_ENTRIES 512
361 #define OBJ_HASH_MAX_ZIPLIST_VALUE 64
362 #define OBJ_SET_MAX_INTSET_ENTRIES 512
363 #define OBJ_ZSET_MAX_ZIPLIST_ENTRIES 128
364 #define OBJ_ZSET_MAX_ZIPLIST_VALUE 64
365 #define OBJ_STREAM_NODE_MAX_BYTES 4096
366 #define OBJ_STREAM_NODE_MAX_ENTRIES 100
367 
368 /* List defaults */
369 #define OBJ_LIST_MAX_ZIPLIST_SIZE -2
370 #define OBJ_LIST_COMPRESS_DEPTH 0
371 
372 /* HyperLogLog defines */
373 #define CONFIG_DEFAULT_HLL_SPARSE_MAX_BYTES 3000
374 
375 /* Sets operations codes */
376 #define SET_OP_UNION 0
377 #define SET_OP_DIFF 1
378 #define SET_OP_INTER 2
379 
380 /* Redis maxmemory strategies. Instead of using just incremental number
381  * for this defines, we use a set of flags so that testing for certain
382  * properties common to multiple policies is faster. */
383 #define MAXMEMORY_FLAG_LRU (1<<0)
384 #define MAXMEMORY_FLAG_LFU (1<<1)
385 #define MAXMEMORY_FLAG_ALLKEYS (1<<2)
386 #define MAXMEMORY_FLAG_NO_SHARED_INTEGERS \
387     (MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_LFU)
388 
389 #define MAXMEMORY_VOLATILE_LRU ((0<<8)|MAXMEMORY_FLAG_LRU)
390 #define MAXMEMORY_VOLATILE_LFU ((1<<8)|MAXMEMORY_FLAG_LFU)
391 #define MAXMEMORY_VOLATILE_TTL (2<<8)
392 #define MAXMEMORY_VOLATILE_RANDOM (3<<8)
393 #define MAXMEMORY_ALLKEYS_LRU ((4<<8)|MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_ALLKEYS)
394 #define MAXMEMORY_ALLKEYS_LFU ((5<<8)|MAXMEMORY_FLAG_LFU|MAXMEMORY_FLAG_ALLKEYS)
395 #define MAXMEMORY_ALLKEYS_RANDOM ((6<<8)|MAXMEMORY_FLAG_ALLKEYS)
396 #define MAXMEMORY_NO_EVICTION (7<<8)
397 
398 #define CONFIG_DEFAULT_MAXMEMORY_POLICY MAXMEMORY_NO_EVICTION
399 
400 /* Scripting */
401 #define LUA_SCRIPT_TIME_LIMIT 5000 /* milliseconds */
402 
403 /* Units */
404 #define UNIT_SECONDS 0
405 #define UNIT_MILLISECONDS 1
406 
407 /* SHUTDOWN flags */
408 #define SHUTDOWN_NOFLAGS 0      /* No flags. */
409 #define SHUTDOWN_SAVE 1         /* Force SAVE on SHUTDOWN even if no save
410                                    points are configured. */
411 #define SHUTDOWN_NOSAVE 2       /* Don't SAVE on SHUTDOWN. */
412 
413 /* Command call flags, see call() function */
414 #define CMD_CALL_NONE 0
415 #define CMD_CALL_SLOWLOG (1<<0)
416 #define CMD_CALL_STATS (1<<1)
417 #define CMD_CALL_PROPAGATE_AOF (1<<2)
418 #define CMD_CALL_PROPAGATE_REPL (1<<3)
419 #define CMD_CALL_PROPAGATE (CMD_CALL_PROPAGATE_AOF|CMD_CALL_PROPAGATE_REPL)
420 #define CMD_CALL_FULL (CMD_CALL_SLOWLOG | CMD_CALL_STATS | CMD_CALL_PROPAGATE)
421 
422 /* Command propagation flags, see propagate() function */
423 #define PROPAGATE_NONE 0
424 #define PROPAGATE_AOF 1
425 #define PROPAGATE_REPL 2
426 
427 /* RDB active child save type. */
428 #define RDB_CHILD_TYPE_NONE 0
429 #define RDB_CHILD_TYPE_DISK 1     /* RDB is written to disk. */
430 #define RDB_CHILD_TYPE_SOCKET 2   /* RDB is written to slave socket. */
431 
432 /* Keyspace changes notification classes. Every class is associated with a
433  * character for configuration purposes. */
434 #define NOTIFY_KEYSPACE (1<<0)    /* K */
435 #define NOTIFY_KEYEVENT (1<<1)    /* E */
436 #define NOTIFY_GENERIC (1<<2)     /* g */
437 #define NOTIFY_STRING (1<<3)      /* $ */
438 #define NOTIFY_LIST (1<<4)        /* l */
439 #define NOTIFY_SET (1<<5)         /* s */
440 #define NOTIFY_HASH (1<<6)        /* h */
441 #define NOTIFY_ZSET (1<<7)        /* z */
442 #define NOTIFY_EXPIRED (1<<8)     /* x */
443 #define NOTIFY_EVICTED (1<<9)     /* e */
444 #define NOTIFY_STREAM (1<<10)     /* t */
445 #define NOTIFY_ALL (NOTIFY_GENERIC | NOTIFY_STRING | NOTIFY_LIST | NOTIFY_SET | NOTIFY_HASH | NOTIFY_ZSET | NOTIFY_EXPIRED | NOTIFY_EVICTED | NOTIFY_STREAM) /* A flag */
446 
447 /* Get the first bind addr or NULL */
448 #define NET_FIRST_BIND_ADDR (server.bindaddr_count ? server.bindaddr[0] : NULL)
449 
450 /* Using the following macro you can run code inside serverCron() with the
451  * specified period, specified in milliseconds.
452  * The actual resolution depends on server.hz. */
453 #define run_with_period(_ms_) if ((_ms_ <= 1000/server.hz) || !(server.cronloops%((_ms_)/(1000/server.hz))))
454 
455 /* We can print the stacktrace, so our assert is defined this way: */
456 #define serverAssertWithInfo(_c,_o,_e) ((_e)?(void)0 : (_serverAssertWithInfo(_c,_o,#_e,__FILE__,__LINE__),_exit(1)))
457 #define serverAssert(_e) ((_e)?(void)0 : (_serverAssert(#_e,__FILE__,__LINE__),_exit(1)))
458 #define serverPanic(...) _serverPanic(__FILE__,__LINE__,__VA_ARGS__),_exit(1)
459 
460 /*-----------------------------------------------------------------------------
461  * Data types
462  *----------------------------------------------------------------------------*/
463 
464 /* A redis object, that is a type able to hold a string / list / set */
465 
466 /* The actual Redis Object */
467 #define OBJ_STRING 0    /* String object. */
468 #define OBJ_LIST 1      /* List object. */
469 #define OBJ_SET 2       /* Set object. */
470 #define OBJ_ZSET 3      /* Sorted set object. */
471 #define OBJ_HASH 4      /* Hash object. */
472 
473 /* The "module" object type is a special one that signals that the object
474  * is one directly managed by a Redis module. In this case the value points
475  * to a moduleValue struct, which contains the object value (which is only
476  * handled by the module itself) and the RedisModuleType struct which lists
477  * function pointers in order to serialize, deserialize, AOF-rewrite and
478  * free the object.
479  *
480  * Inside the RDB file, module types are encoded as OBJ_MODULE followed
481  * by a 64 bit module type ID, which has a 54 bits module-specific signature
482  * in order to dispatch the loading to the right module, plus a 10 bits
483  * encoding version. */
484 #define OBJ_MODULE 5    /* Module object. */
485 #define OBJ_STREAM 6    /* Stream object. */
486 
487 /* Extract encver / signature from a module type ID. */
488 #define REDISMODULE_TYPE_ENCVER_BITS 10
489 #define REDISMODULE_TYPE_ENCVER_MASK ((1<<REDISMODULE_TYPE_ENCVER_BITS)-1)
490 #define REDISMODULE_TYPE_ENCVER(id) (id & REDISMODULE_TYPE_ENCVER_MASK)
491 #define REDISMODULE_TYPE_SIGN(id) ((id & ~((uint64_t)REDISMODULE_TYPE_ENCVER_MASK)) >>REDISMODULE_TYPE_ENCVER_BITS)
492 
493 struct RedisModule;
494 struct RedisModuleIO;
495 struct RedisModuleDigest;
496 struct RedisModuleCtx;
497 struct redisObject;
498 
499 /* Each module type implementation should export a set of methods in order
500  * to serialize and deserialize the value in the RDB file, rewrite the AOF
501  * log, create the digest for "DEBUG DIGEST", and free the value when a key
502  * is deleted. */
503 typedef void *(*moduleTypeLoadFunc)(struct RedisModuleIO *io, int encver);
504 typedef void (*moduleTypeSaveFunc)(struct RedisModuleIO *io, void *value);
505 typedef void (*moduleTypeRewriteFunc)(struct RedisModuleIO *io, struct redisObject *key, void *value);
506 typedef void (*moduleTypeDigestFunc)(struct RedisModuleDigest *digest, void *value);
507 typedef size_t (*moduleTypeMemUsageFunc)(const void *value);
508 typedef void (*moduleTypeFreeFunc)(void *value);
509 
510 /* The module type, which is referenced in each value of a given type, defines
511  * the methods and links to the module exporting the type. */
512 typedef struct RedisModuleType {
513     uint64_t id; /* Higher 54 bits of type ID + 10 lower bits of encoding ver. */
514     struct RedisModule *module;
515     moduleTypeLoadFunc rdb_load;
516     moduleTypeSaveFunc rdb_save;
517     moduleTypeRewriteFunc aof_rewrite;
518     moduleTypeMemUsageFunc mem_usage;
519     moduleTypeDigestFunc digest;
520     moduleTypeFreeFunc free;
521     char name[10]; /* 9 bytes name + null term. Charset: A-Z a-z 0-9 _- */
522 } moduleType;
523 
524 /* In Redis objects 'robj' structures of type OBJ_MODULE, the value pointer
525  * is set to the following structure, referencing the moduleType structure
526  * in order to work with the value, and at the same time providing a raw
527  * pointer to the value, as created by the module commands operating with
528  * the module type.
529  *
530  * So for example in order to free such a value, it is possible to use
531  * the following code:
532  *
533  *  if (robj->type == OBJ_MODULE) {
534  *      moduleValue *mt = robj->ptr;
535  *      mt->type->free(mt->value);
536  *      zfree(mt); // We need to release this in-the-middle struct as well.
537  *  }
538  */
539 typedef struct moduleValue {
540     moduleType *type;
541     void *value;
542 } moduleValue;
543 
544 /* This is a wrapper for the 'rio' streams used inside rdb.c in Redis, so that
545  * the user does not have to take the total count of the written bytes nor
546  * to care about error conditions. */
547 typedef struct RedisModuleIO {
548     size_t bytes;       /* Bytes read / written so far. */
549     rio *rio;           /* Rio stream. */
550     moduleType *type;   /* Module type doing the operation. */
551     int error;          /* True if error condition happened. */
552     int ver;            /* Module serialization version: 1 (old),
553                          * 2 (current version with opcodes annotation). */
554     struct RedisModuleCtx *ctx; /* Optional context, see RM_GetContextFromIO()*/
555     struct redisObject *key;    /* Optional name of key processed */
556 } RedisModuleIO;
557 
558 /* Macro to initialize an IO context. Note that the 'ver' field is populated
559  * inside rdb.c according to the version of the value to load. */
560 #define moduleInitIOContext(iovar,mtype,rioptr,keyptr) do { \
561     iovar.rio = rioptr; \
562     iovar.type = mtype; \
563     iovar.bytes = 0; \
564     iovar.error = 0; \
565     iovar.ver = 0; \
566     iovar.key = keyptr; \
567     iovar.ctx = NULL; \
568 } while(0);
569 
570 /* This is a structure used to export DEBUG DIGEST capabilities to Redis
571  * modules. We want to capture both the ordered and unordered elements of
572  * a data structure, so that a digest can be created in a way that correctly
573  * reflects the values. See the DEBUG DIGEST command implementation for more
574  * background. */
575 typedef struct RedisModuleDigest {
576     unsigned char o[20];    /* Ordered elements. */
577     unsigned char x[20];    /* Xored elements. */
578 } RedisModuleDigest;
579 
580 /* Just start with a digest composed of all zero bytes. */
581 #define moduleInitDigestContext(mdvar) do { \
582     memset(mdvar.o,0,sizeof(mdvar.o)); \
583     memset(mdvar.x,0,sizeof(mdvar.x)); \
584 } while(0);
585 
586 /* Objects encoding. Some kind of objects like Strings and Hashes can be
587  * internally represented in multiple ways. The 'encoding' field of the object
588  * is set to one of this fields for this object. */
589 #define OBJ_ENCODING_RAW 0     /* Raw representation */
590 #define OBJ_ENCODING_INT 1     /* Encoded as integer */
591 #define OBJ_ENCODING_HT 2      /* Encoded as hash table */
592 #define OBJ_ENCODING_ZIPMAP 3  /* Encoded as zipmap */
593 #define OBJ_ENCODING_LINKEDLIST 4 /* No longer used: old list encoding. */
594 #define OBJ_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
595 #define OBJ_ENCODING_INTSET 6  /* Encoded as intset */
596 #define OBJ_ENCODING_SKIPLIST 7  /* Encoded as skiplist */
597 #define OBJ_ENCODING_EMBSTR 8  /* Embedded sds string encoding */
598 #define OBJ_ENCODING_QUICKLIST 9 /* Encoded as linked list of ziplists */
599 #define OBJ_ENCODING_STREAM 10 /* Encoded as a radix tree of listpacks */
600 
601 #define LRU_BITS 24
602 #define LRU_CLOCK_MAX ((1<<LRU_BITS)-1) /* Max value of obj->lru */
603 #define LRU_CLOCK_RESOLUTION 1000 /* LRU clock resolution in ms */
604 
605 #define OBJ_SHARED_REFCOUNT INT_MAX
606 typedef struct redisObject {
607     unsigned type:4;
608     unsigned encoding:4;
609     unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
610                             * LFU data (least significant 8 bits frequency
611                             * and most significant 16 bits access time). */
612     int refcount;
613     void *ptr;
614 } robj;
615 
616 /* Macro used to initialize a Redis object allocated on the stack.
617  * Note that this macro is taken near the structure definition to make sure
618  * we'll update it when the structure is changed, to avoid bugs like
619  * bug #85 introduced exactly in this way. */
620 #define initStaticStringObject(_var,_ptr) do { \
621     _var.refcount = 1; \
622     _var.type = OBJ_STRING; \
623     _var.encoding = OBJ_ENCODING_RAW; \
624     _var.ptr = _ptr; \
625 } while(0)
626 
627 struct evictionPoolEntry; /* Defined in evict.c */
628 
629 /* This structure is used in order to represent the output buffer of a client,
630  * which is actually a linked list of blocks like that, that is: client->reply. */
631 typedef struct clientReplyBlock {
632     size_t size, used;
633     char buf[];
634 } clientReplyBlock;
635 
636 /* Redis database representation. There are multiple databases identified
637  * by integers from 0 (the default database) up to the max configured
638  * database. The database number is the 'id' field in the structure. */
639 typedef struct redisDb {
640     dict *dict;                 /* The keyspace for this DB */
641     dict *expires;              /* Timeout of keys with a timeout set */
642     dict *blocking_keys;        /* Keys with clients waiting for data (BLPOP)*/
643     dict *ready_keys;           /* Blocked keys that received a PUSH */
644     dict *watched_keys;         /* WATCHED keys for MULTI/EXEC CAS */
645     int id;                     /* Database ID */
646     long long avg_ttl;          /* Average TTL, just for stats */
647     list *defrag_later;         /* List of key names to attempt to defrag one by one, gradually. */
648 } redisDb;
649 
650 /* Client MULTI/EXEC state */
651 typedef struct multiCmd {
652     robj **argv;
653     int argc;
654     struct redisCommand *cmd;
655 } multiCmd;
656 
657 typedef struct multiState {
658     multiCmd *commands;     /* Array of MULTI commands */
659     int count;              /* Total number of MULTI commands */
660     int cmd_flags;          /* The accumulated command flags OR-ed together.
661                                So if at least a command has a given flag, it
662                                will be set in this field. */
663     int minreplicas;        /* MINREPLICAS for synchronous replication */
664     time_t minreplicas_timeout; /* MINREPLICAS timeout as unixtime. */
665 } multiState;
666 
667 /* This structure holds the blocking operation state for a client.
668  * The fields used depend on client->btype. */
669 typedef struct blockingState {
670     /* Generic fields. */
671     mstime_t timeout;       /* Blocking operation timeout. If UNIX current time
672                              * is > timeout then the operation timed out. */
673 
674     /* BLOCKED_LIST, BLOCKED_ZSET and BLOCKED_STREAM */
675     dict *keys;             /* The keys we are waiting to terminate a blocking
676                              * operation such as BLPOP or XREAD. Or NULL. */
677     robj *target;           /* The key that should receive the element,
678                              * for BRPOPLPUSH. */
679 
680     /* BLOCK_STREAM */
681     size_t xread_count;     /* XREAD COUNT option. */
682     robj *xread_group;      /* XREADGROUP group name. */
683     robj *xread_consumer;   /* XREADGROUP consumer name. */
684     mstime_t xread_retry_time, xread_retry_ttl;
685     int xread_group_noack;
686 
687     /* BLOCKED_WAIT */
688     int numreplicas;        /* Number of replicas we are waiting for ACK. */
689     long long reploffset;   /* Replication offset to reach. */
690 
691     /* BLOCKED_MODULE */
692     void *module_blocked_handle; /* RedisModuleBlockedClient structure.
693                                     which is opaque for the Redis core, only
694                                     handled in module.c. */
695 } blockingState;
696 
697 /* The following structure represents a node in the server.ready_keys list,
698  * where we accumulate all the keys that had clients blocked with a blocking
699  * operation such as B[LR]POP, but received new data in the context of the
700  * last executed command.
701  *
702  * After the execution of every command or script, we run this list to check
703  * if as a result we should serve data to clients blocked, unblocking them.
704  * Note that server.ready_keys will not have duplicates as there dictionary
705  * also called ready_keys in every structure representing a Redis database,
706  * where we make sure to remember if a given key was already added in the
707  * server.ready_keys list. */
708 typedef struct readyList {
709     redisDb *db;
710     robj *key;
711 } readyList;
712 
713 /* With multiplexing we need to take per-client state.
714  * Clients are taken in a linked list. */
715 typedef struct client {
716     uint64_t id;            /* Client incremental unique ID. */
717     int fd;                 /* Client socket. */
718     redisDb *db;            /* Pointer to currently SELECTed DB. */
719     robj *name;             /* As set by CLIENT SETNAME. */
720     sds querybuf;           /* Buffer we use to accumulate client queries. */
721     size_t qb_pos;          /* The position we have read in querybuf. */
722     sds pending_querybuf;   /* If this client is flagged as master, this buffer
723                                represents the yet not applied portion of the
724                                replication stream that we are receiving from
725                                the master. */
726     size_t querybuf_peak;   /* Recent (100ms or more) peak of querybuf size. */
727     int argc;               /* Num of arguments of current command. */
728     robj **argv;            /* Arguments of current command. */
729     struct redisCommand *cmd, *lastcmd;  /* Last command executed. */
730     int reqtype;            /* Request protocol type: PROTO_REQ_* */
731     int multibulklen;       /* Number of multi bulk arguments left to read. */
732     long bulklen;           /* Length of bulk argument in multi bulk request. */
733     list *reply;            /* List of reply objects to send to the client. */
734     unsigned long long reply_bytes; /* Tot bytes of objects in reply list. */
735     size_t sentlen;         /* Amount of bytes already sent in the current
736                                buffer or object being sent. */
737     time_t ctime;           /* Client creation time. */
738     time_t lastinteraction; /* Time of the last interaction, used for timeout */
739     time_t obuf_soft_limit_reached_time;
740     int flags;              /* Client flags: CLIENT_* macros. */
741     int authenticated;      /* When requirepass is non-NULL. */
742     int replstate;          /* Replication state if this is a slave. */
743     int repl_put_online_on_ack; /* Install slave write handler on ACK. */
744     int repldbfd;           /* Replication DB file descriptor. */
745     off_t repldboff;        /* Replication DB file offset. */
746     off_t repldbsize;       /* Replication DB file size. */
747     sds replpreamble;       /* Replication DB preamble. */
748     long long read_reploff; /* Read replication offset if this is a master. */
749     long long reploff;      /* Applied replication offset if this is a master. */
750     long long repl_ack_off; /* Replication ack offset, if this is a slave. */
751     long long repl_ack_time;/* Replication ack time, if this is a slave. */
752     long long psync_initial_offset; /* FULLRESYNC reply offset other slaves
753                                        copying this slave output buffer
754                                        should use. */
755     char replid[CONFIG_RUN_ID_SIZE+1]; /* Master replication ID (if master). */
756     int slave_listening_port; /* As configured with: SLAVECONF listening-port */
757     char slave_ip[NET_IP_STR_LEN]; /* Optionally given by REPLCONF ip-address */
758     int slave_capa;         /* Slave capabilities: SLAVE_CAPA_* bitwise OR. */
759     multiState mstate;      /* MULTI/EXEC state */
760     int btype;              /* Type of blocking op if CLIENT_BLOCKED. */
761     blockingState bpop;     /* blocking state */
762     long long woff;         /* Last write global replication offset. */
763     list *watched_keys;     /* Keys WATCHED for MULTI/EXEC CAS */
764     dict *pubsub_channels;  /* channels a client is interested in (SUBSCRIBE) */
765     list *pubsub_patterns;  /* patterns a client is interested in (SUBSCRIBE) */
766     sds peerid;             /* Cached peer ID. */
767     listNode *client_list_node; /* list node in client list */
768 
769     /* Response buffer */
770     int bufpos;
771     char buf[PROTO_REPLY_CHUNK_BYTES];
772 } client;
773 
774 struct saveparam {
775     time_t seconds;
776     int changes;
777 };
778 
779 struct moduleLoadQueueEntry {
780     sds path;
781     int argc;
782     robj **argv;
783 };
784 
785 struct sharedObjectsStruct {
786     robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *cnegone, *pong, *space,
787     *colon, *nullbulk, *nullmultibulk, *queued,
788     *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
789     *outofrangeerr, *noscripterr, *loadingerr, *slowscripterr, *bgsaveerr,
790     *masterdownerr, *roslaveerr, *execaborterr, *noautherr, *noreplicaserr,
791     *busykeyerr, *oomerr, *plus, *messagebulk, *pmessagebulk, *subscribebulk,
792     *unsubscribebulk, *psubscribebulk, *punsubscribebulk, *del, *unlink,
793     *rpop, *lpop, *lpush, *rpoplpush, *zpopmin, *zpopmax, *emptyscan,
794     *select[PROTO_SHARED_SELECT_CMDS],
795     *integers[OBJ_SHARED_INTEGERS],
796     *mbulkhdr[OBJ_SHARED_BULKHDR_LEN], /* "*<value>\r\n" */
797     *bulkhdr[OBJ_SHARED_BULKHDR_LEN];  /* "$<value>\r\n" */
798     sds minstring, maxstring;
799 };
800 
801 /* ZSETs use a specialized version of Skiplists */
802 typedef struct zskiplistNode {
803     sds ele;
804     double score;
805     struct zskiplistNode *backward;
806     struct zskiplistLevel {
807         struct zskiplistNode *forward;
808         unsigned long span;
809     } level[];
810 } zskiplistNode;
811 
812 typedef struct zskiplist {
813     struct zskiplistNode *header, *tail;
814     unsigned long length;
815     int level;
816 } zskiplist;
817 
818 typedef struct zset {
819     dict *dict;
820     zskiplist *zsl;
821 } zset;
822 
823 typedef struct clientBufferLimitsConfig {
824     unsigned long long hard_limit_bytes;
825     unsigned long long soft_limit_bytes;
826     time_t soft_limit_seconds;
827 } clientBufferLimitsConfig;
828 
829 extern clientBufferLimitsConfig clientBufferLimitsDefaults[CLIENT_TYPE_OBUF_COUNT];
830 
831 /* The redisOp structure defines a Redis Operation, that is an instance of
832  * a command with an argument vector, database ID, propagation target
833  * (PROPAGATE_*), and command pointer.
834  *
835  * Currently only used to additionally propagate more commands to AOF/Replication
836  * after the propagation of the executed command. */
837 typedef struct redisOp {
838     robj **argv;
839     int argc, dbid, target;
840     struct redisCommand *cmd;
841 } redisOp;
842 
843 /* Defines an array of Redis operations. There is an API to add to this
844  * structure in a easy way.
845  *
846  * redisOpArrayInit();
847  * redisOpArrayAppend();
848  * redisOpArrayFree();
849  */
850 typedef struct redisOpArray {
851     redisOp *ops;
852     int numops;
853 } redisOpArray;
854 
855 /* This structure is returned by the getMemoryOverheadData() function in
856  * order to return memory overhead information. */
857 struct redisMemOverhead {
858     size_t peak_allocated;
859     size_t total_allocated;
860     size_t startup_allocated;
861     size_t repl_backlog;
862     size_t clients_slaves;
863     size_t clients_normal;
864     size_t aof_buffer;
865     size_t lua_caches;
866     size_t overhead_total;
867     size_t dataset;
868     size_t total_keys;
869     size_t bytes_per_key;
870     float dataset_perc;
871     float peak_perc;
872     float total_frag;
873     ssize_t total_frag_bytes;
874     float allocator_frag;
875     ssize_t allocator_frag_bytes;
876     float allocator_rss;
877     ssize_t allocator_rss_bytes;
878     float rss_extra;
879     size_t rss_extra_bytes;
880     size_t num_dbs;
881     struct {
882         size_t dbid;
883         size_t overhead_ht_main;
884         size_t overhead_ht_expires;
885     } *db;
886 };
887 
888 /* This structure can be optionally passed to RDB save/load functions in
889  * order to implement additional functionalities, by storing and loading
890  * metadata to the RDB file.
891  *
892  * Currently the only use is to select a DB at load time, useful in
893  * replication in order to make sure that chained slaves (slaves of slaves)
894  * select the correct DB and are able to accept the stream coming from the
895  * top-level master. */
896 typedef struct rdbSaveInfo {
897     /* Used saving and loading. */
898     int repl_stream_db;  /* DB to select in server.master client. */
899 
900     /* Used only loading. */
901     int repl_id_is_set;  /* True if repl_id field is set. */
902     char repl_id[CONFIG_RUN_ID_SIZE+1];     /* Replication ID. */
903     long long repl_offset;                  /* Replication offset. */
904 } rdbSaveInfo;
905 
906 #define RDB_SAVE_INFO_INIT {-1,0,"000000000000000000000000000000",-1}
907 
908 struct malloc_stats {
909     size_t zmalloc_used;
910     size_t process_rss;
911     size_t allocator_allocated;
912     size_t allocator_active;
913     size_t allocator_resident;
914 };
915 
916 /*-----------------------------------------------------------------------------
917  * Global server state
918  *----------------------------------------------------------------------------*/
919 
920 struct clusterState;
921 
922 /* AIX defines hz to __hz, we don't use this define and in order to allow
923  * Redis build on AIX we need to undef it. */
924 #ifdef _AIX
925 #undef hz
926 #endif
927 
928 #define CHILD_INFO_MAGIC 0xC17DDA7A12345678LL
929 #define CHILD_INFO_TYPE_RDB 0
930 #define CHILD_INFO_TYPE_AOF 1
931 
932 struct redisServer {
933     /* General */
934     pid_t pid;                  /* Main process pid. */
935     char *configfile;           /* Absolute config file path, or NULL */
936     char *executable;           /* Absolute executable file path. */
937     char **exec_argv;           /* Executable argv vector (copy). */
938     int dynamic_hz;             /* Change hz value depending on # of clients. */
939     int config_hz;              /* Configured HZ value. May be different than
940                                    the actual 'hz' field value if dynamic-hz
941                                    is enabled. */
942     int hz;                     /* serverCron() calls frequency in hertz */
943     redisDb *db;
944     dict *commands;             /* Command table */
945     dict *orig_commands;        /* Command table before command renaming. */
946     aeEventLoop *el;
947     unsigned int lruclock;      /* Clock for LRU eviction */
948     int shutdown_asap;          /* SHUTDOWN needed ASAP */
949     int activerehashing;        /* Incremental rehash in serverCron() */
950     int active_defrag_running;  /* Active defragmentation running (holds current scan aggressiveness) */
951     char *requirepass;          /* Pass for AUTH command, or NULL */
952     char *pidfile;              /* PID file path */
953     int arch_bits;              /* 32 or 64 depending on sizeof(long) */
954     int cronloops;              /* Number of times the cron function run */
955     char runid[CONFIG_RUN_ID_SIZE+1];  /* ID always different at every exec. */
956     int sentinel_mode;          /* True if this instance is a Sentinel. */
957     size_t initial_memory_usage; /* Bytes used after initialization. */
958     int always_show_logo;       /* Show logo even for non-stdout logging. */
959     /* Modules */
960     dict *moduleapi;            /* Exported core APIs dictionary for modules. */
961     dict *sharedapi;            /* Like moduleapi but containing the APIs that
962                                    modules share with each other. */
963     list *loadmodule_queue;     /* List of modules to load at startup. */
964     int module_blocked_pipe[2]; /* Pipe used to awake the event loop if a
965                                    client blocked on a module command needs
966                                    to be processed. */
967     /* Networking */
968     int port;                   /* TCP listening port */
969     int tcp_backlog;            /* TCP listen() backlog */
970     char *bindaddr[CONFIG_BINDADDR_MAX]; /* Addresses we should bind to */
971     int bindaddr_count;         /* Number of addresses in server.bindaddr[] */
972     char *unixsocket;           /* UNIX socket path */
973     mode_t unixsocketperm;      /* UNIX socket permission */
974     int ipfd[CONFIG_BINDADDR_MAX]; /* TCP socket file descriptors */
975     int ipfd_count;             /* Used slots in ipfd[] */
976     int sofd;                   /* Unix socket file descriptor */
977     int cfd[CONFIG_BINDADDR_MAX];/* Cluster bus listening socket */
978     int cfd_count;              /* Used slots in cfd[] */
979     list *clients;              /* List of active clients */
980     list *clients_to_close;     /* Clients to close asynchronously */
981     list *clients_pending_write; /* There is to write or install handler. */
982     list *slaves, *monitors;    /* List of slaves and MONITORs */
983     client *current_client; /* Current client, only used on crash report */
984     rax *clients_index;         /* Active clients dictionary by client ID. */
985     int clients_paused;         /* True if clients are currently paused */
986     mstime_t clients_pause_end_time; /* Time when we undo clients_paused */
987     char neterr[ANET_ERR_LEN];   /* Error buffer for anet.c */
988     dict *migrate_cached_sockets;/* MIGRATE cached sockets */
989     uint64_t next_client_id;    /* Next client unique ID. Incremental. */
990     int protected_mode;         /* Don't accept external connections. */
991     /* RDB / AOF loading information */
992     int loading;                /* We are loading data from disk if true */
993     off_t loading_total_bytes;
994     off_t loading_loaded_bytes;
995     time_t loading_start_time;
996     off_t loading_process_events_interval_bytes;
997     /* Fast pointers to often looked up command */
998     struct redisCommand *delCommand, *multiCommand, *lpushCommand,
999                         *lpopCommand, *rpopCommand, *zpopminCommand,
1000                         *zpopmaxCommand, *sremCommand, *execCommand,
1001                         *expireCommand, *pexpireCommand, *xclaimCommand,
1002                         *xgroupCommand;
1003     /* Fields used only for stats */
1004     time_t stat_starttime;          /* Server start time */
1005     long long stat_numcommands;     /* Number of processed commands */
1006     long long stat_numconnections;  /* Number of connections received */
1007     long long stat_expiredkeys;     /* Number of expired keys */
1008     double stat_expired_stale_perc; /* Percentage of keys probably expired */
1009     long long stat_expired_time_cap_reached_count; /* Early expire cylce stops.*/
1010     long long stat_evictedkeys;     /* Number of evicted keys (maxmemory) */
1011     long long stat_keyspace_hits;   /* Number of successful lookups of keys */
1012     long long stat_keyspace_misses; /* Number of failed lookups of keys */
1013     long long stat_active_defrag_hits;      /* number of allocations moved */
1014     long long stat_active_defrag_misses;    /* number of allocations scanned but not moved */
1015     long long stat_active_defrag_key_hits;  /* number of keys with moved allocations */
1016     long long stat_active_defrag_key_misses;/* number of keys scanned and not moved */
1017     long long stat_active_defrag_scanned;   /* number of dictEntries scanned */
1018     size_t stat_peak_memory;        /* Max used memory record */
1019     long long stat_fork_time;       /* Time needed to perform latest fork() */
1020     double stat_fork_rate;          /* Fork rate in GB/sec. */
1021     long long stat_rejected_conn;   /* Clients rejected because of maxclients */
1022     long long stat_sync_full;       /* Number of full resyncs with slaves. */
1023     long long stat_sync_partial_ok; /* Number of accepted PSYNC requests. */
1024     long long stat_sync_partial_err;/* Number of unaccepted PSYNC requests. */
1025     list *slowlog;                  /* SLOWLOG list of commands */
1026     long long slowlog_entry_id;     /* SLOWLOG current entry ID */
1027     long long slowlog_log_slower_than; /* SLOWLOG time limit (to get logged) */
1028     unsigned long slowlog_max_len;     /* SLOWLOG max number of items logged */
1029     struct malloc_stats cron_malloc_stats; /* sampled in serverCron(). */
1030     long long stat_net_input_bytes; /* Bytes read from network. */
1031     long long stat_net_output_bytes; /* Bytes written to network. */
1032     size_t stat_rdb_cow_bytes;      /* Copy on write bytes during RDB saving. */
1033     size_t stat_aof_cow_bytes;      /* Copy on write bytes during AOF rewrite. */
1034     /* The following two are used to track instantaneous metrics, like
1035      * number of operations per second, network traffic. */
1036     struct {
1037         long long last_sample_time; /* Timestamp of last sample in ms */
1038         long long last_sample_count;/* Count in last sample */
1039         long long samples[STATS_METRIC_SAMPLES];
1040         int idx;
1041     } inst_metric[STATS_METRIC_COUNT];
1042     /* Configuration */
1043     int verbosity;                  /* Loglevel in redis.conf */
1044     int maxidletime;                /* Client timeout in seconds */
1045     int tcpkeepalive;               /* Set SO_KEEPALIVE if non-zero. */
1046     int active_expire_enabled;      /* Can be disabled for testing purposes. */
1047     int active_defrag_enabled;
1048     size_t active_defrag_ignore_bytes; /* minimum amount of fragmentation waste to start active defrag */
1049     int active_defrag_threshold_lower; /* minimum percentage of fragmentation to start active defrag */
1050     int active_defrag_threshold_upper; /* maximum percentage of fragmentation at which we use maximum effort */
1051     int active_defrag_cycle_min;       /* minimal effort for defrag in CPU percentage */
1052     int active_defrag_cycle_max;       /* maximal effort for defrag in CPU percentage */
1053     unsigned long active_defrag_max_scan_fields; /* maximum number of fields of set/hash/zset/list to process from within the main dict scan */
1054     size_t client_max_querybuf_len; /* Limit for client query buffer length */
1055     int dbnum;                      /* Total number of configured DBs */
1056     int supervised;                 /* 1 if supervised, 0 otherwise. */
1057     int supervised_mode;            /* See SUPERVISED_* */
1058     int daemonize;                  /* True if running as a daemon */
1059     clientBufferLimitsConfig client_obuf_limits[CLIENT_TYPE_OBUF_COUNT];
1060     /* AOF persistence */
1061     int aof_state;                  /* AOF_(ON|OFF|WAIT_REWRITE) */
1062     int aof_fsync;                  /* Kind of fsync() policy */
1063     char *aof_filename;             /* Name of the AOF file */
1064     int aof_no_fsync_on_rewrite;    /* Don't fsync if a rewrite is in prog. */
1065     int aof_rewrite_perc;           /* Rewrite AOF if % growth is > M and... */
1066     off_t aof_rewrite_min_size;     /* the AOF file is at least N bytes. */
1067     off_t aof_rewrite_base_size;    /* AOF size on latest startup or rewrite. */
1068     off_t aof_current_size;         /* AOF current size. */
1069     off_t aof_fsync_offset;         /* AOF offset which is already synced to disk. */
1070     int aof_rewrite_scheduled;      /* Rewrite once BGSAVE terminates. */
1071     pid_t aof_child_pid;            /* PID if rewriting process */
1072     list *aof_rewrite_buf_blocks;   /* Hold changes during an AOF rewrite. */
1073     sds aof_buf;      /* AOF buffer, written before entering the event loop */
1074     int aof_fd;       /* File descriptor of currently selected AOF file */
1075     int aof_selected_db; /* Currently selected DB in AOF */
1076     time_t aof_flush_postponed_start; /* UNIX time of postponed AOF flush */
1077     time_t aof_last_fsync;            /* UNIX time of last fsync() */
1078     time_t aof_rewrite_time_last;   /* Time used by last AOF rewrite run. */
1079     time_t aof_rewrite_time_start;  /* Current AOF rewrite start time. */
1080     int aof_lastbgrewrite_status;   /* C_OK or C_ERR */
1081     unsigned long aof_delayed_fsync;  /* delayed AOF fsync() counter */
1082     int aof_rewrite_incremental_fsync;/* fsync incrementally while aof rewriting? */
1083     int rdb_save_incremental_fsync;   /* fsync incrementally while rdb saving? */
1084     int aof_last_write_status;      /* C_OK or C_ERR */
1085     int aof_last_write_errno;       /* Valid if aof_last_write_status is ERR */
1086     int aof_load_truncated;         /* Don't stop on unexpected AOF EOF. */
1087     int aof_use_rdb_preamble;       /* Use RDB preamble on AOF rewrites. */
1088     /* AOF pipes used to communicate between parent and child during rewrite. */
1089     int aof_pipe_write_data_to_child;
1090     int aof_pipe_read_data_from_parent;
1091     int aof_pipe_write_ack_to_parent;
1092     int aof_pipe_read_ack_from_child;
1093     int aof_pipe_write_ack_to_child;
1094     int aof_pipe_read_ack_from_parent;
1095     int aof_stop_sending_diff;     /* If true stop sending accumulated diffs
1096                                       to child process. */
1097     sds aof_child_diff;             /* AOF diff accumulator child side. */
1098     /* RDB persistence */
1099     long long dirty;                /* Changes to DB from the last save */
1100     long long dirty_before_bgsave;  /* Used to restore dirty on failed BGSAVE */
1101     pid_t rdb_child_pid;            /* PID of RDB saving child */
1102     struct saveparam *saveparams;   /* Save points array for RDB */
1103     int saveparamslen;              /* Number of saving points */
1104     char *rdb_filename;             /* Name of RDB file */
1105     int rdb_compression;            /* Use compression in RDB? */
1106     int rdb_checksum;               /* Use RDB checksum? */
1107     time_t lastsave;                /* Unix time of last successful save */
1108     time_t lastbgsave_try;          /* Unix time of last attempted bgsave */
1109     time_t rdb_save_time_last;      /* Time used by last RDB save run. */
1110     time_t rdb_save_time_start;     /* Current RDB save start time. */
1111     int rdb_bgsave_scheduled;       /* BGSAVE when possible if true. */
1112     int rdb_child_type;             /* Type of save by active child. */
1113     int lastbgsave_status;          /* C_OK or C_ERR */
1114     int stop_writes_on_bgsave_err;  /* Don't allow writes if can't BGSAVE */
1115     int rdb_pipe_write_result_to_parent; /* RDB pipes used to return the state */
1116     int rdb_pipe_read_result_from_child; /* of each slave in diskless SYNC. */
1117     /* Pipe and data structures for child -> parent info sharing. */
1118     int child_info_pipe[2];         /* Pipe used to write the child_info_data. */
1119     struct {
1120         int process_type;           /* AOF or RDB child? */
1121         size_t cow_size;            /* Copy on write size. */
1122         unsigned long long magic;   /* Magic value to make sure data is valid. */
1123     } child_info_data;
1124     /* Propagation of commands in AOF / replication */
1125     redisOpArray also_propagate;    /* Additional command to propagate. */
1126     /* Logging */
1127     char *logfile;                  /* Path of log file */
1128     int syslog_enabled;             /* Is syslog enabled? */
1129     char *syslog_ident;             /* Syslog ident */
1130     int syslog_facility;            /* Syslog facility */
1131     /* Replication (master) */
1132     char replid[CONFIG_RUN_ID_SIZE+1];  /* My current replication ID. */
1133     char replid2[CONFIG_RUN_ID_SIZE+1]; /* replid inherited from master*/
1134     long long master_repl_offset;   /* My current replication offset */
1135     long long second_replid_offset; /* Accept offsets up to this for replid2. */
1136     int slaveseldb;                 /* Last SELECTed DB in replication output */
1137     int repl_ping_slave_period;     /* Master pings the slave every N seconds */
1138     char *repl_backlog;             /* Replication backlog for partial syncs */
1139     long long repl_backlog_size;    /* Backlog circular buffer size */
1140     long long repl_backlog_histlen; /* Backlog actual data length */
1141     long long repl_backlog_idx;     /* Backlog circular buffer current offset,
1142                                        that is the next byte will'll write to.*/
1143     long long repl_backlog_off;     /* Replication "master offset" of first
1144                                        byte in the replication backlog buffer.*/
1145     time_t repl_backlog_time_limit; /* Time without slaves after the backlog
1146                                        gets released. */
1147     time_t repl_no_slaves_since;    /* We have no slaves since that time.
1148                                        Only valid if server.slaves len is 0. */
1149     int repl_min_slaves_to_write;   /* Min number of slaves to write. */
1150     int repl_min_slaves_max_lag;    /* Max lag of <count> slaves to write. */
1151     int repl_good_slaves_count;     /* Number of slaves with lag <= max_lag. */
1152     int repl_diskless_sync;         /* Send RDB to slaves sockets directly. */
1153     int repl_diskless_sync_delay;   /* Delay to start a diskless repl BGSAVE. */
1154     /* Replication (slave) */
1155     char *masterauth;               /* AUTH with this password with master */
1156     char *masterhost;               /* Hostname of master */
1157     int masterport;                 /* Port of master */
1158     int repl_timeout;               /* Timeout after N seconds of master idle */
1159     client *master;     /* Client that is master for this slave */
1160     client *cached_master; /* Cached master to be reused for PSYNC. */
1161     int repl_syncio_timeout; /* Timeout for synchronous I/O calls */
1162     int repl_state;          /* Replication status if the instance is a slave */
1163     off_t repl_transfer_size; /* Size of RDB to read from master during sync. */
1164     off_t repl_transfer_read; /* Amount of RDB read from master during sync. */
1165     off_t repl_transfer_last_fsync_off; /* Offset when we fsync-ed last time. */
1166     int repl_transfer_s;     /* Slave -> Master SYNC socket */
1167     int repl_transfer_fd;    /* Slave -> Master SYNC temp file descriptor */
1168     char *repl_transfer_tmpfile; /* Slave-> master SYNC temp file name */
1169     time_t repl_transfer_lastio; /* Unix time of the latest read, for timeout */
1170     int repl_serve_stale_data; /* Serve stale data when link is down? */
1171     int repl_slave_ro;          /* Slave is read only? */
1172     int repl_slave_ignore_maxmemory;    /* If true slaves do not evict. */
1173     time_t repl_down_since; /* Unix time at which link with master went down */
1174     int repl_disable_tcp_nodelay;   /* Disable TCP_NODELAY after SYNC? */
1175     int slave_priority;             /* Reported in INFO and used by Sentinel. */
1176     int slave_announce_port;        /* Give the master this listening port. */
1177     char *slave_announce_ip;        /* Give the master this ip address. */
1178     /* The following two fields is where we store master PSYNC replid/offset
1179      * while the PSYNC is in progress. At the end we'll copy the fields into
1180      * the server->master client structure. */
1181     char master_replid[CONFIG_RUN_ID_SIZE+1];  /* Master PSYNC runid. */
1182     long long master_initial_offset;           /* Master PSYNC offset. */
1183     int repl_slave_lazy_flush;          /* Lazy FLUSHALL before loading DB? */
1184     /* Replication script cache. */
1185     dict *repl_scriptcache_dict;        /* SHA1 all slaves are aware of. */
1186     list *repl_scriptcache_fifo;        /* First in, first out LRU eviction. */
1187     unsigned int repl_scriptcache_size; /* Max number of elements. */
1188     /* Synchronous replication. */
1189     list *clients_waiting_acks;         /* Clients waiting in WAIT command. */
1190     int get_ack_from_slaves;            /* If true we send REPLCONF GETACK. */
1191     /* Limits */
1192     unsigned int maxclients;            /* Max number of simultaneous clients */
1193     unsigned long long maxmemory;   /* Max number of memory bytes to use */
1194     int maxmemory_policy;           /* Policy for key eviction */
1195     int maxmemory_samples;          /* Pricision of random sampling */
1196     int lfu_log_factor;             /* LFU logarithmic counter factor. */
1197     int lfu_decay_time;             /* LFU counter decay factor. */
1198     long long proto_max_bulk_len;   /* Protocol bulk length maximum size. */
1199     /* Blocked clients */
1200     unsigned int blocked_clients;   /* # of clients executing a blocking cmd.*/
1201     unsigned int blocked_clients_by_type[BLOCKED_NUM];
1202     list *unblocked_clients; /* list of clients to unblock before next loop */
1203     list *ready_keys;        /* List of readyList structures for BLPOP & co */
1204     /* Sort parameters - qsort_r() is only available under BSD so we
1205      * have to take this state global, in order to pass it to sortCompare() */
1206     int sort_desc;
1207     int sort_alpha;
1208     int sort_bypattern;
1209     int sort_store;
1210     /* Zip structure config, see redis.conf for more information  */
1211     size_t hash_max_ziplist_entries;
1212     size_t hash_max_ziplist_value;
1213     size_t set_max_intset_entries;
1214     size_t zset_max_ziplist_entries;
1215     size_t zset_max_ziplist_value;
1216     size_t hll_sparse_max_bytes;
1217     size_t stream_node_max_bytes;
1218     int64_t stream_node_max_entries;
1219     /* List parameters */
1220     int list_max_ziplist_size;
1221     int list_compress_depth;
1222     /* time cache */
1223     time_t unixtime;    /* Unix time sampled every cron cycle. */
1224     time_t timezone;    /* Cached timezone. As set by tzset(). */
1225     int daylight_active;    /* Currently in daylight saving time. */
1226     long long mstime;   /* Like 'unixtime' but with milliseconds resolution. */
1227     /* Pubsub */
1228     dict *pubsub_channels;  /* Map channels to list of subscribed clients */
1229     list *pubsub_patterns;  /* A list of pubsub_patterns */
1230     int notify_keyspace_events; /* Events to propagate via Pub/Sub. This is an
1231                                    xor of NOTIFY_... flags. */
1232     /* Cluster */
1233     int cluster_enabled;      /* Is cluster enabled? */
1234     mstime_t cluster_node_timeout; /* Cluster node timeout. */
1235     char *cluster_configfile; /* Cluster auto-generated config file name. */
1236     struct clusterState *cluster;  /* State of the cluster */
1237     int cluster_migration_barrier; /* Cluster replicas migration barrier. */
1238     int cluster_slave_validity_factor; /* Slave max data age for failover. */
1239     int cluster_require_full_coverage; /* If true, put the cluster down if
1240                                           there is at least an uncovered slot.*/
1241     int cluster_slave_no_failover;  /* Prevent slave from starting a failover
1242                                        if the master is in failure state. */
1243     char *cluster_announce_ip;  /* IP address to announce on cluster bus. */
1244     int cluster_announce_port;     /* base port to announce on cluster bus. */
1245     int cluster_announce_bus_port; /* bus port to announce on cluster bus. */
1246     int cluster_module_flags;      /* Set of flags that Redis modules are able
1247                                       to set in order to suppress certain
1248                                       native Redis Cluster features. Check the
1249                                       REDISMODULE_CLUSTER_FLAG_*. */
1250     /* Scripting */
1251     lua_State *lua; /* The Lua interpreter. We use just one for all clients */
1252     client *lua_client;   /* The "fake client" to query Redis from Lua */
1253     client *lua_caller;   /* The client running EVAL right now, or NULL */
1254     dict *lua_scripts;         /* A dictionary of SHA1 -> Lua scripts */
1255     unsigned long long lua_scripts_mem;  /* Cached scripts' memory + oh */
1256     mstime_t lua_time_limit;  /* Script timeout in milliseconds */
1257     mstime_t lua_time_start;  /* Start time of script, milliseconds time */
1258     int lua_write_dirty;  /* True if a write command was called during the
1259                              execution of the current script. */
1260     int lua_random_dirty; /* True if a random command was called during the
1261                              execution of the current script. */
1262     int lua_replicate_commands; /* True if we are doing single commands repl. */
1263     int lua_multi_emitted;/* True if we already proagated MULTI. */
1264     int lua_repl;         /* Script replication flags for redis.set_repl(). */
1265     int lua_timedout;     /* True if we reached the time limit for script
1266                              execution. */
1267     int lua_kill;         /* Kill the script if true. */
1268     int lua_always_replicate_commands; /* Default replication type. */
1269     /* Lazy free */
1270     int lazyfree_lazy_eviction;
1271     int lazyfree_lazy_expire;
1272     int lazyfree_lazy_server_del;
1273     /* Latency monitor */
1274     long long latency_monitor_threshold;
1275     dict *latency_events;
1276     /* Assert & bug reporting */
1277     const char *assert_failed;
1278     const char *assert_file;
1279     int assert_line;
1280     int bug_report_start; /* True if bug report header was already logged. */
1281     int watchdog_period;  /* Software watchdog period in ms. 0 = off */
1282     /* System hardware info */
1283     size_t system_memory_size;  /* Total memory in system as reported by OS */
1284 
1285     /* Mutexes used to protect atomic variables when atomic builtins are
1286      * not available. */
1287     pthread_mutex_t lruclock_mutex;
1288     pthread_mutex_t next_client_id_mutex;
1289     pthread_mutex_t unixtime_mutex;
1290 };
1291 
1292 typedef struct pubsubPattern {
1293     client *client;
1294     robj *pattern;
1295 } pubsubPattern;
1296 
1297 typedef void redisCommandProc(client *c);
1298 typedef int *redisGetKeysProc(struct redisCommand *cmd, robj **argv, int argc, int *numkeys);
1299 struct redisCommand {
1300     char *name;
1301     redisCommandProc *proc;
1302     int arity;
1303     char *sflags; /* Flags as string representation, one char per flag. */
1304     int flags;    /* The actual flags, obtained from the 'sflags' field. */
1305     /* Use a function to determine keys arguments in a command line.
1306      * Used for Redis Cluster redirect. */
1307     redisGetKeysProc *getkeys_proc;
1308     /* What keys should be loaded in background when calling this command? */
1309     int firstkey; /* The first argument that's a key (0 = no keys) */
1310     int lastkey;  /* The last argument that's a key */
1311     int keystep;  /* The step between first and last key */
1312     long long microseconds, calls;
1313 };
1314 
1315 struct redisFunctionSym {
1316     char *name;
1317     unsigned long pointer;
1318 };
1319 
1320 typedef struct _redisSortObject {
1321     robj *obj;
1322     union {
1323         double score;
1324         robj *cmpobj;
1325     } u;
1326 } redisSortObject;
1327 
1328 typedef struct _redisSortOperation {
1329     int type;
1330     robj *pattern;
1331 } redisSortOperation;
1332 
1333 /* Structure to hold list iteration abstraction. */
1334 typedef struct {
1335     robj *subject;
1336     unsigned char encoding;
1337     unsigned char direction; /* Iteration direction */
1338     quicklistIter *iter;
1339 } listTypeIterator;
1340 
1341 /* Structure for an entry while iterating over a list. */
1342 typedef struct {
1343     listTypeIterator *li;
1344     quicklistEntry entry; /* Entry in quicklist */
1345 } listTypeEntry;
1346 
1347 /* Structure to hold set iteration abstraction. */
1348 typedef struct {
1349     robj *subject;
1350     int encoding;
1351     int ii; /* intset iterator */
1352     dictIterator *di;
1353 } setTypeIterator;
1354 
1355 /* Structure to hold hash iteration abstraction. Note that iteration over
1356  * hashes involves both fields and values. Because it is possible that
1357  * not both are required, store pointers in the iterator to avoid
1358  * unnecessary memory allocation for fields/values. */
1359 typedef struct {
1360     robj *subject;
1361     int encoding;
1362 
1363     unsigned char *fptr, *vptr;
1364 
1365     dictIterator *di;
1366     dictEntry *de;
1367 } hashTypeIterator;
1368 
1369 #include "stream.h"  /* Stream data type header file. */
1370 
1371 #define OBJ_HASH_KEY 1
1372 #define OBJ_HASH_VALUE 2
1373 
1374 /*-----------------------------------------------------------------------------
1375  * Extern declarations
1376  *----------------------------------------------------------------------------*/
1377 
1378 extern struct redisServer server;
1379 extern struct sharedObjectsStruct shared;
1380 extern dictType objectKeyPointerValueDictType;
1381 extern dictType objectKeyHeapPointerValueDictType;
1382 extern dictType setDictType;
1383 extern dictType zsetDictType;
1384 extern dictType clusterNodesDictType;
1385 extern dictType clusterNodesBlackListDictType;
1386 extern dictType dbDictType;
1387 extern dictType shaScriptObjectDictType;
1388 extern double R_Zero, R_PosInf, R_NegInf, R_Nan;
1389 extern dictType hashDictType;
1390 extern dictType replScriptCacheDictType;
1391 extern dictType keyptrDictType;
1392 extern dictType modulesDictType;
1393 
1394 /*-----------------------------------------------------------------------------
1395  * Functions prototypes
1396  *----------------------------------------------------------------------------*/
1397 
1398 /* Modules */
1399 void moduleInitModulesSystem(void);
1400 int moduleLoad(const char *path, void **argv, int argc);
1401 void moduleLoadFromQueue(void);
1402 int *moduleGetCommandKeysViaAPI(struct redisCommand *cmd, robj **argv, int argc, int *numkeys);
1403 moduleType *moduleTypeLookupModuleByID(uint64_t id);
1404 void moduleTypeNameByID(char *name, uint64_t moduleid);
1405 void moduleFreeContext(struct RedisModuleCtx *ctx);
1406 void unblockClientFromModule(client *c);
1407 void moduleHandleBlockedClients(void);
1408 void moduleBlockedClientTimedOut(client *c);
1409 void moduleBlockedClientPipeReadable(aeEventLoop *el, int fd, void *privdata, int mask);
1410 size_t moduleCount(void);
1411 void moduleAcquireGIL(void);
1412 void moduleReleaseGIL(void);
1413 void moduleNotifyKeyspaceEvent(int type, const char *event, robj *key, int dbid);
1414 void moduleCallCommandFilters(client *c);
1415 
1416 /* Utils */
1417 long long ustime(void);
1418 long long mstime(void);
1419 void getRandomHexChars(char *p, size_t len);
1420 void getRandomBytes(unsigned char *p, size_t len);
1421 uint64_t crc64(uint64_t crc, const unsigned char *s, uint64_t l);
1422 void exitFromChild(int retcode);
1423 size_t redisPopcount(void *s, long count);
1424 void redisSetProcTitle(char *title);
1425 
1426 /* networking.c -- Networking and Client related operations */
1427 client *createClient(int fd);
1428 void closeTimedoutClients(void);
1429 void freeClient(client *c);
1430 void freeClientAsync(client *c);
1431 void resetClient(client *c);
1432 void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask);
1433 void *addDeferredMultiBulkLength(client *c);
1434 void setDeferredMultiBulkLength(client *c, void *node, long length);
1435 void processInputBuffer(client *c);
1436 void processInputBufferAndReplicate(client *c);
1437 void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
1438 void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask);
1439 void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask);
1440 void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
1441 void addReplyString(client *c, const char *s, size_t len);
1442 void AddReplyFromClient(client *c, client *src);
1443 void addReplyBulk(client *c, robj *obj);
1444 void addReplyBulkCString(client *c, const char *s);
1445 void addReplyBulkCBuffer(client *c, const void *p, size_t len);
1446 void addReplyBulkLongLong(client *c, long long ll);
1447 void addReply(client *c, robj *obj);
1448 void addReplySds(client *c, sds s);
1449 void addReplyBulkSds(client *c, sds s);
1450 void addReplyError(client *c, const char *err);
1451 void addReplyStatus(client *c, const char *status);
1452 void addReplyDouble(client *c, double d);
1453 void addReplyHumanLongDouble(client *c, long double d);
1454 void addReplyLongLong(client *c, long long ll);
1455 void addReplyMultiBulkLen(client *c, long length);
1456 void addReplyHelp(client *c, const char **help);
1457 void addReplySubcommandSyntaxError(client *c);
1458 void copyClientOutputBuffer(client *dst, client *src);
1459 size_t sdsZmallocSize(sds s);
1460 size_t getStringObjectSdsUsedMemory(robj *o);
1461 void freeClientReplyValue(void *o);
1462 void *dupClientReplyValue(void *o);
1463 void getClientsMaxBuffers(unsigned long *longest_output_list,
1464                           unsigned long *biggest_input_buffer);
1465 char *getClientPeerId(client *client);
1466 sds catClientInfoString(sds s, client *client);
1467 sds getAllClientsInfoString(int type);
1468 void rewriteClientCommandVector(client *c, int argc, ...);
1469 void rewriteClientCommandArgument(client *c, int i, robj *newval);
1470 void replaceClientCommandVector(client *c, int argc, robj **argv);
1471 unsigned long getClientOutputBufferMemoryUsage(client *c);
1472 void freeClientsInAsyncFreeQueue(void);
1473 void asyncCloseClientOnOutputBufferLimitReached(client *c);
1474 int getClientType(client *c);
1475 int getClientTypeByName(char *name);
1476 char *getClientTypeName(int class);
1477 void flushSlavesOutputBuffers(void);
1478 void disconnectSlaves(void);
1479 int listenToPort(int port, int *fds, int *count);
1480 void pauseClients(mstime_t duration);
1481 int clientsArePaused(void);
1482 int processEventsWhileBlocked(void);
1483 int handleClientsWithPendingWrites(void);
1484 int clientHasPendingReplies(client *c);
1485 void unlinkClient(client *c);
1486 int writeToClient(int fd, client *c, int handler_installed);
1487 void linkClient(client *c);
1488 void protectClient(client *c);
1489 void unprotectClient(client *c);
1490 
1491 #ifdef __GNUC__
1492 void addReplyErrorFormat(client *c, const char *fmt, ...)
1493     __attribute__((format(printf, 2, 3)));
1494 void addReplyStatusFormat(client *c, const char *fmt, ...)
1495     __attribute__((format(printf, 2, 3)));
1496 #else
1497 void addReplyErrorFormat(client *c, const char *fmt, ...);
1498 void addReplyStatusFormat(client *c, const char *fmt, ...);
1499 #endif
1500 
1501 /* List data type */
1502 void listTypeTryConversion(robj *subject, robj *value);
1503 void listTypePush(robj *subject, robj *value, int where);
1504 robj *listTypePop(robj *subject, int where);
1505 unsigned long listTypeLength(const robj *subject);
1506 listTypeIterator *listTypeInitIterator(robj *subject, long index, unsigned char direction);
1507 void listTypeReleaseIterator(listTypeIterator *li);
1508 int listTypeNext(listTypeIterator *li, listTypeEntry *entry);
1509 robj *listTypeGet(listTypeEntry *entry);
1510 void listTypeInsert(listTypeEntry *entry, robj *value, int where);
1511 int listTypeEqual(listTypeEntry *entry, robj *o);
1512 void listTypeDelete(listTypeIterator *iter, listTypeEntry *entry);
1513 void listTypeConvert(robj *subject, int enc);
1514 void unblockClientWaitingData(client *c);
1515 void popGenericCommand(client *c, int where);
1516 
1517 /* MULTI/EXEC/WATCH... */
1518 void unwatchAllKeys(client *c);
1519 void initClientMultiState(client *c);
1520 void freeClientMultiState(client *c);
1521 void queueMultiCommand(client *c);
1522 void touchWatchedKey(redisDb *db, robj *key);
1523 void touchWatchedKeysOnFlush(int dbid);
1524 void discardTransaction(client *c);
1525 void flagTransaction(client *c);
1526 void execCommandPropagateMulti(client *c);
1527 
1528 /* Redis object implementation */
1529 void decrRefCount(robj *o);
1530 void decrRefCountVoid(void *o);
1531 void incrRefCount(robj *o);
1532 robj *makeObjectShared(robj *o);
1533 robj *resetRefCount(robj *obj);
1534 void freeStringObject(robj *o);
1535 void freeListObject(robj *o);
1536 void freeSetObject(robj *o);
1537 void freeZsetObject(robj *o);
1538 void freeHashObject(robj *o);
1539 robj *createObject(int type, void *ptr);
1540 robj *createStringObject(const char *ptr, size_t len);
1541 robj *createRawStringObject(const char *ptr, size_t len);
1542 robj *createEmbeddedStringObject(const char *ptr, size_t len);
1543 robj *dupStringObject(const robj *o);
1544 int isSdsRepresentableAsLongLong(sds s, long long *llval);
1545 int isObjectRepresentableAsLongLong(robj *o, long long *llongval);
1546 robj *tryObjectEncoding(robj *o);
1547 robj *getDecodedObject(robj *o);
1548 size_t stringObjectLen(robj *o);
1549 robj *createStringObjectFromLongLong(long long value);
1550 robj *createStringObjectFromLongLongForValue(long long value);
1551 robj *createStringObjectFromLongDouble(long double value, int humanfriendly);
1552 robj *createQuicklistObject(void);
1553 robj *createZiplistObject(void);
1554 robj *createSetObject(void);
1555 robj *createIntsetObject(void);
1556 robj *createHashObject(void);
1557 robj *createZsetObject(void);
1558 robj *createZsetZiplistObject(void);
1559 robj *createStreamObject(void);
1560 robj *createModuleObject(moduleType *mt, void *value);
1561 int getLongFromObjectOrReply(client *c, robj *o, long *target, const char *msg);
1562 int checkType(client *c, robj *o, int type);
1563 int getLongLongFromObjectOrReply(client *c, robj *o, long long *target, const char *msg);
1564 int getDoubleFromObjectOrReply(client *c, robj *o, double *target, const char *msg);
1565 int getDoubleFromObject(const robj *o, double *target);
1566 int getLongLongFromObject(robj *o, long long *target);
1567 int getLongDoubleFromObject(robj *o, long double *target);
1568 int getLongDoubleFromObjectOrReply(client *c, robj *o, long double *target, const char *msg);
1569 char *strEncoding(int encoding);
1570 int compareStringObjects(robj *a, robj *b);
1571 int collateStringObjects(robj *a, robj *b);
1572 int equalStringObjects(robj *a, robj *b);
1573 unsigned long long estimateObjectIdleTime(robj *o);
1574 void trimStringObjectIfNeeded(robj *o);
1575 #define sdsEncodedObject(objptr) (objptr->encoding == OBJ_ENCODING_RAW || objptr->encoding == OBJ_ENCODING_EMBSTR)
1576 
1577 /* Synchronous I/O with timeout */
1578 ssize_t syncWrite(int fd, char *ptr, ssize_t size, long long timeout);
1579 ssize_t syncRead(int fd, char *ptr, ssize_t size, long long timeout);
1580 ssize_t syncReadLine(int fd, char *ptr, ssize_t size, long long timeout);
1581 
1582 /* Replication */
1583 void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
1584 void replicationFeedSlavesFromMasterStream(list *slaves, char *buf, size_t buflen);
1585 void replicationFeedMonitors(client *c, list *monitors, int dictid, robj **argv, int argc);
1586 void updateSlavesWaitingBgsave(int bgsaveerr, int type);
1587 void replicationCron(void);
1588 void replicationHandleMasterDisconnection(void);
1589 void replicationCacheMaster(client *c);
1590 void resizeReplicationBacklog(long long newsize);
1591 void replicationSetMaster(char *ip, int port);
1592 void replicationUnsetMaster(void);
1593 void refreshGoodSlavesCount(void);
1594 void replicationScriptCacheInit(void);
1595 void replicationScriptCacheFlush(void);
1596 void replicationScriptCacheAdd(sds sha1);
1597 int replicationScriptCacheExists(sds sha1);
1598 void processClientsWaitingReplicas(void);
1599 void unblockClientWaitingReplicas(client *c);
1600 int replicationCountAcksByOffset(long long offset);
1601 void replicationSendNewlineToMaster(void);
1602 long long replicationGetSlaveOffset(void);
1603 char *replicationGetSlaveName(client *c);
1604 long long getPsyncInitialOffset(void);
1605 int replicationSetupSlaveForFullResync(client *slave, long long offset);
1606 void changeReplicationId(void);
1607 void clearReplicationId2(void);
1608 void chopReplicationBacklog(void);
1609 void replicationCacheMasterUsingMyself(void);
1610 void feedReplicationBacklog(void *ptr, size_t len);
1611 
1612 /* Generic persistence functions */
1613 void startLoading(FILE *fp);
1614 void loadingProgress(off_t pos);
1615 void stopLoading(void);
1616 
1617 #define DISK_ERROR_TYPE_AOF 1       /* Don't accept writes: AOF errors. */
1618 #define DISK_ERROR_TYPE_RDB 2       /* Don't accept writes: RDB errors. */
1619 #define DISK_ERROR_TYPE_NONE 0      /* No problems, we can accept writes. */
1620 int writeCommandsDeniedByDiskError(void);
1621 
1622 /* RDB persistence */
1623 #include "rdb.h"
1624 int rdbSaveRio(rio *rdb, int *error, int flags, rdbSaveInfo *rsi);
1625 
1626 /* AOF persistence */
1627 void flushAppendOnlyFile(int force);
1628 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
1629 void aofRemoveTempFile(pid_t childpid);
1630 int rewriteAppendOnlyFileBackground(void);
1631 int loadAppendOnlyFile(char *filename);
1632 void stopAppendOnly(void);
1633 int startAppendOnly(void);
1634 void backgroundRewriteDoneHandler(int exitcode, int bysignal);
1635 void aofRewriteBufferReset(void);
1636 unsigned long aofRewriteBufferSize(void);
1637 ssize_t aofReadDiffFromParent(void);
1638 
1639 /* Child info */
1640 void openChildInfoPipe(void);
1641 void closeChildInfoPipe(void);
1642 void sendChildInfo(int process_type);
1643 void receiveChildInfo(void);
1644 
1645 /* Sorted sets data type */
1646 
1647 /* Input flags. */
1648 #define ZADD_NONE 0
1649 #define ZADD_INCR (1<<0)    /* Increment the score instead of setting it. */
1650 #define ZADD_NX (1<<1)      /* Don't touch elements not already existing. */
1651 #define ZADD_XX (1<<2)      /* Only touch elements already existing. */
1652 
1653 /* Output flags. */
1654 #define ZADD_NOP (1<<3)     /* Operation not performed because of conditionals.*/
1655 #define ZADD_NAN (1<<4)     /* Only touch elements already existing. */
1656 #define ZADD_ADDED (1<<5)   /* The element was new and was added. */
1657 #define ZADD_UPDATED (1<<6) /* The element already existed, score updated. */
1658 
1659 /* Flags only used by the ZADD command but not by zsetAdd() API: */
1660 #define ZADD_CH (1<<16)      /* Return num of elements added or updated. */
1661 
1662 /* Struct to hold a inclusive/exclusive range spec by score comparison. */
1663 typedef struct {
1664     double min, max;
1665     int minex, maxex; /* are min or max exclusive? */
1666 } zrangespec;
1667 
1668 /* Struct to hold an inclusive/exclusive range spec by lexicographic comparison. */
1669 typedef struct {
1670     sds min, max;     /* May be set to shared.(minstring|maxstring) */
1671     int minex, maxex; /* are min or max exclusive? */
1672 } zlexrangespec;
1673 
1674 zskiplist *zslCreate(void);
1675 void zslFree(zskiplist *zsl);
1676 zskiplistNode *zslInsert(zskiplist *zsl, double score, sds ele);
1677 unsigned char *zzlInsert(unsigned char *zl, sds ele, double score);
1678 int zslDelete(zskiplist *zsl, double score, sds ele, zskiplistNode **node);
1679 zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec *range);
1680 zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec *range);
1681 double zzlGetScore(unsigned char *sptr);
1682 void zzlNext(unsigned char *zl, unsigned char **eptr, unsigned char **sptr);
1683 void zzlPrev(unsigned char *zl, unsigned char **eptr, unsigned char **sptr);
1684 unsigned char *zzlFirstInRange(unsigned char *zl, zrangespec *range);
1685 unsigned char *zzlLastInRange(unsigned char *zl, zrangespec *range);
1686 unsigned long zsetLength(const robj *zobj);
1687 void zsetConvert(robj *zobj, int encoding);
1688 void zsetConvertToZiplistIfNeeded(robj *zobj, size_t maxelelen);
1689 int zsetScore(robj *zobj, sds member, double *score);
1690 unsigned long zslGetRank(zskiplist *zsl, double score, sds o);
1691 int zsetAdd(robj *zobj, double score, sds ele, int *flags, double *newscore);
1692 long zsetRank(robj *zobj, sds ele, int reverse);
1693 int zsetDel(robj *zobj, sds ele);
1694 void genericZpopCommand(client *c, robj **keyv, int keyc, int where, int emitkey, robj *countarg);
1695 sds ziplistGetObject(unsigned char *sptr);
1696 int zslValueGteMin(double value, zrangespec *spec);
1697 int zslValueLteMax(double value, zrangespec *spec);
1698 void zslFreeLexRange(zlexrangespec *spec);
1699 int zslParseLexRange(robj *min, robj *max, zlexrangespec *spec);
1700 unsigned char *zzlFirstInLexRange(unsigned char *zl, zlexrangespec *range);
1701 unsigned char *zzlLastInLexRange(unsigned char *zl, zlexrangespec *range);
1702 zskiplistNode *zslFirstInLexRange(zskiplist *zsl, zlexrangespec *range);
1703 zskiplistNode *zslLastInLexRange(zskiplist *zsl, zlexrangespec *range);
1704 int zzlLexValueGteMin(unsigned char *p, zlexrangespec *spec);
1705 int zzlLexValueLteMax(unsigned char *p, zlexrangespec *spec);
1706 int zslLexValueGteMin(sds value, zlexrangespec *spec);
1707 int zslLexValueLteMax(sds value, zlexrangespec *spec);
1708 
1709 /* Core functions */
1710 int getMaxmemoryState(size_t *total, size_t *logical, size_t *tofree, float *level);
1711 size_t freeMemoryGetNotCountedMemory();
1712 int freeMemoryIfNeeded(void);
1713 int freeMemoryIfNeededAndSafe(void);
1714 int processCommand(client *c);
1715 void setupSignalHandlers(void);
1716 struct redisCommand *lookupCommand(sds name);
1717 struct redisCommand *lookupCommandByCString(char *s);
1718 struct redisCommand *lookupCommandOrOriginal(sds name);
1719 void call(client *c, int flags);
1720 void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int flags);
1721 void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int target);
1722 void forceCommandPropagation(client *c, int flags);
1723 void preventCommandPropagation(client *c);
1724 void preventCommandAOF(client *c);
1725 void preventCommandReplication(client *c);
1726 int prepareForShutdown();
1727 #ifdef __GNUC__
1728 void serverLog(int level, const char *fmt, ...)
1729     __attribute__((format(printf, 2, 3)));
1730 #else
1731 void serverLog(int level, const char *fmt, ...);
1732 #endif
1733 void serverLogRaw(int level, const char *msg);
1734 void serverLogFromHandler(int level, const char *msg);
1735 void usage(void);
1736 void updateDictResizePolicy(void);
1737 int htNeedsResize(dict *dict);
1738 void populateCommandTable(void);
1739 void resetCommandTableStats(void);
1740 void adjustOpenFilesLimit(void);
1741 void closeListeningSockets(int unlink_unix_socket);
1742 void resetCpuAffinity(const char* name);
1743 void updateCachedTime(void);
1744 void resetServerStats(void);
1745 void activeDefragCycle(void);
1746 unsigned int getLRUClock(void);
1747 unsigned int LRU_CLOCK(void);
1748 const char *evictPolicyToString(void);
1749 struct redisMemOverhead *getMemoryOverheadData(void);
1750 void freeMemoryOverheadData(struct redisMemOverhead *mh);
1751 
1752 #define RESTART_SERVER_NONE 0
1753 #define RESTART_SERVER_GRACEFULLY (1<<0)     /* Do proper shutdown. */
1754 #define RESTART_SERVER_CONFIG_REWRITE (1<<1) /* CONFIG REWRITE before restart.*/
1755 int restartServer(int flags, mstime_t delay);
1756 
1757 /* Set data type */
1758 robj *setTypeCreate(sds value);
1759 int setTypeAdd(robj *subject, sds value);
1760 int setTypeRemove(robj *subject, sds value);
1761 int setTypeIsMember(robj *subject, sds value);
1762 setTypeIterator *setTypeInitIterator(robj *subject);
1763 void setTypeReleaseIterator(setTypeIterator *si);
1764 int setTypeNext(setTypeIterator *si, sds *sdsele, int64_t *llele);
1765 sds setTypeNextObject(setTypeIterator *si);
1766 int setTypeRandomElement(robj *setobj, sds *sdsele, int64_t *llele);
1767 unsigned long setTypeRandomElements(robj *set, unsigned long count, robj *aux_set);
1768 unsigned long setTypeSize(const robj *subject);
1769 void setTypeConvert(robj *subject, int enc);
1770 
1771 /* Hash data type */
1772 #define HASH_SET_TAKE_FIELD (1<<0)
1773 #define HASH_SET_TAKE_VALUE (1<<1)
1774 #define HASH_SET_COPY 0
1775 
1776 void hashTypeConvert(robj *o, int enc);
1777 void hashTypeTryConversion(robj *subject, robj **argv, int start, int end);
1778 void hashTypeTryObjectEncoding(robj *subject, robj **o1, robj **o2);
1779 int hashTypeExists(robj *o, sds key);
1780 int hashTypeDelete(robj *o, sds key);
1781 unsigned long hashTypeLength(const robj *o);
1782 hashTypeIterator *hashTypeInitIterator(robj *subject);
1783 void hashTypeReleaseIterator(hashTypeIterator *hi);
1784 int hashTypeNext(hashTypeIterator *hi);
1785 void hashTypeCurrentFromZiplist(hashTypeIterator *hi, int what,
1786                                 unsigned char **vstr,
1787                                 unsigned int *vlen,
1788                                 long long *vll);
1789 sds hashTypeCurrentFromHashTable(hashTypeIterator *hi, int what);
1790 void hashTypeCurrentObject(hashTypeIterator *hi, int what, unsigned char **vstr, unsigned int *vlen, long long *vll);
1791 sds hashTypeCurrentObjectNewSds(hashTypeIterator *hi, int what);
1792 robj *hashTypeLookupWriteOrCreate(client *c, robj *key);
1793 robj *hashTypeGetValueObject(robj *o, sds field);
1794 int hashTypeSet(robj *o, sds field, sds value, int flags);
1795 
1796 /* Pub / Sub */
1797 int pubsubUnsubscribeAllChannels(client *c, int notify);
1798 int pubsubUnsubscribeAllPatterns(client *c, int notify);
1799 void freePubsubPattern(void *p);
1800 int listMatchPubsubPattern(void *a, void *b);
1801 int pubsubPublishMessage(robj *channel, robj *message);
1802 
1803 /* Keyspace events notification */
1804 void notifyKeyspaceEvent(int type, char *event, robj *key, int dbid);
1805 int keyspaceEventsStringToFlags(char *classes);
1806 sds keyspaceEventsFlagsToString(int flags);
1807 
1808 /* Configuration */
1809 void loadServerConfig(char *filename, char *options);
1810 void appendServerSaveParams(time_t seconds, int changes);
1811 void resetServerSaveParams(void);
1812 struct rewriteConfigState; /* Forward declaration to export API. */
1813 void rewriteConfigRewriteLine(struct rewriteConfigState *state, const char *option, sds line, int force);
1814 int rewriteConfig(char *path);
1815 
1816 /* db.c -- Keyspace access API */
1817 int removeExpire(redisDb *db, robj *key);
1818 void propagateExpire(redisDb *db, robj *key, int lazy);
1819 int expireIfNeeded(redisDb *db, robj *key);
1820 long long getExpire(redisDb *db, robj *key);
1821 void setExpire(client *c, redisDb *db, robj *key, long long when);
1822 robj *lookupKey(redisDb *db, robj *key, int flags);
1823 robj *lookupKeyRead(redisDb *db, robj *key);
1824 robj *lookupKeyWrite(redisDb *db, robj *key);
1825 robj *lookupKeyReadOrReply(client *c, robj *key, robj *reply);
1826 robj *lookupKeyWriteOrReply(client *c, robj *key, robj *reply);
1827 robj *lookupKeyReadWithFlags(redisDb *db, robj *key, int flags);
1828 robj *objectCommandLookup(client *c, robj *key);
1829 robj *objectCommandLookupOrReply(client *c, robj *key, robj *reply);
1830 void objectSetLRUOrLFU(robj *val, long long lfu_freq, long long lru_idle,
1831                        long long lru_clock);
1832 #define LOOKUP_NONE 0
1833 #define LOOKUP_NOTOUCH (1<<0)
1834 void dbAdd(redisDb *db, robj *key, robj *val);
1835 void dbOverwrite(redisDb *db, robj *key, robj *val);
1836 void setKey(redisDb *db, robj *key, robj *val);
1837 int dbExists(redisDb *db, robj *key);
1838 robj *dbRandomKey(redisDb *db);
1839 int dbSyncDelete(redisDb *db, robj *key);
1840 int dbDelete(redisDb *db, robj *key);
1841 robj *dbUnshareStringValue(redisDb *db, robj *key, robj *o);
1842 
1843 #define EMPTYDB_NO_FLAGS 0      /* No flags. */
1844 #define EMPTYDB_ASYNC (1<<0)    /* Reclaim memory in another thread. */
1845 long long emptyDb(int dbnum, int flags, void(callback)(void*));
1846 
1847 int selectDb(client *c, int id);
1848 void signalModifiedKey(redisDb *db, robj *key);
1849 void signalFlushedDb(int dbid);
1850 unsigned int getKeysInSlot(unsigned int hashslot, robj **keys, unsigned int count);
1851 unsigned int countKeysInSlot(unsigned int hashslot);
1852 unsigned int delKeysInSlot(unsigned int hashslot);
1853 int verifyClusterConfigWithData(void);
1854 void scanGenericCommand(client *c, robj *o, unsigned long cursor);
1855 int parseScanCursorOrReply(client *c, robj *o, unsigned long *cursor);
1856 void slotToKeyAdd(robj *key);
1857 void slotToKeyDel(robj *key);
1858 void slotToKeyFlush(void);
1859 int dbAsyncDelete(redisDb *db, robj *key);
1860 void emptyDbAsync(redisDb *db);
1861 void slotToKeyFlushAsync(void);
1862 size_t lazyfreeGetPendingObjectsCount(void);
1863 void freeObjAsync(robj *o);
1864 
1865 /* API to get key arguments from commands */
1866 int *getKeysFromCommand(struct redisCommand *cmd, robj **argv, int argc, int *numkeys);
1867 void getKeysFreeResult(int *result);
1868 int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys);
1869 int *evalGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys);
1870 int *sortGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys);
1871 int *migrateGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys);
1872 int *georadiusGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys);
1873 int *xreadGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys);
1874 
1875 /* Cluster */
1876 void clusterInit(void);
1877 unsigned short crc16(const char *buf, int len);
1878 unsigned int keyHashSlot(char *key, int keylen);
1879 void clusterCron(void);
1880 void clusterPropagatePublish(robj *channel, robj *message);
1881 void migrateCloseTimedoutSockets(void);
1882 void clusterBeforeSleep(void);
1883 int clusterSendModuleMessageToTarget(const char *target, uint64_t module_id, uint8_t type, unsigned char *payload, uint32_t len);
1884 
1885 /* Sentinel */
1886 void initSentinelConfig(void);
1887 void initSentinel(void);
1888 void sentinelTimer(void);
1889 char *sentinelHandleConfiguration(char **argv, int argc);
1890 void sentinelIsRunning(void);
1891 
1892 /* redis-check-rdb & aof */
1893 int redis_check_rdb(char *rdbfilename, FILE *fp);
1894 int redis_check_rdb_main(int argc, char **argv, FILE *fp);
1895 int redis_check_aof_main(int argc, char **argv);
1896 
1897 /* Scripting */
1898 void scriptingInit(int setup);
1899 int ldbRemoveChild(pid_t pid);
1900 void ldbKillForkedSessions(void);
1901 int ldbPendingChildren(void);
1902 sds luaCreateFunction(client *c, lua_State *lua, robj *body);
1903 
1904 /* Blocked clients */
1905 void processUnblockedClients(void);
1906 void blockClient(client *c, int btype);
1907 void unblockClient(client *c);
1908 void queueClientForReprocessing(client *c);
1909 void replyToBlockedClientTimedOut(client *c);
1910 int getTimeoutFromObjectOrReply(client *c, robj *object, mstime_t *timeout, int unit);
1911 void disconnectAllBlockedClients(void);
1912 void handleClientsBlockedOnKeys(void);
1913 void signalKeyAsReady(redisDb *db, robj *key);
1914 void blockForKeys(client *c, int btype, robj **keys, int numkeys, mstime_t timeout, robj *target, streamID *ids);
1915 
1916 /* expire.c -- Handling of expired keys */
1917 void activeExpireCycle(int type);
1918 void expireSlaveKeys(void);
1919 void rememberSlaveKeyWithExpire(redisDb *db, robj *key);
1920 void flushSlaveKeysWithExpireList(void);
1921 size_t getSlaveKeyWithExpireCount(void);
1922 
1923 /* evict.c -- maxmemory handling and LRU eviction. */
1924 void evictionPoolAlloc(void);
1925 #define LFU_INIT_VAL 5
1926 unsigned long LFUGetTimeInMinutes(void);
1927 uint8_t LFULogIncr(uint8_t value);
1928 unsigned long LFUDecrAndReturn(robj *o);
1929 
1930 /* Keys hashing / comparison functions for dict.c hash tables. */
1931 uint64_t dictSdsHash(const void *key);
1932 int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2);
1933 void dictSdsDestructor(void *privdata, void *val);
1934 
1935 /* Git SHA1 */
1936 char *redisGitSHA1(void);
1937 char *redisGitDirty(void);
1938 uint64_t redisBuildId(void);
1939 
1940 /* Commands prototypes */
1941 void authCommand(client *c);
1942 void pingCommand(client *c);
1943 void echoCommand(client *c);
1944 void commandCommand(client *c);
1945 void setCommand(client *c);
1946 void setnxCommand(client *c);
1947 void setexCommand(client *c);
1948 void psetexCommand(client *c);
1949 void getCommand(client *c);
1950 void delCommand(client *c);
1951 void unlinkCommand(client *c);
1952 void existsCommand(client *c);
1953 void setbitCommand(client *c);
1954 void getbitCommand(client *c);
1955 void bitfieldCommand(client *c);
1956 void setrangeCommand(client *c);
1957 void getrangeCommand(client *c);
1958 void incrCommand(client *c);
1959 void decrCommand(client *c);
1960 void incrbyCommand(client *c);
1961 void decrbyCommand(client *c);
1962 void incrbyfloatCommand(client *c);
1963 void selectCommand(client *c);
1964 void swapdbCommand(client *c);
1965 void randomkeyCommand(client *c);
1966 void keysCommand(client *c);
1967 void scanCommand(client *c);
1968 void dbsizeCommand(client *c);
1969 void lastsaveCommand(client *c);
1970 void saveCommand(client *c);
1971 void bgsaveCommand(client *c);
1972 void bgrewriteaofCommand(client *c);
1973 void shutdownCommand(client *c);
1974 void moveCommand(client *c);
1975 void renameCommand(client *c);
1976 void renamenxCommand(client *c);
1977 void lpushCommand(client *c);
1978 void rpushCommand(client *c);
1979 void lpushxCommand(client *c);
1980 void rpushxCommand(client *c);
1981 void linsertCommand(client *c);
1982 void lpopCommand(client *c);
1983 void rpopCommand(client *c);
1984 void llenCommand(client *c);
1985 void lindexCommand(client *c);
1986 void lrangeCommand(client *c);
1987 void ltrimCommand(client *c);
1988 void typeCommand(client *c);
1989 void lsetCommand(client *c);
1990 void saddCommand(client *c);
1991 void sremCommand(client *c);
1992 void smoveCommand(client *c);
1993 void sismemberCommand(client *c);
1994 void scardCommand(client *c);
1995 void spopCommand(client *c);
1996 void srandmemberCommand(client *c);
1997 void sinterCommand(client *c);
1998 void sinterstoreCommand(client *c);
1999 void sunionCommand(client *c);
2000 void sunionstoreCommand(client *c);
2001 void sdiffCommand(client *c);
2002 void sdiffstoreCommand(client *c);
2003 void sscanCommand(client *c);
2004 void syncCommand(client *c);
2005 void flushdbCommand(client *c);
2006 void flushallCommand(client *c);
2007 void sortCommand(client *c);
2008 void lremCommand(client *c);
2009 void rpoplpushCommand(client *c);
2010 void infoCommand(client *c);
2011 void mgetCommand(client *c);
2012 void monitorCommand(client *c);
2013 void expireCommand(client *c);
2014 void expireatCommand(client *c);
2015 void pexpireCommand(client *c);
2016 void pexpireatCommand(client *c);
2017 void getsetCommand(client *c);
2018 void ttlCommand(client *c);
2019 void touchCommand(client *c);
2020 void pttlCommand(client *c);
2021 void persistCommand(client *c);
2022 void replicaofCommand(client *c);
2023 void roleCommand(client *c);
2024 void debugCommand(client *c);
2025 void msetCommand(client *c);
2026 void msetnxCommand(client *c);
2027 void zaddCommand(client *c);
2028 void zincrbyCommand(client *c);
2029 void zrangeCommand(client *c);
2030 void zrangebyscoreCommand(client *c);
2031 void zrevrangebyscoreCommand(client *c);
2032 void zrangebylexCommand(client *c);
2033 void zrevrangebylexCommand(client *c);
2034 void zcountCommand(client *c);
2035 void zlexcountCommand(client *c);
2036 void zrevrangeCommand(client *c);
2037 void zcardCommand(client *c);
2038 void zremCommand(client *c);
2039 void zscoreCommand(client *c);
2040 void zremrangebyscoreCommand(client *c);
2041 void zremrangebylexCommand(client *c);
2042 void zpopminCommand(client *c);
2043 void zpopmaxCommand(client *c);
2044 void bzpopminCommand(client *c);
2045 void bzpopmaxCommand(client *c);
2046 void multiCommand(client *c);
2047 void execCommand(client *c);
2048 void discardCommand(client *c);
2049 void blpopCommand(client *c);
2050 void brpopCommand(client *c);
2051 void brpoplpushCommand(client *c);
2052 void appendCommand(client *c);
2053 void strlenCommand(client *c);
2054 void zrankCommand(client *c);
2055 void zrevrankCommand(client *c);
2056 void hsetCommand(client *c);
2057 void hsetnxCommand(client *c);
2058 void hgetCommand(client *c);
2059 void hmsetCommand(client *c);
2060 void hmgetCommand(client *c);
2061 void hdelCommand(client *c);
2062 void hlenCommand(client *c);
2063 void hstrlenCommand(client *c);
2064 void zremrangebyrankCommand(client *c);
2065 void zunionstoreCommand(client *c);
2066 void zinterstoreCommand(client *c);
2067 void zscanCommand(client *c);
2068 void hkeysCommand(client *c);
2069 void hvalsCommand(client *c);
2070 void hgetallCommand(client *c);
2071 void hexistsCommand(client *c);
2072 void hscanCommand(client *c);
2073 void configCommand(client *c);
2074 void hincrbyCommand(client *c);
2075 void hincrbyfloatCommand(client *c);
2076 void subscribeCommand(client *c);
2077 void unsubscribeCommand(client *c);
2078 void psubscribeCommand(client *c);
2079 void punsubscribeCommand(client *c);
2080 void publishCommand(client *c);
2081 void pubsubCommand(client *c);
2082 void watchCommand(client *c);
2083 void unwatchCommand(client *c);
2084 void clusterCommand(client *c);
2085 void restoreCommand(client *c);
2086 void migrateCommand(client *c);
2087 void askingCommand(client *c);
2088 void readonlyCommand(client *c);
2089 void readwriteCommand(client *c);
2090 void dumpCommand(client *c);
2091 void objectCommand(client *c);
2092 void memoryCommand(client *c);
2093 void clientCommand(client *c);
2094 void evalCommand(client *c);
2095 void evalShaCommand(client *c);
2096 void scriptCommand(client *c);
2097 void timeCommand(client *c);
2098 void bitopCommand(client *c);
2099 void bitcountCommand(client *c);
2100 void bitposCommand(client *c);
2101 void replconfCommand(client *c);
2102 void waitCommand(client *c);
2103 void geoencodeCommand(client *c);
2104 void geodecodeCommand(client *c);
2105 void georadiusbymemberCommand(client *c);
2106 void georadiusbymemberroCommand(client *c);
2107 void georadiusCommand(client *c);
2108 void georadiusroCommand(client *c);
2109 void geoaddCommand(client *c);
2110 void geohashCommand(client *c);
2111 void geoposCommand(client *c);
2112 void geodistCommand(client *c);
2113 void pfselftestCommand(client *c);
2114 void pfaddCommand(client *c);
2115 void pfcountCommand(client *c);
2116 void pfmergeCommand(client *c);
2117 void pfdebugCommand(client *c);
2118 void latencyCommand(client *c);
2119 void moduleCommand(client *c);
2120 void securityWarningCommand(client *c);
2121 void xaddCommand(client *c);
2122 void xrangeCommand(client *c);
2123 void xrevrangeCommand(client *c);
2124 void xlenCommand(client *c);
2125 void xreadCommand(client *c);
2126 void xgroupCommand(client *c);
2127 void xsetidCommand(client *c);
2128 void xackCommand(client *c);
2129 void xpendingCommand(client *c);
2130 void xclaimCommand(client *c);
2131 void xinfoCommand(client *c);
2132 void xdelCommand(client *c);
2133 void xtrimCommand(client *c);
2134 void lolwutCommand(client *c);
2135 
2136 #if defined(__GNUC__)
2137 void *calloc(size_t count, size_t size) __attribute__ ((deprecated));
2138 void free(void *ptr) __attribute__ ((deprecated));
2139 void *malloc(size_t size) __attribute__ ((deprecated));
2140 void *realloc(void *ptr, size_t size) __attribute__ ((deprecated));
2141 #endif
2142 
2143 /* Debugging stuff */
2144 void _serverAssertWithInfo(const client *c, const robj *o, const char *estr, const char *file, int line);
2145 void _serverAssert(const char *estr, const char *file, int line);
2146 void _serverPanic(const char *file, int line, const char *msg, ...);
2147 void bugReportStart(void);
2148 void serverLogObjectDebugInfo(const robj *o);
2149 void sigsegvHandler(int sig, siginfo_t *info, void *secret);
2150 sds genRedisInfoString(char *section);
2151 void enableWatchdog(int period);
2152 void disableWatchdog(void);
2153 void watchdogScheduleSignal(int period);
2154 void serverLogHexDump(int level, char *descr, void *value, size_t len);
2155 int memtest_preserving_test(unsigned long *m, size_t bytes, int passes);
2156 void mixDigest(unsigned char *digest, void *ptr, size_t len);
2157 void xorDigest(unsigned char *digest, void *ptr, size_t len);
2158 
2159 #define redisDebug(fmt, ...) \
2160     printf("DEBUG %s:%d > " fmt "\n", __FILE__, __LINE__, __VA_ARGS__)
2161 #define redisDebugMark() \
2162     printf("-- MARK %s:%d --\n", __FILE__, __LINE__)
2163 
2164 #endif
2165