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