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 37 #include <stdio.h> 38 #include <stdlib.h> 39 #include <string.h> 40 #include <time.h> 41 #include <limits.h> 42 #include <unistd.h> 43 #include <errno.h> 44 #include <inttypes.h> 45 #include <pthread.h> 46 #include <syslog.h> 47 #include <netinet/in.h> 48 #include <lua.h> 49 #include <signal.h> 50 51 typedef long long mstime_t; /* millisecond time type. */ 52 53 #include "ae.h" /* Event driven programming library */ 54 #include "sds.h" /* Dynamic safe strings */ 55 #include "dict.h" /* Hash tables */ 56 #include "adlist.h" /* Linked lists */ 57 #include "zmalloc.h" /* total memory usage aware version of malloc/free */ 58 #include "anet.h" /* Networking the easy way */ 59 #include "ziplist.h" /* Compact list data structure */ 60 #include "intset.h" /* Compact integer set structure */ 61 #include "version.h" /* Version macro */ 62 #include "util.h" /* Misc functions useful in many places */ 63 #include "latency.h" /* Latency monitor API */ 64 #include "sparkline.h" /* ASCII graphs API */ 65 #include "quicklist.h" 66 67 /* Following includes allow test functions to be called from Redis main() */ 68 #include "zipmap.h" 69 #include "sha1.h" 70 #include "endianconv.h" 71 #include "crc64.h" 72 73 /* Error codes */ 74 #define C_OK 0 75 #define C_ERR -1 76 77 /* Static server configuration */ 78 #define CONFIG_DEFAULT_HZ 10 /* Time interrupt calls/sec. */ 79 #define CONFIG_MIN_HZ 1 80 #define CONFIG_MAX_HZ 500 81 #define CONFIG_DEFAULT_SERVER_PORT 6379 /* TCP port */ 82 #define CONFIG_DEFAULT_TCP_BACKLOG 511 /* TCP listen backlog */ 83 #define CONFIG_DEFAULT_CLIENT_TIMEOUT 0 /* default client timeout: infinite */ 84 #define CONFIG_DEFAULT_DBNUM 16 85 #define CONFIG_MAX_LINE 1024 86 #define CRON_DBS_PER_CALL 16 87 #define NET_MAX_WRITES_PER_EVENT (1024*64) 88 #define PROTO_SHARED_SELECT_CMDS 10 89 #define OBJ_SHARED_INTEGERS 10000 90 #define OBJ_SHARED_BULKHDR_LEN 32 91 #define LOG_MAX_LEN 1024 /* Default maximum length of syslog messages */ 92 #define AOF_REWRITE_PERC 100 93 #define AOF_REWRITE_MIN_SIZE (64*1024*1024) 94 #define AOF_REWRITE_ITEMS_PER_CMD 64 95 #define CONFIG_DEFAULT_SLOWLOG_LOG_SLOWER_THAN 10000 96 #define CONFIG_DEFAULT_SLOWLOG_MAX_LEN 128 97 #define CONFIG_DEFAULT_MAX_CLIENTS 10000 98 #define CONFIG_AUTHPASS_MAX_LEN 512 99 #define CONFIG_DEFAULT_SLAVE_PRIORITY 100 100 #define CONFIG_DEFAULT_REPL_TIMEOUT 60 101 #define CONFIG_DEFAULT_REPL_PING_SLAVE_PERIOD 10 102 #define CONFIG_RUN_ID_SIZE 40 103 #define RDB_EOF_MARK_SIZE 40 104 #define CONFIG_DEFAULT_REPL_BACKLOG_SIZE (1024*1024) /* 1mb */ 105 #define CONFIG_DEFAULT_REPL_BACKLOG_TIME_LIMIT (60*60) /* 1 hour */ 106 #define CONFIG_REPL_BACKLOG_MIN_SIZE (1024*16) /* 16k */ 107 #define CONFIG_BGSAVE_RETRY_DELAY 5 /* Wait a few secs before trying again. */ 108 #define CONFIG_DEFAULT_PID_FILE "/var/run/redis.pid" 109 #define CONFIG_DEFAULT_SYSLOG_IDENT "redis" 110 #define CONFIG_DEFAULT_CLUSTER_CONFIG_FILE "nodes.conf" 111 #define CONFIG_DEFAULT_DAEMONIZE 0 112 #define CONFIG_DEFAULT_UNIX_SOCKET_PERM 0 113 #define CONFIG_DEFAULT_TCP_KEEPALIVE 0 114 #define CONFIG_DEFAULT_PROTECTED_MODE 1 115 #define CONFIG_DEFAULT_LOGFILE "" 116 #define CONFIG_DEFAULT_SYSLOG_ENABLED 0 117 #define CONFIG_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR 1 118 #define CONFIG_DEFAULT_RDB_COMPRESSION 1 119 #define CONFIG_DEFAULT_RDB_CHECKSUM 1 120 #define CONFIG_DEFAULT_RDB_FILENAME "dump.rdb" 121 #define CONFIG_DEFAULT_REPL_DISKLESS_SYNC 0 122 #define CONFIG_DEFAULT_REPL_DISKLESS_SYNC_DELAY 5 123 #define CONFIG_DEFAULT_SLAVE_SERVE_STALE_DATA 1 124 #define CONFIG_DEFAULT_SLAVE_READ_ONLY 1 125 #define CONFIG_DEFAULT_REPL_DISABLE_TCP_NODELAY 0 126 #define CONFIG_DEFAULT_MAXMEMORY 0 127 #define CONFIG_DEFAULT_MAXMEMORY_SAMPLES 5 128 #define CONFIG_DEFAULT_AOF_FILENAME "appendonly.aof" 129 #define CONFIG_DEFAULT_AOF_NO_FSYNC_ON_REWRITE 0 130 #define CONFIG_DEFAULT_AOF_LOAD_TRUNCATED 1 131 #define CONFIG_DEFAULT_ACTIVE_REHASHING 1 132 #define CONFIG_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC 1 133 #define CONFIG_DEFAULT_MIN_SLAVES_TO_WRITE 0 134 #define CONFIG_DEFAULT_MIN_SLAVES_MAX_LAG 10 135 #define NET_IP_STR_LEN 46 /* INET6_ADDRSTRLEN is 46, but we need to be sure */ 136 #define NET_PEER_ID_LEN (NET_IP_STR_LEN+32) /* Must be enough for ip:port */ 137 #define CONFIG_BINDADDR_MAX 16 138 #define CONFIG_MIN_RESERVED_FDS 32 139 #define CONFIG_DEFAULT_LATENCY_MONITOR_THRESHOLD 0 140 141 #define ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP 20 /* Loopkups per loop. */ 142 #define ACTIVE_EXPIRE_CYCLE_FAST_DURATION 1000 /* Microseconds */ 143 #define ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC 25 /* CPU max % for keys collection */ 144 #define ACTIVE_EXPIRE_CYCLE_SLOW 0 145 #define ACTIVE_EXPIRE_CYCLE_FAST 1 146 147 /* Instantaneous metrics tracking. */ 148 #define STATS_METRIC_SAMPLES 16 /* Number of samples per metric. */ 149 #define STATS_METRIC_COMMAND 0 /* Number of commands executed. */ 150 #define STATS_METRIC_NET_INPUT 1 /* Bytes read to network .*/ 151 #define STATS_METRIC_NET_OUTPUT 2 /* Bytes written to network. */ 152 #define STATS_METRIC_COUNT 3 153 154 /* Protocol and I/O related defines */ 155 #define PROTO_MAX_QUERYBUF_LEN (1024*1024*1024) /* 1GB max query buffer. */ 156 #define PROTO_IOBUF_LEN (1024*16) /* Generic I/O buffer size */ 157 #define PROTO_REPLY_CHUNK_BYTES (16*1024) /* 16k output buffer */ 158 #define PROTO_INLINE_MAX_SIZE (1024*64) /* Max size of inline reads */ 159 #define PROTO_MBULK_BIG_ARG (1024*32) 160 #define LONG_STR_SIZE 21 /* Bytes needed for long -> str + '\0' */ 161 #define AOF_AUTOSYNC_BYTES (1024*1024*32) /* fdatasync every 32MB */ 162 163 /* When configuring the server eventloop, we setup it so that the total number 164 * of file descriptors we can handle are server.maxclients + RESERVED_FDS + 165 * a few more to stay safe. Since RESERVED_FDS defaults to 32, we add 96 166 * in order to make sure of not over provisioning more than 128 fds. */ 167 #define CONFIG_FDSET_INCR (CONFIG_MIN_RESERVED_FDS+96) 168 169 /* Hash table parameters */ 170 #define HASHTABLE_MIN_FILL 10 /* Minimal hash table fill 10% */ 171 172 /* Command flags. Please check the command table defined in the redis.c file 173 * for more information about the meaning of every flag. */ 174 #define CMD_WRITE 1 /* "w" flag */ 175 #define CMD_READONLY 2 /* "r" flag */ 176 #define CMD_DENYOOM 4 /* "m" flag */ 177 #define CMD_NOT_USED_1 8 /* no longer used flag */ 178 #define CMD_ADMIN 16 /* "a" flag */ 179 #define CMD_PUBSUB 32 /* "p" flag */ 180 #define CMD_NOSCRIPT 64 /* "s" flag */ 181 #define CMD_RANDOM 128 /* "R" flag */ 182 #define CMD_SORT_FOR_SCRIPT 256 /* "S" flag */ 183 #define CMD_LOADING 512 /* "l" flag */ 184 #define CMD_STALE 1024 /* "t" flag */ 185 #define CMD_SKIP_MONITOR 2048 /* "M" flag */ 186 #define CMD_ASKING 4096 /* "k" flag */ 187 #define CMD_FAST 8192 /* "F" flag */ 188 189 /* Object types */ 190 #define OBJ_STRING 0 191 #define OBJ_LIST 1 192 #define OBJ_SET 2 193 #define OBJ_ZSET 3 194 #define OBJ_HASH 4 195 196 /* Objects encoding. Some kind of objects like Strings and Hashes can be 197 * internally represented in multiple ways. The 'encoding' field of the object 198 * is set to one of this fields for this object. */ 199 #define OBJ_ENCODING_RAW 0 /* Raw representation */ 200 #define OBJ_ENCODING_INT 1 /* Encoded as integer */ 201 #define OBJ_ENCODING_HT 2 /* Encoded as hash table */ 202 #define OBJ_ENCODING_ZIPMAP 3 /* Encoded as zipmap */ 203 #define OBJ_ENCODING_LINKEDLIST 4 /* Encoded as regular linked list */ 204 #define OBJ_ENCODING_ZIPLIST 5 /* Encoded as ziplist */ 205 #define OBJ_ENCODING_INTSET 6 /* Encoded as intset */ 206 #define OBJ_ENCODING_SKIPLIST 7 /* Encoded as skiplist */ 207 #define OBJ_ENCODING_EMBSTR 8 /* Embedded sds string encoding */ 208 #define OBJ_ENCODING_QUICKLIST 9 /* Encoded as linked list of ziplists */ 209 210 /* Defines related to the dump file format. To store 32 bits lengths for short 211 * keys requires a lot of space, so we check the most significant 2 bits of 212 * the first byte to interpreter the length: 213 * 214 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte 215 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte 216 * 10|000000 [32 bit integer] => if it's 10, a full 32 bit len will follow 217 * 11|000000 this means: specially encoded object will follow. The six bits 218 * number specify the kind of object that follows. 219 * See the RDB_ENC_* defines. 220 * 221 * Lengths up to 63 are stored using a single byte, most DB keys, and may 222 * values, will fit inside. */ 223 #define RDB_6BITLEN 0 224 #define RDB_14BITLEN 1 225 #define RDB_32BITLEN 2 226 #define RDB_ENCVAL 3 227 #define RDB_LENERR UINT_MAX 228 229 /* When a length of a string object stored on disk has the first two bits 230 * set, the remaining two bits specify a special encoding for the object 231 * accordingly to the following defines: */ 232 #define RDB_ENC_INT8 0 /* 8 bit signed integer */ 233 #define RDB_ENC_INT16 1 /* 16 bit signed integer */ 234 #define RDB_ENC_INT32 2 /* 32 bit signed integer */ 235 #define RDB_ENC_LZF 3 /* string compressed with FASTLZ */ 236 237 /* AOF states */ 238 #define AOF_OFF 0 /* AOF is off */ 239 #define AOF_ON 1 /* AOF is on */ 240 #define AOF_WAIT_REWRITE 2 /* AOF waits rewrite to start appending */ 241 242 /* Client flags */ 243 #define CLIENT_SLAVE (1<<0) /* This client is a slave server */ 244 #define CLIENT_MASTER (1<<1) /* This client is a master server */ 245 #define CLIENT_MONITOR (1<<2) /* This client is a slave monitor, see MONITOR */ 246 #define CLIENT_MULTI (1<<3) /* This client is in a MULTI context */ 247 #define CLIENT_BLOCKED (1<<4) /* The client is waiting in a blocking operation */ 248 #define CLIENT_DIRTY_CAS (1<<5) /* Watched keys modified. EXEC will fail. */ 249 #define CLIENT_CLOSE_AFTER_REPLY (1<<6) /* Close after writing entire reply. */ 250 #define CLIENT_UNBLOCKED (1<<7) /* This client was unblocked and is stored in 251 server.unblocked_clients */ 252 #define CLIENT_LUA (1<<8) /* This is a non connected client used by Lua */ 253 #define CLIENT_ASKING (1<<9) /* Client issued the ASKING command */ 254 #define CLIENT_CLOSE_ASAP (1<<10)/* Close this client ASAP */ 255 #define CLIENT_UNIX_SOCKET (1<<11) /* Client connected via Unix domain socket */ 256 #define CLIENT_DIRTY_EXEC (1<<12) /* EXEC will fail for errors while queueing */ 257 #define CLIENT_MASTER_FORCE_REPLY (1<<13) /* Queue replies even if is master */ 258 #define CLIENT_FORCE_AOF (1<<14) /* Force AOF propagation of current cmd. */ 259 #define CLIENT_FORCE_REPL (1<<15) /* Force replication of current cmd. */ 260 #define CLIENT_PRE_PSYNC (1<<16) /* Instance don't understand PSYNC. */ 261 #define CLIENT_READONLY (1<<17) /* Cluster client is in read-only state. */ 262 #define CLIENT_PUBSUB (1<<18) /* Client is in Pub/Sub mode. */ 263 #define CLIENT_PREVENT_AOF_PROP (1<<19) /* Don't propagate to AOF. */ 264 #define CLIENT_PREVENT_REPL_PROP (1<<20) /* Don't propagate to slaves. */ 265 #define CLIENT_PREVENT_PROP (CLIENT_PREVENT_AOF_PROP|CLIENT_PREVENT_REPL_PROP) 266 #define CLIENT_PENDING_WRITE (1<<21) /* Client has output to send but a write 267 handler is yet not installed. */ 268 #define CLIENT_REPLY_OFF (1<<22) /* Don't send replies to client. */ 269 #define CLIENT_REPLY_SKIP_NEXT (1<<23) /* Set CLIENT_REPLY_SKIP for next cmd */ 270 #define CLIENT_REPLY_SKIP (1<<24) /* Don't send just this reply. */ 271 #define CLIENT_LUA_DEBUG (1<<25) /* Run EVAL in debug mode. */ 272 #define CLIENT_LUA_DEBUG_SYNC (1<<26) /* EVAL debugging without fork() */ 273 274 /* Client block type (btype field in client structure) 275 * if CLIENT_BLOCKED flag is set. */ 276 #define BLOCKED_NONE 0 /* Not blocked, no CLIENT_BLOCKED flag set. */ 277 #define BLOCKED_LIST 1 /* BLPOP & co. */ 278 #define BLOCKED_WAIT 2 /* WAIT for synchronous replication. */ 279 280 /* Client request types */ 281 #define PROTO_REQ_INLINE 1 282 #define PROTO_REQ_MULTIBULK 2 283 284 /* Client classes for client limits, currently used only for 285 * the max-client-output-buffer limit implementation. */ 286 #define CLIENT_TYPE_NORMAL 0 /* Normal req-reply clients + MONITORs */ 287 #define CLIENT_TYPE_SLAVE 1 /* Slaves. */ 288 #define CLIENT_TYPE_PUBSUB 2 /* Clients subscribed to PubSub channels. */ 289 #define CLIENT_TYPE_MASTER 3 /* Master. */ 290 #define CLIENT_TYPE_OBUF_COUNT 3 /* Number of clients to expose to output 291 buffer configuration. Just the first 292 three: normal, slave, pubsub. */ 293 294 /* Slave replication state. Used in server.repl_state for slaves to remember 295 * what to do next. */ 296 #define REPL_STATE_NONE 0 /* No active replication */ 297 #define REPL_STATE_CONNECT 1 /* Must connect to master */ 298 #define REPL_STATE_CONNECTING 2 /* Connecting to master */ 299 /* --- Handshake states, must be ordered --- */ 300 #define REPL_STATE_RECEIVE_PONG 3 /* Wait for PING reply */ 301 #define REPL_STATE_SEND_AUTH 4 /* Send AUTH to master */ 302 #define REPL_STATE_RECEIVE_AUTH 5 /* Wait for AUTH reply */ 303 #define REPL_STATE_SEND_PORT 6 /* Send REPLCONF listening-port */ 304 #define REPL_STATE_RECEIVE_PORT 7 /* Wait for REPLCONF reply */ 305 #define REPL_STATE_SEND_CAPA 8 /* Send REPLCONF capa */ 306 #define REPL_STATE_RECEIVE_CAPA 9 /* Wait for REPLCONF reply */ 307 #define REPL_STATE_SEND_PSYNC 10 /* Send PSYNC */ 308 #define REPL_STATE_RECEIVE_PSYNC 11 /* Wait for PSYNC reply */ 309 /* --- End of handshake states --- */ 310 #define REPL_STATE_TRANSFER 12 /* Receiving .rdb from master */ 311 #define REPL_STATE_CONNECTED 13 /* Connected to master */ 312 313 /* State of slaves from the POV of the master. Used in client->replstate. 314 * In SEND_BULK and ONLINE state the slave receives new updates 315 * in its output queue. In the WAIT_BGSAVE states instead the server is waiting 316 * to start the next background saving in order to send updates to it. */ 317 #define SLAVE_STATE_WAIT_BGSAVE_START 6 /* We need to produce a new RDB file. */ 318 #define SLAVE_STATE_WAIT_BGSAVE_END 7 /* Waiting RDB file creation to finish. */ 319 #define SLAVE_STATE_SEND_BULK 8 /* Sending RDB file to slave. */ 320 #define SLAVE_STATE_ONLINE 9 /* RDB file transmitted, sending just updates. */ 321 322 /* Slave capabilities. */ 323 #define SLAVE_CAPA_NONE 0 324 #define SLAVE_CAPA_EOF (1<<0) /* Can parse the RDB EOF streaming format. */ 325 326 /* Synchronous read timeout - slave side */ 327 #define CONFIG_REPL_SYNCIO_TIMEOUT 5 328 329 /* List related stuff */ 330 #define LIST_HEAD 0 331 #define LIST_TAIL 1 332 333 /* Sort operations */ 334 #define SORT_OP_GET 0 335 336 /* Log levels */ 337 #define LL_DEBUG 0 338 #define LL_VERBOSE 1 339 #define LL_NOTICE 2 340 #define LL_WARNING 3 341 #define LL_RAW (1<<10) /* Modifier to log without timestamp */ 342 #define CONFIG_DEFAULT_VERBOSITY LL_NOTICE 343 344 /* Supervision options */ 345 #define SUPERVISED_NONE 0 346 #define SUPERVISED_AUTODETECT 1 347 #define SUPERVISED_SYSTEMD 2 348 #define SUPERVISED_UPSTART 3 349 350 /* Anti-warning macro... */ 351 #define UNUSED(V) ((void) V) 352 353 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */ 354 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */ 355 356 /* Append only defines */ 357 #define AOF_FSYNC_NO 0 358 #define AOF_FSYNC_ALWAYS 1 359 #define AOF_FSYNC_EVERYSEC 2 360 #define CONFIG_DEFAULT_AOF_FSYNC AOF_FSYNC_EVERYSEC 361 362 /* Zip structure related defaults */ 363 #define OBJ_HASH_MAX_ZIPLIST_ENTRIES 512 364 #define OBJ_HASH_MAX_ZIPLIST_VALUE 64 365 #define OBJ_SET_MAX_INTSET_ENTRIES 512 366 #define OBJ_ZSET_MAX_ZIPLIST_ENTRIES 128 367 #define OBJ_ZSET_MAX_ZIPLIST_VALUE 64 368 369 /* List defaults */ 370 #define OBJ_LIST_MAX_ZIPLIST_SIZE -2 371 #define OBJ_LIST_COMPRESS_DEPTH 0 372 373 /* HyperLogLog defines */ 374 #define CONFIG_DEFAULT_HLL_SPARSE_MAX_BYTES 3000 375 376 /* Sets operations codes */ 377 #define SET_OP_UNION 0 378 #define SET_OP_DIFF 1 379 #define SET_OP_INTER 2 380 381 /* Redis maxmemory strategies */ 382 #define MAXMEMORY_VOLATILE_LRU 0 383 #define MAXMEMORY_VOLATILE_TTL 1 384 #define MAXMEMORY_VOLATILE_RANDOM 2 385 #define MAXMEMORY_ALLKEYS_LRU 3 386 #define MAXMEMORY_ALLKEYS_RANDOM 4 387 #define MAXMEMORY_NO_EVICTION 5 388 #define CONFIG_DEFAULT_MAXMEMORY_POLICY MAXMEMORY_NO_EVICTION 389 390 /* Scripting */ 391 #define LUA_SCRIPT_TIME_LIMIT 5000 /* milliseconds */ 392 393 /* Units */ 394 #define UNIT_SECONDS 0 395 #define UNIT_MILLISECONDS 1 396 397 /* SHUTDOWN flags */ 398 #define SHUTDOWN_NOFLAGS 0 /* No flags. */ 399 #define SHUTDOWN_SAVE 1 /* Force SAVE on SHUTDOWN even if no save 400 points are configured. */ 401 #define SHUTDOWN_NOSAVE 2 /* Don't SAVE on SHUTDOWN. */ 402 403 /* Command call flags, see call() function */ 404 #define CMD_CALL_NONE 0 405 #define CMD_CALL_SLOWLOG (1<<0) 406 #define CMD_CALL_STATS (1<<1) 407 #define CMD_CALL_PROPAGATE_AOF (1<<2) 408 #define CMD_CALL_PROPAGATE_REPL (1<<3) 409 #define CMD_CALL_PROPAGATE (CMD_CALL_PROPAGATE_AOF|CMD_CALL_PROPAGATE_REPL) 410 #define CMD_CALL_FULL (CMD_CALL_SLOWLOG | CMD_CALL_STATS | CMD_CALL_PROPAGATE) 411 412 /* Command propagation flags, see propagate() function */ 413 #define PROPAGATE_NONE 0 414 #define PROPAGATE_AOF 1 415 #define PROPAGATE_REPL 2 416 417 /* RDB active child save type. */ 418 #define RDB_CHILD_TYPE_NONE 0 419 #define RDB_CHILD_TYPE_DISK 1 /* RDB is written to disk. */ 420 #define RDB_CHILD_TYPE_SOCKET 2 /* RDB is written to slave socket. */ 421 422 /* Keyspace changes notification classes. Every class is associated with a 423 * character for configuration purposes. */ 424 #define NOTIFY_KEYSPACE (1<<0) /* K */ 425 #define NOTIFY_KEYEVENT (1<<1) /* E */ 426 #define NOTIFY_GENERIC (1<<2) /* g */ 427 #define NOTIFY_STRING (1<<3) /* $ */ 428 #define NOTIFY_LIST (1<<4) /* l */ 429 #define NOTIFY_SET (1<<5) /* s */ 430 #define NOTIFY_HASH (1<<6) /* h */ 431 #define NOTIFY_ZSET (1<<7) /* z */ 432 #define NOTIFY_EXPIRED (1<<8) /* x */ 433 #define NOTIFY_EVICTED (1<<9) /* e */ 434 #define NOTIFY_ALL (NOTIFY_GENERIC | NOTIFY_STRING | NOTIFY_LIST | NOTIFY_SET | NOTIFY_HASH | NOTIFY_ZSET | NOTIFY_EXPIRED | NOTIFY_EVICTED) /* A */ 435 436 /* Get the first bind addr or NULL */ 437 #define NET_FIRST_BIND_ADDR (server.bindaddr_count ? server.bindaddr[0] : NULL) 438 439 /* Using the following macro you can run code inside serverCron() with the 440 * specified period, specified in milliseconds. 441 * The actual resolution depends on server.hz. */ 442 #define run_with_period(_ms_) if ((_ms_ <= 1000/server.hz) || !(server.cronloops%((_ms_)/(1000/server.hz)))) 443 444 /* We can print the stacktrace, so our assert is defined this way: */ 445 #define serverAssertWithInfo(_c,_o,_e) ((_e)?(void)0 : (_serverAssertWithInfo(_c,_o,#_e,__FILE__,__LINE__),_exit(1))) 446 #define serverAssert(_e) ((_e)?(void)0 : (_serverAssert(#_e,__FILE__,__LINE__),_exit(1))) 447 #define serverPanic(_e) _serverPanic(#_e,__FILE__,__LINE__),_exit(1) 448 449 /*----------------------------------------------------------------------------- 450 * Data types 451 *----------------------------------------------------------------------------*/ 452 453 /* A redis object, that is a type able to hold a string / list / set */ 454 455 /* The actual Redis Object */ 456 #define LRU_BITS 24 457 #define LRU_CLOCK_MAX ((1<<LRU_BITS)-1) /* Max value of obj->lru */ 458 #define LRU_CLOCK_RESOLUTION 1000 /* LRU clock resolution in ms */ 459 typedef struct redisObject { 460 unsigned type:4; 461 unsigned encoding:4; 462 unsigned lru:LRU_BITS; /* lru time (relative to server.lruclock) */ 463 int refcount; 464 void *ptr; 465 } robj; 466 467 /* Macro used to obtain the current LRU clock. 468 * If the current resolution is lower than the frequency we refresh the 469 * LRU clock (as it should be in production servers) we return the 470 * precomputed value, otherwise we need to resort to a system call. */ 471 #define LRU_CLOCK() ((1000/server.hz <= LRU_CLOCK_RESOLUTION) ? server.lruclock : getLRUClock()) 472 473 /* Macro used to initialize a Redis object allocated on the stack. 474 * Note that this macro is taken near the structure definition to make sure 475 * we'll update it when the structure is changed, to avoid bugs like 476 * bug #85 introduced exactly in this way. */ 477 #define initStaticStringObject(_var,_ptr) do { \ 478 _var.refcount = 1; \ 479 _var.type = OBJ_STRING; \ 480 _var.encoding = OBJ_ENCODING_RAW; \ 481 _var.ptr = _ptr; \ 482 } while(0) 483 484 /* To improve the quality of the LRU approximation we take a set of keys 485 * that are good candidate for eviction across freeMemoryIfNeeded() calls. 486 * 487 * Entries inside the eviciton pool are taken ordered by idle time, putting 488 * greater idle times to the right (ascending order). 489 * 490 * Empty entries have the key pointer set to NULL. */ 491 #define MAXMEMORY_EVICTION_POOL_SIZE 16 492 struct evictionPoolEntry { 493 unsigned long long idle; /* Object idle time. */ 494 sds key; /* Key name. */ 495 }; 496 497 /* Redis database representation. There are multiple databases identified 498 * by integers from 0 (the default database) up to the max configured 499 * database. The database number is the 'id' field in the structure. */ 500 typedef struct redisDb { 501 dict *dict; /* The keyspace for this DB */ 502 dict *expires; /* Timeout of keys with a timeout set */ 503 dict *blocking_keys; /* Keys with clients waiting for data (BLPOP) */ 504 dict *ready_keys; /* Blocked keys that received a PUSH */ 505 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */ 506 struct evictionPoolEntry *eviction_pool; /* Eviction pool of keys */ 507 int id; /* Database ID */ 508 long long avg_ttl; /* Average TTL, just for stats */ 509 } redisDb; 510 511 /* Client MULTI/EXEC state */ 512 typedef struct multiCmd { 513 robj **argv; 514 int argc; 515 struct redisCommand *cmd; 516 } multiCmd; 517 518 typedef struct multiState { 519 multiCmd *commands; /* Array of MULTI commands */ 520 int count; /* Total number of MULTI commands */ 521 int minreplicas; /* MINREPLICAS for synchronous replication */ 522 time_t minreplicas_timeout; /* MINREPLICAS timeout as unixtime. */ 523 } multiState; 524 525 /* This structure holds the blocking operation state for a client. 526 * The fields used depend on client->btype. */ 527 typedef struct blockingState { 528 /* Generic fields. */ 529 mstime_t timeout; /* Blocking operation timeout. If UNIX current time 530 * is > timeout then the operation timed out. */ 531 532 /* BLOCKED_LIST */ 533 dict *keys; /* The keys we are waiting to terminate a blocking 534 * operation such as BLPOP. Otherwise NULL. */ 535 robj *target; /* The key that should receive the element, 536 * for BRPOPLPUSH. */ 537 538 /* BLOCKED_WAIT */ 539 int numreplicas; /* Number of replicas we are waiting for ACK. */ 540 long long reploffset; /* Replication offset to reach. */ 541 } blockingState; 542 543 /* The following structure represents a node in the server.ready_keys list, 544 * where we accumulate all the keys that had clients blocked with a blocking 545 * operation such as B[LR]POP, but received new data in the context of the 546 * last executed command. 547 * 548 * After the execution of every command or script, we run this list to check 549 * if as a result we should serve data to clients blocked, unblocking them. 550 * Note that server.ready_keys will not have duplicates as there dictionary 551 * also called ready_keys in every structure representing a Redis database, 552 * where we make sure to remember if a given key was already added in the 553 * server.ready_keys list. */ 554 typedef struct readyList { 555 redisDb *db; 556 robj *key; 557 } readyList; 558 559 /* With multiplexing we need to take per-client state. 560 * Clients are taken in a linked list. */ 561 typedef struct client { 562 uint64_t id; /* Client incremental unique ID. */ 563 int fd; /* Client socket. */ 564 redisDb *db; /* Pointer to currently SELECTed DB. */ 565 int dictid; /* ID of the currently SELECTed DB. */ 566 robj *name; /* As set by CLIENT SETNAME. */ 567 sds querybuf; /* Buffer we use to accumulate client queries. */ 568 size_t querybuf_peak; /* Recent (100ms or more) peak of querybuf size. */ 569 int argc; /* Num of arguments of current command. */ 570 robj **argv; /* Arguments of current command. */ 571 struct redisCommand *cmd, *lastcmd; /* Last command executed. */ 572 int reqtype; /* Request protocol type: PROTO_REQ_* */ 573 int multibulklen; /* Number of multi bulk arguments left to read. */ 574 long bulklen; /* Length of bulk argument in multi bulk request. */ 575 list *reply; /* List of reply objects to send to the client. */ 576 unsigned long long reply_bytes; /* Tot bytes of objects in reply list. */ 577 size_t sentlen; /* Amount of bytes already sent in the current 578 buffer or object being sent. */ 579 time_t ctime; /* Client creation time. */ 580 time_t lastinteraction; /* Time of the last interaction, used for timeout */ 581 time_t obuf_soft_limit_reached_time; 582 int flags; /* Client flags: CLIENT_* macros. */ 583 int authenticated; /* When requirepass is non-NULL. */ 584 int replstate; /* Replication state if this is a slave. */ 585 int repl_put_online_on_ack; /* Install slave write handler on ACK. */ 586 int repldbfd; /* Replication DB file descriptor. */ 587 off_t repldboff; /* Replication DB file offset. */ 588 off_t repldbsize; /* Replication DB file size. */ 589 sds replpreamble; /* Replication DB preamble. */ 590 long long reploff; /* Replication offset if this is our master. */ 591 long long repl_ack_off; /* Replication ack offset, if this is a slave. */ 592 long long repl_ack_time;/* Replication ack time, if this is a slave. */ 593 long long psync_initial_offset; /* FULLRESYNC reply offset other slaves 594 copying this slave output buffer 595 should use. */ 596 char replrunid[CONFIG_RUN_ID_SIZE+1]; /* Master run id if is a master. */ 597 int slave_listening_port; /* As configured with: SLAVECONF listening-port */ 598 int slave_capa; /* Slave capabilities: SLAVE_CAPA_* bitwise OR. */ 599 multiState mstate; /* MULTI/EXEC state */ 600 int btype; /* Type of blocking op if CLIENT_BLOCKED. */ 601 blockingState bpop; /* blocking state */ 602 long long woff; /* Last write global replication offset. */ 603 list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */ 604 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */ 605 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */ 606 sds peerid; /* Cached peer ID. */ 607 608 /* Response buffer */ 609 int bufpos; 610 char buf[PROTO_REPLY_CHUNK_BYTES]; 611 } client; 612 613 struct saveparam { 614 time_t seconds; 615 int changes; 616 }; 617 618 struct sharedObjectsStruct { 619 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *cnegone, *pong, *space, 620 *colon, *nullbulk, *nullmultibulk, *queued, 621 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr, 622 *outofrangeerr, *noscripterr, *loadingerr, *slowscripterr, *bgsaveerr, 623 *masterdownerr, *roslaveerr, *execaborterr, *noautherr, *noreplicaserr, 624 *busykeyerr, *oomerr, *plus, *messagebulk, *pmessagebulk, *subscribebulk, 625 *unsubscribebulk, *psubscribebulk, *punsubscribebulk, *del, *rpop, *lpop, 626 *lpush, *emptyscan, *minstring, *maxstring, 627 *select[PROTO_SHARED_SELECT_CMDS], 628 *integers[OBJ_SHARED_INTEGERS], 629 *mbulkhdr[OBJ_SHARED_BULKHDR_LEN], /* "*<value>\r\n" */ 630 *bulkhdr[OBJ_SHARED_BULKHDR_LEN]; /* "$<value>\r\n" */ 631 }; 632 633 /* ZSETs use a specialized version of Skiplists */ 634 typedef struct zskiplistNode { 635 robj *obj; 636 double score; 637 struct zskiplistNode *backward; 638 struct zskiplistLevel { 639 struct zskiplistNode *forward; 640 unsigned int span; 641 } level[]; 642 } zskiplistNode; 643 644 typedef struct zskiplist { 645 struct zskiplistNode *header, *tail; 646 unsigned long length; 647 int level; 648 } zskiplist; 649 650 typedef struct zset { 651 dict *dict; 652 zskiplist *zsl; 653 } zset; 654 655 typedef struct clientBufferLimitsConfig { 656 unsigned long long hard_limit_bytes; 657 unsigned long long soft_limit_bytes; 658 time_t soft_limit_seconds; 659 } clientBufferLimitsConfig; 660 661 extern clientBufferLimitsConfig clientBufferLimitsDefaults[CLIENT_TYPE_OBUF_COUNT]; 662 663 /* The redisOp structure defines a Redis Operation, that is an instance of 664 * a command with an argument vector, database ID, propagation target 665 * (PROPAGATE_*), and command pointer. 666 * 667 * Currently only used to additionally propagate more commands to AOF/Replication 668 * after the propagation of the executed command. */ 669 typedef struct redisOp { 670 robj **argv; 671 int argc, dbid, target; 672 struct redisCommand *cmd; 673 } redisOp; 674 675 /* Defines an array of Redis operations. There is an API to add to this 676 * structure in a easy way. 677 * 678 * redisOpArrayInit(); 679 * redisOpArrayAppend(); 680 * redisOpArrayFree(); 681 */ 682 typedef struct redisOpArray { 683 redisOp *ops; 684 int numops; 685 } redisOpArray; 686 687 /*----------------------------------------------------------------------------- 688 * Global server state 689 *----------------------------------------------------------------------------*/ 690 691 struct clusterState; 692 693 /* AIX defines hz to __hz, we don't use this define and in order to allow 694 * Redis build on AIX we need to undef it. */ 695 #ifdef _AIX 696 #undef hz 697 #endif 698 699 struct redisServer { 700 /* General */ 701 pid_t pid; /* Main process pid. */ 702 char *configfile; /* Absolute config file path, or NULL */ 703 char *executable; /* Absolute executable file path. */ 704 char **exec_argv; /* Executable argv vector (copy). */ 705 int hz; /* serverCron() calls frequency in hertz */ 706 redisDb *db; 707 dict *commands; /* Command table */ 708 dict *orig_commands; /* Command table before command renaming. */ 709 aeEventLoop *el; 710 unsigned lruclock:LRU_BITS; /* Clock for LRU eviction */ 711 int shutdown_asap; /* SHUTDOWN needed ASAP */ 712 int activerehashing; /* Incremental rehash in serverCron() */ 713 char *requirepass; /* Pass for AUTH command, or NULL */ 714 char *pidfile; /* PID file path */ 715 int arch_bits; /* 32 or 64 depending on sizeof(long) */ 716 int cronloops; /* Number of times the cron function run */ 717 char runid[CONFIG_RUN_ID_SIZE+1]; /* ID always different at every exec. */ 718 int sentinel_mode; /* True if this instance is a Sentinel. */ 719 /* Networking */ 720 int port; /* TCP listening port */ 721 int tcp_backlog; /* TCP listen() backlog */ 722 char *bindaddr[CONFIG_BINDADDR_MAX]; /* Addresses we should bind to */ 723 int bindaddr_count; /* Number of addresses in server.bindaddr[] */ 724 char *unixsocket; /* UNIX socket path */ 725 mode_t unixsocketperm; /* UNIX socket permission */ 726 int ipfd[CONFIG_BINDADDR_MAX]; /* TCP socket file descriptors */ 727 int ipfd_count; /* Used slots in ipfd[] */ 728 int sofd; /* Unix socket file descriptor */ 729 int cfd[CONFIG_BINDADDR_MAX];/* Cluster bus listening socket */ 730 int cfd_count; /* Used slots in cfd[] */ 731 list *clients; /* List of active clients */ 732 list *clients_to_close; /* Clients to close asynchronously */ 733 list *clients_pending_write; /* There is to write or install handler. */ 734 list *slaves, *monitors; /* List of slaves and MONITORs */ 735 client *current_client; /* Current client, only used on crash report */ 736 int clients_paused; /* True if clients are currently paused */ 737 mstime_t clients_pause_end_time; /* Time when we undo clients_paused */ 738 char neterr[ANET_ERR_LEN]; /* Error buffer for anet.c */ 739 dict *migrate_cached_sockets;/* MIGRATE cached sockets */ 740 uint64_t next_client_id; /* Next client unique ID. Incremental. */ 741 int protected_mode; /* Don't accept external connections. */ 742 /* RDB / AOF loading information */ 743 int loading; /* We are loading data from disk if true */ 744 off_t loading_total_bytes; 745 off_t loading_loaded_bytes; 746 time_t loading_start_time; 747 off_t loading_process_events_interval_bytes; 748 /* Fast pointers to often looked up command */ 749 struct redisCommand *delCommand, *multiCommand, *lpushCommand, *lpopCommand, 750 *rpopCommand, *sremCommand, *execCommand; 751 /* Fields used only for stats */ 752 time_t stat_starttime; /* Server start time */ 753 long long stat_numcommands; /* Number of processed commands */ 754 long long stat_numconnections; /* Number of connections received */ 755 long long stat_expiredkeys; /* Number of expired keys */ 756 long long stat_evictedkeys; /* Number of evicted keys (maxmemory) */ 757 long long stat_keyspace_hits; /* Number of successful lookups of keys */ 758 long long stat_keyspace_misses; /* Number of failed lookups of keys */ 759 size_t stat_peak_memory; /* Max used memory record */ 760 long long stat_fork_time; /* Time needed to perform latest fork() */ 761 double stat_fork_rate; /* Fork rate in GB/sec. */ 762 long long stat_rejected_conn; /* Clients rejected because of maxclients */ 763 long long stat_sync_full; /* Number of full resyncs with slaves. */ 764 long long stat_sync_partial_ok; /* Number of accepted PSYNC requests. */ 765 long long stat_sync_partial_err;/* Number of unaccepted PSYNC requests. */ 766 list *slowlog; /* SLOWLOG list of commands */ 767 long long slowlog_entry_id; /* SLOWLOG current entry ID */ 768 long long slowlog_log_slower_than; /* SLOWLOG time limit (to get logged) */ 769 unsigned long slowlog_max_len; /* SLOWLOG max number of items logged */ 770 size_t resident_set_size; /* RSS sampled in serverCron(). */ 771 long long stat_net_input_bytes; /* Bytes read from network. */ 772 long long stat_net_output_bytes; /* Bytes written to network. */ 773 /* The following two are used to track instantaneous metrics, like 774 * number of operations per second, network traffic. */ 775 struct { 776 long long last_sample_time; /* Timestamp of last sample in ms */ 777 long long last_sample_count;/* Count in last sample */ 778 long long samples[STATS_METRIC_SAMPLES]; 779 int idx; 780 } inst_metric[STATS_METRIC_COUNT]; 781 /* Configuration */ 782 int verbosity; /* Loglevel in redis.conf */ 783 int maxidletime; /* Client timeout in seconds */ 784 int tcpkeepalive; /* Set SO_KEEPALIVE if non-zero. */ 785 int active_expire_enabled; /* Can be disabled for testing purposes. */ 786 size_t client_max_querybuf_len; /* Limit for client query buffer length */ 787 int dbnum; /* Total number of configured DBs */ 788 int supervised; /* 1 if supervised, 0 otherwise. */ 789 int supervised_mode; /* See SUPERVISED_* */ 790 int daemonize; /* True if running as a daemon */ 791 clientBufferLimitsConfig client_obuf_limits[CLIENT_TYPE_OBUF_COUNT]; 792 /* AOF persistence */ 793 int aof_state; /* AOF_(ON|OFF|WAIT_REWRITE) */ 794 int aof_fsync; /* Kind of fsync() policy */ 795 char *aof_filename; /* Name of the AOF file */ 796 int aof_no_fsync_on_rewrite; /* Don't fsync if a rewrite is in prog. */ 797 int aof_rewrite_perc; /* Rewrite AOF if % growth is > M and... */ 798 off_t aof_rewrite_min_size; /* the AOF file is at least N bytes. */ 799 off_t aof_rewrite_base_size; /* AOF size on latest startup or rewrite. */ 800 off_t aof_current_size; /* AOF current size. */ 801 int aof_rewrite_scheduled; /* Rewrite once BGSAVE terminates. */ 802 pid_t aof_child_pid; /* PID if rewriting process */ 803 list *aof_rewrite_buf_blocks; /* Hold changes during an AOF rewrite. */ 804 sds aof_buf; /* AOF buffer, written before entering the event loop */ 805 int aof_fd; /* File descriptor of currently selected AOF file */ 806 int aof_selected_db; /* Currently selected DB in AOF */ 807 time_t aof_flush_postponed_start; /* UNIX time of postponed AOF flush */ 808 time_t aof_last_fsync; /* UNIX time of last fsync() */ 809 time_t aof_rewrite_time_last; /* Time used by last AOF rewrite run. */ 810 time_t aof_rewrite_time_start; /* Current AOF rewrite start time. */ 811 int aof_lastbgrewrite_status; /* C_OK or C_ERR */ 812 unsigned long aof_delayed_fsync; /* delayed AOF fsync() counter */ 813 int aof_rewrite_incremental_fsync;/* fsync incrementally while rewriting? */ 814 int aof_last_write_status; /* C_OK or C_ERR */ 815 int aof_last_write_errno; /* Valid if aof_last_write_status is ERR */ 816 int aof_load_truncated; /* Don't stop on unexpected AOF EOF. */ 817 /* AOF pipes used to communicate between parent and child during rewrite. */ 818 int aof_pipe_write_data_to_child; 819 int aof_pipe_read_data_from_parent; 820 int aof_pipe_write_ack_to_parent; 821 int aof_pipe_read_ack_from_child; 822 int aof_pipe_write_ack_to_child; 823 int aof_pipe_read_ack_from_parent; 824 int aof_stop_sending_diff; /* If true stop sending accumulated diffs 825 to child process. */ 826 sds aof_child_diff; /* AOF diff accumulator child side. */ 827 /* RDB persistence */ 828 long long dirty; /* Changes to DB from the last save */ 829 long long dirty_before_bgsave; /* Used to restore dirty on failed BGSAVE */ 830 pid_t rdb_child_pid; /* PID of RDB saving child */ 831 struct saveparam *saveparams; /* Save points array for RDB */ 832 int saveparamslen; /* Number of saving points */ 833 char *rdb_filename; /* Name of RDB file */ 834 int rdb_compression; /* Use compression in RDB? */ 835 int rdb_checksum; /* Use RDB checksum? */ 836 time_t lastsave; /* Unix time of last successful save */ 837 time_t lastbgsave_try; /* Unix time of last attempted bgsave */ 838 time_t rdb_save_time_last; /* Time used by last RDB save run. */ 839 time_t rdb_save_time_start; /* Current RDB save start time. */ 840 int rdb_child_type; /* Type of save by active child. */ 841 int lastbgsave_status; /* C_OK or C_ERR */ 842 int stop_writes_on_bgsave_err; /* Don't allow writes if can't BGSAVE */ 843 int rdb_pipe_write_result_to_parent; /* RDB pipes used to return the state */ 844 int rdb_pipe_read_result_from_child; /* of each slave in diskless SYNC. */ 845 /* Propagation of commands in AOF / replication */ 846 redisOpArray also_propagate; /* Additional command to propagate. */ 847 /* Logging */ 848 char *logfile; /* Path of log file */ 849 int syslog_enabled; /* Is syslog enabled? */ 850 char *syslog_ident; /* Syslog ident */ 851 int syslog_facility; /* Syslog facility */ 852 /* Replication (master) */ 853 int slaveseldb; /* Last SELECTed DB in replication output */ 854 long long master_repl_offset; /* Global replication offset */ 855 int repl_ping_slave_period; /* Master pings the slave every N seconds */ 856 char *repl_backlog; /* Replication backlog for partial syncs */ 857 long long repl_backlog_size; /* Backlog circular buffer size */ 858 long long repl_backlog_histlen; /* Backlog actual data length */ 859 long long repl_backlog_idx; /* Backlog circular buffer current offset */ 860 long long repl_backlog_off; /* Replication offset of first byte in the 861 backlog buffer. */ 862 time_t repl_backlog_time_limit; /* Time without slaves after the backlog 863 gets released. */ 864 time_t repl_no_slaves_since; /* We have no slaves since that time. 865 Only valid if server.slaves len is 0. */ 866 int repl_min_slaves_to_write; /* Min number of slaves to write. */ 867 int repl_min_slaves_max_lag; /* Max lag of <count> slaves to write. */ 868 int repl_good_slaves_count; /* Number of slaves with lag <= max_lag. */ 869 int repl_diskless_sync; /* Send RDB to slaves sockets directly. */ 870 int repl_diskless_sync_delay; /* Delay to start a diskless repl BGSAVE. */ 871 /* Replication (slave) */ 872 char *masterauth; /* AUTH with this password with master */ 873 char *masterhost; /* Hostname of master */ 874 int masterport; /* Port of master */ 875 int repl_timeout; /* Timeout after N seconds of master idle */ 876 client *master; /* Client that is master for this slave */ 877 client *cached_master; /* Cached master to be reused for PSYNC. */ 878 int repl_syncio_timeout; /* Timeout for synchronous I/O calls */ 879 int repl_state; /* Replication status if the instance is a slave */ 880 off_t repl_transfer_size; /* Size of RDB to read from master during sync. */ 881 off_t repl_transfer_read; /* Amount of RDB read from master during sync. */ 882 off_t repl_transfer_last_fsync_off; /* Offset when we fsync-ed last time. */ 883 int repl_transfer_s; /* Slave -> Master SYNC socket */ 884 int repl_transfer_fd; /* Slave -> Master SYNC temp file descriptor */ 885 char *repl_transfer_tmpfile; /* Slave-> master SYNC temp file name */ 886 time_t repl_transfer_lastio; /* Unix time of the latest read, for timeout */ 887 int repl_serve_stale_data; /* Serve stale data when link is down? */ 888 int repl_slave_ro; /* Slave is read only? */ 889 time_t repl_down_since; /* Unix time at which link with master went down */ 890 int repl_disable_tcp_nodelay; /* Disable TCP_NODELAY after SYNC? */ 891 int slave_priority; /* Reported in INFO and used by Sentinel. */ 892 char repl_master_runid[CONFIG_RUN_ID_SIZE+1]; /* Master run id for PSYNC. */ 893 long long repl_master_initial_offset; /* Master PSYNC offset. */ 894 /* Replication script cache. */ 895 dict *repl_scriptcache_dict; /* SHA1 all slaves are aware of. */ 896 list *repl_scriptcache_fifo; /* First in, first out LRU eviction. */ 897 unsigned int repl_scriptcache_size; /* Max number of elements. */ 898 /* Synchronous replication. */ 899 list *clients_waiting_acks; /* Clients waiting in WAIT command. */ 900 int get_ack_from_slaves; /* If true we send REPLCONF GETACK. */ 901 /* Limits */ 902 unsigned int maxclients; /* Max number of simultaneous clients */ 903 unsigned long long maxmemory; /* Max number of memory bytes to use */ 904 int maxmemory_policy; /* Policy for key eviction */ 905 int maxmemory_samples; /* Pricision of random sampling */ 906 /* Blocked clients */ 907 unsigned int bpop_blocked_clients; /* Number of clients blocked by lists */ 908 list *unblocked_clients; /* list of clients to unblock before next loop */ 909 list *ready_keys; /* List of readyList structures for BLPOP & co */ 910 /* Sort parameters - qsort_r() is only available under BSD so we 911 * have to take this state global, in order to pass it to sortCompare() */ 912 int sort_desc; 913 int sort_alpha; 914 int sort_bypattern; 915 int sort_store; 916 /* Zip structure config, see redis.conf for more information */ 917 size_t hash_max_ziplist_entries; 918 size_t hash_max_ziplist_value; 919 size_t set_max_intset_entries; 920 size_t zset_max_ziplist_entries; 921 size_t zset_max_ziplist_value; 922 size_t hll_sparse_max_bytes; 923 /* List parameters */ 924 int list_max_ziplist_size; 925 int list_compress_depth; 926 /* time cache */ 927 time_t unixtime; /* Unix time sampled every cron cycle. */ 928 long long mstime; /* Like 'unixtime' but with milliseconds resolution. */ 929 /* Pubsub */ 930 dict *pubsub_channels; /* Map channels to list of subscribed clients */ 931 list *pubsub_patterns; /* A list of pubsub_patterns */ 932 int notify_keyspace_events; /* Events to propagate via Pub/Sub. This is an 933 xor of NOTIFY_... flags. */ 934 /* Cluster */ 935 int cluster_enabled; /* Is cluster enabled? */ 936 mstime_t cluster_node_timeout; /* Cluster node timeout. */ 937 char *cluster_configfile; /* Cluster auto-generated config file name. */ 938 struct clusterState *cluster; /* State of the cluster */ 939 int cluster_migration_barrier; /* Cluster replicas migration barrier. */ 940 int cluster_slave_validity_factor; /* Slave max data age for failover. */ 941 int cluster_require_full_coverage; /* If true, put the cluster down if 942 there is at least an uncovered slot.*/ 943 /* Scripting */ 944 lua_State *lua; /* The Lua interpreter. We use just one for all clients */ 945 client *lua_client; /* The "fake client" to query Redis from Lua */ 946 client *lua_caller; /* The client running EVAL right now, or NULL */ 947 dict *lua_scripts; /* A dictionary of SHA1 -> Lua scripts */ 948 mstime_t lua_time_limit; /* Script timeout in milliseconds */ 949 mstime_t lua_time_start; /* Start time of script, milliseconds time */ 950 int lua_write_dirty; /* True if a write command was called during the 951 execution of the current script. */ 952 int lua_random_dirty; /* True if a random command was called during the 953 execution of the current script. */ 954 int lua_replicate_commands; /* True if we are doing single commands repl. */ 955 int lua_multi_emitted;/* True if we already proagated MULTI. */ 956 int lua_repl; /* Script replication flags for redis.set_repl(). */ 957 int lua_timedout; /* True if we reached the time limit for script 958 execution. */ 959 int lua_kill; /* Kill the script if true. */ 960 int lua_always_replicate_commands; /* Default replication type. */ 961 /* Latency monitor */ 962 long long latency_monitor_threshold; 963 dict *latency_events; 964 /* Assert & bug reporting */ 965 char *assert_failed; 966 char *assert_file; 967 int assert_line; 968 int bug_report_start; /* True if bug report header was already logged. */ 969 int watchdog_period; /* Software watchdog period in ms. 0 = off */ 970 /* System hardware info */ 971 size_t system_memory_size; /* Total memory in system as reported by OS */ 972 }; 973 974 typedef struct pubsubPattern { 975 client *client; 976 robj *pattern; 977 } pubsubPattern; 978 979 typedef void redisCommandProc(client *c); 980 typedef int *redisGetKeysProc(struct redisCommand *cmd, robj **argv, int argc, int *numkeys); 981 struct redisCommand { 982 char *name; 983 redisCommandProc *proc; 984 int arity; 985 char *sflags; /* Flags as string representation, one char per flag. */ 986 int flags; /* The actual flags, obtained from the 'sflags' field. */ 987 /* Use a function to determine keys arguments in a command line. 988 * Used for Redis Cluster redirect. */ 989 redisGetKeysProc *getkeys_proc; 990 /* What keys should be loaded in background when calling this command? */ 991 int firstkey; /* The first argument that's a key (0 = no keys) */ 992 int lastkey; /* The last argument that's a key */ 993 int keystep; /* The step between first and last key */ 994 long long microseconds, calls; 995 }; 996 997 struct redisFunctionSym { 998 char *name; 999 unsigned long pointer; 1000 }; 1001 1002 typedef struct _redisSortObject { 1003 robj *obj; 1004 union { 1005 double score; 1006 robj *cmpobj; 1007 } u; 1008 } redisSortObject; 1009 1010 typedef struct _redisSortOperation { 1011 int type; 1012 robj *pattern; 1013 } redisSortOperation; 1014 1015 /* Structure to hold list iteration abstraction. */ 1016 typedef struct { 1017 robj *subject; 1018 unsigned char encoding; 1019 unsigned char direction; /* Iteration direction */ 1020 quicklistIter *iter; 1021 } listTypeIterator; 1022 1023 /* Structure for an entry while iterating over a list. */ 1024 typedef struct { 1025 listTypeIterator *li; 1026 quicklistEntry entry; /* Entry in quicklist */ 1027 } listTypeEntry; 1028 1029 /* Structure to hold set iteration abstraction. */ 1030 typedef struct { 1031 robj *subject; 1032 int encoding; 1033 int ii; /* intset iterator */ 1034 dictIterator *di; 1035 } setTypeIterator; 1036 1037 /* Structure to hold hash iteration abstraction. Note that iteration over 1038 * hashes involves both fields and values. Because it is possible that 1039 * not both are required, store pointers in the iterator to avoid 1040 * unnecessary memory allocation for fields/values. */ 1041 typedef struct { 1042 robj *subject; 1043 int encoding; 1044 1045 unsigned char *fptr, *vptr; 1046 1047 dictIterator *di; 1048 dictEntry *de; 1049 } hashTypeIterator; 1050 1051 #define OBJ_HASH_KEY 1 1052 #define OBJ_HASH_VALUE 2 1053 1054 /*----------------------------------------------------------------------------- 1055 * Extern declarations 1056 *----------------------------------------------------------------------------*/ 1057 1058 extern struct redisServer server; 1059 extern struct sharedObjectsStruct shared; 1060 extern dictType setDictType; 1061 extern dictType zsetDictType; 1062 extern dictType clusterNodesDictType; 1063 extern dictType clusterNodesBlackListDictType; 1064 extern dictType dbDictType; 1065 extern dictType shaScriptObjectDictType; 1066 extern double R_Zero, R_PosInf, R_NegInf, R_Nan; 1067 extern dictType hashDictType; 1068 extern dictType replScriptCacheDictType; 1069 1070 /*----------------------------------------------------------------------------- 1071 * Functions prototypes 1072 *----------------------------------------------------------------------------*/ 1073 1074 /* Utils */ 1075 long long ustime(void); 1076 long long mstime(void); 1077 void getRandomHexChars(char *p, unsigned int len); 1078 uint64_t crc64(uint64_t crc, const unsigned char *s, uint64_t l); 1079 void exitFromChild(int retcode); 1080 size_t redisPopcount(void *s, long count); 1081 void redisSetProcTitle(char *title); 1082 1083 /* networking.c -- Networking and Client related operations */ 1084 client *createClient(int fd); 1085 void closeTimedoutClients(void); 1086 void freeClient(client *c); 1087 void freeClientAsync(client *c); 1088 void resetClient(client *c); 1089 void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask); 1090 void *addDeferredMultiBulkLength(client *c); 1091 void setDeferredMultiBulkLength(client *c, void *node, long length); 1092 void processInputBuffer(client *c); 1093 void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask); 1094 void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask); 1095 void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask); 1096 void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask); 1097 void addReplyBulk(client *c, robj *obj); 1098 void addReplyBulkCString(client *c, const char *s); 1099 void addReplyBulkCBuffer(client *c, const void *p, size_t len); 1100 void addReplyBulkLongLong(client *c, long long ll); 1101 void addReply(client *c, robj *obj); 1102 void addReplySds(client *c, sds s); 1103 void addReplyBulkSds(client *c, sds s); 1104 void addReplyError(client *c, const char *err); 1105 void addReplyStatus(client *c, const char *status); 1106 void addReplyDouble(client *c, double d); 1107 void addReplyHumanLongDouble(client *c, long double d); 1108 void addReplyLongLong(client *c, long long ll); 1109 void addReplyMultiBulkLen(client *c, long length); 1110 void copyClientOutputBuffer(client *dst, client *src); 1111 void *dupClientReplyValue(void *o); 1112 void getClientsMaxBuffers(unsigned long *longest_output_list, 1113 unsigned long *biggest_input_buffer); 1114 char *getClientPeerId(client *client); 1115 sds catClientInfoString(sds s, client *client); 1116 sds getAllClientsInfoString(void); 1117 void rewriteClientCommandVector(client *c, int argc, ...); 1118 void rewriteClientCommandArgument(client *c, int i, robj *newval); 1119 void replaceClientCommandVector(client *c, int argc, robj **argv); 1120 unsigned long getClientOutputBufferMemoryUsage(client *c); 1121 void freeClientsInAsyncFreeQueue(void); 1122 void asyncCloseClientOnOutputBufferLimitReached(client *c); 1123 int getClientType(client *c); 1124 int getClientTypeByName(char *name); 1125 char *getClientTypeName(int class); 1126 void flushSlavesOutputBuffers(void); 1127 void disconnectSlaves(void); 1128 int listenToPort(int port, int *fds, int *count); 1129 void pauseClients(mstime_t duration); 1130 int clientsArePaused(void); 1131 int processEventsWhileBlocked(void); 1132 int handleClientsWithPendingWrites(void); 1133 int clientHasPendingReplies(client *c); 1134 void unlinkClient(client *c); 1135 int writeToClient(int fd, client *c, int handler_installed); 1136 1137 #ifdef __GNUC__ 1138 void addReplyErrorFormat(client *c, const char *fmt, ...) 1139 __attribute__((format(printf, 2, 3))); 1140 void addReplyStatusFormat(client *c, const char *fmt, ...) 1141 __attribute__((format(printf, 2, 3))); 1142 #else 1143 void addReplyErrorFormat(client *c, const char *fmt, ...); 1144 void addReplyStatusFormat(client *c, const char *fmt, ...); 1145 #endif 1146 1147 /* List data type */ 1148 void listTypeTryConversion(robj *subject, robj *value); 1149 void listTypePush(robj *subject, robj *value, int where); 1150 robj *listTypePop(robj *subject, int where); 1151 unsigned long listTypeLength(robj *subject); 1152 listTypeIterator *listTypeInitIterator(robj *subject, long index, unsigned char direction); 1153 void listTypeReleaseIterator(listTypeIterator *li); 1154 int listTypeNext(listTypeIterator *li, listTypeEntry *entry); 1155 robj *listTypeGet(listTypeEntry *entry); 1156 void listTypeInsert(listTypeEntry *entry, robj *value, int where); 1157 int listTypeEqual(listTypeEntry *entry, robj *o); 1158 void listTypeDelete(listTypeIterator *iter, listTypeEntry *entry); 1159 void listTypeConvert(robj *subject, int enc); 1160 void unblockClientWaitingData(client *c); 1161 void handleClientsBlockedOnLists(void); 1162 void popGenericCommand(client *c, int where); 1163 void signalListAsReady(redisDb *db, robj *key); 1164 1165 /* MULTI/EXEC/WATCH... */ 1166 void unwatchAllKeys(client *c); 1167 void initClientMultiState(client *c); 1168 void freeClientMultiState(client *c); 1169 void queueMultiCommand(client *c); 1170 void touchWatchedKey(redisDb *db, robj *key); 1171 void touchWatchedKeysOnFlush(int dbid); 1172 void discardTransaction(client *c); 1173 void flagTransaction(client *c); 1174 void execCommandPropagateMulti(client *c); 1175 1176 /* Redis object implementation */ 1177 void decrRefCount(robj *o); 1178 void decrRefCountVoid(void *o); 1179 void incrRefCount(robj *o); 1180 robj *resetRefCount(robj *obj); 1181 void freeStringObject(robj *o); 1182 void freeListObject(robj *o); 1183 void freeSetObject(robj *o); 1184 void freeZsetObject(robj *o); 1185 void freeHashObject(robj *o); 1186 robj *createObject(int type, void *ptr); 1187 robj *createStringObject(const char *ptr, size_t len); 1188 robj *createRawStringObject(const char *ptr, size_t len); 1189 robj *createEmbeddedStringObject(const char *ptr, size_t len); 1190 robj *dupStringObject(robj *o); 1191 int isObjectRepresentableAsLongLong(robj *o, long long *llongval); 1192 robj *tryObjectEncoding(robj *o); 1193 robj *getDecodedObject(robj *o); 1194 size_t stringObjectLen(robj *o); 1195 robj *createStringObjectFromLongLong(long long value); 1196 robj *createStringObjectFromLongDouble(long double value, int humanfriendly); 1197 robj *createQuicklistObject(void); 1198 robj *createZiplistObject(void); 1199 robj *createSetObject(void); 1200 robj *createIntsetObject(void); 1201 robj *createHashObject(void); 1202 robj *createZsetObject(void); 1203 robj *createZsetZiplistObject(void); 1204 int getLongFromObjectOrReply(client *c, robj *o, long *target, const char *msg); 1205 int checkType(client *c, robj *o, int type); 1206 int getLongLongFromObjectOrReply(client *c, robj *o, long long *target, const char *msg); 1207 int getDoubleFromObjectOrReply(client *c, robj *o, double *target, const char *msg); 1208 int getLongLongFromObject(robj *o, long long *target); 1209 int getLongDoubleFromObject(robj *o, long double *target); 1210 int getLongDoubleFromObjectOrReply(client *c, robj *o, long double *target, const char *msg); 1211 char *strEncoding(int encoding); 1212 int compareStringObjects(robj *a, robj *b); 1213 int collateStringObjects(robj *a, robj *b); 1214 int equalStringObjects(robj *a, robj *b); 1215 unsigned long long estimateObjectIdleTime(robj *o); 1216 #define sdsEncodedObject(objptr) (objptr->encoding == OBJ_ENCODING_RAW || objptr->encoding == OBJ_ENCODING_EMBSTR) 1217 1218 /* Synchronous I/O with timeout */ 1219 ssize_t syncWrite(int fd, char *ptr, ssize_t size, long long timeout); 1220 ssize_t syncRead(int fd, char *ptr, ssize_t size, long long timeout); 1221 ssize_t syncReadLine(int fd, char *ptr, ssize_t size, long long timeout); 1222 1223 /* Replication */ 1224 void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc); 1225 void replicationFeedMonitors(client *c, list *monitors, int dictid, robj **argv, int argc); 1226 void updateSlavesWaitingBgsave(int bgsaveerr, int type); 1227 void replicationCron(void); 1228 void replicationHandleMasterDisconnection(void); 1229 void replicationCacheMaster(client *c); 1230 void resizeReplicationBacklog(long long newsize); 1231 void replicationSetMaster(char *ip, int port); 1232 void replicationUnsetMaster(void); 1233 void refreshGoodSlavesCount(void); 1234 void replicationScriptCacheInit(void); 1235 void replicationScriptCacheFlush(void); 1236 void replicationScriptCacheAdd(sds sha1); 1237 int replicationScriptCacheExists(sds sha1); 1238 void processClientsWaitingReplicas(void); 1239 void unblockClientWaitingReplicas(client *c); 1240 int replicationCountAcksByOffset(long long offset); 1241 void replicationSendNewlineToMaster(void); 1242 long long replicationGetSlaveOffset(void); 1243 char *replicationGetSlaveName(client *c); 1244 long long getPsyncInitialOffset(void); 1245 int replicationSetupSlaveForFullResync(client *slave, long long offset); 1246 1247 /* Generic persistence functions */ 1248 void startLoading(FILE *fp); 1249 void loadingProgress(off_t pos); 1250 void stopLoading(void); 1251 1252 /* RDB persistence */ 1253 #include "rdb.h" 1254 1255 /* AOF persistence */ 1256 void flushAppendOnlyFile(int force); 1257 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc); 1258 void aofRemoveTempFile(pid_t childpid); 1259 int rewriteAppendOnlyFileBackground(void); 1260 int loadAppendOnlyFile(char *filename); 1261 void stopAppendOnly(void); 1262 int startAppendOnly(void); 1263 void backgroundRewriteDoneHandler(int exitcode, int bysignal); 1264 void aofRewriteBufferReset(void); 1265 unsigned long aofRewriteBufferSize(void); 1266 1267 /* Sorted sets data type */ 1268 1269 /* Struct to hold a inclusive/exclusive range spec by score comparison. */ 1270 typedef struct { 1271 double min, max; 1272 int minex, maxex; /* are min or max exclusive? */ 1273 } zrangespec; 1274 1275 /* Struct to hold an inclusive/exclusive range spec by lexicographic comparison. */ 1276 typedef struct { 1277 robj *min, *max; /* May be set to shared.(minstring|maxstring) */ 1278 int minex, maxex; /* are min or max exclusive? */ 1279 } zlexrangespec; 1280 1281 zskiplist *zslCreate(void); 1282 void zslFree(zskiplist *zsl); 1283 zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj); 1284 unsigned char *zzlInsert(unsigned char *zl, robj *ele, double score); 1285 int zslDelete(zskiplist *zsl, double score, robj *obj); 1286 zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec *range); 1287 zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec *range); 1288 double zzlGetScore(unsigned char *sptr); 1289 void zzlNext(unsigned char *zl, unsigned char **eptr, unsigned char **sptr); 1290 void zzlPrev(unsigned char *zl, unsigned char **eptr, unsigned char **sptr); 1291 unsigned int zsetLength(robj *zobj); 1292 void zsetConvert(robj *zobj, int encoding); 1293 void zsetConvertToZiplistIfNeeded(robj *zobj, size_t maxelelen); 1294 int zsetScore(robj *zobj, robj *member, double *score); 1295 unsigned long zslGetRank(zskiplist *zsl, double score, robj *o); 1296 1297 /* Core functions */ 1298 int freeMemoryIfNeeded(void); 1299 int processCommand(client *c); 1300 void setupSignalHandlers(void); 1301 struct redisCommand *lookupCommand(sds name); 1302 struct redisCommand *lookupCommandByCString(char *s); 1303 struct redisCommand *lookupCommandOrOriginal(sds name); 1304 void call(client *c, int flags); 1305 void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int flags); 1306 void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int target); 1307 void forceCommandPropagation(client *c, int flags); 1308 void preventCommandPropagation(client *c); 1309 void preventCommandAOF(client *c); 1310 void preventCommandReplication(client *c); 1311 int prepareForShutdown(); 1312 #ifdef __GNUC__ 1313 void serverLog(int level, const char *fmt, ...) 1314 __attribute__((format(printf, 2, 3))); 1315 #else 1316 void serverLog(int level, const char *fmt, ...); 1317 #endif 1318 void serverLogRaw(int level, const char *msg); 1319 void serverLogFromHandler(int level, const char *msg); 1320 void usage(void); 1321 void updateDictResizePolicy(void); 1322 int htNeedsResize(dict *dict); 1323 void populateCommandTable(void); 1324 void resetCommandTableStats(void); 1325 void adjustOpenFilesLimit(void); 1326 void closeListeningSockets(int unlink_unix_socket); 1327 void updateCachedTime(void); 1328 void resetServerStats(void); 1329 unsigned int getLRUClock(void); 1330 const char *evictPolicyToString(void); 1331 1332 #define RESTART_SERVER_NONE 0 1333 #define RESTART_SERVER_GRACEFULLY (1<<0) /* Do proper shutdown. */ 1334 #define RESTART_SERVER_CONFIG_REWRITE (1<<1) /* CONFIG REWRITE before restart.*/ 1335 int restartServer(int flags, mstime_t delay); 1336 1337 /* Set data type */ 1338 robj *setTypeCreate(robj *value); 1339 int setTypeAdd(robj *subject, robj *value); 1340 int setTypeRemove(robj *subject, robj *value); 1341 int setTypeIsMember(robj *subject, robj *value); 1342 setTypeIterator *setTypeInitIterator(robj *subject); 1343 void setTypeReleaseIterator(setTypeIterator *si); 1344 int setTypeNext(setTypeIterator *si, robj **objele, int64_t *llele); 1345 robj *setTypeNextObject(setTypeIterator *si); 1346 int setTypeRandomElement(robj *setobj, robj **objele, int64_t *llele); 1347 unsigned long setTypeRandomElements(robj *set, unsigned long count, robj *aux_set); 1348 unsigned long setTypeSize(robj *subject); 1349 void setTypeConvert(robj *subject, int enc); 1350 1351 /* Hash data type */ 1352 void hashTypeConvert(robj *o, int enc); 1353 void hashTypeTryConversion(robj *subject, robj **argv, int start, int end); 1354 void hashTypeTryObjectEncoding(robj *subject, robj **o1, robj **o2); 1355 robj *hashTypeGetObject(robj *o, robj *key); 1356 int hashTypeExists(robj *o, robj *key); 1357 int hashTypeSet(robj *o, robj *key, robj *value); 1358 int hashTypeDelete(robj *o, robj *key); 1359 unsigned long hashTypeLength(robj *o); 1360 hashTypeIterator *hashTypeInitIterator(robj *subject); 1361 void hashTypeReleaseIterator(hashTypeIterator *hi); 1362 int hashTypeNext(hashTypeIterator *hi); 1363 void hashTypeCurrentFromZiplist(hashTypeIterator *hi, int what, 1364 unsigned char **vstr, 1365 unsigned int *vlen, 1366 long long *vll); 1367 void hashTypeCurrentFromHashTable(hashTypeIterator *hi, int what, robj **dst); 1368 robj *hashTypeCurrentObject(hashTypeIterator *hi, int what); 1369 robj *hashTypeLookupWriteOrCreate(client *c, robj *key); 1370 1371 /* Pub / Sub */ 1372 int pubsubUnsubscribeAllChannels(client *c, int notify); 1373 int pubsubUnsubscribeAllPatterns(client *c, int notify); 1374 void freePubsubPattern(void *p); 1375 int listMatchPubsubPattern(void *a, void *b); 1376 int pubsubPublishMessage(robj *channel, robj *message); 1377 1378 /* Keyspace events notification */ 1379 void notifyKeyspaceEvent(int type, char *event, robj *key, int dbid); 1380 int keyspaceEventsStringToFlags(char *classes); 1381 sds keyspaceEventsFlagsToString(int flags); 1382 1383 /* Configuration */ 1384 void loadServerConfig(char *filename, char *options); 1385 void appendServerSaveParams(time_t seconds, int changes); 1386 void resetServerSaveParams(void); 1387 struct rewriteConfigState; /* Forward declaration to export API. */ 1388 void rewriteConfigRewriteLine(struct rewriteConfigState *state, const char *option, sds line, int force); 1389 int rewriteConfig(char *path); 1390 1391 /* db.c -- Keyspace access API */ 1392 int removeExpire(redisDb *db, robj *key); 1393 void propagateExpire(redisDb *db, robj *key); 1394 int expireIfNeeded(redisDb *db, robj *key); 1395 long long getExpire(redisDb *db, robj *key); 1396 void setExpire(redisDb *db, robj *key, long long when); 1397 robj *lookupKey(redisDb *db, robj *key); 1398 robj *lookupKeyRead(redisDb *db, robj *key); 1399 robj *lookupKeyWrite(redisDb *db, robj *key); 1400 robj *lookupKeyReadOrReply(client *c, robj *key, robj *reply); 1401 robj *lookupKeyWriteOrReply(client *c, robj *key, robj *reply); 1402 void dbAdd(redisDb *db, robj *key, robj *val); 1403 void dbOverwrite(redisDb *db, robj *key, robj *val); 1404 void setKey(redisDb *db, robj *key, robj *val); 1405 int dbExists(redisDb *db, robj *key); 1406 robj *dbRandomKey(redisDb *db); 1407 int dbDelete(redisDb *db, robj *key); 1408 robj *dbUnshareStringValue(redisDb *db, robj *key, robj *o); 1409 long long emptyDb(void(callback)(void*)); 1410 int selectDb(client *c, int id); 1411 void signalModifiedKey(redisDb *db, robj *key); 1412 void signalFlushedDb(int dbid); 1413 unsigned int getKeysInSlot(unsigned int hashslot, robj **keys, unsigned int count); 1414 unsigned int countKeysInSlot(unsigned int hashslot); 1415 unsigned int delKeysInSlot(unsigned int hashslot); 1416 int verifyClusterConfigWithData(void); 1417 void scanGenericCommand(client *c, robj *o, unsigned long cursor); 1418 int parseScanCursorOrReply(client *c, robj *o, unsigned long *cursor); 1419 1420 /* API to get key arguments from commands */ 1421 int *getKeysFromCommand(struct redisCommand *cmd, robj **argv, int argc, int *numkeys); 1422 void getKeysFreeResult(int *result); 1423 int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys); 1424 int *evalGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys); 1425 int *sortGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys); 1426 int *migrateGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys); 1427 1428 /* Cluster */ 1429 void clusterInit(void); 1430 unsigned short crc16(const char *buf, int len); 1431 unsigned int keyHashSlot(char *key, int keylen); 1432 void clusterCron(void); 1433 void clusterPropagatePublish(robj *channel, robj *message); 1434 void migrateCloseTimedoutSockets(void); 1435 void clusterBeforeSleep(void); 1436 1437 /* Sentinel */ 1438 void initSentinelConfig(void); 1439 void initSentinel(void); 1440 void sentinelTimer(void); 1441 char *sentinelHandleConfiguration(char **argv, int argc); 1442 void sentinelIsRunning(void); 1443 1444 /* redis-check-rdb */ 1445 int redis_check_rdb(char *rdbfilename); 1446 int redis_check_rdb_main(char **argv, int argc); 1447 1448 /* Scripting */ 1449 void scriptingInit(int setup); 1450 int ldbRemoveChild(pid_t pid); 1451 void ldbKillForkedSessions(void); 1452 int ldbPendingChildren(void); 1453 1454 /* Blocked clients */ 1455 void processUnblockedClients(void); 1456 void blockClient(client *c, int btype); 1457 void unblockClient(client *c); 1458 void replyToBlockedClientTimedOut(client *c); 1459 int getTimeoutFromObjectOrReply(client *c, robj *object, mstime_t *timeout, int unit); 1460 void disconnectAllBlockedClients(void); 1461 1462 /* Git SHA1 */ 1463 char *redisGitSHA1(void); 1464 char *redisGitDirty(void); 1465 uint64_t redisBuildId(void); 1466 1467 /* Commands prototypes */ 1468 void authCommand(client *c); 1469 void pingCommand(client *c); 1470 void echoCommand(client *c); 1471 void commandCommand(client *c); 1472 void setCommand(client *c); 1473 void setnxCommand(client *c); 1474 void setexCommand(client *c); 1475 void psetexCommand(client *c); 1476 void getCommand(client *c); 1477 void delCommand(client *c); 1478 void existsCommand(client *c); 1479 void setbitCommand(client *c); 1480 void getbitCommand(client *c); 1481 void bitfieldCommand(client *c); 1482 void setrangeCommand(client *c); 1483 void getrangeCommand(client *c); 1484 void incrCommand(client *c); 1485 void decrCommand(client *c); 1486 void incrbyCommand(client *c); 1487 void decrbyCommand(client *c); 1488 void incrbyfloatCommand(client *c); 1489 void selectCommand(client *c); 1490 void randomkeyCommand(client *c); 1491 void keysCommand(client *c); 1492 void scanCommand(client *c); 1493 void dbsizeCommand(client *c); 1494 void lastsaveCommand(client *c); 1495 void saveCommand(client *c); 1496 void bgsaveCommand(client *c); 1497 void bgrewriteaofCommand(client *c); 1498 void shutdownCommand(client *c); 1499 void moveCommand(client *c); 1500 void renameCommand(client *c); 1501 void renamenxCommand(client *c); 1502 void lpushCommand(client *c); 1503 void rpushCommand(client *c); 1504 void lpushxCommand(client *c); 1505 void rpushxCommand(client *c); 1506 void linsertCommand(client *c); 1507 void lpopCommand(client *c); 1508 void rpopCommand(client *c); 1509 void llenCommand(client *c); 1510 void lindexCommand(client *c); 1511 void lrangeCommand(client *c); 1512 void ltrimCommand(client *c); 1513 void typeCommand(client *c); 1514 void lsetCommand(client *c); 1515 void saddCommand(client *c); 1516 void sremCommand(client *c); 1517 void smoveCommand(client *c); 1518 void sismemberCommand(client *c); 1519 void scardCommand(client *c); 1520 void spopCommand(client *c); 1521 void srandmemberCommand(client *c); 1522 void sinterCommand(client *c); 1523 void sinterstoreCommand(client *c); 1524 void sunionCommand(client *c); 1525 void sunionstoreCommand(client *c); 1526 void sdiffCommand(client *c); 1527 void sdiffstoreCommand(client *c); 1528 void sscanCommand(client *c); 1529 void syncCommand(client *c); 1530 void flushdbCommand(client *c); 1531 void flushallCommand(client *c); 1532 void sortCommand(client *c); 1533 void lremCommand(client *c); 1534 void rpoplpushCommand(client *c); 1535 void infoCommand(client *c); 1536 void mgetCommand(client *c); 1537 void monitorCommand(client *c); 1538 void expireCommand(client *c); 1539 void expireatCommand(client *c); 1540 void pexpireCommand(client *c); 1541 void pexpireatCommand(client *c); 1542 void getsetCommand(client *c); 1543 void ttlCommand(client *c); 1544 void pttlCommand(client *c); 1545 void persistCommand(client *c); 1546 void slaveofCommand(client *c); 1547 void roleCommand(client *c); 1548 void debugCommand(client *c); 1549 void msetCommand(client *c); 1550 void msetnxCommand(client *c); 1551 void zaddCommand(client *c); 1552 void zincrbyCommand(client *c); 1553 void zrangeCommand(client *c); 1554 void zrangebyscoreCommand(client *c); 1555 void zrevrangebyscoreCommand(client *c); 1556 void zrangebylexCommand(client *c); 1557 void zrevrangebylexCommand(client *c); 1558 void zcountCommand(client *c); 1559 void zlexcountCommand(client *c); 1560 void zrevrangeCommand(client *c); 1561 void zcardCommand(client *c); 1562 void zremCommand(client *c); 1563 void zscoreCommand(client *c); 1564 void zremrangebyscoreCommand(client *c); 1565 void zremrangebylexCommand(client *c); 1566 void multiCommand(client *c); 1567 void execCommand(client *c); 1568 void discardCommand(client *c); 1569 void blpopCommand(client *c); 1570 void brpopCommand(client *c); 1571 void brpoplpushCommand(client *c); 1572 void appendCommand(client *c); 1573 void strlenCommand(client *c); 1574 void zrankCommand(client *c); 1575 void zrevrankCommand(client *c); 1576 void hsetCommand(client *c); 1577 void hsetnxCommand(client *c); 1578 void hgetCommand(client *c); 1579 void hmsetCommand(client *c); 1580 void hmgetCommand(client *c); 1581 void hdelCommand(client *c); 1582 void hlenCommand(client *c); 1583 void hstrlenCommand(client *c); 1584 void zremrangebyrankCommand(client *c); 1585 void zunionstoreCommand(client *c); 1586 void zinterstoreCommand(client *c); 1587 void zscanCommand(client *c); 1588 void hkeysCommand(client *c); 1589 void hvalsCommand(client *c); 1590 void hgetallCommand(client *c); 1591 void hexistsCommand(client *c); 1592 void hscanCommand(client *c); 1593 void configCommand(client *c); 1594 void hincrbyCommand(client *c); 1595 void hincrbyfloatCommand(client *c); 1596 void subscribeCommand(client *c); 1597 void unsubscribeCommand(client *c); 1598 void psubscribeCommand(client *c); 1599 void punsubscribeCommand(client *c); 1600 void publishCommand(client *c); 1601 void pubsubCommand(client *c); 1602 void watchCommand(client *c); 1603 void unwatchCommand(client *c); 1604 void clusterCommand(client *c); 1605 void restoreCommand(client *c); 1606 void migrateCommand(client *c); 1607 void askingCommand(client *c); 1608 void readonlyCommand(client *c); 1609 void readwriteCommand(client *c); 1610 void dumpCommand(client *c); 1611 void objectCommand(client *c); 1612 void clientCommand(client *c); 1613 void evalCommand(client *c); 1614 void evalShaCommand(client *c); 1615 void scriptCommand(client *c); 1616 void timeCommand(client *c); 1617 void bitopCommand(client *c); 1618 void bitcountCommand(client *c); 1619 void bitposCommand(client *c); 1620 void replconfCommand(client *c); 1621 void waitCommand(client *c); 1622 void geoencodeCommand(client *c); 1623 void geodecodeCommand(client *c); 1624 void georadiusByMemberCommand(client *c); 1625 void georadiusCommand(client *c); 1626 void geoaddCommand(client *c); 1627 void geohashCommand(client *c); 1628 void geoposCommand(client *c); 1629 void geodistCommand(client *c); 1630 void pfselftestCommand(client *c); 1631 void pfaddCommand(client *c); 1632 void pfcountCommand(client *c); 1633 void pfmergeCommand(client *c); 1634 void pfdebugCommand(client *c); 1635 void latencyCommand(client *c); 1636 1637 #if defined(__GNUC__) 1638 void *calloc(size_t count, size_t size) __attribute__ ((deprecated)); 1639 void free(void *ptr) __attribute__ ((deprecated)); 1640 void *malloc(size_t size) __attribute__ ((deprecated)); 1641 void *realloc(void *ptr, size_t size) __attribute__ ((deprecated)); 1642 #endif 1643 1644 /* Debugging stuff */ 1645 void _serverAssertWithInfo(client *c, robj *o, char *estr, char *file, int line); 1646 void _serverAssert(char *estr, char *file, int line); 1647 void _serverPanic(char *msg, char *file, int line); 1648 void bugReportStart(void); 1649 void serverLogObjectDebugInfo(robj *o); 1650 void sigsegvHandler(int sig, siginfo_t *info, void *secret); 1651 sds genRedisInfoString(char *section); 1652 void enableWatchdog(int period); 1653 void disableWatchdog(void); 1654 void watchdogScheduleSignal(int period); 1655 void serverLogHexDump(int level, char *descr, void *value, size_t len); 1656 int memtest_preserving_test(unsigned long *m, size_t bytes, int passes); 1657 1658 #define redisDebug(fmt, ...) \ 1659 printf("DEBUG %s:%d > " fmt "\n", __FILE__, __LINE__, __VA_ARGS__) 1660 #define redisDebugMark() \ 1661 printf("-- MARK %s:%d --\n", __FILE__, __LINE__) 1662 1663 #endif 1664