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