]> git.saurik.com Git - redis.git/blame - src/redis.h
Better implementation for BRPOP/BLPOP in the non blocking case.
[redis.git] / src / redis.h
CommitLineData
e2641e09 1#ifndef __REDIS_H
2#define __REDIS_H
3
4#include "fmacros.h"
5#include "config.h"
6
7#if defined(__sun)
8#include "solarisfixes.h"
9#endif
10
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <time.h>
15#include <limits.h>
16#include <unistd.h>
17#include <errno.h>
3688d7f3 18#include <inttypes.h>
d06a5b23 19#include <pthread.h>
e1a586ee 20#include <syslog.h>
ecc91094 21#include <netinet/in.h>
7585836e 22#include <lua.h>
eea8c7a4 23#include <signal.h>
e2641e09 24
daa70b17 25#include "ae.h" /* Event driven programming library */
26#include "sds.h" /* Dynamic safe strings */
27#include "dict.h" /* Hash tables */
28#include "adlist.h" /* Linked lists */
e2641e09 29#include "zmalloc.h" /* total memory usage aware version of malloc/free */
daa70b17 30#include "anet.h" /* Networking the easy way */
31#include "zipmap.h" /* Compact string -> string data structure */
e2641e09 32#include "ziplist.h" /* Compact list data structure */
daa70b17 33#include "intset.h" /* Compact integer set structure */
34#include "version.h" /* Version macro */
35#include "util.h" /* Misc functions useful in many places */
e2641e09 36
37/* Error codes */
38#define REDIS_OK 0
39#define REDIS_ERR -1
40
41/* Static server configuration */
42#define REDIS_SERVERPORT 6379 /* TCP port */
3570629f 43#define REDIS_MAXIDLETIME 0 /* default client timeout: infinite */
e2641e09 44#define REDIS_DEFAULT_DBNUM 16
45#define REDIS_CONFIGLINE_MAX 1024
e2641e09 46#define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
47#define REDIS_MAX_WRITE_PER_EVENT (1024*64)
e2641e09 48#define REDIS_SHARED_INTEGERS 10000
355f8591 49#define REDIS_SHARED_BULKHDR_LEN 32
e1a586ee 50#define REDIS_MAX_LOGMSG_LEN 1024 /* Default maximum length of syslog messages */
2c915bcf 51#define REDIS_AOF_REWRITE_PERC 100
52#define REDIS_AOF_REWRITE_MIN_SIZE (1024*1024)
53#define REDIS_AOF_REWRITE_ITEMS_PER_CMD 64
daa70b17 54#define REDIS_SLOWLOG_LOG_SLOWER_THAN 10000
55#define REDIS_SLOWLOG_MAX_LEN 64
58732c23 56#define REDIS_MAX_CLIENTS 10000
834ef78e 57
8996bf77 58#define REDIS_REPL_TIMEOUT 60
59#define REDIS_REPL_PING_SLAVE_PERIOD 10
f42e2f1b 60
61/* Protocol and I/O related defines */
62#define REDIS_MAX_QUERYBUF_LEN (1024*1024*1024) /* 1GB max query buffer. */
63#define REDIS_IOBUF_LEN (1024*16) /* Generic I/O buffer size */
64#define REDIS_REPLY_CHUNK_BYTES (16*1024) /* 16k output buffer */
11e0c4c5 65#define REDIS_INLINE_MAX_SIZE (1024*64) /* Max size of inline reads */
f42e2f1b 66#define REDIS_MBULK_BIG_ARG (1024*32)
8996bf77 67
e2641e09 68/* Hash table parameters */
69#define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
70
5d02b00f 71/* Command flags. Please check the command table defined in the redis.c file
72 * for more information about the meaning of every flag. */
73#define REDIS_CMD_WRITE 1 /* "w" flag */
74#define REDIS_CMD_READONLY 2 /* "r" flag */
75#define REDIS_CMD_DENYOOM 4 /* "m" flag */
76#define REDIS_CMD_FORCE_REPLICATION 8 /* "f" flag */
77#define REDIS_CMD_ADMIN 16 /* "a" flag */
78#define REDIS_CMD_PUBSUB 32 /* "p" flag */
b60ed6e8 79#define REDIS_CMD_NOSCRIPT 64 /* "s" flag */
80#define REDIS_CMD_RANDOM 128 /* "R" flag */
548efd91 81#define REDIS_CMD_SORT_FOR_SCRIPT 256 /* "S" flag */
e2641e09 82
83/* Object types */
84#define REDIS_STRING 0
85#define REDIS_LIST 1
86#define REDIS_SET 2
87#define REDIS_ZSET 3
88#define REDIS_HASH 4
89#define REDIS_VMPOINTER 8
e12b27ac 90
e2641e09 91/* Objects encoding. Some kind of objects like Strings and Hashes can be
92 * internally represented in multiple ways. The 'encoding' field of the object
93 * is set to one of this fields for this object. */
94#define REDIS_ENCODING_RAW 0 /* Raw representation */
95#define REDIS_ENCODING_INT 1 /* Encoded as integer */
96#define REDIS_ENCODING_HT 2 /* Encoded as hash table */
97#define REDIS_ENCODING_ZIPMAP 3 /* Encoded as zipmap */
98#define REDIS_ENCODING_LINKEDLIST 4 /* Encoded as regular linked list */
99#define REDIS_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
96ffb2fe 100#define REDIS_ENCODING_INTSET 6 /* Encoded as intset */
0b7f6d09 101#define REDIS_ENCODING_SKIPLIST 7 /* Encoded as skiplist */
e2641e09 102
e2641e09 103/* Defines related to the dump file format. To store 32 bits lengths for short
104 * keys requires a lot of space, so we check the most significant 2 bits of
105 * the first byte to interpreter the length:
106 *
107 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
108 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
109 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
110 * 11|000000 this means: specially encoded object will follow. The six bits
111 * number specify the kind of object that follows.
112 * See the REDIS_RDB_ENC_* defines.
113 *
114 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
115 * values, will fit inside. */
116#define REDIS_RDB_6BITLEN 0
117#define REDIS_RDB_14BITLEN 1
118#define REDIS_RDB_32BITLEN 2
119#define REDIS_RDB_ENCVAL 3
120#define REDIS_RDB_LENERR UINT_MAX
121
122/* When a length of a string object stored on disk has the first two bits
123 * set, the remaining two bits specify a special encoding for the object
124 * accordingly to the following defines: */
125#define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
126#define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
127#define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
128#define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
129
c6ac7d03 130/* AOF states */
131#define REDIS_AOF_OFF 0 /* AOF is off */
132#define REDIS_AOF_ON 1 /* AOF is on */
133#define REDIS_AOF_WAIT_REWRITE 2 /* AOF waits rewrite to start appending */
134
e2641e09 135/* Client flags */
136#define REDIS_SLAVE 1 /* This client is a slave server */
137#define REDIS_MASTER 2 /* This client is a master server */
138#define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
139#define REDIS_MULTI 8 /* This client is in a MULTI context */
140#define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
e2641e09 141#define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
5e78edb3 142#define REDIS_CLOSE_AFTER_REPLY 128 /* Close after writing entire reply. */
3bcffcbe
PN
143#define REDIS_UNBLOCKED 256 /* This client was unblocked and is stored in
144 server.unblocked_clients */
7156f43c 145#define REDIS_LUA_CLIENT 512 /* This is a non connected client used by Lua */
6856c7b4 146#define REDIS_ASKING 1024 /* Client issued the ASKING command */
7eac2a75 147#define REDIS_CLOSE_ASAP 2048 /* Close this client ASAP */
cd8788f2
PN
148
149/* Client request types */
150#define REDIS_REQ_INLINE 1
151#define REDIS_REQ_MULTIBULK 2
e2641e09 152
498dc555 153/* Client classes for client limits, currently used only for
154 * the max-client-output-buffer limit implementation. */
155#define REDIS_CLIENT_LIMIT_CLASS_NORMAL 0
156#define REDIS_CLIENT_LIMIT_CLASS_SLAVE 1
157#define REDIS_CLIENT_LIMIT_CLASS_PUBSUB 2
7eac2a75 158#define REDIS_CLIENT_LIMIT_NUM_CLASSES 3
498dc555 159
e2641e09 160/* Slave replication state - slave side */
a3309139
PN
161#define REDIS_REPL_NONE 0 /* No active replication */
162#define REDIS_REPL_CONNECT 1 /* Must connect to master */
b075621f
PN
163#define REDIS_REPL_CONNECTING 2 /* Connecting to master */
164#define REDIS_REPL_TRANSFER 3 /* Receiving .rdb from master */
165#define REDIS_REPL_CONNECTED 4 /* Connected to master */
e2641e09 166
890a2ed9
PN
167/* Synchronous read timeout - slave side */
168#define REDIS_REPL_SYNCIO_TIMEOUT 5
e2641e09 169
170/* Slave replication state - from the point of view of master
171 * Note that in SEND_BULK and ONLINE state the slave receives new updates
172 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
173 * to start the next background saving in order to send updates to it. */
174#define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
175#define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
176#define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
177#define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
178
179/* List related stuff */
180#define REDIS_HEAD 0
181#define REDIS_TAIL 1
182
183/* Sort operations */
184#define REDIS_SORT_GET 0
185#define REDIS_SORT_ASC 1
186#define REDIS_SORT_DESC 2
187#define REDIS_SORTKEY_MAX 1024
188
189/* Log levels */
190#define REDIS_DEBUG 0
191#define REDIS_VERBOSE 1
192#define REDIS_NOTICE 2
193#define REDIS_WARNING 3
996d503d 194#define REDIS_LOG_RAW (1<<10) /* Modifier to log without timestamp */
e2641e09 195
196/* Anti-warning macro... */
197#define REDIS_NOTUSED(V) ((void) V)
198
199#define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
200#define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
201
202/* Append only defines */
2c915bcf 203#define AOF_FSYNC_NO 0
204#define AOF_FSYNC_ALWAYS 1
205#define AOF_FSYNC_EVERYSEC 2
e2641e09 206
207/* Zip structure related defaults */
52dc87bb 208#define REDIS_HASH_MAX_ZIPMAP_ENTRIES 512
209#define REDIS_HASH_MAX_ZIPMAP_VALUE 64
6a246b1e 210#define REDIS_LIST_MAX_ZIPLIST_ENTRIES 512
211#define REDIS_LIST_MAX_ZIPLIST_VALUE 64
212#define REDIS_SET_MAX_INTSET_ENTRIES 512
3ea204e1
PN
213#define REDIS_ZSET_MAX_ZIPLIST_ENTRIES 128
214#define REDIS_ZSET_MAX_ZIPLIST_VALUE 64
e2641e09 215
216/* Sets operations codes */
217#define REDIS_OP_UNION 0
218#define REDIS_OP_DIFF 1
219#define REDIS_OP_INTER 2
220
165346ca 221/* Redis maxmemory strategies */
222#define REDIS_MAXMEMORY_VOLATILE_LRU 0
223#define REDIS_MAXMEMORY_VOLATILE_TTL 1
224#define REDIS_MAXMEMORY_VOLATILE_RANDOM 2
225#define REDIS_MAXMEMORY_ALLKEYS_LRU 3
226#define REDIS_MAXMEMORY_ALLKEYS_RANDOM 4
5402c426 227#define REDIS_MAXMEMORY_NO_EVICTION 5
165346ca 228
eeffcf38 229/* Scripting */
8cb8d417 230#define REDIS_LUA_TIME_LIMIT 5000 /* milliseconds */
eeffcf38 231
12d293ca 232/* Units */
233#define UNIT_SECONDS 0
234#define UNIT_MILLISECONDS 1
235
4ab8695d 236/* SHUTDOWN flags */
237#define REDIS_SHUTDOWN_SAVE 1 /* Force SAVE on SHUTDOWN even if no save
238 points are configured. */
239#define REDIS_SHUTDOWN_NOSAVE 2 /* Don't SAVE on SHUTDOWN. */
240
ce8b772b 241/* Command call flags, see call() function */
242#define REDIS_CALL_NONE 0
243#define REDIS_CALL_SLOWLOG 1
244#define REDIS_CALL_STATS 2
245#define REDIS_CALL_PROPAGATE 4
246#define REDIS_CALL_FULL (REDIS_CALL_SLOWLOG | REDIS_CALL_STATS | REDIS_CALL_PROPAGATE)
247
ad08d059 248/* Command propagation flags, see propagate() function */
249#define REDIS_PROPAGATE_NONE 0
250#define REDIS_PROPAGATE_AOF 1
251#define REDIS_PROPAGATE_REPL 2
252
e2641e09 253/* We can print the stacktrace, so our assert is defined this way: */
bab205f7 254#define redisAssertWithInfo(_c,_o,_e) ((_e)?(void)0 : (_redisAssertWithInfo(_c,_o,#_e,__FILE__,__LINE__),_exit(1)))
e2641e09 255#define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
256#define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
e2641e09 257
258/*-----------------------------------------------------------------------------
259 * Data types
260 *----------------------------------------------------------------------------*/
261
262/* A redis object, that is a type able to hold a string / list / set */
263
264/* The actual Redis Object */
ef59a8bc 265#define REDIS_LRU_CLOCK_MAX ((1<<21)-1) /* Max value of obj->lru */
165346ca 266#define REDIS_LRU_CLOCK_RESOLUTION 10 /* LRU clock resolution in seconds */
e2641e09 267typedef struct redisObject {
268 unsigned type:4;
3be00d7e 269 unsigned notused:2; /* Not used */
e2641e09 270 unsigned encoding:4;
271 unsigned lru:22; /* lru time (relative to server.lruclock) */
272 int refcount;
273 void *ptr;
e2641e09 274} robj;
275
e2641e09 276/* Macro used to initalize a Redis object allocated on the stack.
277 * Note that this macro is taken near the structure definition to make sure
278 * we'll update it when the structure is changed, to avoid bugs like
279 * bug #85 introduced exactly in this way. */
280#define initStaticStringObject(_var,_ptr) do { \
281 _var.refcount = 1; \
282 _var.type = REDIS_STRING; \
283 _var.encoding = REDIS_ENCODING_RAW; \
284 _var.ptr = _ptr; \
e2641e09 285} while(0);
286
287typedef struct redisDb {
288 dict *dict; /* The keyspace for this DB */
289 dict *expires; /* Timeout of keys with a timeout set */
290 dict *blocking_keys; /* Keys with clients waiting for data (BLPOP) */
e2641e09 291 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
292 int id;
293} redisDb;
294
295/* Client MULTI/EXEC state */
296typedef struct multiCmd {
297 robj **argv;
298 int argc;
299 struct redisCommand *cmd;
300} multiCmd;
301
302typedef struct multiState {
303 multiCmd *commands; /* Array of MULTI commands */
304 int count; /* Total number of MULTI commands */
305} multiState;
306
357a8417
DJMM
307typedef struct blockingState {
308 robj **keys; /* The key we are waiting to terminate a blocking
309 * operation such as BLPOP. Otherwise NULL. */
310 int count; /* Number of blocking keys */
311 time_t timeout; /* Blocking operation timeout. If UNIX current time
312 * is >= timeout then the operation timed out. */
313 robj *target; /* The key that should receive the element,
314 * for BRPOPLPUSH. */
315} blockingState;
316
e2641e09 317/* With multiplexing we need to take per-clinet state.
318 * Clients are taken in a liked list. */
319typedef struct redisClient {
320 int fd;
321 redisDb *db;
322 int dictid;
323 sds querybuf;
cd8788f2
PN
324 int argc;
325 robj **argv;
2c74a9f9 326 struct redisCommand *cmd, *lastcmd;
cd8788f2
PN
327 int reqtype;
328 int multibulklen; /* number of multi bulk arguments left to read */
329 long bulklen; /* length of bulk argument in multi bulk request */
e2641e09 330 list *reply;
3853c168 331 unsigned long reply_bytes; /* Tot bytes of objects in reply list */
e2641e09 332 int sentlen;
333 time_t lastinteraction; /* time of the last interaction, used for timeout */
7eac2a75 334 time_t obuf_soft_limit_reached_time;
e2641e09 335 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
336 int slaveseldb; /* slave selected db, if this client is a slave */
337 int authenticated; /* when requirepass is non-NULL */
338 int replstate; /* replication state if this is a slave */
339 int repldbfd; /* replication DB file descriptor */
340 long repldboff; /* replication DB file offset */
341 off_t repldbsize; /* replication DB file size */
342 multiState mstate; /* MULTI/EXEC state */
e3c51c4b 343 blockingState bpop; /* blocking state */
e2641e09 344 list *io_keys; /* Keys this client is waiting to be loaded from the
345 * swap file in order to continue. */
346 list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */
347 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
348 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
834ef78e
PN
349
350 /* Response buffer */
351 int bufpos;
f3357792 352 char buf[REDIS_REPLY_CHUNK_BYTES];
e2641e09 353} redisClient;
354
355struct saveparam {
356 time_t seconds;
357 int changes;
358};
359
360struct sharedObjectsStruct {
361 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *cnegone, *pong, *space,
362 *colon, *nullbulk, *nullmultibulk, *queued,
363 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
115e3ff3 364 *outofrangeerr, *noscripterr, *loadingerr, *slowscripterr, *plus,
e2641e09 365 *select0, *select1, *select2, *select3, *select4,
366 *select5, *select6, *select7, *select8, *select9,
355f8591 367 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk,
c1db214e 368 *psubscribebulk, *punsubscribebulk, *del, *rpop, *lpop,
355f8591 369 *integers[REDIS_SHARED_INTEGERS],
370 *mbulkhdr[REDIS_SHARED_BULKHDR_LEN], /* "*<value>\r\n" */
371 *bulkhdr[REDIS_SHARED_BULKHDR_LEN]; /* "$<value>\r\n" */
e2641e09 372};
373
c772d9c6 374/* ZSETs use a specialized version of Skiplists */
375typedef struct zskiplistNode {
376 robj *obj;
377 double score;
378 struct zskiplistNode *backward;
379 struct zskiplistLevel {
380 struct zskiplistNode *forward;
381 unsigned int span;
382 } level[];
383} zskiplistNode;
384
385typedef struct zskiplist {
386 struct zskiplistNode *header, *tail;
387 unsigned long length;
388 int level;
389} zskiplist;
390
391typedef struct zset {
392 dict *dict;
393 zskiplist *zsl;
394} zset;
395
7eac2a75 396typedef struct clientBufferLimitsConfig {
7fe8d49a 397 unsigned long long hard_limit_bytes;
398 unsigned long long soft_limit_bytes;
7eac2a75 399 time_t soft_limit_seconds;
400} clientBufferLimitsConfig;
401
78d6a22d 402/* The redisOp structure defines a Redis Operation, that is an instance of
403 * a command with an argument vector, database ID, propagation target
404 * (REDIS_PROPAGATE_*), and command pointer.
405 *
406 * Currently only used to additionally propagate more commands to AOF/Replication
407 * after the propagation of the executed command. */
408typedef struct redisOp {
eeb34eff 409 robj **argv;
410 int argc, dbid, target;
411 struct redisCommand *cmd;
78d6a22d 412} redisOp;
413
414/* Defines an array of Redis operations. There is an API to add to this
415 * structure in a easy way.
416 *
417 * redisOpArrayInit();
418 * redisOpArrayAppend();
419 * redisOpArrayFree();
420 */
421typedef struct redisOpArray {
422 redisOp *ops;
423 int numops;
424} redisOpArray;
eeb34eff 425
ecc91094 426/*-----------------------------------------------------------------------------
427 * Redis cluster data structures
428 *----------------------------------------------------------------------------*/
429
430#define REDIS_CLUSTER_SLOTS 4096
431#define REDIS_CLUSTER_OK 0 /* Everything looks ok */
432#define REDIS_CLUSTER_FAIL 1 /* The cluster can't work */
433#define REDIS_CLUSTER_NEEDHELP 2 /* The cluster works, but needs some help */
434#define REDIS_CLUSTER_NAMELEN 40 /* sha1 hex length */
435#define REDIS_CLUSTER_PORT_INCR 10000 /* Cluster port = baseport + PORT_INCR */
436
437struct clusterNode;
438
439/* clusterLink encapsulates everything needed to talk with a remote node. */
440typedef struct clusterLink {
441 int fd; /* TCP socket file descriptor */
442 sds sndbuf; /* Packet send buffer */
443 sds rcvbuf; /* Packet reception buffer */
444 struct clusterNode *node; /* Node related to this link if any, or NULL */
445} clusterLink;
446
447/* Node flags */
448#define REDIS_NODE_MASTER 1 /* The node is a master */
449#define REDIS_NODE_SLAVE 2 /* The node is a slave */
450#define REDIS_NODE_PFAIL 4 /* Failure? Need acknowledge */
451#define REDIS_NODE_FAIL 8 /* The node is believed to be malfunctioning */
452#define REDIS_NODE_MYSELF 16 /* This node is myself */
453#define REDIS_NODE_HANDSHAKE 32 /* We have still to exchange the first ping */
454#define REDIS_NODE_NOADDR 64 /* We don't know the address of this node */
455#define REDIS_NODE_MEET 128 /* Send a MEET message to this node */
456#define REDIS_NODE_NULL_NAME "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
457
458struct clusterNode {
459 char name[REDIS_CLUSTER_NAMELEN]; /* Node name, hex string, sha1-size */
460 int flags; /* REDIS_NODE_... */
461 unsigned char slots[REDIS_CLUSTER_SLOTS/8]; /* slots handled by this node */
462 int numslaves; /* Number of slave nodes, if this is a master */
463 struct clusterNode **slaves; /* pointers to slave nodes */
464 struct clusterNode *slaveof; /* pointer to the master node */
465 time_t ping_sent; /* Unix time we sent latest ping */
466 time_t pong_received; /* Unix time we received the pong */
467 char *configdigest; /* Configuration digest of this node */
468 time_t configdigest_ts; /* Configuration digest timestamp */
469 char ip[16]; /* Latest known IP address of this node */
470 int port; /* Latest known port of this node */
471 clusterLink *link; /* TCP/IP link with this node */
472};
473typedef struct clusterNode clusterNode;
474
475typedef struct {
ef21ab96 476 char *configfile;
ecc91094 477 clusterNode *myself; /* This node */
478 int state; /* REDIS_CLUSTER_OK, REDIS_CLUSTER_FAIL, ... */
479 int node_timeout;
480 dict *nodes; /* Hash table of name -> clusterNode structures */
481 clusterNode *migrating_slots_to[REDIS_CLUSTER_SLOTS];
482 clusterNode *importing_slots_from[REDIS_CLUSTER_SLOTS];
483 clusterNode *slots[REDIS_CLUSTER_SLOTS];
c772d9c6 484 zskiplist *slots_to_keys;
ecc91094 485} clusterState;
486
487/* Redis cluster messages header */
488
489/* Note that the PING, PONG and MEET messages are actually the same exact
490 * kind of packet. PONG is the reply to ping, in the extact format as a PING,
491 * while MEET is a special PING that forces the receiver to add the sender
492 * as a node (if it is not already in the list). */
493#define CLUSTERMSG_TYPE_PING 0 /* Ping */
494#define CLUSTERMSG_TYPE_PONG 1 /* Pong (reply to Ping) */
495#define CLUSTERMSG_TYPE_MEET 2 /* Meet "let's join" message */
496#define CLUSTERMSG_TYPE_FAIL 3 /* Mark node xxx as failing */
c563ce46 497#define CLUSTERMSG_TYPE_PUBLISH 4 /* Pub/Sub Publish propatagion */
ecc91094 498
499/* Initially we don't know our "name", but we'll find it once we connect
500 * to the first node, using the getsockname() function. Then we'll use this
501 * address for all the next messages. */
502typedef struct {
503 char nodename[REDIS_CLUSTER_NAMELEN];
504 uint32_t ping_sent;
505 uint32_t pong_received;
506 char ip[16]; /* IP address last time it was seen */
507 uint16_t port; /* port last time it was seen */
508 uint16_t flags;
509 uint32_t notused; /* for 64 bit alignment */
510} clusterMsgDataGossip;
511
512typedef struct {
513 char nodename[REDIS_CLUSTER_NAMELEN];
514} clusterMsgDataFail;
515
c563ce46 516typedef struct {
517 uint32_t channel_len;
518 uint32_t message_len;
519 unsigned char bulk_data[8]; /* defined as 8 just for alignment concerns. */
520} clusterMsgDataPublish;
521
ecc91094 522union clusterMsgData {
523 /* PING, MEET and PONG */
524 struct {
525 /* Array of N clusterMsgDataGossip structures */
526 clusterMsgDataGossip gossip[1];
527 } ping;
c563ce46 528
ecc91094 529 /* FAIL */
530 struct {
531 clusterMsgDataFail about;
532 } fail;
c563ce46 533
534 /* PUBLISH */
535 struct {
536 clusterMsgDataPublish msg;
537 } publish;
ecc91094 538};
539
540typedef struct {
541 uint32_t totlen; /* Total length of this message */
542 uint16_t type; /* Message type */
543 uint16_t count; /* Only used for some kind of messages. */
544 char sender[REDIS_CLUSTER_NAMELEN]; /* Name of the sender node */
545 unsigned char myslots[REDIS_CLUSTER_SLOTS/8];
546 char slaveof[REDIS_CLUSTER_NAMELEN];
547 char configdigest[32];
548 uint16_t port; /* Sender TCP base port */
549 unsigned char state; /* Cluster state from the POV of the sender */
550 unsigned char notused[5]; /* Reserved for future use. For alignment. */
551 union clusterMsgData data;
552} clusterMsg;
553
554/*-----------------------------------------------------------------------------
555 * Global server state
556 *----------------------------------------------------------------------------*/
557
e2641e09 558struct redisServer {
5b831607 559 /* General */
5b831607 560 redisDb *db;
561 dict *commands; /* Command table hahs table */
562 aeEventLoop *el;
c6ac7d03 563 unsigned lruclock:22; /* Clock incrementing every minute, for LRU */
564 unsigned lruclock_padding:10;
565 int shutdown_asap; /* SHUTDOWN needed ASAP */
566 int activerehashing; /* Incremental rehash in serverCron() */
567 char *requirepass; /* Pass for AUTH command, or NULL */
568 char *pidfile; /* PID file path */
75eaac5c 569 int arch_bits; /* 32 or 64 depending on sizeof(long) */
5b831607 570 /* Networking */
c6ac7d03 571 int port; /* TCP listening port */
572 char *bindaddr; /* Bind address or NULL */
573 char *unixsocket; /* UNIX socket path */
574 mode_t unixsocketperm; /* UNIX socket permission */
575 int ipfd; /* TCP socket file descriptor */
576 int sofd; /* Unix socket file descriptor */
577 int cfd; /* Cluster bus lisetning socket */
578 list *clients; /* List of active clients */
7eac2a75 579 list *clients_to_close; /* Clients to close asynchronously */
c6ac7d03 580 list *slaves, *monitors; /* List of slaves and MONITORs */
00010fa9 581 redisClient *current_client; /* Current client, only used on crash report */
c6ac7d03 582 char neterr[ANET_ERR_LEN]; /* Error buffer for anet.c */
97e7f8ae 583 /* RDB / AOF loading information */
c6ac7d03 584 int loading; /* We are loading data from disk if true */
97e7f8ae 585 off_t loading_total_bytes;
586 off_t loading_loaded_bytes;
587 time_t loading_start_time;
4ebfc455 588 /* Fast pointers to often looked up command */
eeb34eff 589 struct redisCommand *delCommand, *multiCommand, *lpushCommand;
c6ac7d03 590 int cronloops; /* Number of times the cron function run */
53eeeaff 591 time_t lastsave; /* Unix time of last save succeeede */
e2641e09 592 /* Fields used only for stats */
c6ac7d03 593 time_t stat_starttime; /* Server start time */
594 long long stat_numcommands; /* Number of processed commands */
595 long long stat_numconnections; /* Number of connections received */
596 long long stat_expiredkeys; /* Number of expired keys */
597 long long stat_evictedkeys; /* Number of evicted keys (maxmemory) */
598 long long stat_keyspace_hits; /* Number of successful lookups of keys */
599 long long stat_keyspace_misses; /* Number of failed lookups of keys */
600 size_t stat_peak_memory; /* Max used memory record */
601 long long stat_fork_time; /* Time needed to perform latets fork() */
602 long long stat_rejected_conn; /* Clients rejected because of maxclients */
603 list *slowlog; /* SLOWLOG list of commands */
604 long long slowlog_entry_id; /* SLOWLOG current entry ID */
605 long long slowlog_log_slower_than; /* SLOWLOG time limit (to get logged) */
606 unsigned long slowlog_max_len; /* SLOWLOG max number of items logged */
e2641e09 607 /* Configuration */
c6ac7d03 608 int verbosity; /* Loglevel in redis.conf */
609 int maxidletime; /* Client timeout in seconds */
610 size_t client_max_querybuf_len; /* Limit for client query buffer length */
611 int dbnum; /* Total number of configured DBs */
612 int daemonize; /* True if running as a daemon */
7eac2a75 613 clientBufferLimitsConfig client_obuf_limits[REDIS_CLIENT_LIMIT_NUM_CLASSES];
c6ac7d03 614 /* AOF persistence */
615 int aof_state; /* REDIS_AOF_(ON|OFF|WAIT_REWRITE) */
2c915bcf 616 int aof_fsync; /* Kind of fsync() policy */
617 char *aof_filename; /* Name of the AOF file */
618 int aof_no_fsync_on_rewrite; /* Don't fsync if a rewrite is in prog. */
619 int aof_rewrite_perc; /* Rewrite AOF if % growth is > M and... */
620 off_t aof_rewrite_min_size; /* the AOF file is at least N bytes. */
621 off_t aof_rewrite_base_size; /* AOF size on latest startup or rewrite. */
622 off_t aof_current_size; /* AOF current size. */
623 int aof_rewrite_scheduled; /* Rewrite once BGSAVE terminates. */
ff2145ad 624 pid_t aof_child_pid; /* PID if rewriting process */
625 sds aof_rewrite_buf; /* buffer taken by parent during oppend only rewrite */
626 sds aof_buf; /* AOF buffer, written before entering the event loop */
627 int aof_fd; /* File descriptor of currently selected AOF file */
628 int aof_selected_db; /* Currently selected DB in AOF */
c6ac7d03 629 time_t aof_flush_postponed_start; /* UNIX time of postponed AOF flush */
ff2145ad 630 time_t aof_last_fsync; /* UNIX time of last fsync() */
c6ac7d03 631 /* RDB persistence */
632 long long dirty; /* Changes to DB from the last save */
633 long long dirty_before_bgsave; /* Used to restore dirty on failed BGSAVE */
f48cd4b9 634 pid_t rdb_child_pid; /* PID of RDB saving child */
c6ac7d03 635 struct saveparam *saveparams; /* Save points array for RDB */
636 int saveparamslen; /* Number of saving points */
f48cd4b9 637 char *rdb_filename; /* Name of RDB file */
638 int rdb_compression; /* Use compression in RDB? */
eeb34eff 639 /* Propagation of commands in AOF / replication */
78d6a22d 640 redisOpArray also_propagate; /* Additional command to propagate. */
36c17a53 641 /* Logging */
c6ac7d03 642 char *logfile; /* Path of log file */
643 int syslog_enabled; /* Is syslog enabled? */
644 char *syslog_ident; /* Syslog ident */
645 int syslog_facility; /* Syslog facility */
f4aa600b 646 /* Slave specific fields */
c6ac7d03 647 char *masterauth; /* AUTH with this password with master */
648 char *masterhost; /* Hostname of master */
649 int masterport; /* Port of master */
650 int repl_ping_slave_period; /* Master pings the salve every N seconds */
651 int repl_timeout; /* Timeout after N seconds of master idle */
652 redisClient *master; /* Client that is master for this slave */
653 int repl_syncio_timeout; /* Timeout for synchronous I/O calls */
1844f990 654 int repl_state; /* Replication status if the instance is a slave */
c6ac7d03 655 off_t repl_transfer_left; /* Bytes left reading .rdb */
656 int repl_transfer_s; /* Slave -> Master SYNC socket */
657 int repl_transfer_fd; /* Slave -> Master SYNC temp file descriptor */
658 char *repl_transfer_tmpfile; /* Slave-> master SYNC temp file name */
659 time_t repl_transfer_lastio; /* Unix time of the latest read, for timeout */
4ebfc455 660 int repl_serve_stale_data; /* Serve stale data when link is down? */
c6ac7d03 661 time_t repl_down_since; /* Unix time at which link with master went down */
f4aa600b 662 /* Limits */
c6ac7d03 663 unsigned int maxclients; /* Max number of simultaneous clients */
664 unsigned long long maxmemory; /* Max number of memory bytes to use */
665 int maxmemory_policy; /* Policy for key evition */
666 int maxmemory_samples; /* Pricision of random sampling */
f4aa600b 667 /* Blocked clients */
c6ac7d03 668 unsigned int bpop_blocked_clients; /* Number of clients blocked by lists */
cea8c5cd 669 list *unblocked_clients; /* list of clients to unblock before next loop */
e2641e09 670 /* Sort parameters - qsort_r() is only available under BSD so we
671 * have to take this state global, in order to pass it to sortCompare() */
2c861050 672 int sort_dontsort;
e2641e09 673 int sort_desc;
674 int sort_alpha;
675 int sort_bypattern;
c6ac7d03 676 /* Zip structure config, see redis.conf for more information */
e2641e09 677 size_t hash_max_zipmap_entries;
678 size_t hash_max_zipmap_value;
679 size_t list_max_ziplist_entries;
680 size_t list_max_ziplist_value;
96ffb2fe 681 size_t set_max_intset_entries;
3ea204e1
PN
682 size_t zset_max_ziplist_entries;
683 size_t zset_max_ziplist_value;
c6ac7d03 684 time_t unixtime; /* Unix time sampled every second. */
e2641e09 685 /* Pubsub */
c6ac7d03 686 dict *pubsub_channels; /* Map channels to list of subscribed clients */
687 list *pubsub_patterns; /* A list of pubsub_patterns */
c772d9c6 688 /* Cluster */
c6ac7d03 689 int cluster_enabled; /* Is cluster enabled? */
690 clusterState cluster; /* State of the cluster */
7585836e 691 /* Scripting */
4dd444bb 692 lua_State *lua; /* The Lua interpreter. We use just one for all clients */
c6ac7d03 693 redisClient *lua_client; /* The "fake client" to query Redis from Lua */
694 redisClient *lua_caller; /* The client running EVAL right now, or NULL */
695 dict *lua_scripts; /* A dictionary of SHA1 -> Lua scripts */
696 long long lua_time_limit; /* Script timeout in seconds */
697 long long lua_time_start; /* Start time of script */
4ab8695d 698 int lua_write_dirty; /* True if a write command was called during the
699 execution of the current script. */
9f772cc2 700 int lua_random_dirty; /* True if a random command was called during the
4ab8695d 701 execution of the current script. */
115e3ff3 702 int lua_timedout; /* True if we reached the time limit for script
703 execution. */
4ab8695d 704 int lua_kill; /* Kill the script if true. */
fa5af017 705 /* Assert & bug reportign */
706 char *assert_failed;
707 char *assert_file;
708 int assert_line;
c6ac7d03 709 int bug_report_start; /* True if bug report header was already logged. */
e2641e09 710};
711
712typedef struct pubsubPattern {
713 redisClient *client;
714 robj *pattern;
715} pubsubPattern;
716
717typedef void redisCommandProc(redisClient *c);
9791f0f8 718typedef int *redisGetKeysProc(struct redisCommand *cmd, robj **argv, int argc, int *numkeys, int flags);
e2641e09 719struct redisCommand {
720 char *name;
721 redisCommandProc *proc;
722 int arity;
5d02b00f 723 char *sflags; /* Flags as string represenation, one char per flag. */
724 int flags; /* The actual flags, obtained from the 'sflags' field. */
9791f0f8 725 /* Use a function to determine keys arguments in a command line.
c9d0c362 726 * Used for Redis Cluster redirect. */
9791f0f8 727 redisGetKeysProc *getkeys_proc;
e2641e09 728 /* What keys should be loaded in background when calling this command? */
9791f0f8 729 int firstkey; /* The first argument that's a key (0 = no keys) */
730 int lastkey; /* THe last argument that's a key */
731 int keystep; /* The step between first and last key */
0d808ef2 732 long long microseconds, calls;
e2641e09 733};
734
735struct redisFunctionSym {
736 char *name;
737 unsigned long pointer;
738};
739
740typedef struct _redisSortObject {
741 robj *obj;
742 union {
743 double score;
744 robj *cmpobj;
745 } u;
746} redisSortObject;
747
748typedef struct _redisSortOperation {
749 int type;
750 robj *pattern;
751} redisSortOperation;
752
e2641e09 753/* Structure to hold list iteration abstraction. */
754typedef struct {
755 robj *subject;
756 unsigned char encoding;
757 unsigned char direction; /* Iteration direction */
758 unsigned char *zi;
759 listNode *ln;
760} listTypeIterator;
761
762/* Structure for an entry while iterating over a list. */
763typedef struct {
764 listTypeIterator *li;
765 unsigned char *zi; /* Entry in ziplist */
766 listNode *ln; /* Entry in linked list */
767} listTypeEntry;
768
96ffb2fe
PN
769/* Structure to hold set iteration abstraction. */
770typedef struct {
771 robj *subject;
772 int encoding;
773 int ii; /* intset iterator */
774 dictIterator *di;
cb72d0f1 775} setTypeIterator;
96ffb2fe 776
e2641e09 777/* Structure to hold hash iteration abstration. Note that iteration over
778 * hashes involves both fields and values. Because it is possible that
779 * not both are required, store pointers in the iterator to avoid
780 * unnecessary memory allocation for fields/values. */
781typedef struct {
782 int encoding;
783 unsigned char *zi;
784 unsigned char *zk, *zv;
785 unsigned int zklen, zvlen;
786
787 dictIterator *di;
788 dictEntry *de;
789} hashTypeIterator;
790
791#define REDIS_HASH_KEY 1
792#define REDIS_HASH_VALUE 2
793
794/*-----------------------------------------------------------------------------
795 * Extern declarations
796 *----------------------------------------------------------------------------*/
797
798extern struct redisServer server;
799extern struct sharedObjectsStruct shared;
800extern dictType setDictType;
801extern dictType zsetDictType;
ecc91094 802extern dictType clusterNodesDictType;
4dd444bb 803extern dictType dbDictType;
e2641e09 804extern double R_Zero, R_PosInf, R_NegInf, R_Nan;
805dictType hashDictType;
806
807/*-----------------------------------------------------------------------------
808 * Functions prototypes
809 *----------------------------------------------------------------------------*/
810
419e1cca 811/* Utils */
812long long ustime(void);
2c2b2085 813long long mstime(void);
419e1cca 814
e2641e09 815/* networking.c -- Networking and Client related operations */
816redisClient *createClient(int fd);
817void closeTimedoutClients(void);
818void freeClient(redisClient *c);
819void resetClient(redisClient *c);
820void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask);
e2641e09 821void addReply(redisClient *c, robj *obj);
b301c1fc
PN
822void *addDeferredMultiBulkLength(redisClient *c);
823void setDeferredMultiBulkLength(redisClient *c, void *node, long length);
e2641e09 824void addReplySds(redisClient *c, sds s);
825void processInputBuffer(redisClient *c);
ab17b909
PN
826void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask);
827void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask);
e2641e09 828void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
829void addReplyBulk(redisClient *c, robj *obj);
830void addReplyBulkCString(redisClient *c, char *s);
d51ebef5 831void addReplyBulkCBuffer(redisClient *c, void *p, size_t len);
832void addReplyBulkLongLong(redisClient *c, long long ll);
e2641e09 833void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
834void addReply(redisClient *c, robj *obj);
835void addReplySds(redisClient *c, sds s);
3ab20376
PN
836void addReplyError(redisClient *c, char *err);
837void addReplyStatus(redisClient *c, char *status);
e2641e09 838void addReplyDouble(redisClient *c, double d);
839void addReplyLongLong(redisClient *c, long long ll);
0537e7bf 840void addReplyMultiBulkLen(redisClient *c, long length);
1824e3a3 841void copyClientOutputBuffer(redisClient *dst, redisClient *src);
e2641e09 842void *dupClientReplyValue(void *o);
7a1fd61e 843void getClientsMaxBuffers(unsigned long *longest_output_list,
844 unsigned long *biggest_input_buffer);
becf5fdb 845sds getClientInfoString(redisClient *client);
45e7a1ce 846sds getAllClientsInfoString(void);
c1c9d551 847void rewriteClientCommandVector(redisClient *c, int argc, ...);
4dd444bb 848void rewriteClientCommandArgument(redisClient *c, int i, robj *newval);
3853c168 849unsigned long getClientOutputBufferMemoryUsage(redisClient *c);
7eac2a75 850void freeClientsInAsyncFreeQueue(void);
06b3dced 851void asyncCloseClientOnOutputBufferLimitReached(redisClient *c);
7fe8d49a 852int getClientLimitClassByName(char *name);
853char *getClientLimitClassName(int class);
8b7c3455 854void flushSlavesOutputBuffers(void);
e2641e09 855
3ab20376
PN
856#ifdef __GNUC__
857void addReplyErrorFormat(redisClient *c, const char *fmt, ...)
858 __attribute__((format(printf, 2, 3)));
859void addReplyStatusFormat(redisClient *c, const char *fmt, ...)
860 __attribute__((format(printf, 2, 3)));
861#else
862void addReplyErrorFormat(redisClient *c, const char *fmt, ...);
863void addReplyStatusFormat(redisClient *c, const char *fmt, ...);
864#endif
865
e2641e09 866/* List data type */
867void listTypeTryConversion(robj *subject, robj *value);
868void listTypePush(robj *subject, robj *value, int where);
869robj *listTypePop(robj *subject, int where);
870unsigned long listTypeLength(robj *subject);
3c08fdae 871listTypeIterator *listTypeInitIterator(robj *subject, long index, unsigned char direction);
e2641e09 872void listTypeReleaseIterator(listTypeIterator *li);
873int listTypeNext(listTypeIterator *li, listTypeEntry *entry);
874robj *listTypeGet(listTypeEntry *entry);
875void listTypeInsert(listTypeEntry *entry, robj *value, int where);
876int listTypeEqual(listTypeEntry *entry, robj *o);
877void listTypeDelete(listTypeEntry *entry);
878void listTypeConvert(robj *subject, int enc);
879void unblockClientWaitingData(redisClient *c);
880int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
881void popGenericCommand(redisClient *c, int where);
882
883/* MULTI/EXEC/WATCH... */
884void unwatchAllKeys(redisClient *c);
885void initClientMultiState(redisClient *c);
886void freeClientMultiState(redisClient *c);
09e2d9ee 887void queueMultiCommand(redisClient *c);
e2641e09 888void touchWatchedKey(redisDb *db, robj *key);
889void touchWatchedKeysOnFlush(int dbid);
890
891/* Redis object implementation */
892void decrRefCount(void *o);
893void incrRefCount(robj *o);
4dd444bb 894robj *resetRefCount(robj *obj);
e2641e09 895void freeStringObject(robj *o);
896void freeListObject(robj *o);
897void freeSetObject(robj *o);
898void freeZsetObject(robj *o);
899void freeHashObject(robj *o);
900robj *createObject(int type, void *ptr);
901robj *createStringObject(char *ptr, size_t len);
902robj *dupStringObject(robj *o);
5d081931 903int isObjectRepresentableAsLongLong(robj *o, long long *llongval);
e2641e09 904robj *tryObjectEncoding(robj *o);
905robj *getDecodedObject(robj *o);
906size_t stringObjectLen(robj *o);
e2641e09 907robj *createStringObjectFromLongLong(long long value);
5574b53e 908robj *createStringObjectFromLongDouble(long double value);
e2641e09 909robj *createListObject(void);
910robj *createZiplistObject(void);
911robj *createSetObject(void);
96ffb2fe 912robj *createIntsetObject(void);
e2641e09 913robj *createHashObject(void);
914robj *createZsetObject(void);
9e7cee0e 915robj *createZsetZiplistObject(void);
e2641e09 916int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg);
917int checkType(redisClient *c, robj *o, int type);
918int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg);
919int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg);
920int getLongLongFromObject(robj *o, long long *target);
5574b53e 921int getLongDoubleFromObject(robj *o, long double *target);
922int getLongDoubleFromObjectOrReply(redisClient *c, robj *o, long double *target, const char *msg);
e2641e09 923char *strEncoding(int encoding);
924int compareStringObjects(robj *a, robj *b);
925int equalStringObjects(robj *a, robj *b);
ef59a8bc 926unsigned long estimateObjectIdleTime(robj *o);
e2641e09 927
19e61097 928/* Synchronous I/O with timeout */
929int syncWrite(int fd, char *ptr, ssize_t size, int timeout);
930int syncRead(int fd, char *ptr, ssize_t size, int timeout);
931int syncReadLine(int fd, char *ptr, ssize_t size, int timeout);
932
e2641e09 933/* Replication */
934void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
935void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
e2641e09 936void updateSlavesWaitingBgsave(int bgsaveerr);
f4aa600b 937void replicationCron(void);
e2641e09 938
97e7f8ae 939/* Generic persistence functions */
940void startLoading(FILE *fp);
941void loadingProgress(off_t pos);
942void stopLoading(void);
943
e2641e09 944/* RDB persistence */
2e4b0e77 945#include "rdb.h"
e2641e09 946
947/* AOF persistence */
a3fcd6bc 948void flushAppendOnlyFile(int force);
e2641e09 949void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
950void aofRemoveTempFile(pid_t childpid);
951int rewriteAppendOnlyFileBackground(void);
952int loadAppendOnlyFile(char *filename);
953void stopAppendOnly(void);
954int startAppendOnly(void);
36c17a53 955void backgroundRewriteDoneHandler(int exitcode, int bysignal);
e2641e09 956
957/* Sorted sets data type */
c772d9c6 958
959/* Struct to hold a inclusive/exclusive range spec. */
960typedef struct {
961 double min, max;
962 int minex, maxex; /* are min or max exclusive? */
963} zrangespec;
964
e2641e09 965zskiplist *zslCreate(void);
966void zslFree(zskiplist *zsl);
69ef89f2 967zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj);
8588bfa3 968unsigned char *zzlInsert(unsigned char *zl, robj *ele, double score);
c772d9c6 969int zslDelete(zskiplist *zsl, double score, robj *obj);
970zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec range);
dddf5335
PN
971double zzlGetScore(unsigned char *sptr);
972void zzlNext(unsigned char *zl, unsigned char **eptr, unsigned char **sptr);
973void zzlPrev(unsigned char *zl, unsigned char **eptr, unsigned char **sptr);
df26a0ae
PN
974unsigned int zsetLength(robj *zobj);
975void zsetConvert(robj *zobj, int encoding);
e2641e09 976
977/* Core functions */
f6b32c14 978int freeMemoryIfNeeded(void);
e2641e09 979int processCommand(redisClient *c);
633a9410 980void setupSignalHandlers(void);
1b1f47c9 981struct redisCommand *lookupCommand(sds name);
982struct redisCommand *lookupCommandByCString(char *s);
ce8b772b 983void call(redisClient *c, int flags);
d8b1228b 984void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int flags);
eeb34eff 985void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int target);
e2641e09 986int prepareForShutdown();
987void redisLog(int level, const char *fmt, ...);
288f811f 988void redisLogRaw(int level, const char *msg);
e2641e09 989void usage();
990void updateDictResizePolicy(void);
991int htNeedsResize(dict *dict);
992void oom(const char *msg);
1b1f47c9 993void populateCommandTable(void);
d7ed7fd2 994void resetCommandTableStats(void);
e2641e09 995
96ffb2fe
PN
996/* Set data type */
997robj *setTypeCreate(robj *value);
998int setTypeAdd(robj *subject, robj *value);
999int setTypeRemove(robj *subject, robj *value);
1000int setTypeIsMember(robj *subject, robj *value);
cb72d0f1
PN
1001setTypeIterator *setTypeInitIterator(robj *subject);
1002void setTypeReleaseIterator(setTypeIterator *si);
1b508da7 1003int setTypeNext(setTypeIterator *si, robj **objele, int64_t *llele);
1004robj *setTypeNextObject(setTypeIterator *si);
dd48de74 1005int setTypeRandomElement(robj *setobj, robj **objele, int64_t *llele);
96ffb2fe
PN
1006unsigned long setTypeSize(robj *subject);
1007void setTypeConvert(robj *subject, int enc);
1008
e2641e09 1009/* Hash data type */
1010void convertToRealHash(robj *o);
1011void hashTypeTryConversion(robj *subject, robj **argv, int start, int end);
1012void hashTypeTryObjectEncoding(robj *subject, robj **o1, robj **o2);
3d24304f 1013int hashTypeGet(robj *o, robj *key, robj **objval, unsigned char **v, unsigned int *vlen);
1014robj *hashTypeGetObject(robj *o, robj *key);
e2641e09 1015int hashTypeExists(robj *o, robj *key);
1016int hashTypeSet(robj *o, robj *key, robj *value);
1017int hashTypeDelete(robj *o, robj *key);
1018unsigned long hashTypeLength(robj *o);
1019hashTypeIterator *hashTypeInitIterator(robj *subject);
1020void hashTypeReleaseIterator(hashTypeIterator *hi);
1021int hashTypeNext(hashTypeIterator *hi);
8c304be3 1022int hashTypeCurrent(hashTypeIterator *hi, int what, robj **objval, unsigned char **v, unsigned int *vlen);
1023robj *hashTypeCurrentObject(hashTypeIterator *hi, int what);
e2641e09 1024robj *hashTypeLookupWriteOrCreate(redisClient *c, robj *key);
1025
1026/* Pub / Sub */
1027int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
1028int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
1029void freePubsubPattern(void *p);
1030int listMatchPubsubPattern(void *a, void *b);
d38ef520 1031int pubsubPublishMessage(robj *channel, robj *message);
e2641e09 1032
e2641e09 1033/* Configuration */
67c6f0f6 1034void loadServerConfig(char *filename, char *options);
e2641e09 1035void appendServerSaveParams(time_t seconds, int changes);
1036void resetServerSaveParams();
1037
1038/* db.c -- Keyspace access API */
1039int removeExpire(redisDb *db, robj *key);
bcf2995c 1040void propagateExpire(redisDb *db, robj *key);
e2641e09 1041int expireIfNeeded(redisDb *db, robj *key);
7dcc10b6 1042long long getExpire(redisDb *db, robj *key);
1043void setExpire(redisDb *db, robj *key, long long when);
e2641e09 1044robj *lookupKey(redisDb *db, robj *key);
1045robj *lookupKeyRead(redisDb *db, robj *key);
1046robj *lookupKeyWrite(redisDb *db, robj *key);
1047robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply);
1048robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply);
f85cd526 1049void dbAdd(redisDb *db, robj *key, robj *val);
1050void dbOverwrite(redisDb *db, robj *key, robj *val);
1051void setKey(redisDb *db, robj *key, robj *val);
e2641e09 1052int dbExists(redisDb *db, robj *key);
1053robj *dbRandomKey(redisDb *db);
1054int dbDelete(redisDb *db, robj *key);
1055long long emptyDb();
1056int selectDb(redisClient *c, int id);
cea8c5cd 1057void signalModifiedKey(redisDb *db, robj *key);
1058void signalFlushedDb(int dbid);
484354ff 1059unsigned int GetKeysInSlot(unsigned int hashslot, robj **keys, unsigned int count);
e2641e09 1060
9791f0f8 1061/* API to get key arguments from commands */
1062#define REDIS_GETKEYS_ALL 0
1063#define REDIS_GETKEYS_PRELOAD 1
1064int *getKeysFromCommand(struct redisCommand *cmd, robj **argv, int argc, int *numkeys, int flags);
1065void getKeysFreeResult(int *result);
1066int *noPreloadGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags);
1067int *renameGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags);
1068int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags);
1069
ecc91094 1070/* Cluster */
1071void clusterInit(void);
1072unsigned short crc16(const char *buf, int len);
1073unsigned int keyHashSlot(char *key, int keylen);
1074clusterNode *createClusterNode(char *nodename, int flags);
1075int clusterAddNode(clusterNode *node);
1076void clusterCron(void);
eda827f8 1077clusterNode *getNodeByQuery(redisClient *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot, int *ask);
c563ce46 1078void clusterPropagatePublish(robj *channel, robj *message);
ecc91094 1079
7585836e 1080/* Scripting */
1081void scriptingInit(void);
1082
e2641e09 1083/* Git SHA1 */
1084char *redisGitSHA1(void);
1085char *redisGitDirty(void);
1086
1087/* Commands prototypes */
1088void authCommand(redisClient *c);
1089void pingCommand(redisClient *c);
1090void echoCommand(redisClient *c);
1091void setCommand(redisClient *c);
1092void setnxCommand(redisClient *c);
1093void setexCommand(redisClient *c);
12d293ca 1094void psetexCommand(redisClient *c);
e2641e09 1095void getCommand(redisClient *c);
1096void delCommand(redisClient *c);
1097void existsCommand(redisClient *c);
3c1bf495
PN
1098void setbitCommand(redisClient *c);
1099void getbitCommand(redisClient *c);
9f9e1cea 1100void setrangeCommand(redisClient *c);
ef11bccc 1101void getrangeCommand(redisClient *c);
e2641e09 1102void incrCommand(redisClient *c);
1103void decrCommand(redisClient *c);
1104void incrbyCommand(redisClient *c);
1105void decrbyCommand(redisClient *c);
5574b53e 1106void incrbyfloatCommand(redisClient *c);
e2641e09 1107void selectCommand(redisClient *c);
1108void randomkeyCommand(redisClient *c);
1109void keysCommand(redisClient *c);
1110void dbsizeCommand(redisClient *c);
1111void lastsaveCommand(redisClient *c);
1112void saveCommand(redisClient *c);
1113void bgsaveCommand(redisClient *c);
1114void bgrewriteaofCommand(redisClient *c);
1115void shutdownCommand(redisClient *c);
1116void moveCommand(redisClient *c);
1117void renameCommand(redisClient *c);
1118void renamenxCommand(redisClient *c);
1119void lpushCommand(redisClient *c);
1120void rpushCommand(redisClient *c);
1121void lpushxCommand(redisClient *c);
1122void rpushxCommand(redisClient *c);
1123void linsertCommand(redisClient *c);
1124void lpopCommand(redisClient *c);
1125void rpopCommand(redisClient *c);
1126void llenCommand(redisClient *c);
1127void lindexCommand(redisClient *c);
1128void lrangeCommand(redisClient *c);
1129void ltrimCommand(redisClient *c);
1130void typeCommand(redisClient *c);
1131void lsetCommand(redisClient *c);
1132void saddCommand(redisClient *c);
1133void sremCommand(redisClient *c);
1134void smoveCommand(redisClient *c);
1135void sismemberCommand(redisClient *c);
1136void scardCommand(redisClient *c);
1137void spopCommand(redisClient *c);
1138void srandmemberCommand(redisClient *c);
1139void sinterCommand(redisClient *c);
1140void sinterstoreCommand(redisClient *c);
1141void sunionCommand(redisClient *c);
1142void sunionstoreCommand(redisClient *c);
1143void sdiffCommand(redisClient *c);
1144void sdiffstoreCommand(redisClient *c);
1145void syncCommand(redisClient *c);
1146void flushdbCommand(redisClient *c);
1147void flushallCommand(redisClient *c);
1148void sortCommand(redisClient *c);
1149void lremCommand(redisClient *c);
8a979f03 1150void rpoplpushCommand(redisClient *c);
e2641e09 1151void infoCommand(redisClient *c);
1152void mgetCommand(redisClient *c);
1153void monitorCommand(redisClient *c);
1154void expireCommand(redisClient *c);
1155void expireatCommand(redisClient *c);
12d293ca 1156void pexpireCommand(redisClient *c);
1157void pexpireatCommand(redisClient *c);
e2641e09 1158void getsetCommand(redisClient *c);
1159void ttlCommand(redisClient *c);
12d293ca 1160void pttlCommand(redisClient *c);
a539d29a 1161void persistCommand(redisClient *c);
e2641e09 1162void slaveofCommand(redisClient *c);
1163void debugCommand(redisClient *c);
1164void msetCommand(redisClient *c);
1165void msetnxCommand(redisClient *c);
1166void zaddCommand(redisClient *c);
1167void zincrbyCommand(redisClient *c);
1168void zrangeCommand(redisClient *c);
1169void zrangebyscoreCommand(redisClient *c);
25bb8a44 1170void zrevrangebyscoreCommand(redisClient *c);
e2641e09 1171void zcountCommand(redisClient *c);
1172void zrevrangeCommand(redisClient *c);
1173void zcardCommand(redisClient *c);
1174void zremCommand(redisClient *c);
1175void zscoreCommand(redisClient *c);
1176void zremrangebyscoreCommand(redisClient *c);
1177void multiCommand(redisClient *c);
1178void execCommand(redisClient *c);
1179void discardCommand(redisClient *c);
1180void blpopCommand(redisClient *c);
1181void brpopCommand(redisClient *c);
b2a7fd0c 1182void brpoplpushCommand(redisClient *c);
e2641e09 1183void appendCommand(redisClient *c);
80091bba 1184void strlenCommand(redisClient *c);
e2641e09 1185void zrankCommand(redisClient *c);
1186void zrevrankCommand(redisClient *c);
1187void hsetCommand(redisClient *c);
1188void hsetnxCommand(redisClient *c);
1189void hgetCommand(redisClient *c);
1190void hmsetCommand(redisClient *c);
1191void hmgetCommand(redisClient *c);
1192void hdelCommand(redisClient *c);
1193void hlenCommand(redisClient *c);
1194void zremrangebyrankCommand(redisClient *c);
1195void zunionstoreCommand(redisClient *c);
1196void zinterstoreCommand(redisClient *c);
1197void hkeysCommand(redisClient *c);
1198void hvalsCommand(redisClient *c);
1199void hgetallCommand(redisClient *c);
1200void hexistsCommand(redisClient *c);
1201void configCommand(redisClient *c);
1202void hincrbyCommand(redisClient *c);
68bfe993 1203void hincrbyfloatCommand(redisClient *c);
e2641e09 1204void subscribeCommand(redisClient *c);
1205void unsubscribeCommand(redisClient *c);
1206void psubscribeCommand(redisClient *c);
1207void punsubscribeCommand(redisClient *c);
1208void publishCommand(redisClient *c);
1209void watchCommand(redisClient *c);
1210void unwatchCommand(redisClient *c);
ecc91094 1211void clusterCommand(redisClient *c);
1212void restoreCommand(redisClient *c);
1213void migrateCommand(redisClient *c);
6856c7b4 1214void askingCommand(redisClient *c);
626f6b2d 1215void dumpCommand(redisClient *c);
ece74202 1216void objectCommand(redisClient *c);
3cd12b56 1217void clientCommand(redisClient *c);
7585836e 1218void evalCommand(redisClient *c);
7229d60d 1219void evalShaCommand(redisClient *c);
070e3945 1220void scriptCommand(redisClient *c);
e2641e09 1221
b3aa6d71 1222#if defined(__GNUC__)
b3aa6d71 1223void *calloc(size_t count, size_t size) __attribute__ ((deprecated));
1224void free(void *ptr) __attribute__ ((deprecated));
1225void *malloc(size_t size) __attribute__ ((deprecated));
1226void *realloc(void *ptr, size_t size) __attribute__ ((deprecated));
1227#endif
1228
e3e69935 1229/* Debugging stuff */
bab205f7 1230void _redisAssertWithInfo(redisClient *c, robj *o, char *estr, char *file, int line);
e3e69935 1231void _redisAssert(char *estr, char *file, int line);
1232void _redisPanic(char *msg, char *file, int line);
fa5af017 1233void bugReportStart(void);
00010fa9 1234void redisLogObjectDebugInfo(robj *o);
d4d20859 1235void sigsegvHandler(int sig, siginfo_t *info, void *secret);
1236sds genRedisInfoString(char *section);
e2641e09 1237#endif