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