]> git.saurik.com Git - redis.git/blob - src/redis.h
870439d7b01d3b83c929bebe2eb4f7d2db15238d
[redis.git] / src / redis.h
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>
18 #include <inttypes.h>
19 #include <pthread.h>
20 #include <syslog.h>
21 #include <netinet/in.h>
22 #include <lua.h>
23 #include <signal.h>
24
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 */
29 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
30 #include "anet.h" /* Networking the easy way */
31 #include "zipmap.h" /* Compact string -> string data structure */
32 #include "ziplist.h" /* Compact list data structure */
33 #include "intset.h" /* Compact integer set structure */
34 #include "version.h" /* Version macro */
35 #include "util.h" /* Misc functions useful in many places */
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 */
43 #define REDIS_MAXIDLETIME 0 /* default client timeout: infinite */
44 #define REDIS_DEFAULT_DBNUM 16
45 #define REDIS_CONFIGLINE_MAX 1024
46 #define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
47 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
48 #define REDIS_SHARED_INTEGERS 10000
49 #define REDIS_SHARED_BULKHDR_LEN 32
50 #define REDIS_MAX_LOGMSG_LEN 1024 /* Default maximum length of syslog messages */
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
54 #define REDIS_SLOWLOG_LOG_SLOWER_THAN 10000
55 #define REDIS_SLOWLOG_MAX_LEN 64
56 #define REDIS_MAX_CLIENTS 10000
57
58 #define REDIS_REPL_TIMEOUT 60
59 #define REDIS_REPL_PING_SLAVE_PERIOD 10
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 */
65 #define REDIS_INLINE_MAX_SIZE (1024*64) /* Max size of inline reads */
66 #define REDIS_MBULK_BIG_ARG (1024*32)
67
68 /* Hash table parameters */
69 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
70
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 */
79 #define REDIS_CMD_NOSCRIPT 64 /* "s" flag */
80 #define REDIS_CMD_RANDOM 128 /* "R" flag */
81 #define REDIS_CMD_SORT_FOR_SCRIPT 256 /* "S" flag */
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
90
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 */
100 #define REDIS_ENCODING_INTSET 6 /* Encoded as intset */
101 #define REDIS_ENCODING_SKIPLIST 7 /* Encoded as skiplist */
102
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
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
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 */
141 #define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
142 #define REDIS_CLOSE_AFTER_REPLY 128 /* Close after writing entire reply. */
143 #define REDIS_UNBLOCKED 256 /* This client was unblocked and is stored in
144 server.unblocked_clients */
145 #define REDIS_LUA_CLIENT 512 /* This is a non connected client used by Lua */
146 #define REDIS_ASKING 1024 /* Client issued the ASKING command */
147 #define REDIS_CLOSE_ASAP 2048 /* Close this client ASAP */
148
149 /* Client request types */
150 #define REDIS_REQ_INLINE 1
151 #define REDIS_REQ_MULTIBULK 2
152
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
158 #define REDIS_CLIENT_LIMIT_NUM_CLASSES 3
159
160 /* Slave replication state - slave side */
161 #define REDIS_REPL_NONE 0 /* No active replication */
162 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
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 */
166
167 /* Synchronous read timeout - slave side */
168 #define REDIS_REPL_SYNCIO_TIMEOUT 5
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
194 #define REDIS_LOG_RAW (1<<10) /* Modifier to log without timestamp */
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 */
203 #define AOF_FSYNC_NO 0
204 #define AOF_FSYNC_ALWAYS 1
205 #define AOF_FSYNC_EVERYSEC 2
206
207 /* Zip structure related defaults */
208 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 512
209 #define REDIS_HASH_MAX_ZIPMAP_VALUE 64
210 #define REDIS_LIST_MAX_ZIPLIST_ENTRIES 512
211 #define REDIS_LIST_MAX_ZIPLIST_VALUE 64
212 #define REDIS_SET_MAX_INTSET_ENTRIES 512
213 #define REDIS_ZSET_MAX_ZIPLIST_ENTRIES 128
214 #define REDIS_ZSET_MAX_ZIPLIST_VALUE 64
215
216 /* Sets operations codes */
217 #define REDIS_OP_UNION 0
218 #define REDIS_OP_DIFF 1
219 #define REDIS_OP_INTER 2
220
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
227 #define REDIS_MAXMEMORY_NO_EVICTION 5
228
229 /* Scripting */
230 #define REDIS_LUA_TIME_LIMIT 5000 /* milliseconds */
231
232 /* Units */
233 #define UNIT_SECONDS 0
234 #define UNIT_MILLISECONDS 1
235
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
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
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
253 /* We can print the stacktrace, so our assert is defined this way: */
254 #define redisAssertWithInfo(_c,_o,_e) ((_e)?(void)0 : (_redisAssertWithInfo(_c,_o,#_e,__FILE__,__LINE__),_exit(1)))
255 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
256 #define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
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 */
265 #define REDIS_LRU_CLOCK_MAX ((1<<21)-1) /* Max value of obj->lru */
266 #define REDIS_LRU_CLOCK_RESOLUTION 10 /* LRU clock resolution in seconds */
267 typedef struct redisObject {
268 unsigned type:4;
269 unsigned notused:2; /* Not used */
270 unsigned encoding:4;
271 unsigned lru:22; /* lru time (relative to server.lruclock) */
272 int refcount;
273 void *ptr;
274 } robj;
275
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; \
285 } while(0);
286
287 typedef 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) */
291 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
292 int id;
293 } redisDb;
294
295 /* Client MULTI/EXEC state */
296 typedef struct multiCmd {
297 robj **argv;
298 int argc;
299 struct redisCommand *cmd;
300 } multiCmd;
301
302 typedef struct multiState {
303 multiCmd *commands; /* Array of MULTI commands */
304 int count; /* Total number of MULTI commands */
305 } multiState;
306
307 typedef 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
317 /* With multiplexing we need to take per-clinet state.
318 * Clients are taken in a liked list. */
319 typedef struct redisClient {
320 int fd;
321 redisDb *db;
322 int dictid;
323 sds querybuf;
324 int argc;
325 robj **argv;
326 struct redisCommand *cmd, *lastcmd;
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 */
330 list *reply;
331 unsigned long reply_bytes; /* Tot bytes of objects in reply list */
332 int sentlen;
333 time_t lastinteraction; /* time of the last interaction, used for timeout */
334 time_t obuf_soft_limit_reached_time;
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 */
343 blockingState bpop; /* blocking state */
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) */
349
350 /* Response buffer */
351 int bufpos;
352 char buf[REDIS_REPLY_CHUNK_BYTES];
353 } redisClient;
354
355 struct saveparam {
356 time_t seconds;
357 int changes;
358 };
359
360 struct sharedObjectsStruct {
361 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *cnegone, *pong, *space,
362 *colon, *nullbulk, *nullmultibulk, *queued,
363 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
364 *outofrangeerr, *noscripterr, *loadingerr, *slowscripterr, *plus,
365 *select0, *select1, *select2, *select3, *select4,
366 *select5, *select6, *select7, *select8, *select9,
367 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk,
368 *psubscribebulk, *punsubscribebulk, *del, *rpop, *lpop,
369 *integers[REDIS_SHARED_INTEGERS],
370 *mbulkhdr[REDIS_SHARED_BULKHDR_LEN], /* "*<value>\r\n" */
371 *bulkhdr[REDIS_SHARED_BULKHDR_LEN]; /* "$<value>\r\n" */
372 };
373
374 /* ZSETs use a specialized version of Skiplists */
375 typedef 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
385 typedef struct zskiplist {
386 struct zskiplistNode *header, *tail;
387 unsigned long length;
388 int level;
389 } zskiplist;
390
391 typedef struct zset {
392 dict *dict;
393 zskiplist *zsl;
394 } zset;
395
396 typedef struct clientBufferLimitsConfig {
397 unsigned long long hard_limit_bytes;
398 unsigned long long soft_limit_bytes;
399 time_t soft_limit_seconds;
400 } clientBufferLimitsConfig;
401
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. */
408 typedef struct redisOp {
409 robj **argv;
410 int argc, dbid, target;
411 struct redisCommand *cmd;
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 */
421 typedef struct redisOpArray {
422 redisOp *ops;
423 int numops;
424 } redisOpArray;
425
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
437 struct clusterNode;
438
439 /* clusterLink encapsulates everything needed to talk with a remote node. */
440 typedef 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
458 struct 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 };
473 typedef struct clusterNode clusterNode;
474
475 typedef struct {
476 char *configfile;
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];
484 zskiplist *slots_to_keys;
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 */
497 #define CLUSTERMSG_TYPE_PUBLISH 4 /* Pub/Sub Publish propatagion */
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. */
502 typedef 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
512 typedef struct {
513 char nodename[REDIS_CLUSTER_NAMELEN];
514 } clusterMsgDataFail;
515
516 typedef 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
522 union clusterMsgData {
523 /* PING, MEET and PONG */
524 struct {
525 /* Array of N clusterMsgDataGossip structures */
526 clusterMsgDataGossip gossip[1];
527 } ping;
528
529 /* FAIL */
530 struct {
531 clusterMsgDataFail about;
532 } fail;
533
534 /* PUBLISH */
535 struct {
536 clusterMsgDataPublish msg;
537 } publish;
538 };
539
540 typedef 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
558 struct redisServer {
559 /* General */
560 redisDb *db;
561 dict *commands; /* Command table hahs table */
562 aeEventLoop *el;
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 */
569 int arch_bits; /* 32 or 64 depending on sizeof(long) */
570 /* Networking */
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 */
579 list *clients_to_close; /* Clients to close asynchronously */
580 list *slaves, *monitors; /* List of slaves and MONITORs */
581 redisClient *current_client; /* Current client, only used on crash report */
582 char neterr[ANET_ERR_LEN]; /* Error buffer for anet.c */
583 /* RDB / AOF loading information */
584 int loading; /* We are loading data from disk if true */
585 off_t loading_total_bytes;
586 off_t loading_loaded_bytes;
587 time_t loading_start_time;
588 /* Fast pointers to often looked up command */
589 struct redisCommand *delCommand, *multiCommand, *lpushCommand;
590 int cronloops; /* Number of times the cron function run */
591 time_t lastsave; /* Unix time of last save succeeede */
592 /* Fields used only for stats */
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 */
607 /* Configuration */
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 */
613 clientBufferLimitsConfig client_obuf_limits[REDIS_CLIENT_LIMIT_NUM_CLASSES];
614 /* AOF persistence */
615 int aof_state; /* REDIS_AOF_(ON|OFF|WAIT_REWRITE) */
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. */
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 */
629 time_t aof_flush_postponed_start; /* UNIX time of postponed AOF flush */
630 time_t aof_last_fsync; /* UNIX time of last fsync() */
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 */
634 pid_t rdb_child_pid; /* PID of RDB saving child */
635 struct saveparam *saveparams; /* Save points array for RDB */
636 int saveparamslen; /* Number of saving points */
637 char *rdb_filename; /* Name of RDB file */
638 int rdb_compression; /* Use compression in RDB? */
639 /* Propagation of commands in AOF / replication */
640 redisOpArray also_propagate; /* Additional command to propagate. */
641 /* Logging */
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 */
646 /* Slave specific fields */
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 */
654 int repl_state; /* Replication status if the instance is a slave */
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 */
660 int repl_serve_stale_data; /* Serve stale data when link is down? */
661 time_t repl_down_since; /* Unix time at which link with master went down */
662 /* Limits */
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 */
667 /* Blocked clients */
668 unsigned int bpop_blocked_clients; /* Number of clients blocked by lists */
669 list *unblocked_clients; /* list of clients to unblock before next loop */
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() */
672 int sort_dontsort;
673 int sort_desc;
674 int sort_alpha;
675 int sort_bypattern;
676 /* Zip structure config, see redis.conf for more information */
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;
681 size_t set_max_intset_entries;
682 size_t zset_max_ziplist_entries;
683 size_t zset_max_ziplist_value;
684 time_t unixtime; /* Unix time sampled every second. */
685 /* Pubsub */
686 dict *pubsub_channels; /* Map channels to list of subscribed clients */
687 list *pubsub_patterns; /* A list of pubsub_patterns */
688 /* Cluster */
689 int cluster_enabled; /* Is cluster enabled? */
690 clusterState cluster; /* State of the cluster */
691 /* Scripting */
692 lua_State *lua; /* The Lua interpreter. We use just one for all clients */
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 */
698 int lua_write_dirty; /* True if a write command was called during the
699 execution of the current script. */
700 int lua_random_dirty; /* True if a random command was called during the
701 execution of the current script. */
702 int lua_timedout; /* True if we reached the time limit for script
703 execution. */
704 int lua_kill; /* Kill the script if true. */
705 /* Assert & bug reportign */
706 char *assert_failed;
707 char *assert_file;
708 int assert_line;
709 int bug_report_start; /* True if bug report header was already logged. */
710 };
711
712 typedef struct pubsubPattern {
713 redisClient *client;
714 robj *pattern;
715 } pubsubPattern;
716
717 typedef void redisCommandProc(redisClient *c);
718 typedef int *redisGetKeysProc(struct redisCommand *cmd, robj **argv, int argc, int *numkeys, int flags);
719 struct redisCommand {
720 char *name;
721 redisCommandProc *proc;
722 int arity;
723 char *sflags; /* Flags as string represenation, one char per flag. */
724 int flags; /* The actual flags, obtained from the 'sflags' field. */
725 /* Use a function to determine keys arguments in a command line.
726 * Used for Redis Cluster redirect. */
727 redisGetKeysProc *getkeys_proc;
728 /* What keys should be loaded in background when calling this command? */
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 */
732 long long microseconds, calls;
733 };
734
735 struct redisFunctionSym {
736 char *name;
737 unsigned long pointer;
738 };
739
740 typedef struct _redisSortObject {
741 robj *obj;
742 union {
743 double score;
744 robj *cmpobj;
745 } u;
746 } redisSortObject;
747
748 typedef struct _redisSortOperation {
749 int type;
750 robj *pattern;
751 } redisSortOperation;
752
753 /* Structure to hold list iteration abstraction. */
754 typedef 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. */
763 typedef struct {
764 listTypeIterator *li;
765 unsigned char *zi; /* Entry in ziplist */
766 listNode *ln; /* Entry in linked list */
767 } listTypeEntry;
768
769 /* Structure to hold set iteration abstraction. */
770 typedef struct {
771 robj *subject;
772 int encoding;
773 int ii; /* intset iterator */
774 dictIterator *di;
775 } setTypeIterator;
776
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. */
781 typedef 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
798 extern struct redisServer server;
799 extern struct sharedObjectsStruct shared;
800 extern dictType setDictType;
801 extern dictType zsetDictType;
802 extern dictType clusterNodesDictType;
803 extern dictType dbDictType;
804 extern double R_Zero, R_PosInf, R_NegInf, R_Nan;
805 dictType hashDictType;
806
807 /*-----------------------------------------------------------------------------
808 * Functions prototypes
809 *----------------------------------------------------------------------------*/
810
811 /* Utils */
812 long long ustime(void);
813 long long mstime(void);
814
815 /* networking.c -- Networking and Client related operations */
816 redisClient *createClient(int fd);
817 void closeTimedoutClients(void);
818 void freeClient(redisClient *c);
819 void resetClient(redisClient *c);
820 void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask);
821 void addReply(redisClient *c, robj *obj);
822 void *addDeferredMultiBulkLength(redisClient *c);
823 void setDeferredMultiBulkLength(redisClient *c, void *node, long length);
824 void addReplySds(redisClient *c, sds s);
825 void processInputBuffer(redisClient *c);
826 void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask);
827 void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask);
828 void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
829 void addReplyBulk(redisClient *c, robj *obj);
830 void addReplyBulkCString(redisClient *c, char *s);
831 void addReplyBulkCBuffer(redisClient *c, void *p, size_t len);
832 void addReplyBulkLongLong(redisClient *c, long long ll);
833 void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
834 void addReply(redisClient *c, robj *obj);
835 void addReplySds(redisClient *c, sds s);
836 void addReplyError(redisClient *c, char *err);
837 void addReplyStatus(redisClient *c, char *status);
838 void addReplyDouble(redisClient *c, double d);
839 void addReplyLongLong(redisClient *c, long long ll);
840 void addReplyMultiBulkLen(redisClient *c, long length);
841 void copyClientOutputBuffer(redisClient *dst, redisClient *src);
842 void *dupClientReplyValue(void *o);
843 void getClientsMaxBuffers(unsigned long *longest_output_list,
844 unsigned long *biggest_input_buffer);
845 sds getClientInfoString(redisClient *client);
846 sds getAllClientsInfoString(void);
847 void rewriteClientCommandVector(redisClient *c, int argc, ...);
848 void rewriteClientCommandArgument(redisClient *c, int i, robj *newval);
849 unsigned long getClientOutputBufferMemoryUsage(redisClient *c);
850 void freeClientsInAsyncFreeQueue(void);
851 void asyncCloseClientOnOutputBufferLimitReached(redisClient *c);
852 int getClientLimitClassByName(char *name);
853 char *getClientLimitClassName(int class);
854 void flushSlavesOutputBuffers(void);
855
856 #ifdef __GNUC__
857 void addReplyErrorFormat(redisClient *c, const char *fmt, ...)
858 __attribute__((format(printf, 2, 3)));
859 void addReplyStatusFormat(redisClient *c, const char *fmt, ...)
860 __attribute__((format(printf, 2, 3)));
861 #else
862 void addReplyErrorFormat(redisClient *c, const char *fmt, ...);
863 void addReplyStatusFormat(redisClient *c, const char *fmt, ...);
864 #endif
865
866 /* List data type */
867 void listTypeTryConversion(robj *subject, robj *value);
868 void listTypePush(robj *subject, robj *value, int where);
869 robj *listTypePop(robj *subject, int where);
870 unsigned long listTypeLength(robj *subject);
871 listTypeIterator *listTypeInitIterator(robj *subject, long index, unsigned char direction);
872 void listTypeReleaseIterator(listTypeIterator *li);
873 int listTypeNext(listTypeIterator *li, listTypeEntry *entry);
874 robj *listTypeGet(listTypeEntry *entry);
875 void listTypeInsert(listTypeEntry *entry, robj *value, int where);
876 int listTypeEqual(listTypeEntry *entry, robj *o);
877 void listTypeDelete(listTypeEntry *entry);
878 void listTypeConvert(robj *subject, int enc);
879 void unblockClientWaitingData(redisClient *c);
880 int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
881 void popGenericCommand(redisClient *c, int where);
882
883 /* MULTI/EXEC/WATCH... */
884 void unwatchAllKeys(redisClient *c);
885 void initClientMultiState(redisClient *c);
886 void freeClientMultiState(redisClient *c);
887 void queueMultiCommand(redisClient *c);
888 void touchWatchedKey(redisDb *db, robj *key);
889 void touchWatchedKeysOnFlush(int dbid);
890
891 /* Redis object implementation */
892 void decrRefCount(void *o);
893 void incrRefCount(robj *o);
894 robj *resetRefCount(robj *obj);
895 void freeStringObject(robj *o);
896 void freeListObject(robj *o);
897 void freeSetObject(robj *o);
898 void freeZsetObject(robj *o);
899 void freeHashObject(robj *o);
900 robj *createObject(int type, void *ptr);
901 robj *createStringObject(char *ptr, size_t len);
902 robj *dupStringObject(robj *o);
903 int isObjectRepresentableAsLongLong(robj *o, long long *llongval);
904 robj *tryObjectEncoding(robj *o);
905 robj *getDecodedObject(robj *o);
906 size_t stringObjectLen(robj *o);
907 robj *createStringObjectFromLongLong(long long value);
908 robj *createStringObjectFromLongDouble(long double value);
909 robj *createListObject(void);
910 robj *createZiplistObject(void);
911 robj *createSetObject(void);
912 robj *createIntsetObject(void);
913 robj *createHashObject(void);
914 robj *createZsetObject(void);
915 robj *createZsetZiplistObject(void);
916 int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg);
917 int checkType(redisClient *c, robj *o, int type);
918 int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg);
919 int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg);
920 int getLongLongFromObject(robj *o, long long *target);
921 int getLongDoubleFromObject(robj *o, long double *target);
922 int getLongDoubleFromObjectOrReply(redisClient *c, robj *o, long double *target, const char *msg);
923 char *strEncoding(int encoding);
924 int compareStringObjects(robj *a, robj *b);
925 int equalStringObjects(robj *a, robj *b);
926 unsigned long estimateObjectIdleTime(robj *o);
927
928 /* Synchronous I/O with timeout */
929 int syncWrite(int fd, char *ptr, ssize_t size, int timeout);
930 int syncRead(int fd, char *ptr, ssize_t size, int timeout);
931 int syncReadLine(int fd, char *ptr, ssize_t size, int timeout);
932
933 /* Replication */
934 void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
935 void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
936 void updateSlavesWaitingBgsave(int bgsaveerr);
937 void replicationCron(void);
938
939 /* Generic persistence functions */
940 void startLoading(FILE *fp);
941 void loadingProgress(off_t pos);
942 void stopLoading(void);
943
944 /* RDB persistence */
945 #include "rdb.h"
946
947 /* AOF persistence */
948 void flushAppendOnlyFile(int force);
949 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
950 void aofRemoveTempFile(pid_t childpid);
951 int rewriteAppendOnlyFileBackground(void);
952 int loadAppendOnlyFile(char *filename);
953 void stopAppendOnly(void);
954 int startAppendOnly(void);
955 void backgroundRewriteDoneHandler(int exitcode, int bysignal);
956
957 /* Sorted sets data type */
958
959 /* Struct to hold a inclusive/exclusive range spec. */
960 typedef struct {
961 double min, max;
962 int minex, maxex; /* are min or max exclusive? */
963 } zrangespec;
964
965 zskiplist *zslCreate(void);
966 void zslFree(zskiplist *zsl);
967 zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj);
968 unsigned char *zzlInsert(unsigned char *zl, robj *ele, double score);
969 int zslDelete(zskiplist *zsl, double score, robj *obj);
970 zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec range);
971 double zzlGetScore(unsigned char *sptr);
972 void zzlNext(unsigned char *zl, unsigned char **eptr, unsigned char **sptr);
973 void zzlPrev(unsigned char *zl, unsigned char **eptr, unsigned char **sptr);
974 unsigned int zsetLength(robj *zobj);
975 void zsetConvert(robj *zobj, int encoding);
976
977 /* Core functions */
978 int freeMemoryIfNeeded(void);
979 int processCommand(redisClient *c);
980 void setupSignalHandlers(void);
981 struct redisCommand *lookupCommand(sds name);
982 struct redisCommand *lookupCommandByCString(char *s);
983 void call(redisClient *c, int flags);
984 void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int flags);
985 void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int target);
986 int prepareForShutdown();
987 void redisLog(int level, const char *fmt, ...);
988 void redisLogRaw(int level, const char *msg);
989 void usage();
990 void updateDictResizePolicy(void);
991 int htNeedsResize(dict *dict);
992 void oom(const char *msg);
993 void populateCommandTable(void);
994 void resetCommandTableStats(void);
995
996 /* Set data type */
997 robj *setTypeCreate(robj *value);
998 int setTypeAdd(robj *subject, robj *value);
999 int setTypeRemove(robj *subject, robj *value);
1000 int setTypeIsMember(robj *subject, robj *value);
1001 setTypeIterator *setTypeInitIterator(robj *subject);
1002 void setTypeReleaseIterator(setTypeIterator *si);
1003 int setTypeNext(setTypeIterator *si, robj **objele, int64_t *llele);
1004 robj *setTypeNextObject(setTypeIterator *si);
1005 int setTypeRandomElement(robj *setobj, robj **objele, int64_t *llele);
1006 unsigned long setTypeSize(robj *subject);
1007 void setTypeConvert(robj *subject, int enc);
1008
1009 /* Hash data type */
1010 void convertToRealHash(robj *o);
1011 void hashTypeTryConversion(robj *subject, robj **argv, int start, int end);
1012 void hashTypeTryObjectEncoding(robj *subject, robj **o1, robj **o2);
1013 int hashTypeGet(robj *o, robj *key, robj **objval, unsigned char **v, unsigned int *vlen);
1014 robj *hashTypeGetObject(robj *o, robj *key);
1015 int hashTypeExists(robj *o, robj *key);
1016 int hashTypeSet(robj *o, robj *key, robj *value);
1017 int hashTypeDelete(robj *o, robj *key);
1018 unsigned long hashTypeLength(robj *o);
1019 hashTypeIterator *hashTypeInitIterator(robj *subject);
1020 void hashTypeReleaseIterator(hashTypeIterator *hi);
1021 int hashTypeNext(hashTypeIterator *hi);
1022 int hashTypeCurrent(hashTypeIterator *hi, int what, robj **objval, unsigned char **v, unsigned int *vlen);
1023 robj *hashTypeCurrentObject(hashTypeIterator *hi, int what);
1024 robj *hashTypeLookupWriteOrCreate(redisClient *c, robj *key);
1025
1026 /* Pub / Sub */
1027 int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
1028 int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
1029 void freePubsubPattern(void *p);
1030 int listMatchPubsubPattern(void *a, void *b);
1031 int pubsubPublishMessage(robj *channel, robj *message);
1032
1033 /* Configuration */
1034 void loadServerConfig(char *filename, char *options);
1035 void appendServerSaveParams(time_t seconds, int changes);
1036 void resetServerSaveParams();
1037
1038 /* db.c -- Keyspace access API */
1039 int removeExpire(redisDb *db, robj *key);
1040 void propagateExpire(redisDb *db, robj *key);
1041 int expireIfNeeded(redisDb *db, robj *key);
1042 long long getExpire(redisDb *db, robj *key);
1043 void setExpire(redisDb *db, robj *key, long long when);
1044 robj *lookupKey(redisDb *db, robj *key);
1045 robj *lookupKeyRead(redisDb *db, robj *key);
1046 robj *lookupKeyWrite(redisDb *db, robj *key);
1047 robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply);
1048 robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply);
1049 void dbAdd(redisDb *db, robj *key, robj *val);
1050 void dbOverwrite(redisDb *db, robj *key, robj *val);
1051 void setKey(redisDb *db, robj *key, robj *val);
1052 int dbExists(redisDb *db, robj *key);
1053 robj *dbRandomKey(redisDb *db);
1054 int dbDelete(redisDb *db, robj *key);
1055 long long emptyDb();
1056 int selectDb(redisClient *c, int id);
1057 void signalModifiedKey(redisDb *db, robj *key);
1058 void signalFlushedDb(int dbid);
1059 unsigned int GetKeysInSlot(unsigned int hashslot, robj **keys, unsigned int count);
1060
1061 /* API to get key arguments from commands */
1062 #define REDIS_GETKEYS_ALL 0
1063 #define REDIS_GETKEYS_PRELOAD 1
1064 int *getKeysFromCommand(struct redisCommand *cmd, robj **argv, int argc, int *numkeys, int flags);
1065 void getKeysFreeResult(int *result);
1066 int *noPreloadGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags);
1067 int *renameGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags);
1068 int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags);
1069
1070 /* Cluster */
1071 void clusterInit(void);
1072 unsigned short crc16(const char *buf, int len);
1073 unsigned int keyHashSlot(char *key, int keylen);
1074 clusterNode *createClusterNode(char *nodename, int flags);
1075 int clusterAddNode(clusterNode *node);
1076 void clusterCron(void);
1077 clusterNode *getNodeByQuery(redisClient *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot, int *ask);
1078 void clusterPropagatePublish(robj *channel, robj *message);
1079
1080 /* Scripting */
1081 void scriptingInit(void);
1082
1083 /* Git SHA1 */
1084 char *redisGitSHA1(void);
1085 char *redisGitDirty(void);
1086
1087 /* Commands prototypes */
1088 void authCommand(redisClient *c);
1089 void pingCommand(redisClient *c);
1090 void echoCommand(redisClient *c);
1091 void setCommand(redisClient *c);
1092 void setnxCommand(redisClient *c);
1093 void setexCommand(redisClient *c);
1094 void psetexCommand(redisClient *c);
1095 void getCommand(redisClient *c);
1096 void delCommand(redisClient *c);
1097 void existsCommand(redisClient *c);
1098 void setbitCommand(redisClient *c);
1099 void getbitCommand(redisClient *c);
1100 void setrangeCommand(redisClient *c);
1101 void getrangeCommand(redisClient *c);
1102 void incrCommand(redisClient *c);
1103 void decrCommand(redisClient *c);
1104 void incrbyCommand(redisClient *c);
1105 void decrbyCommand(redisClient *c);
1106 void incrbyfloatCommand(redisClient *c);
1107 void selectCommand(redisClient *c);
1108 void randomkeyCommand(redisClient *c);
1109 void keysCommand(redisClient *c);
1110 void dbsizeCommand(redisClient *c);
1111 void lastsaveCommand(redisClient *c);
1112 void saveCommand(redisClient *c);
1113 void bgsaveCommand(redisClient *c);
1114 void bgrewriteaofCommand(redisClient *c);
1115 void shutdownCommand(redisClient *c);
1116 void moveCommand(redisClient *c);
1117 void renameCommand(redisClient *c);
1118 void renamenxCommand(redisClient *c);
1119 void lpushCommand(redisClient *c);
1120 void rpushCommand(redisClient *c);
1121 void lpushxCommand(redisClient *c);
1122 void rpushxCommand(redisClient *c);
1123 void linsertCommand(redisClient *c);
1124 void lpopCommand(redisClient *c);
1125 void rpopCommand(redisClient *c);
1126 void llenCommand(redisClient *c);
1127 void lindexCommand(redisClient *c);
1128 void lrangeCommand(redisClient *c);
1129 void ltrimCommand(redisClient *c);
1130 void typeCommand(redisClient *c);
1131 void lsetCommand(redisClient *c);
1132 void saddCommand(redisClient *c);
1133 void sremCommand(redisClient *c);
1134 void smoveCommand(redisClient *c);
1135 void sismemberCommand(redisClient *c);
1136 void scardCommand(redisClient *c);
1137 void spopCommand(redisClient *c);
1138 void srandmemberCommand(redisClient *c);
1139 void sinterCommand(redisClient *c);
1140 void sinterstoreCommand(redisClient *c);
1141 void sunionCommand(redisClient *c);
1142 void sunionstoreCommand(redisClient *c);
1143 void sdiffCommand(redisClient *c);
1144 void sdiffstoreCommand(redisClient *c);
1145 void syncCommand(redisClient *c);
1146 void flushdbCommand(redisClient *c);
1147 void flushallCommand(redisClient *c);
1148 void sortCommand(redisClient *c);
1149 void lremCommand(redisClient *c);
1150 void rpoplpushCommand(redisClient *c);
1151 void infoCommand(redisClient *c);
1152 void mgetCommand(redisClient *c);
1153 void monitorCommand(redisClient *c);
1154 void expireCommand(redisClient *c);
1155 void expireatCommand(redisClient *c);
1156 void pexpireCommand(redisClient *c);
1157 void pexpireatCommand(redisClient *c);
1158 void getsetCommand(redisClient *c);
1159 void ttlCommand(redisClient *c);
1160 void pttlCommand(redisClient *c);
1161 void persistCommand(redisClient *c);
1162 void slaveofCommand(redisClient *c);
1163 void debugCommand(redisClient *c);
1164 void msetCommand(redisClient *c);
1165 void msetnxCommand(redisClient *c);
1166 void zaddCommand(redisClient *c);
1167 void zincrbyCommand(redisClient *c);
1168 void zrangeCommand(redisClient *c);
1169 void zrangebyscoreCommand(redisClient *c);
1170 void zrevrangebyscoreCommand(redisClient *c);
1171 void zcountCommand(redisClient *c);
1172 void zrevrangeCommand(redisClient *c);
1173 void zcardCommand(redisClient *c);
1174 void zremCommand(redisClient *c);
1175 void zscoreCommand(redisClient *c);
1176 void zremrangebyscoreCommand(redisClient *c);
1177 void multiCommand(redisClient *c);
1178 void execCommand(redisClient *c);
1179 void discardCommand(redisClient *c);
1180 void blpopCommand(redisClient *c);
1181 void brpopCommand(redisClient *c);
1182 void brpoplpushCommand(redisClient *c);
1183 void appendCommand(redisClient *c);
1184 void strlenCommand(redisClient *c);
1185 void zrankCommand(redisClient *c);
1186 void zrevrankCommand(redisClient *c);
1187 void hsetCommand(redisClient *c);
1188 void hsetnxCommand(redisClient *c);
1189 void hgetCommand(redisClient *c);
1190 void hmsetCommand(redisClient *c);
1191 void hmgetCommand(redisClient *c);
1192 void hdelCommand(redisClient *c);
1193 void hlenCommand(redisClient *c);
1194 void zremrangebyrankCommand(redisClient *c);
1195 void zunionstoreCommand(redisClient *c);
1196 void zinterstoreCommand(redisClient *c);
1197 void hkeysCommand(redisClient *c);
1198 void hvalsCommand(redisClient *c);
1199 void hgetallCommand(redisClient *c);
1200 void hexistsCommand(redisClient *c);
1201 void configCommand(redisClient *c);
1202 void hincrbyCommand(redisClient *c);
1203 void hincrbyfloatCommand(redisClient *c);
1204 void subscribeCommand(redisClient *c);
1205 void unsubscribeCommand(redisClient *c);
1206 void psubscribeCommand(redisClient *c);
1207 void punsubscribeCommand(redisClient *c);
1208 void publishCommand(redisClient *c);
1209 void watchCommand(redisClient *c);
1210 void unwatchCommand(redisClient *c);
1211 void clusterCommand(redisClient *c);
1212 void restoreCommand(redisClient *c);
1213 void migrateCommand(redisClient *c);
1214 void askingCommand(redisClient *c);
1215 void dumpCommand(redisClient *c);
1216 void objectCommand(redisClient *c);
1217 void clientCommand(redisClient *c);
1218 void evalCommand(redisClient *c);
1219 void evalShaCommand(redisClient *c);
1220 void scriptCommand(redisClient *c);
1221 void timeCommand(redisClient *c);
1222
1223 #if defined(__GNUC__)
1224 void *calloc(size_t count, size_t size) __attribute__ ((deprecated));
1225 void free(void *ptr) __attribute__ ((deprecated));
1226 void *malloc(size_t size) __attribute__ ((deprecated));
1227 void *realloc(void *ptr, size_t size) __attribute__ ((deprecated));
1228 #endif
1229
1230 /* Debugging stuff */
1231 void _redisAssertWithInfo(redisClient *c, robj *o, char *estr, char *file, int line);
1232 void _redisAssert(char *estr, char *file, int line);
1233 void _redisPanic(char *msg, char *file, int line);
1234 void bugReportStart(void);
1235 void redisLogObjectDebugInfo(robj *o);
1236 void sigsegvHandler(int sig, siginfo_t *info, void *secret);
1237 sds genRedisInfoString(char *section);
1238 #endif