]> git.saurik.com Git - redis.git/blob - src/redis.h
CLUSTER SETSLOT implemented
[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
23 #include "ae.h" /* Event driven programming library */
24 #include "sds.h" /* Dynamic safe strings */
25 #include "dict.h" /* Hash tables */
26 #include "adlist.h" /* Linked lists */
27 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
28 #include "anet.h" /* Networking the easy way */
29 #include "zipmap.h" /* Compact string -> string data structure */
30 #include "ziplist.h" /* Compact list data structure */
31 #include "intset.h" /* Compact integer set structure */
32 #include "version.h"
33
34 /* Error codes */
35 #define REDIS_OK 0
36 #define REDIS_ERR -1
37
38 /* Static server configuration */
39 #define REDIS_SERVERPORT 6379 /* TCP port */
40 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
41 #define REDIS_IOBUF_LEN 1024
42 #define REDIS_LOADBUF_LEN 1024
43 #define REDIS_STATIC_ARGS 8
44 #define REDIS_DEFAULT_DBNUM 16
45 #define REDIS_CONFIGLINE_MAX 1024
46 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
47 #define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
48 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
49 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
50 #define REDIS_SHARED_INTEGERS 10000
51 #define REDIS_REPLY_CHUNK_BYTES (5*1500) /* 5 TCP packets with default MTU */
52 #define REDIS_MAX_LOGMSG_LEN 1024 /* Default maximum length of syslog messages */
53
54 /* Hash table parameters */
55 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
56
57 /* Command flags:
58 * REDIS_CMD_DENYOOM:
59 * Commands marked with this flag will return an error when 'maxmemory' is
60 * set and the server is using more than 'maxmemory' bytes of memory.
61 * In short: commands with this flag are denied on low memory conditions.
62 * REDIS_CMD_FORCE_REPLICATION:
63 * Force replication even if dirty is 0. */
64 #define REDIS_CMD_DENYOOM 4
65 #define REDIS_CMD_FORCE_REPLICATION 8
66
67 /* Object types */
68 #define REDIS_STRING 0
69 #define REDIS_LIST 1
70 #define REDIS_SET 2
71 #define REDIS_ZSET 3
72 #define REDIS_HASH 4
73 #define REDIS_VMPOINTER 8
74
75 /* Object types only used for persistence in .rdb files */
76 #define REDIS_HASH_ZIPMAP 9
77 #define REDIS_LIST_ZIPLIST 10
78 #define REDIS_SET_INTSET 11
79 #define REDIS_ZSET_ZIPLIST 12
80
81 /* Objects encoding. Some kind of objects like Strings and Hashes can be
82 * internally represented in multiple ways. The 'encoding' field of the object
83 * is set to one of this fields for this object. */
84 #define REDIS_ENCODING_RAW 0 /* Raw representation */
85 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
86 #define REDIS_ENCODING_HT 2 /* Encoded as hash table */
87 #define REDIS_ENCODING_ZIPMAP 3 /* Encoded as zipmap */
88 #define REDIS_ENCODING_LINKEDLIST 4 /* Encoded as regular linked list */
89 #define REDIS_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
90 #define REDIS_ENCODING_INTSET 6 /* Encoded as intset */
91 #define REDIS_ENCODING_SKIPLIST 7 /* Encoded as skiplist */
92
93 /* Object types only used for dumping to disk */
94 #define REDIS_EXPIRETIME 253
95 #define REDIS_SELECTDB 254
96 #define REDIS_EOF 255
97
98 /* Defines related to the dump file format. To store 32 bits lengths for short
99 * keys requires a lot of space, so we check the most significant 2 bits of
100 * the first byte to interpreter the length:
101 *
102 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
103 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
104 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
105 * 11|000000 this means: specially encoded object will follow. The six bits
106 * number specify the kind of object that follows.
107 * See the REDIS_RDB_ENC_* defines.
108 *
109 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
110 * values, will fit inside. */
111 #define REDIS_RDB_6BITLEN 0
112 #define REDIS_RDB_14BITLEN 1
113 #define REDIS_RDB_32BITLEN 2
114 #define REDIS_RDB_ENCVAL 3
115 #define REDIS_RDB_LENERR UINT_MAX
116
117 /* When a length of a string object stored on disk has the first two bits
118 * set, the remaining two bits specify a special encoding for the object
119 * accordingly to the following defines: */
120 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
121 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
122 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
123 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
124
125 /* Scheduled IO opeations flags. */
126 #define REDIS_IO_LOAD 1
127 #define REDIS_IO_SAVE 2
128 #define REDIS_IO_LOADINPROG 4
129 #define REDIS_IO_SAVEINPROG 8
130
131 /* Generic IO flags */
132 #define REDIS_IO_ONLYLOADS 1
133 #define REDIS_IO_ASAP 2
134
135 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
136 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
137
138 /* Client flags */
139 #define REDIS_SLAVE 1 /* This client is a slave server */
140 #define REDIS_MASTER 2 /* This client is a master server */
141 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
142 #define REDIS_MULTI 8 /* This client is in a MULTI context */
143 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
144 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
145 #define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
146 #define REDIS_CLOSE_AFTER_REPLY 128 /* Close after writing entire reply. */
147 #define REDIS_UNBLOCKED 256 /* This client was unblocked and is stored in
148 server.unblocked_clients */
149
150 /* Client request types */
151 #define REDIS_REQ_INLINE 1
152 #define REDIS_REQ_MULTIBULK 2
153
154 /* Slave replication state - slave side */
155 #define REDIS_REPL_NONE 0 /* No active replication */
156 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
157 #define REDIS_REPL_TRANSFER 2 /* Receiving .rdb from master */
158 #define REDIS_REPL_CONNECTED 3 /* Connected to master */
159
160 /* Slave replication state - from the point of view of master
161 * Note that in SEND_BULK and ONLINE state the slave receives new updates
162 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
163 * to start the next background saving in order to send updates to it. */
164 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
165 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
166 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
167 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
168
169 /* List related stuff */
170 #define REDIS_HEAD 0
171 #define REDIS_TAIL 1
172
173 /* Sort operations */
174 #define REDIS_SORT_GET 0
175 #define REDIS_SORT_ASC 1
176 #define REDIS_SORT_DESC 2
177 #define REDIS_SORTKEY_MAX 1024
178
179 /* Log levels */
180 #define REDIS_DEBUG 0
181 #define REDIS_VERBOSE 1
182 #define REDIS_NOTICE 2
183 #define REDIS_WARNING 3
184 #define REDIS_LOG_RAW (1<<10) /* Modifier to log without timestamp */
185
186 /* Anti-warning macro... */
187 #define REDIS_NOTUSED(V) ((void) V)
188
189 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
190 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
191
192 /* Append only defines */
193 #define APPENDFSYNC_NO 0
194 #define APPENDFSYNC_ALWAYS 1
195 #define APPENDFSYNC_EVERYSEC 2
196
197 /* Zip structure related defaults */
198 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 512
199 #define REDIS_HASH_MAX_ZIPMAP_VALUE 64
200 #define REDIS_LIST_MAX_ZIPLIST_ENTRIES 512
201 #define REDIS_LIST_MAX_ZIPLIST_VALUE 64
202 #define REDIS_SET_MAX_INTSET_ENTRIES 512
203 #define REDIS_ZSET_MAX_ZIPLIST_ENTRIES 128
204 #define REDIS_ZSET_MAX_ZIPLIST_VALUE 64
205
206 /* Sets operations codes */
207 #define REDIS_OP_UNION 0
208 #define REDIS_OP_DIFF 1
209 #define REDIS_OP_INTER 2
210
211 /* Redis maxmemory strategies */
212 #define REDIS_MAXMEMORY_VOLATILE_LRU 0
213 #define REDIS_MAXMEMORY_VOLATILE_TTL 1
214 #define REDIS_MAXMEMORY_VOLATILE_RANDOM 2
215 #define REDIS_MAXMEMORY_ALLKEYS_LRU 3
216 #define REDIS_MAXMEMORY_ALLKEYS_RANDOM 4
217 #define REDIS_MAXMEMORY_NO_EVICTION 5
218
219 /* Diskstore background saving thread states */
220 #define REDIS_BGSAVE_THREAD_UNACTIVE 0
221 #define REDIS_BGSAVE_THREAD_ACTIVE 1
222 #define REDIS_BGSAVE_THREAD_DONE_OK 2
223 #define REDIS_BGSAVE_THREAD_DONE_ERR 3
224
225 /* We can print the stacktrace, so our assert is defined this way: */
226 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
227 #define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
228 void _redisAssert(char *estr, char *file, int line);
229 void _redisPanic(char *msg, char *file, int line);
230
231 /*-----------------------------------------------------------------------------
232 * Data types
233 *----------------------------------------------------------------------------*/
234
235 /* A redis object, that is a type able to hold a string / list / set */
236
237 /* The actual Redis Object */
238 #define REDIS_LRU_CLOCK_MAX ((1<<21)-1) /* Max value of obj->lru */
239 #define REDIS_LRU_CLOCK_RESOLUTION 10 /* LRU clock resolution in seconds */
240 typedef struct redisObject {
241 unsigned type:4;
242 unsigned notused:2; /* Not used */
243 unsigned encoding:4;
244 unsigned lru:22; /* lru time (relative to server.lruclock) */
245 int refcount;
246 void *ptr;
247 /* VM fields are only allocated if VM is active, otherwise the
248 * object allocation function will just allocate
249 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
250 * Redis without VM active will not have any overhead. */
251 } robj;
252
253 /* The VM pointer structure - identifies an object in the swap file.
254 *
255 * This object is stored in place of the value
256 * object in the main key->value hash table representing a database.
257 * Note that the first fields (type, storage) are the same as the redisObject
258 * structure so that vmPointer strucuters can be accessed even when casted
259 * as redisObject structures.
260 *
261 * This is useful as we don't know if a value object is or not on disk, but we
262 * are always able to read obj->storage to check this. For vmPointer
263 * structures "type" is set to REDIS_VMPOINTER (even if without this field
264 * is still possible to check the kind of object from the value of 'storage').*/
265 typedef struct vmPointer {
266 unsigned type:4;
267 unsigned storage:2; /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
268 unsigned notused:26;
269 unsigned int vtype; /* type of the object stored in the swap file */
270 off_t page; /* the page at witch the object is stored on disk */
271 off_t usedpages; /* number of pages used on disk */
272 } vmpointer;
273
274 /* Macro used to initalize a Redis object allocated on the stack.
275 * Note that this macro is taken near the structure definition to make sure
276 * we'll update it when the structure is changed, to avoid bugs like
277 * bug #85 introduced exactly in this way. */
278 #define initStaticStringObject(_var,_ptr) do { \
279 _var.refcount = 1; \
280 _var.type = REDIS_STRING; \
281 _var.encoding = REDIS_ENCODING_RAW; \
282 _var.ptr = _ptr; \
283 } while(0);
284
285 typedef struct redisDb {
286 dict *dict; /* The keyspace for this DB */
287 dict *expires; /* Timeout of keys with a timeout set */
288 dict *blocking_keys; /* Keys with clients waiting for data (BLPOP) */
289 dict *io_keys; /* Keys with clients waiting for DS I/O */
290 dict *io_negcache; /* Negative caching for disk store */
291 dict *io_queued; /* Queued IO operations hash table */
292 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
293 int id;
294 } redisDb;
295
296 /* Client MULTI/EXEC state */
297 typedef struct multiCmd {
298 robj **argv;
299 int argc;
300 struct redisCommand *cmd;
301 } multiCmd;
302
303 typedef struct multiState {
304 multiCmd *commands; /* Array of MULTI commands */
305 int count; /* Total number of MULTI commands */
306 } multiState;
307
308 typedef struct blockingState {
309 robj **keys; /* The key we are waiting to terminate a blocking
310 * operation such as BLPOP. Otherwise NULL. */
311 int count; /* Number of blocking keys */
312 time_t timeout; /* Blocking operation timeout. If UNIX current time
313 * is >= timeout then the operation timed out. */
314 robj *target; /* The key that should receive the element,
315 * for BRPOPLPUSH. */
316 } blockingState;
317
318 /* With multiplexing we need to take per-clinet state.
319 * Clients are taken in a liked list. */
320 typedef struct redisClient {
321 int fd;
322 redisDb *db;
323 int dictid;
324 sds querybuf;
325 int argc;
326 robj **argv;
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 int sentlen;
332 time_t lastinteraction; /* time of the last interaction, used for timeout */
333 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
334 int slaveseldb; /* slave selected db, if this client is a slave */
335 int authenticated; /* when requirepass is non-NULL */
336 int replstate; /* replication state if this is a slave */
337 int repldbfd; /* replication DB file descriptor */
338 long repldboff; /* replication DB file offset */
339 off_t repldbsize; /* replication DB file size */
340 multiState mstate; /* MULTI/EXEC state */
341 blockingState bpop; /* blocking state */
342 list *io_keys; /* Keys this client is waiting to be loaded from the
343 * swap file in order to continue. */
344 list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */
345 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
346 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
347
348 /* Response buffer */
349 int bufpos;
350 char buf[REDIS_REPLY_CHUNK_BYTES];
351 } redisClient;
352
353 struct saveparam {
354 time_t seconds;
355 int changes;
356 };
357
358 struct sharedObjectsStruct {
359 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *cnegone, *pong, *space,
360 *colon, *nullbulk, *nullmultibulk, *queued,
361 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
362 *outofrangeerr, *loadingerr, *plus,
363 *select0, *select1, *select2, *select3, *select4,
364 *select5, *select6, *select7, *select8, *select9,
365 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk, *mbulk3,
366 *mbulk4, *psubscribebulk, *punsubscribebulk,
367 *integers[REDIS_SHARED_INTEGERS];
368 };
369
370 /* ZSETs use a specialized version of Skiplists */
371 typedef struct zskiplistNode {
372 robj *obj;
373 double score;
374 struct zskiplistNode *backward;
375 struct zskiplistLevel {
376 struct zskiplistNode *forward;
377 unsigned int span;
378 } level[];
379 } zskiplistNode;
380
381 typedef struct zskiplist {
382 struct zskiplistNode *header, *tail;
383 unsigned long length;
384 int level;
385 } zskiplist;
386
387 typedef struct zset {
388 dict *dict;
389 zskiplist *zsl;
390 } zset;
391
392 /*-----------------------------------------------------------------------------
393 * Redis cluster data structures
394 *----------------------------------------------------------------------------*/
395
396 #define REDIS_CLUSTER_SLOTS 4096
397 #define REDIS_CLUSTER_OK 0 /* Everything looks ok */
398 #define REDIS_CLUSTER_FAIL 1 /* The cluster can't work */
399 #define REDIS_CLUSTER_NEEDHELP 2 /* The cluster works, but needs some help */
400 #define REDIS_CLUSTER_NAMELEN 40 /* sha1 hex length */
401 #define REDIS_CLUSTER_PORT_INCR 10000 /* Cluster port = baseport + PORT_INCR */
402
403 struct clusterNode;
404
405 /* clusterLink encapsulates everything needed to talk with a remote node. */
406 typedef struct clusterLink {
407 int fd; /* TCP socket file descriptor */
408 sds sndbuf; /* Packet send buffer */
409 sds rcvbuf; /* Packet reception buffer */
410 struct clusterNode *node; /* Node related to this link if any, or NULL */
411 } clusterLink;
412
413 /* Node flags */
414 #define REDIS_NODE_MASTER 1 /* The node is a master */
415 #define REDIS_NODE_SLAVE 2 /* The node is a slave */
416 #define REDIS_NODE_PFAIL 4 /* Failure? Need acknowledge */
417 #define REDIS_NODE_FAIL 8 /* The node is believed to be malfunctioning */
418 #define REDIS_NODE_MYSELF 16 /* This node is myself */
419 #define REDIS_NODE_HANDSHAKE 32 /* We have still to exchange the first ping */
420 #define REDIS_NODE_NOADDR 64 /* We don't know the address of this node */
421 #define REDIS_NODE_MEET 128 /* Send a MEET message to this node */
422 #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"
423
424 struct clusterNode {
425 char name[REDIS_CLUSTER_NAMELEN]; /* Node name, hex string, sha1-size */
426 int flags; /* REDIS_NODE_... */
427 unsigned char slots[REDIS_CLUSTER_SLOTS/8]; /* slots handled by this node */
428 int numslaves; /* Number of slave nodes, if this is a master */
429 struct clusterNode **slaves; /* pointers to slave nodes */
430 struct clusterNode *slaveof; /* pointer to the master node */
431 time_t ping_sent; /* Unix time we sent latest ping */
432 time_t pong_received; /* Unix time we received the pong */
433 char *configdigest; /* Configuration digest of this node */
434 time_t configdigest_ts; /* Configuration digest timestamp */
435 char ip[16]; /* Latest known IP address of this node */
436 int port; /* Latest known port of this node */
437 clusterLink *link; /* TCP/IP link with this node */
438 };
439 typedef struct clusterNode clusterNode;
440
441 typedef struct {
442 char *configfile;
443 clusterNode *myself; /* This node */
444 int state; /* REDIS_CLUSTER_OK, REDIS_CLUSTER_FAIL, ... */
445 int node_timeout;
446 dict *nodes; /* Hash table of name -> clusterNode structures */
447 clusterNode *migrating_slots_to[REDIS_CLUSTER_SLOTS];
448 clusterNode *importing_slots_from[REDIS_CLUSTER_SLOTS];
449 clusterNode *slots[REDIS_CLUSTER_SLOTS];
450 zskiplist *slots_to_keys;
451 } clusterState;
452
453 /* Redis cluster messages header */
454
455 /* Note that the PING, PONG and MEET messages are actually the same exact
456 * kind of packet. PONG is the reply to ping, in the extact format as a PING,
457 * while MEET is a special PING that forces the receiver to add the sender
458 * as a node (if it is not already in the list). */
459 #define CLUSTERMSG_TYPE_PING 0 /* Ping */
460 #define CLUSTERMSG_TYPE_PONG 1 /* Pong (reply to Ping) */
461 #define CLUSTERMSG_TYPE_MEET 2 /* Meet "let's join" message */
462 #define CLUSTERMSG_TYPE_FAIL 3 /* Mark node xxx as failing */
463
464 /* Initially we don't know our "name", but we'll find it once we connect
465 * to the first node, using the getsockname() function. Then we'll use this
466 * address for all the next messages. */
467 typedef struct {
468 char nodename[REDIS_CLUSTER_NAMELEN];
469 uint32_t ping_sent;
470 uint32_t pong_received;
471 char ip[16]; /* IP address last time it was seen */
472 uint16_t port; /* port last time it was seen */
473 uint16_t flags;
474 uint32_t notused; /* for 64 bit alignment */
475 } clusterMsgDataGossip;
476
477 typedef struct {
478 char nodename[REDIS_CLUSTER_NAMELEN];
479 } clusterMsgDataFail;
480
481 union clusterMsgData {
482 /* PING, MEET and PONG */
483 struct {
484 /* Array of N clusterMsgDataGossip structures */
485 clusterMsgDataGossip gossip[1];
486 } ping;
487 /* FAIL */
488 struct {
489 clusterMsgDataFail about;
490 } fail;
491 };
492
493 typedef struct {
494 uint32_t totlen; /* Total length of this message */
495 uint16_t type; /* Message type */
496 uint16_t count; /* Only used for some kind of messages. */
497 char sender[REDIS_CLUSTER_NAMELEN]; /* Name of the sender node */
498 unsigned char myslots[REDIS_CLUSTER_SLOTS/8];
499 char slaveof[REDIS_CLUSTER_NAMELEN];
500 char configdigest[32];
501 uint16_t port; /* Sender TCP base port */
502 unsigned char state; /* Cluster state from the POV of the sender */
503 unsigned char notused[5]; /* Reserved for future use. For alignment. */
504 union clusterMsgData data;
505 } clusterMsg;
506
507 /*-----------------------------------------------------------------------------
508 * Global server state
509 *----------------------------------------------------------------------------*/
510
511 struct redisServer {
512 /* General */
513 pthread_t mainthread;
514 redisDb *db;
515 dict *commands; /* Command table hahs table */
516 aeEventLoop *el;
517 /* Networking */
518 int port;
519 char *bindaddr;
520 char *unixsocket;
521 int ipfd;
522 int sofd;
523 int cfd;
524 list *clients;
525 list *slaves, *monitors;
526 char neterr[ANET_ERR_LEN];
527 /* RDB / AOF loading information */
528 int loading;
529 off_t loading_total_bytes;
530 off_t loading_loaded_bytes;
531 time_t loading_start_time;
532 /* Fast pointers to often looked up command */
533 struct redisCommand *delCommand, *multiCommand;
534 int cronloops; /* number of times the cron function run */
535 time_t lastsave; /* Unix time of last save succeeede */
536 /* Fields used only for stats */
537 time_t stat_starttime; /* server start time */
538 long long stat_numcommands; /* number of processed commands */
539 long long stat_numconnections; /* number of connections received */
540 long long stat_expiredkeys; /* number of expired keys */
541 long long stat_evictedkeys; /* number of evicted keys (maxmemory) */
542 long long stat_keyspace_hits; /* number of successful lookups of keys */
543 long long stat_keyspace_misses; /* number of failed lookups of keys */
544 size_t stat_peak_memory; /* max used memory record */
545 /* Configuration */
546 int verbosity;
547 int maxidletime;
548 int dbnum;
549 int daemonize;
550 int appendonly;
551 int appendfsync;
552 int no_appendfsync_on_rewrite;
553 int shutdown_asap;
554 int activerehashing;
555 char *requirepass;
556 /* Persistence */
557 long long dirty; /* changes to DB from the last save */
558 long long dirty_before_bgsave; /* used to restore dirty on failed BGSAVE */
559 time_t lastfsync;
560 int appendfd;
561 int appendseldb;
562 char *pidfile;
563 pid_t bgsavechildpid;
564 pid_t bgrewritechildpid;
565 int bgsavethread_state;
566 pthread_mutex_t bgsavethread_mutex;
567 pthread_t bgsavethread;
568 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
569 sds aofbuf; /* AOF buffer, written before entering the event loop */
570 struct saveparam *saveparams;
571 int saveparamslen;
572 char *dbfilename;
573 int rdbcompression;
574 char *appendfilename;
575 /* Logging */
576 char *logfile;
577 int syslog_enabled;
578 char *syslog_ident;
579 int syslog_facility;
580 /* Replication related */
581 int isslave;
582 /* Slave specific fields */
583 char *masterauth;
584 char *masterhost;
585 int masterport;
586 redisClient *master; /* client that is master for this slave */
587 int replstate; /* replication status if the instance is a slave */
588 off_t repl_transfer_left; /* bytes left reading .rdb */
589 int repl_transfer_s; /* slave -> master SYNC socket */
590 int repl_transfer_fd; /* slave -> master SYNC temp file descriptor */
591 char *repl_transfer_tmpfile; /* slave-> master SYNC temp file name */
592 time_t repl_transfer_lastio; /* unix time of the latest read, for timeout */
593 int repl_serve_stale_data; /* Serve stale data when link is down? */
594 /* Limits */
595 unsigned int maxclients;
596 unsigned long long maxmemory;
597 int maxmemory_policy;
598 int maxmemory_samples;
599 /* Blocked clients */
600 unsigned int bpop_blocked_clients;
601 unsigned int cache_blocked_clients;
602 list *unblocked_clients; /* list of clients to unblock before next loop */
603 list *cache_io_queue; /* IO operations queue */
604 int cache_flush_delay; /* seconds to wait before flushing keys */
605 /* Sort parameters - qsort_r() is only available under BSD so we
606 * have to take this state global, in order to pass it to sortCompare() */
607 int sort_desc;
608 int sort_alpha;
609 int sort_bypattern;
610 /* Virtual memory configuration */
611 int ds_enabled; /* backend disk in redis.conf */
612 char *ds_path; /* location of the disk store on disk */
613 unsigned long long cache_max_memory;
614 /* Zip structure config */
615 size_t hash_max_zipmap_entries;
616 size_t hash_max_zipmap_value;
617 size_t list_max_ziplist_entries;
618 size_t list_max_ziplist_value;
619 size_t set_max_intset_entries;
620 size_t zset_max_ziplist_entries;
621 size_t zset_max_ziplist_value;
622 time_t unixtime; /* Unix time sampled every second. */
623 /* Virtual memory I/O threads stuff */
624 /* An I/O thread process an element taken from the io_jobs queue and
625 * put the result of the operation in the io_done list. While the
626 * job is being processed, it's put on io_processing queue. */
627 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
628 list *io_processing; /* List of VM I/O jobs being processed */
629 list *io_processed; /* List of VM I/O jobs already processed */
630 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
631 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
632 pthread_cond_t io_condvar; /* I/O threads conditional variable */
633 pthread_attr_t io_threads_attr; /* attributes for threads creation */
634 int io_active_threads; /* Number of running I/O threads */
635 int vm_max_threads; /* Max number of I/O threads running at the same time */
636 /* Our main thread is blocked on the event loop, locking for sockets ready
637 * to be read or written, so when a threaded I/O operation is ready to be
638 * processed by the main thread, the I/O thread will use a unix pipe to
639 * awake the main thread. The followings are the two pipe FDs. */
640 int io_ready_pipe_read;
641 int io_ready_pipe_write;
642 /* Virtual memory stats */
643 unsigned long long vm_stats_used_pages;
644 unsigned long long vm_stats_swapped_objects;
645 unsigned long long vm_stats_swapouts;
646 unsigned long long vm_stats_swapins;
647 /* Pubsub */
648 dict *pubsub_channels; /* Map channels to list of subscribed clients */
649 list *pubsub_patterns; /* A list of pubsub_patterns */
650 /* Misc */
651 unsigned lruclock:22; /* clock incrementing every minute, for LRU */
652 unsigned lruclock_padding:10;
653 /* Cluster */
654 int cluster_enabled;
655 clusterState cluster;
656 };
657
658 typedef struct pubsubPattern {
659 redisClient *client;
660 robj *pattern;
661 } pubsubPattern;
662
663 typedef void redisCommandProc(redisClient *c);
664 typedef int *redisGetKeysProc(struct redisCommand *cmd, robj **argv, int argc, int *numkeys, int flags);
665 struct redisCommand {
666 char *name;
667 redisCommandProc *proc;
668 int arity;
669 int flags;
670 /* Use a function to determine keys arguments in a command line.
671 * Used both for diskstore preloading and Redis Cluster. */
672 redisGetKeysProc *getkeys_proc;
673 /* What keys should be loaded in background when calling this command? */
674 int firstkey; /* The first argument that's a key (0 = no keys) */
675 int lastkey; /* THe last argument that's a key */
676 int keystep; /* The step between first and last key */
677 long long microseconds, calls;
678 };
679
680 struct redisFunctionSym {
681 char *name;
682 unsigned long pointer;
683 };
684
685 typedef struct _redisSortObject {
686 robj *obj;
687 union {
688 double score;
689 robj *cmpobj;
690 } u;
691 } redisSortObject;
692
693 typedef struct _redisSortOperation {
694 int type;
695 robj *pattern;
696 } redisSortOperation;
697
698 /* DIsk store threaded I/O request message */
699 #define REDIS_IOJOB_LOAD 0
700 #define REDIS_IOJOB_SAVE 1
701
702 typedef struct iojob {
703 int type; /* Request type, REDIS_IOJOB_* */
704 redisDb *db;/* Redis database */
705 robj *key; /* This I/O request is about this key */
706 robj *val; /* the value to swap for REDIS_IOJOB_SAVE, otherwise this
707 * field is populated by the I/O thread for REDIS_IOJOB_LOAD. */
708 time_t expire; /* Expire time for this key on REDIS_IOJOB_LOAD */
709 } iojob;
710
711 /* IO operations scheduled -- check dscache.c for more info */
712 typedef struct ioop {
713 int type;
714 redisDb *db;
715 robj *key;
716 time_t ctime; /* This is the creation time of the entry. */
717 } ioop;
718
719 /* Structure to hold list iteration abstraction. */
720 typedef struct {
721 robj *subject;
722 unsigned char encoding;
723 unsigned char direction; /* Iteration direction */
724 unsigned char *zi;
725 listNode *ln;
726 } listTypeIterator;
727
728 /* Structure for an entry while iterating over a list. */
729 typedef struct {
730 listTypeIterator *li;
731 unsigned char *zi; /* Entry in ziplist */
732 listNode *ln; /* Entry in linked list */
733 } listTypeEntry;
734
735 /* Structure to hold set iteration abstraction. */
736 typedef struct {
737 robj *subject;
738 int encoding;
739 int ii; /* intset iterator */
740 dictIterator *di;
741 } setTypeIterator;
742
743 /* Structure to hold hash iteration abstration. Note that iteration over
744 * hashes involves both fields and values. Because it is possible that
745 * not both are required, store pointers in the iterator to avoid
746 * unnecessary memory allocation for fields/values. */
747 typedef struct {
748 int encoding;
749 unsigned char *zi;
750 unsigned char *zk, *zv;
751 unsigned int zklen, zvlen;
752
753 dictIterator *di;
754 dictEntry *de;
755 } hashTypeIterator;
756
757 #define REDIS_HASH_KEY 1
758 #define REDIS_HASH_VALUE 2
759
760 /*-----------------------------------------------------------------------------
761 * Extern declarations
762 *----------------------------------------------------------------------------*/
763
764 extern struct redisServer server;
765 extern struct sharedObjectsStruct shared;
766 extern dictType setDictType;
767 extern dictType zsetDictType;
768 extern dictType clusterNodesDictType;
769 extern double R_Zero, R_PosInf, R_NegInf, R_Nan;
770 dictType hashDictType;
771
772 /*-----------------------------------------------------------------------------
773 * Functions prototypes
774 *----------------------------------------------------------------------------*/
775
776 /* Utils */
777 long long ustime(void);
778
779 /* networking.c -- Networking and Client related operations */
780 redisClient *createClient(int fd);
781 void closeTimedoutClients(void);
782 void freeClient(redisClient *c);
783 void resetClient(redisClient *c);
784 void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask);
785 void addReply(redisClient *c, robj *obj);
786 void *addDeferredMultiBulkLength(redisClient *c);
787 void setDeferredMultiBulkLength(redisClient *c, void *node, long length);
788 void addReplySds(redisClient *c, sds s);
789 void processInputBuffer(redisClient *c);
790 void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask);
791 void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask);
792 void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
793 void addReplyBulk(redisClient *c, robj *obj);
794 void addReplyBulkCString(redisClient *c, char *s);
795 void addReplyBulkCBuffer(redisClient *c, void *p, size_t len);
796 void addReplyBulkLongLong(redisClient *c, long long ll);
797 void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
798 void addReply(redisClient *c, robj *obj);
799 void addReplySds(redisClient *c, sds s);
800 void addReplyError(redisClient *c, char *err);
801 void addReplyStatus(redisClient *c, char *status);
802 void addReplyDouble(redisClient *c, double d);
803 void addReplyLongLong(redisClient *c, long long ll);
804 void addReplyMultiBulkLen(redisClient *c, long length);
805 void *dupClientReplyValue(void *o);
806 void getClientsMaxBuffers(unsigned long *longest_output_list,
807 unsigned long *biggest_input_buffer);
808
809 #ifdef __GNUC__
810 void addReplyErrorFormat(redisClient *c, const char *fmt, ...)
811 __attribute__((format(printf, 2, 3)));
812 void addReplyStatusFormat(redisClient *c, const char *fmt, ...)
813 __attribute__((format(printf, 2, 3)));
814 #else
815 void addReplyErrorFormat(redisClient *c, const char *fmt, ...);
816 void addReplyStatusFormat(redisClient *c, const char *fmt, ...);
817 #endif
818
819 /* List data type */
820 void listTypeTryConversion(robj *subject, robj *value);
821 void listTypePush(robj *subject, robj *value, int where);
822 robj *listTypePop(robj *subject, int where);
823 unsigned long listTypeLength(robj *subject);
824 listTypeIterator *listTypeInitIterator(robj *subject, int index, unsigned char direction);
825 void listTypeReleaseIterator(listTypeIterator *li);
826 int listTypeNext(listTypeIterator *li, listTypeEntry *entry);
827 robj *listTypeGet(listTypeEntry *entry);
828 void listTypeInsert(listTypeEntry *entry, robj *value, int where);
829 int listTypeEqual(listTypeEntry *entry, robj *o);
830 void listTypeDelete(listTypeEntry *entry);
831 void listTypeConvert(robj *subject, int enc);
832 void unblockClientWaitingData(redisClient *c);
833 int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
834 void popGenericCommand(redisClient *c, int where);
835
836 /* MULTI/EXEC/WATCH... */
837 void unwatchAllKeys(redisClient *c);
838 void initClientMultiState(redisClient *c);
839 void freeClientMultiState(redisClient *c);
840 void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
841 void touchWatchedKey(redisDb *db, robj *key);
842 void touchWatchedKeysOnFlush(int dbid);
843
844 /* Redis object implementation */
845 void decrRefCount(void *o);
846 void incrRefCount(robj *o);
847 void freeStringObject(robj *o);
848 void freeListObject(robj *o);
849 void freeSetObject(robj *o);
850 void freeZsetObject(robj *o);
851 void freeHashObject(robj *o);
852 robj *createObject(int type, void *ptr);
853 robj *createStringObject(char *ptr, size_t len);
854 robj *dupStringObject(robj *o);
855 robj *tryObjectEncoding(robj *o);
856 robj *getDecodedObject(robj *o);
857 size_t stringObjectLen(robj *o);
858 robj *createStringObjectFromLongLong(long long value);
859 robj *createListObject(void);
860 robj *createZiplistObject(void);
861 robj *createSetObject(void);
862 robj *createIntsetObject(void);
863 robj *createHashObject(void);
864 robj *createZsetObject(void);
865 robj *createZsetZiplistObject(void);
866 int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg);
867 int checkType(redisClient *c, robj *o, int type);
868 int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg);
869 int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg);
870 int getLongLongFromObject(robj *o, long long *target);
871 char *strEncoding(int encoding);
872 int compareStringObjects(robj *a, robj *b);
873 int equalStringObjects(robj *a, robj *b);
874 unsigned long estimateObjectIdleTime(robj *o);
875
876 /* Synchronous I/O with timeout */
877 int syncWrite(int fd, char *ptr, ssize_t size, int timeout);
878 int syncRead(int fd, char *ptr, ssize_t size, int timeout);
879 int syncReadLine(int fd, char *ptr, ssize_t size, int timeout);
880 int fwriteBulkString(FILE *fp, char *s, unsigned long len);
881 int fwriteBulkDouble(FILE *fp, double d);
882 int fwriteBulkLongLong(FILE *fp, long long l);
883 int fwriteBulkObject(FILE *fp, robj *obj);
884 int fwriteBulkCount(FILE *fp, char prefix, int count);
885
886 /* Replication */
887 void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
888 void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
889 int syncWithMaster(void);
890 void updateSlavesWaitingBgsave(int bgsaveerr);
891 void replicationCron(void);
892
893 /* Generic persistence functions */
894 void startLoading(FILE *fp);
895 void loadingProgress(off_t pos);
896 void stopLoading(void);
897
898 /* RDB persistence */
899 int rdbLoad(char *filename);
900 int rdbSaveBackground(char *filename);
901 void rdbRemoveTempFile(pid_t childpid);
902 int rdbSave(char *filename);
903 int rdbSaveObject(FILE *fp, robj *o);
904 off_t rdbSavedObjectLen(robj *o);
905 off_t rdbSavedObjectPages(robj *o);
906 robj *rdbLoadObject(int type, FILE *fp);
907 void backgroundSaveDoneHandler(int exitcode, int bysignal);
908 int rdbSaveKeyValuePair(FILE *fp, robj *key, robj *val, time_t expireitme, time_t now);
909 int rdbLoadType(FILE *fp);
910 time_t rdbLoadTime(FILE *fp);
911 robj *rdbLoadStringObject(FILE *fp);
912 int rdbSaveType(FILE *fp, unsigned char type);
913 int rdbSaveLen(FILE *fp, uint32_t len);
914
915 /* AOF persistence */
916 void flushAppendOnlyFile(void);
917 void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
918 void aofRemoveTempFile(pid_t childpid);
919 int rewriteAppendOnlyFileBackground(void);
920 int loadAppendOnlyFile(char *filename);
921 void stopAppendOnly(void);
922 int startAppendOnly(void);
923 void backgroundRewriteDoneHandler(int exitcode, int bysignal);
924
925 /* Sorted sets data type */
926
927 /* Struct to hold a inclusive/exclusive range spec. */
928 typedef struct {
929 double min, max;
930 int minex, maxex; /* are min or max exclusive? */
931 } zrangespec;
932
933 zskiplist *zslCreate(void);
934 void zslFree(zskiplist *zsl);
935 zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj);
936 unsigned char *zzlInsert(unsigned char *zl, robj *ele, double score);
937 int zslDelete(zskiplist *zsl, double score, robj *obj);
938 zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec range);
939 double zzlGetScore(unsigned char *sptr);
940 void zzlNext(unsigned char *zl, unsigned char **eptr, unsigned char **sptr);
941 void zzlPrev(unsigned char *zl, unsigned char **eptr, unsigned char **sptr);
942 unsigned int zsetLength(robj *zobj);
943 void zsetConvert(robj *zobj, int encoding);
944
945 /* Core functions */
946 void freeMemoryIfNeeded(void);
947 int processCommand(redisClient *c);
948 void setupSignalHandlers(void);
949 struct redisCommand *lookupCommand(sds name);
950 struct redisCommand *lookupCommandByCString(char *s);
951 void call(redisClient *c, struct redisCommand *cmd);
952 int prepareForShutdown();
953 void redisLog(int level, const char *fmt, ...);
954 void usage();
955 void updateDictResizePolicy(void);
956 int htNeedsResize(dict *dict);
957 void oom(const char *msg);
958 void populateCommandTable(void);
959 void resetCommandTableStats(void);
960
961 /* Disk store */
962 int dsOpen(void);
963 int dsClose(void);
964 int dsSet(redisDb *db, robj *key, robj *val, time_t expire);
965 robj *dsGet(redisDb *db, robj *key, time_t *expire);
966 int dsDel(redisDb *db, robj *key);
967 int dsExists(redisDb *db, robj *key);
968 void dsFlushDb(int dbid);
969 int dsRdbSaveBackground(char *filename);
970 int dsRdbSave(char *filename);
971
972 /* Disk Store Cache */
973 void dsInit(void);
974 void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
975 void lockThreadedIO(void);
976 void unlockThreadedIO(void);
977 void freeIOJob(iojob *j);
978 void queueIOJob(iojob *j);
979 void waitEmptyIOJobsQueue(void);
980 void processAllPendingIOJobs(void);
981 int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd);
982 int dontWaitForSwappedKey(redisClient *c, robj *key);
983 void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
984 int cacheFreeOneEntry(void);
985 void cacheScheduleIOAddFlag(redisDb *db, robj *key, long flag);
986 void cacheScheduleIODelFlag(redisDb *db, robj *key, long flag);
987 int cacheScheduleIOGetFlags(redisDb *db, robj *key);
988 void cacheScheduleIO(redisDb *db, robj *key, int type);
989 void cacheCron(void);
990 int cacheKeyMayExist(redisDb *db, robj *key);
991 void cacheSetKeyMayExist(redisDb *db, robj *key);
992 void cacheSetKeyDoesNotExist(redisDb *db, robj *key);
993 void cacheForcePointInTime(void);
994
995 /* Set data type */
996 robj *setTypeCreate(robj *value);
997 int setTypeAdd(robj *subject, robj *value);
998 int setTypeRemove(robj *subject, robj *value);
999 int setTypeIsMember(robj *subject, robj *value);
1000 setTypeIterator *setTypeInitIterator(robj *subject);
1001 void setTypeReleaseIterator(setTypeIterator *si);
1002 int setTypeNext(setTypeIterator *si, robj **objele, int64_t *llele);
1003 robj *setTypeNextObject(setTypeIterator *si);
1004 int setTypeRandomElement(robj *setobj, robj **objele, int64_t *llele);
1005 unsigned long setTypeSize(robj *subject);
1006 void setTypeConvert(robj *subject, int enc);
1007
1008 /* Hash data type */
1009 void convertToRealHash(robj *o);
1010 void hashTypeTryConversion(robj *subject, robj **argv, int start, int end);
1011 void hashTypeTryObjectEncoding(robj *subject, robj **o1, robj **o2);
1012 int hashTypeGet(robj *o, robj *key, robj **objval, unsigned char **v, unsigned int *vlen);
1013 robj *hashTypeGetObject(robj *o, robj *key);
1014 int hashTypeExists(robj *o, robj *key);
1015 int hashTypeSet(robj *o, robj *key, robj *value);
1016 int hashTypeDelete(robj *o, robj *key);
1017 unsigned long hashTypeLength(robj *o);
1018 hashTypeIterator *hashTypeInitIterator(robj *subject);
1019 void hashTypeReleaseIterator(hashTypeIterator *hi);
1020 int hashTypeNext(hashTypeIterator *hi);
1021 int hashTypeCurrent(hashTypeIterator *hi, int what, robj **objval, unsigned char **v, unsigned int *vlen);
1022 robj *hashTypeCurrentObject(hashTypeIterator *hi, int what);
1023 robj *hashTypeLookupWriteOrCreate(redisClient *c, robj *key);
1024
1025 /* Pub / Sub */
1026 int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
1027 int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
1028 void freePubsubPattern(void *p);
1029 int listMatchPubsubPattern(void *a, void *b);
1030
1031 /* Utility functions */
1032 int stringmatchlen(const char *pattern, int patternLen,
1033 const char *string, int stringLen, int nocase);
1034 int stringmatch(const char *pattern, const char *string, int nocase);
1035 long long memtoll(const char *p, int *err);
1036 int ll2string(char *s, size_t len, long long value);
1037 int string2ll(char *s, size_t len, long long *value);
1038 int d2string(char *s, size_t len, double value);
1039 int isStringRepresentableAsLong(sds s, long *longval);
1040 int isStringRepresentableAsLongLong(sds s, long long *longval);
1041 int isObjectRepresentableAsLongLong(robj *o, long long *llongval);
1042
1043 /* Configuration */
1044 void loadServerConfig(char *filename);
1045 void appendServerSaveParams(time_t seconds, int changes);
1046 void resetServerSaveParams();
1047
1048 /* db.c -- Keyspace access API */
1049 int removeExpire(redisDb *db, robj *key);
1050 void propagateExpire(redisDb *db, robj *key);
1051 int expireIfNeeded(redisDb *db, robj *key);
1052 time_t getExpire(redisDb *db, robj *key);
1053 void setExpire(redisDb *db, robj *key, time_t when);
1054 robj *lookupKey(redisDb *db, robj *key);
1055 robj *lookupKeyRead(redisDb *db, robj *key);
1056 robj *lookupKeyWrite(redisDb *db, robj *key);
1057 robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply);
1058 robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply);
1059 int dbAdd(redisDb *db, robj *key, robj *val);
1060 int dbReplace(redisDb *db, robj *key, robj *val);
1061 int dbExists(redisDb *db, robj *key);
1062 robj *dbRandomKey(redisDb *db);
1063 int dbDelete(redisDb *db, robj *key);
1064 long long emptyDb();
1065 int selectDb(redisClient *c, int id);
1066 void signalModifiedKey(redisDb *db, robj *key);
1067 void signalFlushedDb(int dbid);
1068 unsigned int GetKeysInSlot(unsigned int hashslot, robj **keys, unsigned int count);
1069
1070 /* API to get key arguments from commands */
1071 #define REDIS_GETKEYS_ALL 0
1072 #define REDIS_GETKEYS_PRELOAD 1
1073 int *getKeysFromCommand(struct redisCommand *cmd, robj **argv, int argc, int *numkeys, int flags);
1074 void getKeysFreeResult(int *result);
1075 int *noPreloadGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags);
1076 int *renameGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags);
1077 int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags);
1078
1079 /* Cluster */
1080 void clusterInit(void);
1081 unsigned short crc16(const char *buf, int len);
1082 unsigned int keyHashSlot(char *key, int keylen);
1083 clusterNode *createClusterNode(char *nodename, int flags);
1084 int clusterAddNode(clusterNode *node);
1085 void clusterCron(void);
1086 clusterNode *getNodeByQuery(redisClient *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot);
1087
1088 /* Git SHA1 */
1089 char *redisGitSHA1(void);
1090 char *redisGitDirty(void);
1091
1092 /* Commands prototypes */
1093 void authCommand(redisClient *c);
1094 void pingCommand(redisClient *c);
1095 void echoCommand(redisClient *c);
1096 void setCommand(redisClient *c);
1097 void setnxCommand(redisClient *c);
1098 void setexCommand(redisClient *c);
1099 void getCommand(redisClient *c);
1100 void delCommand(redisClient *c);
1101 void existsCommand(redisClient *c);
1102 void setbitCommand(redisClient *c);
1103 void getbitCommand(redisClient *c);
1104 void setrangeCommand(redisClient *c);
1105 void getrangeCommand(redisClient *c);
1106 void incrCommand(redisClient *c);
1107 void decrCommand(redisClient *c);
1108 void incrbyCommand(redisClient *c);
1109 void decrbyCommand(redisClient *c);
1110 void selectCommand(redisClient *c);
1111 void randomkeyCommand(redisClient *c);
1112 void keysCommand(redisClient *c);
1113 void dbsizeCommand(redisClient *c);
1114 void lastsaveCommand(redisClient *c);
1115 void saveCommand(redisClient *c);
1116 void bgsaveCommand(redisClient *c);
1117 void bgrewriteaofCommand(redisClient *c);
1118 void shutdownCommand(redisClient *c);
1119 void moveCommand(redisClient *c);
1120 void renameCommand(redisClient *c);
1121 void renamenxCommand(redisClient *c);
1122 void lpushCommand(redisClient *c);
1123 void rpushCommand(redisClient *c);
1124 void lpushxCommand(redisClient *c);
1125 void rpushxCommand(redisClient *c);
1126 void linsertCommand(redisClient *c);
1127 void lpopCommand(redisClient *c);
1128 void rpopCommand(redisClient *c);
1129 void llenCommand(redisClient *c);
1130 void lindexCommand(redisClient *c);
1131 void lrangeCommand(redisClient *c);
1132 void ltrimCommand(redisClient *c);
1133 void typeCommand(redisClient *c);
1134 void lsetCommand(redisClient *c);
1135 void saddCommand(redisClient *c);
1136 void sremCommand(redisClient *c);
1137 void smoveCommand(redisClient *c);
1138 void sismemberCommand(redisClient *c);
1139 void scardCommand(redisClient *c);
1140 void spopCommand(redisClient *c);
1141 void srandmemberCommand(redisClient *c);
1142 void sinterCommand(redisClient *c);
1143 void sinterstoreCommand(redisClient *c);
1144 void sunionCommand(redisClient *c);
1145 void sunionstoreCommand(redisClient *c);
1146 void sdiffCommand(redisClient *c);
1147 void sdiffstoreCommand(redisClient *c);
1148 void syncCommand(redisClient *c);
1149 void flushdbCommand(redisClient *c);
1150 void flushallCommand(redisClient *c);
1151 void sortCommand(redisClient *c);
1152 void lremCommand(redisClient *c);
1153 void rpoplpushCommand(redisClient *c);
1154 void infoCommand(redisClient *c);
1155 void mgetCommand(redisClient *c);
1156 void monitorCommand(redisClient *c);
1157 void expireCommand(redisClient *c);
1158 void expireatCommand(redisClient *c);
1159 void getsetCommand(redisClient *c);
1160 void ttlCommand(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 subscribeCommand(redisClient *c);
1204 void unsubscribeCommand(redisClient *c);
1205 void psubscribeCommand(redisClient *c);
1206 void punsubscribeCommand(redisClient *c);
1207 void publishCommand(redisClient *c);
1208 void watchCommand(redisClient *c);
1209 void unwatchCommand(redisClient *c);
1210 void clusterCommand(redisClient *c);
1211 void restoreCommand(redisClient *c);
1212 void migrateCommand(redisClient *c);
1213 void dumpCommand(redisClient *c);
1214 void objectCommand(redisClient *c);
1215 void clientCommand(redisClient *c);
1216
1217 #if defined(__GNUC__)
1218 void *calloc(size_t count, size_t size) __attribute__ ((deprecated));
1219 void free(void *ptr) __attribute__ ((deprecated));
1220 void *malloc(size_t size) __attribute__ ((deprecated));
1221 void *realloc(void *ptr, size_t size) __attribute__ ((deprecated));
1222 #endif
1223
1224 #endif