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