]> git.saurik.com Git - redis.git/blame - src/redis.h
redis-cli in interactive mode now prints the time elapsed of the operation performed...
[redis.git] / src / redis.h
CommitLineData
e2641e09 1#ifndef __REDIS_H
2#define __REDIS_H
3
4#include "fmacros.h"
5#include "config.h"
6
7#if defined(__sun)
8#include "solarisfixes.h"
9#endif
10
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <time.h>
15#include <limits.h>
16#include <unistd.h>
17#include <errno.h>
3688d7f3 18#include <inttypes.h>
d06a5b23 19#include <pthread.h>
e2641e09 20
21#include "ae.h" /* Event driven programming library */
22#include "sds.h" /* Dynamic safe strings */
23#include "dict.h" /* Hash tables */
24#include "adlist.h" /* Linked lists */
25#include "zmalloc.h" /* total memory usage aware version of malloc/free */
26#include "anet.h" /* Networking the easy way */
27#include "zipmap.h" /* Compact string -> string data structure */
28#include "ziplist.h" /* Compact list data structure */
96ffb2fe 29#include "intset.h" /* Compact integer set structure */
e2641e09 30#include "version.h"
31
32/* Error codes */
33#define REDIS_OK 0
34#define REDIS_ERR -1
35
36/* Static server configuration */
37#define REDIS_SERVERPORT 6379 /* TCP port */
38#define REDIS_MAXIDLETIME (60*5) /* default client timeout */
39#define REDIS_IOBUF_LEN 1024
40#define REDIS_LOADBUF_LEN 1024
41#define REDIS_STATIC_ARGS 8
42#define REDIS_DEFAULT_DBNUM 16
43#define REDIS_CONFIGLINE_MAX 1024
44#define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
45#define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
46#define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
47#define REDIS_MAX_WRITE_PER_EVENT (1024*64)
48#define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
49#define REDIS_SHARED_INTEGERS 10000
36c19d03 50#define REDIS_REPLY_CHUNK_BYTES (5*1500) /* 5 TCP packets with default MTU */
834ef78e 51
e2641e09 52/* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
53#define REDIS_WRITEV_THRESHOLD 3
54/* Max number of iovecs used for each writev call */
55#define REDIS_WRITEV_IOVEC_COUNT 256
56
57/* Hash table parameters */
58#define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
59
33aba595
PN
60/* Command flags:
61 * REDIS_CMD_DENYOOM:
62 * Commands marked with this flag will return an error when 'maxmemory' is
63 * set and the server is using more than 'maxmemory' bytes of memory.
64 * In short: commands with this flag are denied on low memory conditions.
65 * REDIS_CMD_FORCE_REPLICATION:
66 * Force replication even if dirty is 0. */
67#define REDIS_CMD_DENYOOM 4
68#define REDIS_CMD_FORCE_REPLICATION 8
e2641e09 69
70/* Object types */
71#define REDIS_STRING 0
72#define REDIS_LIST 1
73#define REDIS_SET 2
74#define REDIS_ZSET 3
75#define REDIS_HASH 4
76#define REDIS_VMPOINTER 8
77
78/* Objects encoding. Some kind of objects like Strings and Hashes can be
79 * internally represented in multiple ways. The 'encoding' field of the object
80 * is set to one of this fields for this object. */
81#define REDIS_ENCODING_RAW 0 /* Raw representation */
82#define REDIS_ENCODING_INT 1 /* Encoded as integer */
83#define REDIS_ENCODING_HT 2 /* Encoded as hash table */
84#define REDIS_ENCODING_ZIPMAP 3 /* Encoded as zipmap */
85#define REDIS_ENCODING_LINKEDLIST 4 /* Encoded as regular linked list */
86#define REDIS_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
96ffb2fe 87#define REDIS_ENCODING_INTSET 6 /* Encoded as intset */
e2641e09 88
89/* Object types only used for dumping to disk */
90#define REDIS_EXPIRETIME 253
91#define REDIS_SELECTDB 254
92#define REDIS_EOF 255
93
94/* Defines related to the dump file format. To store 32 bits lengths for short
95 * keys requires a lot of space, so we check the most significant 2 bits of
96 * the first byte to interpreter the length:
97 *
98 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
99 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
100 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
101 * 11|000000 this means: specially encoded object will follow. The six bits
102 * number specify the kind of object that follows.
103 * See the REDIS_RDB_ENC_* defines.
104 *
105 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
106 * values, will fit inside. */
107#define REDIS_RDB_6BITLEN 0
108#define REDIS_RDB_14BITLEN 1
109#define REDIS_RDB_32BITLEN 2
110#define REDIS_RDB_ENCVAL 3
111#define REDIS_RDB_LENERR UINT_MAX
112
113/* When a length of a string object stored on disk has the first two bits
114 * set, the remaining two bits specify a special encoding for the object
115 * accordingly to the following defines: */
116#define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
117#define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
118#define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
119#define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
120
121/* Virtual memory object->where field. */
122#define REDIS_VM_MEMORY 0 /* The object is on memory */
123#define REDIS_VM_SWAPPED 1 /* The object is on disk */
124#define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
125#define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
126
127/* Virtual memory static configuration stuff.
128 * Check vmFindContiguousPages() to know more about this magic numbers. */
129#define REDIS_VM_MAX_NEAR_PAGES 65536
130#define REDIS_VM_MAX_RANDOM_JUMP 4096
131#define REDIS_VM_MAX_THREADS 32
132#define REDIS_THREAD_STACK_SIZE (1024*1024*4)
133/* The following is the *percentage* of completed I/O jobs to process when the
134 * handelr is called. While Virtual Memory I/O operations are performed by
135 * threads, this operations must be processed by the main thread when completed
136 * in order to take effect. */
137#define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
138
139/* Client flags */
140#define REDIS_SLAVE 1 /* This client is a slave server */
141#define REDIS_MASTER 2 /* This client is a master server */
142#define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
143#define REDIS_MULTI 8 /* This client is in a MULTI context */
144#define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
145#define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
146#define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
5e78edb3 147#define REDIS_CLOSE_AFTER_REPLY 128 /* Close after writing entire reply. */
cd8788f2
PN
148
149/* Client request types */
150#define REDIS_REQ_INLINE 1
151#define REDIS_REQ_MULTIBULK 2
e2641e09 152
153/* Slave replication state - slave side */
154#define REDIS_REPL_NONE 0 /* No active replication */
155#define REDIS_REPL_CONNECT 1 /* Must connect to master */
156#define REDIS_REPL_CONNECTED 2 /* Connected to master */
157
158/* Slave replication state - from the point of view of master
159 * Note that in SEND_BULK and ONLINE state the slave receives new updates
160 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
161 * to start the next background saving in order to send updates to it. */
162#define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
163#define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
164#define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
165#define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
166
167/* List related stuff */
168#define REDIS_HEAD 0
169#define REDIS_TAIL 1
170
171/* Sort operations */
172#define REDIS_SORT_GET 0
173#define REDIS_SORT_ASC 1
174#define REDIS_SORT_DESC 2
175#define REDIS_SORTKEY_MAX 1024
176
177/* Log levels */
178#define REDIS_DEBUG 0
179#define REDIS_VERBOSE 1
180#define REDIS_NOTICE 2
181#define REDIS_WARNING 3
182
183/* Anti-warning macro... */
184#define REDIS_NOTUSED(V) ((void) V)
185
186#define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
187#define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
188
189/* Append only defines */
190#define APPENDFSYNC_NO 0
191#define APPENDFSYNC_ALWAYS 1
192#define APPENDFSYNC_EVERYSEC 2
193
194/* Zip structure related defaults */
195#define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
196#define REDIS_HASH_MAX_ZIPMAP_VALUE 512
197#define REDIS_LIST_MAX_ZIPLIST_ENTRIES 1024
198#define REDIS_LIST_MAX_ZIPLIST_VALUE 32
96ffb2fe 199#define REDIS_SET_MAX_INTSET_ENTRIES 4096
e2641e09 200
201/* Sets operations codes */
202#define REDIS_OP_UNION 0
203#define REDIS_OP_DIFF 1
204#define REDIS_OP_INTER 2
205
165346ca 206/* Redis maxmemory strategies */
207#define REDIS_MAXMEMORY_VOLATILE_LRU 0
208#define REDIS_MAXMEMORY_VOLATILE_TTL 1
209#define REDIS_MAXMEMORY_VOLATILE_RANDOM 2
210#define REDIS_MAXMEMORY_ALLKEYS_LRU 3
211#define REDIS_MAXMEMORY_ALLKEYS_RANDOM 4
212
e2641e09 213/* We can print the stacktrace, so our assert is defined this way: */
214#define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
215#define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
216void _redisAssert(char *estr, char *file, int line);
217void _redisPanic(char *msg, char *file, int line);
218
219/*-----------------------------------------------------------------------------
220 * Data types
221 *----------------------------------------------------------------------------*/
222
223/* A redis object, that is a type able to hold a string / list / set */
224
225/* The actual Redis Object */
ef59a8bc 226#define REDIS_LRU_CLOCK_MAX ((1<<21)-1) /* Max value of obj->lru */
165346ca 227#define REDIS_LRU_CLOCK_RESOLUTION 10 /* LRU clock resolution in seconds */
e2641e09 228typedef struct redisObject {
229 unsigned type:4;
230 unsigned storage:2; /* REDIS_VM_MEMORY or REDIS_VM_SWAPPING */
231 unsigned encoding:4;
232 unsigned lru:22; /* lru time (relative to server.lruclock) */
233 int refcount;
234 void *ptr;
235 /* VM fields are only allocated if VM is active, otherwise the
236 * object allocation function will just allocate
237 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
238 * Redis without VM active will not have any overhead. */
239} robj;
240
241/* The VM pointer structure - identifies an object in the swap file.
242 *
243 * This object is stored in place of the value
244 * object in the main key->value hash table representing a database.
245 * Note that the first fields (type, storage) are the same as the redisObject
246 * structure so that vmPointer strucuters can be accessed even when casted
247 * as redisObject structures.
248 *
249 * This is useful as we don't know if a value object is or not on disk, but we
250 * are always able to read obj->storage to check this. For vmPointer
251 * structures "type" is set to REDIS_VMPOINTER (even if without this field
252 * is still possible to check the kind of object from the value of 'storage').*/
253typedef struct vmPointer {
254 unsigned type:4;
255 unsigned storage:2; /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
256 unsigned notused:26;
257 unsigned int vtype; /* type of the object stored in the swap file */
258 off_t page; /* the page at witch the object is stored on disk */
259 off_t usedpages; /* number of pages used on disk */
260} vmpointer;
261
262/* Macro used to initalize a Redis object allocated on the stack.
263 * Note that this macro is taken near the structure definition to make sure
264 * we'll update it when the structure is changed, to avoid bugs like
265 * bug #85 introduced exactly in this way. */
266#define initStaticStringObject(_var,_ptr) do { \
267 _var.refcount = 1; \
268 _var.type = REDIS_STRING; \
269 _var.encoding = REDIS_ENCODING_RAW; \
270 _var.ptr = _ptr; \
271 _var.storage = REDIS_VM_MEMORY; \
272} while(0);
273
274typedef struct redisDb {
275 dict *dict; /* The keyspace for this DB */
276 dict *expires; /* Timeout of keys with a timeout set */
277 dict *blocking_keys; /* Keys with clients waiting for data (BLPOP) */
278 dict *io_keys; /* Keys with clients waiting for VM I/O */
279 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
280 int id;
281} redisDb;
282
283/* Client MULTI/EXEC state */
284typedef struct multiCmd {
285 robj **argv;
286 int argc;
287 struct redisCommand *cmd;
288} multiCmd;
289
290typedef struct multiState {
291 multiCmd *commands; /* Array of MULTI commands */
292 int count; /* Total number of MULTI commands */
293} multiState;
294
295/* With multiplexing we need to take per-clinet state.
296 * Clients are taken in a liked list. */
297typedef struct redisClient {
298 int fd;
299 redisDb *db;
300 int dictid;
301 sds querybuf;
cd8788f2
PN
302 int argc;
303 robj **argv;
304 int reqtype;
305 int multibulklen; /* number of multi bulk arguments left to read */
306 long bulklen; /* length of bulk argument in multi bulk request */
e2641e09 307 list *reply;
308 int sentlen;
309 time_t lastinteraction; /* time of the last interaction, used for timeout */
310 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
311 int slaveseldb; /* slave selected db, if this client is a slave */
312 int authenticated; /* when requirepass is non-NULL */
313 int replstate; /* replication state if this is a slave */
314 int repldbfd; /* replication DB file descriptor */
315 long repldboff; /* replication DB file offset */
316 off_t repldbsize; /* replication DB file size */
317 multiState mstate; /* MULTI/EXEC state */
318 robj **blocking_keys; /* The key we are waiting to terminate a blocking
319 * operation such as BLPOP. Otherwise NULL. */
320 int blocking_keys_num; /* Number of blocking keys */
321 time_t blockingto; /* Blocking operation timeout. If UNIX current time
322 * is >= blockingto then the operation timed out. */
323 list *io_keys; /* Keys this client is waiting to be loaded from the
324 * swap file in order to continue. */
325 list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */
326 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
327 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
834ef78e
PN
328
329 /* Response buffer */
330 int bufpos;
f3357792 331 char buf[REDIS_REPLY_CHUNK_BYTES];
e2641e09 332} redisClient;
333
334struct saveparam {
335 time_t seconds;
336 int changes;
337};
338
339struct sharedObjectsStruct {
340 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *cnegone, *pong, *space,
341 *colon, *nullbulk, *nullmultibulk, *queued,
342 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
343 *outofrangeerr, *plus,
344 *select0, *select1, *select2, *select3, *select4,
345 *select5, *select6, *select7, *select8, *select9,
346 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk, *mbulk3,
347 *mbulk4, *psubscribebulk, *punsubscribebulk,
348 *integers[REDIS_SHARED_INTEGERS];
349};
350
351/* Global server state structure */
352struct redisServer {
0e5441d8 353 pthread_t mainthread;
e2641e09 354 int port;
355 int fd;
356 redisDb *db;
357 long long dirty; /* changes to DB from the last save */
2f6b31c3 358 long long dirty_before_bgsave; /* used to restore dirty on failed BGSAVE */
e2641e09 359 list *clients;
360 list *slaves, *monitors;
361 char neterr[ANET_ERR_LEN];
362 aeEventLoop *el;
363 int cronloops; /* number of times the cron function run */
364 list *objfreelist; /* A list of freed objects to avoid malloc() */
53eeeaff 365 time_t lastsave; /* Unix time of last save succeeede */
e2641e09 366 /* Fields used only for stats */
53eeeaff 367 time_t stat_starttime; /* server start time */
368 long long stat_numcommands; /* number of processed commands */
369 long long stat_numconnections; /* number of connections received */
370 long long stat_expiredkeys; /* number of expired keys */
371 long long stat_keyspace_hits; /* number of successful lookups of keys */
372 long long stat_keyspace_misses; /* number of failed lookups of keys */
e2641e09 373 /* Configuration */
374 int verbosity;
375 int glueoutputbuf;
376 int maxidletime;
377 int dbnum;
378 int daemonize;
379 int appendonly;
380 int appendfsync;
381 int no_appendfsync_on_rewrite;
382 int shutdown_asap;
383 time_t lastfsync;
384 int appendfd;
385 int appendseldb;
386 char *pidfile;
387 pid_t bgsavechildpid;
388 pid_t bgrewritechildpid;
389 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
390 sds aofbuf; /* AOF buffer, written before entering the event loop */
391 struct saveparam *saveparams;
392 int saveparamslen;
393 char *logfile;
394 char *bindaddr;
395 char *dbfilename;
396 char *appendfilename;
397 char *requirepass;
398 int rdbcompression;
399 int activerehashing;
400 /* Replication related */
401 int isslave;
402 char *masterauth;
403 char *masterhost;
404 int masterport;
405 redisClient *master; /* client that is master for this slave */
406 int replstate;
407 unsigned int maxclients;
408 unsigned long long maxmemory;
165346ca 409 int maxmemory_policy;
410 int maxmemory_samples;
e2641e09 411 unsigned int blpop_blocked_clients;
412 unsigned int vm_blocked_clients;
413 /* Sort parameters - qsort_r() is only available under BSD so we
414 * have to take this state global, in order to pass it to sortCompare() */
415 int sort_desc;
416 int sort_alpha;
417 int sort_bypattern;
418 /* Virtual memory configuration */
419 int vm_enabled;
420 char *vm_swap_file;
421 off_t vm_page_size;
422 off_t vm_pages;
423 unsigned long long vm_max_memory;
424 /* Zip structure config */
425 size_t hash_max_zipmap_entries;
426 size_t hash_max_zipmap_value;
427 size_t list_max_ziplist_entries;
428 size_t list_max_ziplist_value;
96ffb2fe 429 size_t set_max_intset_entries;
e2641e09 430 /* Virtual memory state */
431 FILE *vm_fp;
432 int vm_fd;
433 off_t vm_next_page; /* Next probably empty page */
434 off_t vm_near_pages; /* Number of pages allocated sequentially */
435 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
436 time_t unixtime; /* Unix time sampled every second. */
437 /* Virtual memory I/O threads stuff */
438 /* An I/O thread process an element taken from the io_jobs queue and
439 * put the result of the operation in the io_done list. While the
440 * job is being processed, it's put on io_processing queue. */
441 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
442 list *io_processing; /* List of VM I/O jobs being processed */
443 list *io_processed; /* List of VM I/O jobs already processed */
444 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
445 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
446 pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
447 pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
448 pthread_attr_t io_threads_attr; /* attributes for threads creation */
449 int io_active_threads; /* Number of running I/O threads */
450 int vm_max_threads; /* Max number of I/O threads running at the same time */
451 /* Our main thread is blocked on the event loop, locking for sockets ready
452 * to be read or written, so when a threaded I/O operation is ready to be
453 * processed by the main thread, the I/O thread will use a unix pipe to
454 * awake the main thread. The followings are the two pipe FDs. */
455 int io_ready_pipe_read;
456 int io_ready_pipe_write;
457 /* Virtual memory stats */
458 unsigned long long vm_stats_used_pages;
459 unsigned long long vm_stats_swapped_objects;
460 unsigned long long vm_stats_swapouts;
461 unsigned long long vm_stats_swapins;
462 /* Pubsub */
463 dict *pubsub_channels; /* Map channels to list of subscribed clients */
464 list *pubsub_patterns; /* A list of pubsub_patterns */
465 /* Misc */
466 FILE *devnull;
467 unsigned lruclock:22; /* clock incrementing every minute, for LRU */
468 unsigned lruclock_padding:10;
469};
470
471typedef struct pubsubPattern {
472 redisClient *client;
473 robj *pattern;
474} pubsubPattern;
475
476typedef void redisCommandProc(redisClient *c);
477typedef void redisVmPreloadProc(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
478struct redisCommand {
479 char *name;
480 redisCommandProc *proc;
481 int arity;
482 int flags;
483 /* Use a function to determine which keys need to be loaded
484 * in the background prior to executing this command. Takes precedence
485 * over vm_firstkey and others, ignored when NULL */
486 redisVmPreloadProc *vm_preload_proc;
487 /* What keys should be loaded in background when calling this command? */
488 int vm_firstkey; /* The first argument that's a key (0 = no keys) */
489 int vm_lastkey; /* THe last argument that's a key */
490 int vm_keystep; /* The step between first and last key */
491};
492
493struct redisFunctionSym {
494 char *name;
495 unsigned long pointer;
496};
497
498typedef struct _redisSortObject {
499 robj *obj;
500 union {
501 double score;
502 robj *cmpobj;
503 } u;
504} redisSortObject;
505
506typedef struct _redisSortOperation {
507 int type;
508 robj *pattern;
509} redisSortOperation;
510
511/* ZSETs use a specialized version of Skiplists */
e2641e09 512typedef struct zskiplistNode {
e2641e09 513 robj *obj;
2159782b
PN
514 double score;
515 struct zskiplistNode *backward;
516 struct zskiplistLevel {
517 struct zskiplistNode *forward;
518 unsigned int span;
519 } level[];
e2641e09 520} zskiplistNode;
521
522typedef struct zskiplist {
523 struct zskiplistNode *header, *tail;
524 unsigned long length;
525 int level;
526} zskiplist;
527
528typedef struct zset {
529 dict *dict;
530 zskiplist *zsl;
531} zset;
532
533/* VM threaded I/O request message */
534#define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
535#define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
536#define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
537typedef struct iojob {
538 int type; /* Request type, REDIS_IOJOB_* */
539 redisDb *db;/* Redis database */
540 robj *key; /* This I/O request is about swapping this key */
541 robj *id; /* Unique identifier of this job:
542 this is the object to swap for REDIS_IOREQ_*_SWAP, or the
543 vmpointer objct for REDIS_IOREQ_LOAD. */
544 robj *val; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
545 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
546 off_t page; /* Swap page where to read/write the object */
547 off_t pages; /* Swap pages needed to save object. PREPARE_SWAP return val */
548 int canceled; /* True if this command was canceled by blocking side of VM */
549 pthread_t thread; /* ID of the thread processing this entry */
550} iojob;
551
552/* Structure to hold list iteration abstraction. */
553typedef struct {
554 robj *subject;
555 unsigned char encoding;
556 unsigned char direction; /* Iteration direction */
557 unsigned char *zi;
558 listNode *ln;
559} listTypeIterator;
560
561/* Structure for an entry while iterating over a list. */
562typedef struct {
563 listTypeIterator *li;
564 unsigned char *zi; /* Entry in ziplist */
565 listNode *ln; /* Entry in linked list */
566} listTypeEntry;
567
96ffb2fe
PN
568/* Structure to hold set iteration abstraction. */
569typedef struct {
570 robj *subject;
571 int encoding;
572 int ii; /* intset iterator */
573 dictIterator *di;
cb72d0f1 574} setTypeIterator;
96ffb2fe 575
e2641e09 576/* Structure to hold hash iteration abstration. Note that iteration over
577 * hashes involves both fields and values. Because it is possible that
578 * not both are required, store pointers in the iterator to avoid
579 * unnecessary memory allocation for fields/values. */
580typedef struct {
581 int encoding;
582 unsigned char *zi;
583 unsigned char *zk, *zv;
584 unsigned int zklen, zvlen;
585
586 dictIterator *di;
587 dictEntry *de;
588} hashTypeIterator;
589
590#define REDIS_HASH_KEY 1
591#define REDIS_HASH_VALUE 2
592
593/*-----------------------------------------------------------------------------
594 * Extern declarations
595 *----------------------------------------------------------------------------*/
596
597extern struct redisServer server;
598extern struct sharedObjectsStruct shared;
599extern dictType setDictType;
600extern dictType zsetDictType;
601extern double R_Zero, R_PosInf, R_NegInf, R_Nan;
602dictType hashDictType;
603
604/*-----------------------------------------------------------------------------
605 * Functions prototypes
606 *----------------------------------------------------------------------------*/
607
608/* networking.c -- Networking and Client related operations */
609redisClient *createClient(int fd);
610void closeTimedoutClients(void);
611void freeClient(redisClient *c);
612void resetClient(redisClient *c);
613void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask);
614void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
615void addReply(redisClient *c, robj *obj);
b301c1fc
PN
616void *addDeferredMultiBulkLength(redisClient *c);
617void setDeferredMultiBulkLength(redisClient *c, void *node, long length);
e2641e09 618void addReplySds(redisClient *c, sds s);
619void processInputBuffer(redisClient *c);
620void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
621void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
622void addReplyBulk(redisClient *c, robj *obj);
623void addReplyBulkCString(redisClient *c, char *s);
624void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
625void addReply(redisClient *c, robj *obj);
626void addReplySds(redisClient *c, sds s);
3ab20376
PN
627void addReplyError(redisClient *c, char *err);
628void addReplyStatus(redisClient *c, char *status);
e2641e09 629void addReplyDouble(redisClient *c, double d);
630void addReplyLongLong(redisClient *c, long long ll);
0537e7bf 631void addReplyMultiBulkLen(redisClient *c, long length);
e2641e09 632void *dupClientReplyValue(void *o);
633
3ab20376
PN
634#ifdef __GNUC__
635void addReplyErrorFormat(redisClient *c, const char *fmt, ...)
636 __attribute__((format(printf, 2, 3)));
637void addReplyStatusFormat(redisClient *c, const char *fmt, ...)
638 __attribute__((format(printf, 2, 3)));
639#else
640void addReplyErrorFormat(redisClient *c, const char *fmt, ...);
641void addReplyStatusFormat(redisClient *c, const char *fmt, ...);
642#endif
643
e2641e09 644/* List data type */
645void listTypeTryConversion(robj *subject, robj *value);
646void listTypePush(robj *subject, robj *value, int where);
647robj *listTypePop(robj *subject, int where);
648unsigned long listTypeLength(robj *subject);
649listTypeIterator *listTypeInitIterator(robj *subject, int index, unsigned char direction);
650void listTypeReleaseIterator(listTypeIterator *li);
651int listTypeNext(listTypeIterator *li, listTypeEntry *entry);
652robj *listTypeGet(listTypeEntry *entry);
653void listTypeInsert(listTypeEntry *entry, robj *value, int where);
654int listTypeEqual(listTypeEntry *entry, robj *o);
655void listTypeDelete(listTypeEntry *entry);
656void listTypeConvert(robj *subject, int enc);
657void unblockClientWaitingData(redisClient *c);
658int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
659void popGenericCommand(redisClient *c, int where);
660
661/* MULTI/EXEC/WATCH... */
662void unwatchAllKeys(redisClient *c);
663void initClientMultiState(redisClient *c);
664void freeClientMultiState(redisClient *c);
665void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
666void touchWatchedKey(redisDb *db, robj *key);
667void touchWatchedKeysOnFlush(int dbid);
668
669/* Redis object implementation */
670void decrRefCount(void *o);
671void incrRefCount(robj *o);
672void freeStringObject(robj *o);
673void freeListObject(robj *o);
674void freeSetObject(robj *o);
675void freeZsetObject(robj *o);
676void freeHashObject(robj *o);
677robj *createObject(int type, void *ptr);
678robj *createStringObject(char *ptr, size_t len);
679robj *dupStringObject(robj *o);
680robj *tryObjectEncoding(robj *o);
681robj *getDecodedObject(robj *o);
682size_t stringObjectLen(robj *o);
683int tryFreeOneObjectFromFreelist(void);
684robj *createStringObjectFromLongLong(long long value);
685robj *createListObject(void);
686robj *createZiplistObject(void);
687robj *createSetObject(void);
96ffb2fe 688robj *createIntsetObject(void);
e2641e09 689robj *createHashObject(void);
690robj *createZsetObject(void);
691int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg);
692int checkType(redisClient *c, robj *o, int type);
693int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg);
694int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg);
695int getLongLongFromObject(robj *o, long long *target);
696char *strEncoding(int encoding);
697int compareStringObjects(robj *a, robj *b);
698int equalStringObjects(robj *a, robj *b);
ef59a8bc 699unsigned long estimateObjectIdleTime(robj *o);
e2641e09 700
19e61097 701/* Synchronous I/O with timeout */
702int syncWrite(int fd, char *ptr, ssize_t size, int timeout);
703int syncRead(int fd, char *ptr, ssize_t size, int timeout);
704int syncReadLine(int fd, char *ptr, ssize_t size, int timeout);
d08fac3e 705int fwriteBulkString(FILE *fp, char *s, unsigned long len);
706int fwriteBulkDouble(FILE *fp, double d);
707int fwriteBulkLongLong(FILE *fp, long long l);
244201f6 708int fwriteBulkObject(FILE *fp, robj *obj);
19e61097 709
e2641e09 710/* Replication */
711void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
712void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
713int syncWithMaster(void);
714void updateSlavesWaitingBgsave(int bgsaveerr);
715
716/* RDB persistence */
717int rdbLoad(char *filename);
718int rdbSaveBackground(char *filename);
719void rdbRemoveTempFile(pid_t childpid);
720int rdbSave(char *filename);
721int rdbSaveObject(FILE *fp, robj *o);
722off_t rdbSavedObjectPages(robj *o, FILE *fp);
723off_t rdbSavedObjectLen(robj *o, FILE *fp);
724robj *rdbLoadObject(int type, FILE *fp);
725void backgroundSaveDoneHandler(int statloc);
726
727/* AOF persistence */
728void flushAppendOnlyFile(void);
729void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
730void aofRemoveTempFile(pid_t childpid);
731int rewriteAppendOnlyFileBackground(void);
732int loadAppendOnlyFile(char *filename);
733void stopAppendOnly(void);
734int startAppendOnly(void);
735void backgroundRewriteDoneHandler(int statloc);
736
737/* Sorted sets data type */
738zskiplist *zslCreate(void);
739void zslFree(zskiplist *zsl);
69ef89f2 740zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj);
e2641e09 741
742/* Core functions */
743void freeMemoryIfNeeded(void);
744int processCommand(redisClient *c);
745void setupSigSegvAction(void);
746struct redisCommand *lookupCommand(char *name);
747void call(redisClient *c, struct redisCommand *cmd);
748int prepareForShutdown();
749void redisLog(int level, const char *fmt, ...);
750void usage();
751void updateDictResizePolicy(void);
752int htNeedsResize(dict *dict);
753void oom(const char *msg);
754
755/* Virtual Memory */
756void vmInit(void);
757void vmMarkPagesFree(off_t page, off_t count);
758robj *vmLoadObject(robj *o);
759robj *vmPreviewObject(robj *o);
760int vmSwapOneObjectBlocking(void);
761int vmSwapOneObjectThreaded(void);
762int vmCanSwapOut(void);
763void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
764void vmCancelThreadedIOJob(robj *o);
765void lockThreadedIO(void);
766void unlockThreadedIO(void);
767int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
768void freeIOJob(iojob *j);
769void queueIOJob(iojob *j);
770int vmWriteObjectOnSwap(robj *o, off_t page);
771robj *vmReadObjectFromSwap(off_t page, int type);
772void waitEmptyIOJobsQueue(void);
773void vmReopenSwapFile(void);
774int vmFreePage(off_t page);
775void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
776void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
777int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd);
778int dontWaitForSwappedKey(redisClient *c, robj *key);
779void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
780vmpointer *vmSwapObjectBlocking(robj *val);
781
96ffb2fe
PN
782/* Set data type */
783robj *setTypeCreate(robj *value);
784int setTypeAdd(robj *subject, robj *value);
785int setTypeRemove(robj *subject, robj *value);
786int setTypeIsMember(robj *subject, robj *value);
cb72d0f1
PN
787setTypeIterator *setTypeInitIterator(robj *subject);
788void setTypeReleaseIterator(setTypeIterator *si);
789robj *setTypeNext(setTypeIterator *si);
96ffb2fe
PN
790robj *setTypeRandomElement(robj *subject);
791unsigned long setTypeSize(robj *subject);
792void setTypeConvert(robj *subject, int enc);
793
e2641e09 794/* Hash data type */
795void convertToRealHash(robj *o);
796void hashTypeTryConversion(robj *subject, robj **argv, int start, int end);
797void hashTypeTryObjectEncoding(robj *subject, robj **o1, robj **o2);
798robj *hashTypeGet(robj *o, robj *key);
799int hashTypeExists(robj *o, robj *key);
800int hashTypeSet(robj *o, robj *key, robj *value);
801int hashTypeDelete(robj *o, robj *key);
802unsigned long hashTypeLength(robj *o);
803hashTypeIterator *hashTypeInitIterator(robj *subject);
804void hashTypeReleaseIterator(hashTypeIterator *hi);
805int hashTypeNext(hashTypeIterator *hi);
806robj *hashTypeCurrent(hashTypeIterator *hi, int what);
807robj *hashTypeLookupWriteOrCreate(redisClient *c, robj *key);
808
809/* Pub / Sub */
810int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
811int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
812void freePubsubPattern(void *p);
813int listMatchPubsubPattern(void *a, void *b);
814
815/* Utility functions */
816int stringmatchlen(const char *pattern, int patternLen,
817 const char *string, int stringLen, int nocase);
818int stringmatch(const char *pattern, const char *string, int nocase);
819long long memtoll(const char *p, int *err);
820int ll2string(char *s, size_t len, long long value);
821int isStringRepresentableAsLong(sds s, long *longval);
ec7e1389 822int isStringRepresentableAsLongLong(sds s, long long *longval);
823int isObjectRepresentableAsLongLong(robj *o, long long *llongval);
e2641e09 824
825/* Configuration */
826void loadServerConfig(char *filename);
827void appendServerSaveParams(time_t seconds, int changes);
828void resetServerSaveParams();
829
830/* db.c -- Keyspace access API */
831int removeExpire(redisDb *db, robj *key);
bcf2995c 832void propagateExpire(redisDb *db, robj *key);
e2641e09 833int expireIfNeeded(redisDb *db, robj *key);
e2641e09 834time_t getExpire(redisDb *db, robj *key);
0cf5b7b5 835void setExpire(redisDb *db, robj *key, time_t when);
e2641e09 836robj *lookupKey(redisDb *db, robj *key);
837robj *lookupKeyRead(redisDb *db, robj *key);
838robj *lookupKeyWrite(redisDb *db, robj *key);
839robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply);
840robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply);
841int dbAdd(redisDb *db, robj *key, robj *val);
842int dbReplace(redisDb *db, robj *key, robj *val);
843int dbExists(redisDb *db, robj *key);
844robj *dbRandomKey(redisDb *db);
845int dbDelete(redisDb *db, robj *key);
846long long emptyDb();
847int selectDb(redisClient *c, int id);
848
849/* Git SHA1 */
850char *redisGitSHA1(void);
851char *redisGitDirty(void);
852
853/* Commands prototypes */
854void authCommand(redisClient *c);
855void pingCommand(redisClient *c);
856void echoCommand(redisClient *c);
857void setCommand(redisClient *c);
858void setnxCommand(redisClient *c);
859void setexCommand(redisClient *c);
860void getCommand(redisClient *c);
861void delCommand(redisClient *c);
862void existsCommand(redisClient *c);
863void incrCommand(redisClient *c);
864void decrCommand(redisClient *c);
865void incrbyCommand(redisClient *c);
866void decrbyCommand(redisClient *c);
867void selectCommand(redisClient *c);
868void randomkeyCommand(redisClient *c);
869void keysCommand(redisClient *c);
870void dbsizeCommand(redisClient *c);
871void lastsaveCommand(redisClient *c);
872void saveCommand(redisClient *c);
873void bgsaveCommand(redisClient *c);
874void bgrewriteaofCommand(redisClient *c);
875void shutdownCommand(redisClient *c);
876void moveCommand(redisClient *c);
877void renameCommand(redisClient *c);
878void renamenxCommand(redisClient *c);
879void lpushCommand(redisClient *c);
880void rpushCommand(redisClient *c);
881void lpushxCommand(redisClient *c);
882void rpushxCommand(redisClient *c);
883void linsertCommand(redisClient *c);
884void lpopCommand(redisClient *c);
885void rpopCommand(redisClient *c);
886void llenCommand(redisClient *c);
887void lindexCommand(redisClient *c);
888void lrangeCommand(redisClient *c);
889void ltrimCommand(redisClient *c);
890void typeCommand(redisClient *c);
891void lsetCommand(redisClient *c);
892void saddCommand(redisClient *c);
893void sremCommand(redisClient *c);
894void smoveCommand(redisClient *c);
895void sismemberCommand(redisClient *c);
896void scardCommand(redisClient *c);
897void spopCommand(redisClient *c);
898void srandmemberCommand(redisClient *c);
899void sinterCommand(redisClient *c);
900void sinterstoreCommand(redisClient *c);
901void sunionCommand(redisClient *c);
902void sunionstoreCommand(redisClient *c);
903void sdiffCommand(redisClient *c);
904void sdiffstoreCommand(redisClient *c);
905void syncCommand(redisClient *c);
906void flushdbCommand(redisClient *c);
907void flushallCommand(redisClient *c);
908void sortCommand(redisClient *c);
909void lremCommand(redisClient *c);
910void rpoplpushcommand(redisClient *c);
911void infoCommand(redisClient *c);
912void mgetCommand(redisClient *c);
913void monitorCommand(redisClient *c);
914void expireCommand(redisClient *c);
915void expireatCommand(redisClient *c);
916void getsetCommand(redisClient *c);
917void ttlCommand(redisClient *c);
a539d29a 918void persistCommand(redisClient *c);
e2641e09 919void slaveofCommand(redisClient *c);
920void debugCommand(redisClient *c);
921void msetCommand(redisClient *c);
922void msetnxCommand(redisClient *c);
923void zaddCommand(redisClient *c);
924void zincrbyCommand(redisClient *c);
925void zrangeCommand(redisClient *c);
926void zrangebyscoreCommand(redisClient *c);
25bb8a44 927void zrevrangebyscoreCommand(redisClient *c);
e2641e09 928void zcountCommand(redisClient *c);
929void zrevrangeCommand(redisClient *c);
930void zcardCommand(redisClient *c);
931void zremCommand(redisClient *c);
932void zscoreCommand(redisClient *c);
933void zremrangebyscoreCommand(redisClient *c);
934void multiCommand(redisClient *c);
935void execCommand(redisClient *c);
936void discardCommand(redisClient *c);
937void blpopCommand(redisClient *c);
938void brpopCommand(redisClient *c);
939void appendCommand(redisClient *c);
940void substrCommand(redisClient *c);
80091bba 941void strlenCommand(redisClient *c);
e2641e09 942void zrankCommand(redisClient *c);
943void zrevrankCommand(redisClient *c);
944void hsetCommand(redisClient *c);
945void hsetnxCommand(redisClient *c);
946void hgetCommand(redisClient *c);
947void hmsetCommand(redisClient *c);
948void hmgetCommand(redisClient *c);
949void hdelCommand(redisClient *c);
950void hlenCommand(redisClient *c);
951void zremrangebyrankCommand(redisClient *c);
952void zunionstoreCommand(redisClient *c);
953void zinterstoreCommand(redisClient *c);
954void hkeysCommand(redisClient *c);
955void hvalsCommand(redisClient *c);
956void hgetallCommand(redisClient *c);
957void hexistsCommand(redisClient *c);
958void configCommand(redisClient *c);
959void hincrbyCommand(redisClient *c);
960void subscribeCommand(redisClient *c);
961void unsubscribeCommand(redisClient *c);
962void psubscribeCommand(redisClient *c);
963void punsubscribeCommand(redisClient *c);
964void publishCommand(redisClient *c);
965void watchCommand(redisClient *c);
966void unwatchCommand(redisClient *c);
967
b3aa6d71 968#if defined(__GNUC__)
b3aa6d71 969void *calloc(size_t count, size_t size) __attribute__ ((deprecated));
970void free(void *ptr) __attribute__ ((deprecated));
971void *malloc(size_t size) __attribute__ ((deprecated));
972void *realloc(void *ptr, size_t size) __attribute__ ((deprecated));
973#endif
974
e2641e09 975#endif