]> git.saurik.com Git - redis.git/blob - redis.c
4f5f68a7c9a1caaf78e119931b928c159553c1cb
[redis.git] / redis.c
1 /*
2 * Copyright (c) 2009-2010, 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 #define REDIS_VERSION "2.1.1"
31
32 #include "fmacros.h"
33 #include "config.h"
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39 #include <unistd.h>
40 #include <signal.h>
41
42 #ifdef HAVE_BACKTRACE
43 #include <execinfo.h>
44 #include <ucontext.h>
45 #endif /* HAVE_BACKTRACE */
46
47 #include <sys/wait.h>
48 #include <errno.h>
49 #include <assert.h>
50 #include <ctype.h>
51 #include <stdarg.h>
52 #include <inttypes.h>
53 #include <arpa/inet.h>
54 #include <sys/stat.h>
55 #include <fcntl.h>
56 #include <sys/time.h>
57 #include <sys/resource.h>
58 #include <sys/uio.h>
59 #include <limits.h>
60 #include <float.h>
61 #include <math.h>
62 #include <pthread.h>
63
64 #if defined(__sun)
65 #include "solarisfixes.h"
66 #endif
67
68 #include "redis.h"
69 #include "ae.h" /* Event driven programming library */
70 #include "sds.h" /* Dynamic safe strings */
71 #include "anet.h" /* Networking the easy way */
72 #include "dict.h" /* Hash tables */
73 #include "adlist.h" /* Linked lists */
74 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
75 #include "lzf.h" /* LZF compression library */
76 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
77 #include "zipmap.h" /* Compact dictionary-alike data structure */
78 #include "ziplist.h" /* Compact list data structure */
79 #include "sha1.h" /* SHA1 is used for DEBUG DIGEST */
80 #include "release.h" /* Release and/or git repository information */
81
82 /* Error codes */
83 #define REDIS_OK 0
84 #define REDIS_ERR -1
85
86 /* Static server configuration */
87 #define REDIS_SERVERPORT 6379 /* TCP port */
88 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
89 #define REDIS_IOBUF_LEN 1024
90 #define REDIS_LOADBUF_LEN 1024
91 #define REDIS_STATIC_ARGS 8
92 #define REDIS_DEFAULT_DBNUM 16
93 #define REDIS_CONFIGLINE_MAX 1024
94 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
95 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
96 #define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
97 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
98 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
99
100 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
101 #define REDIS_WRITEV_THRESHOLD 3
102 /* Max number of iovecs used for each writev call */
103 #define REDIS_WRITEV_IOVEC_COUNT 256
104
105 /* Hash table parameters */
106 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
107
108 /* Command flags */
109 #define REDIS_CMD_BULK 1 /* Bulk write command */
110 #define REDIS_CMD_INLINE 2 /* Inline command */
111 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
112 this flags will return an error when the 'maxmemory' option is set in the
113 config file and the server is using more than maxmemory bytes of memory.
114 In short this commands are denied on low memory conditions. */
115 #define REDIS_CMD_DENYOOM 4
116 #define REDIS_CMD_FORCE_REPLICATION 8 /* Force replication even if dirty is 0 */
117
118 /* Object types */
119 #define REDIS_STRING 0
120 #define REDIS_LIST 1
121 #define REDIS_SET 2
122 #define REDIS_ZSET 3
123 #define REDIS_HASH 4
124 #define REDIS_VMPOINTER 8
125
126 /* Objects encoding. Some kind of objects like Strings and Hashes can be
127 * internally represented in multiple ways. The 'encoding' field of the object
128 * is set to one of this fields for this object. */
129 #define REDIS_ENCODING_RAW 0 /* Raw representation */
130 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
131 #define REDIS_ENCODING_HT 2 /* Encoded as hash table */
132 #define REDIS_ENCODING_ZIPMAP 3 /* Encoded as zipmap */
133 #define REDIS_ENCODING_LIST 4 /* Encoded as zipmap */
134 #define REDIS_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
135
136 static char* strencoding[] = {
137 "raw", "int", "hashtable", "zipmap", "list", "ziplist"
138 };
139
140 /* Object types only used for dumping to disk */
141 #define REDIS_EXPIRETIME 253
142 #define REDIS_SELECTDB 254
143 #define REDIS_EOF 255
144
145 /* Defines related to the dump file format. To store 32 bits lengths for short
146 * keys requires a lot of space, so we check the most significant 2 bits of
147 * the first byte to interpreter the length:
148 *
149 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
150 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
151 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
152 * 11|000000 this means: specially encoded object will follow. The six bits
153 * number specify the kind of object that follows.
154 * See the REDIS_RDB_ENC_* defines.
155 *
156 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
157 * values, will fit inside. */
158 #define REDIS_RDB_6BITLEN 0
159 #define REDIS_RDB_14BITLEN 1
160 #define REDIS_RDB_32BITLEN 2
161 #define REDIS_RDB_ENCVAL 3
162 #define REDIS_RDB_LENERR UINT_MAX
163
164 /* When a length of a string object stored on disk has the first two bits
165 * set, the remaining two bits specify a special encoding for the object
166 * accordingly to the following defines: */
167 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
168 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
169 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
170 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
171
172 /* Virtual memory object->where field. */
173 #define REDIS_VM_MEMORY 0 /* The object is on memory */
174 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
175 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
176 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
177
178 /* Virtual memory static configuration stuff.
179 * Check vmFindContiguousPages() to know more about this magic numbers. */
180 #define REDIS_VM_MAX_NEAR_PAGES 65536
181 #define REDIS_VM_MAX_RANDOM_JUMP 4096
182 #define REDIS_VM_MAX_THREADS 32
183 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
184 /* The following is the *percentage* of completed I/O jobs to process when the
185 * handelr is called. While Virtual Memory I/O operations are performed by
186 * threads, this operations must be processed by the main thread when completed
187 * in order to take effect. */
188 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
189
190 /* Client flags */
191 #define REDIS_SLAVE 1 /* This client is a slave server */
192 #define REDIS_MASTER 2 /* This client is a master server */
193 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
194 #define REDIS_MULTI 8 /* This client is in a MULTI context */
195 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
196 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
197 #define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
198
199 /* Slave replication state - slave side */
200 #define REDIS_REPL_NONE 0 /* No active replication */
201 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
202 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
203
204 /* Slave replication state - from the point of view of master
205 * Note that in SEND_BULK and ONLINE state the slave receives new updates
206 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
207 * to start the next background saving in order to send updates to it. */
208 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
209 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
210 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
211 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
212
213 /* List related stuff */
214 #define REDIS_HEAD 0
215 #define REDIS_TAIL 1
216
217 /* Sort operations */
218 #define REDIS_SORT_GET 0
219 #define REDIS_SORT_ASC 1
220 #define REDIS_SORT_DESC 2
221 #define REDIS_SORTKEY_MAX 1024
222
223 /* Log levels */
224 #define REDIS_DEBUG 0
225 #define REDIS_VERBOSE 1
226 #define REDIS_NOTICE 2
227 #define REDIS_WARNING 3
228
229 /* Anti-warning macro... */
230 #define REDIS_NOTUSED(V) ((void) V)
231
232 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
233 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
234
235 /* Append only defines */
236 #define APPENDFSYNC_NO 0
237 #define APPENDFSYNC_ALWAYS 1
238 #define APPENDFSYNC_EVERYSEC 2
239
240 /* Zip structure related defaults */
241 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
242 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
243 #define REDIS_LIST_MAX_ZIPLIST_ENTRIES 1024
244 #define REDIS_LIST_MAX_ZIPLIST_VALUE 32
245
246 /* We can print the stacktrace, so our assert is defined this way: */
247 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
248 #define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
249 static void _redisAssert(char *estr, char *file, int line);
250 static void _redisPanic(char *msg, char *file, int line);
251
252 /*================================= Data types ============================== */
253
254 /* A redis object, that is a type able to hold a string / list / set */
255
256 /* The actual Redis Object */
257 typedef struct redisObject {
258 unsigned type:4;
259 unsigned storage:2; /* REDIS_VM_MEMORY or REDIS_VM_SWAPPING */
260 unsigned encoding:4;
261 unsigned lru:22; /* lru time (relative to server.lruclock) */
262 int refcount;
263 void *ptr;
264 /* VM fields are only allocated if VM is active, otherwise the
265 * object allocation function will just allocate
266 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
267 * Redis without VM active will not have any overhead. */
268 } robj;
269
270 /* The VM pointer structure - identifies an object in the swap file.
271 *
272 * This object is stored in place of the value
273 * object in the main key->value hash table representing a database.
274 * Note that the first fields (type, storage) are the same as the redisObject
275 * structure so that vmPointer strucuters can be accessed even when casted
276 * as redisObject structures.
277 *
278 * This is useful as we don't know if a value object is or not on disk, but we
279 * are always able to read obj->storage to check this. For vmPointer
280 * structures "type" is set to REDIS_VMPOINTER (even if without this field
281 * is still possible to check the kind of object from the value of 'storage').*/
282 typedef struct vmPointer {
283 unsigned type:4;
284 unsigned storage:2; /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
285 unsigned notused:26;
286 unsigned int vtype; /* type of the object stored in the swap file */
287 off_t page; /* the page at witch the object is stored on disk */
288 off_t usedpages; /* number of pages used on disk */
289 } vmpointer;
290
291 /* Macro used to initalize a Redis object allocated on the stack.
292 * Note that this macro is taken near the structure definition to make sure
293 * we'll update it when the structure is changed, to avoid bugs like
294 * bug #85 introduced exactly in this way. */
295 #define initStaticStringObject(_var,_ptr) do { \
296 _var.refcount = 1; \
297 _var.type = REDIS_STRING; \
298 _var.encoding = REDIS_ENCODING_RAW; \
299 _var.ptr = _ptr; \
300 _var.storage = REDIS_VM_MEMORY; \
301 } while(0);
302
303 typedef struct redisDb {
304 dict *dict; /* The keyspace for this DB */
305 dict *expires; /* Timeout of keys with a timeout set */
306 dict *blocking_keys; /* Keys with clients waiting for data (BLPOP) */
307 dict *io_keys; /* Keys with clients waiting for VM I/O */
308 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
309 int id;
310 } redisDb;
311
312 /* Client MULTI/EXEC state */
313 typedef struct multiCmd {
314 robj **argv;
315 int argc;
316 struct redisCommand *cmd;
317 } multiCmd;
318
319 typedef struct multiState {
320 multiCmd *commands; /* Array of MULTI commands */
321 int count; /* Total number of MULTI commands */
322 } multiState;
323
324 /* With multiplexing we need to take per-clinet state.
325 * Clients are taken in a liked list. */
326 typedef struct redisClient {
327 int fd;
328 redisDb *db;
329 int dictid;
330 sds querybuf;
331 robj **argv, **mbargv;
332 int argc, mbargc;
333 int bulklen; /* bulk read len. -1 if not in bulk read mode */
334 int multibulk; /* multi bulk command format active */
335 list *reply;
336 int sentlen;
337 time_t lastinteraction; /* time of the last interaction, used for timeout */
338 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
339 int slaveseldb; /* slave selected db, if this client is a slave */
340 int authenticated; /* when requirepass is non-NULL */
341 int replstate; /* replication state if this is a slave */
342 int repldbfd; /* replication DB file descriptor */
343 long repldboff; /* replication DB file offset */
344 off_t repldbsize; /* replication DB file size */
345 multiState mstate; /* MULTI/EXEC state */
346 robj **blocking_keys; /* The key we are waiting to terminate a blocking
347 * operation such as BLPOP. Otherwise NULL. */
348 int blocking_keys_num; /* Number of blocking keys */
349 time_t blockingto; /* Blocking operation timeout. If UNIX current time
350 * is >= blockingto then the operation timed out. */
351 list *io_keys; /* Keys this client is waiting to be loaded from the
352 * swap file in order to continue. */
353 list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */
354 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
355 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
356 } redisClient;
357
358 struct saveparam {
359 time_t seconds;
360 int changes;
361 };
362
363 /* Global server state structure */
364 struct redisServer {
365 int port;
366 int fd;
367 redisDb *db;
368 long long dirty; /* changes to DB from the last save */
369 list *clients;
370 list *slaves, *monitors;
371 char neterr[ANET_ERR_LEN];
372 aeEventLoop *el;
373 int cronloops; /* number of times the cron function run */
374 list *objfreelist; /* A list of freed objects to avoid malloc() */
375 time_t lastsave; /* Unix time of last save succeeede */
376 /* Fields used only for stats */
377 time_t stat_starttime; /* server start time */
378 long long stat_numcommands; /* number of processed commands */
379 long long stat_numconnections; /* number of connections received */
380 long long stat_expiredkeys; /* number of expired keys */
381 /* Configuration */
382 int verbosity;
383 int glueoutputbuf;
384 int maxidletime;
385 int dbnum;
386 int daemonize;
387 int appendonly;
388 int appendfsync;
389 int no_appendfsync_on_rewrite;
390 int shutdown_asap;
391 time_t lastfsync;
392 int appendfd;
393 int appendseldb;
394 char *pidfile;
395 pid_t bgsavechildpid;
396 pid_t bgrewritechildpid;
397 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
398 sds aofbuf; /* AOF buffer, written before entering the event loop */
399 struct saveparam *saveparams;
400 int saveparamslen;
401 char *logfile;
402 char *bindaddr;
403 char *dbfilename;
404 char *appendfilename;
405 char *requirepass;
406 int rdbcompression;
407 int activerehashing;
408 /* Replication related */
409 int isslave;
410 char *masterauth;
411 char *masterhost;
412 int masterport;
413 redisClient *master; /* client that is master for this slave */
414 int replstate;
415 unsigned int maxclients;
416 unsigned long long maxmemory;
417 unsigned int blpop_blocked_clients;
418 unsigned int vm_blocked_clients;
419 /* Sort parameters - qsort_r() is only available under BSD so we
420 * have to take this state global, in order to pass it to sortCompare() */
421 int sort_desc;
422 int sort_alpha;
423 int sort_bypattern;
424 /* Virtual memory configuration */
425 int vm_enabled;
426 char *vm_swap_file;
427 off_t vm_page_size;
428 off_t vm_pages;
429 unsigned long long vm_max_memory;
430 /* Zip structure config */
431 size_t hash_max_zipmap_entries;
432 size_t hash_max_zipmap_value;
433 size_t list_max_ziplist_entries;
434 size_t list_max_ziplist_value;
435 /* Virtual memory state */
436 FILE *vm_fp;
437 int vm_fd;
438 off_t vm_next_page; /* Next probably empty page */
439 off_t vm_near_pages; /* Number of pages allocated sequentially */
440 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
441 time_t unixtime; /* Unix time sampled every second. */
442 /* Virtual memory I/O threads stuff */
443 /* An I/O thread process an element taken from the io_jobs queue and
444 * put the result of the operation in the io_done list. While the
445 * job is being processed, it's put on io_processing queue. */
446 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
447 list *io_processing; /* List of VM I/O jobs being processed */
448 list *io_processed; /* List of VM I/O jobs already processed */
449 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
450 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
451 pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
452 pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
453 pthread_attr_t io_threads_attr; /* attributes for threads creation */
454 int io_active_threads; /* Number of running I/O threads */
455 int vm_max_threads; /* Max number of I/O threads running at the same time */
456 /* Our main thread is blocked on the event loop, locking for sockets ready
457 * to be read or written, so when a threaded I/O operation is ready to be
458 * processed by the main thread, the I/O thread will use a unix pipe to
459 * awake the main thread. The followings are the two pipe FDs. */
460 int io_ready_pipe_read;
461 int io_ready_pipe_write;
462 /* Virtual memory stats */
463 unsigned long long vm_stats_used_pages;
464 unsigned long long vm_stats_swapped_objects;
465 unsigned long long vm_stats_swapouts;
466 unsigned long long vm_stats_swapins;
467 /* Pubsub */
468 dict *pubsub_channels; /* Map channels to list of subscribed clients */
469 list *pubsub_patterns; /* A list of pubsub_patterns */
470 /* Misc */
471 FILE *devnull;
472 unsigned lruclock:22; /* clock incrementing every minute, for LRU */
473 unsigned lruclock_padding:10;
474 };
475
476 typedef struct pubsubPattern {
477 redisClient *client;
478 robj *pattern;
479 } pubsubPattern;
480
481 typedef void redisCommandProc(redisClient *c);
482 typedef void redisVmPreloadProc(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
483 struct redisCommand {
484 char *name;
485 redisCommandProc *proc;
486 int arity;
487 int flags;
488 /* Use a function to determine which keys need to be loaded
489 * in the background prior to executing this command. Takes precedence
490 * over vm_firstkey and others, ignored when NULL */
491 redisVmPreloadProc *vm_preload_proc;
492 /* What keys should be loaded in background when calling this command? */
493 int vm_firstkey; /* The first argument that's a key (0 = no keys) */
494 int vm_lastkey; /* THe last argument that's a key */
495 int vm_keystep; /* The step between first and last key */
496 };
497
498 struct redisFunctionSym {
499 char *name;
500 unsigned long pointer;
501 };
502
503 typedef struct _redisSortObject {
504 robj *obj;
505 union {
506 double score;
507 robj *cmpobj;
508 } u;
509 } redisSortObject;
510
511 typedef struct _redisSortOperation {
512 int type;
513 robj *pattern;
514 } redisSortOperation;
515
516 /* ZSETs use a specialized version of Skiplists */
517
518 typedef struct zskiplistNode {
519 struct zskiplistNode **forward;
520 struct zskiplistNode *backward;
521 unsigned int *span;
522 double score;
523 robj *obj;
524 } zskiplistNode;
525
526 typedef struct zskiplist {
527 struct zskiplistNode *header, *tail;
528 unsigned long length;
529 int level;
530 } zskiplist;
531
532 typedef struct zset {
533 dict *dict;
534 zskiplist *zsl;
535 } zset;
536
537 /* Our shared "common" objects */
538
539 #define REDIS_SHARED_INTEGERS 10000
540 struct sharedObjectsStruct {
541 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *cnegone, *pong, *space,
542 *colon, *nullbulk, *nullmultibulk, *queued,
543 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
544 *outofrangeerr, *plus,
545 *select0, *select1, *select2, *select3, *select4,
546 *select5, *select6, *select7, *select8, *select9,
547 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk, *mbulk3,
548 *mbulk4, *psubscribebulk, *punsubscribebulk,
549 *integers[REDIS_SHARED_INTEGERS];
550 } shared;
551
552 /* Global vars that are actally used as constants. The following double
553 * values are used for double on-disk serialization, and are initialized
554 * at runtime to avoid strange compiler optimizations. */
555
556 static double R_Zero, R_PosInf, R_NegInf, R_Nan;
557
558 /* VM threaded I/O request message */
559 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
560 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
561 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
562 typedef struct iojob {
563 int type; /* Request type, REDIS_IOJOB_* */
564 redisDb *db;/* Redis database */
565 robj *key; /* This I/O request is about swapping this key */
566 robj *id; /* Unique identifier of this job:
567 this is the object to swap for REDIS_IOREQ_*_SWAP, or the
568 vmpointer objct for REDIS_IOREQ_LOAD. */
569 robj *val; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
570 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
571 off_t page; /* Swap page where to read/write the object */
572 off_t pages; /* Swap pages needed to save object. PREPARE_SWAP return val */
573 int canceled; /* True if this command was canceled by blocking side of VM */
574 pthread_t thread; /* ID of the thread processing this entry */
575 } iojob;
576
577 /*================================ Prototypes =============================== */
578
579 static void freeStringObject(robj *o);
580 static void freeListObject(robj *o);
581 static void freeSetObject(robj *o);
582 static void decrRefCount(void *o);
583 static robj *createObject(int type, void *ptr);
584 static void freeClient(redisClient *c);
585 static int rdbLoad(char *filename);
586 static void addReply(redisClient *c, robj *obj);
587 static void addReplySds(redisClient *c, sds s);
588 static void incrRefCount(robj *o);
589 static int rdbSaveBackground(char *filename);
590 static robj *createStringObject(char *ptr, size_t len);
591 static robj *dupStringObject(robj *o);
592 static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
593 static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
594 static void flushAppendOnlyFile(void);
595 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
596 static int syncWithMaster(void);
597 static robj *tryObjectEncoding(robj *o);
598 static robj *getDecodedObject(robj *o);
599 static int removeExpire(redisDb *db, robj *key);
600 static int expireIfNeeded(redisDb *db, robj *key);
601 static int deleteIfVolatile(redisDb *db, robj *key);
602 static int dbDelete(redisDb *db, robj *key);
603 static time_t getExpire(redisDb *db, robj *key);
604 static int setExpire(redisDb *db, robj *key, time_t when);
605 static void updateSlavesWaitingBgsave(int bgsaveerr);
606 static void freeMemoryIfNeeded(void);
607 static int processCommand(redisClient *c);
608 static void setupSigSegvAction(void);
609 static void rdbRemoveTempFile(pid_t childpid);
610 static void aofRemoveTempFile(pid_t childpid);
611 static size_t stringObjectLen(robj *o);
612 static void processInputBuffer(redisClient *c);
613 static zskiplist *zslCreate(void);
614 static void zslFree(zskiplist *zsl);
615 static void zslInsert(zskiplist *zsl, double score, robj *obj);
616 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
617 static void initClientMultiState(redisClient *c);
618 static void freeClientMultiState(redisClient *c);
619 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
620 static void unblockClientWaitingData(redisClient *c);
621 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
622 static void vmInit(void);
623 static void vmMarkPagesFree(off_t page, off_t count);
624 static robj *vmLoadObject(robj *o);
625 static robj *vmPreviewObject(robj *o);
626 static int vmSwapOneObjectBlocking(void);
627 static int vmSwapOneObjectThreaded(void);
628 static int vmCanSwapOut(void);
629 static int tryFreeOneObjectFromFreelist(void);
630 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
631 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
632 static void vmCancelThreadedIOJob(robj *o);
633 static void lockThreadedIO(void);
634 static void unlockThreadedIO(void);
635 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
636 static void freeIOJob(iojob *j);
637 static void queueIOJob(iojob *j);
638 static int vmWriteObjectOnSwap(robj *o, off_t page);
639 static robj *vmReadObjectFromSwap(off_t page, int type);
640 static void waitEmptyIOJobsQueue(void);
641 static void vmReopenSwapFile(void);
642 static int vmFreePage(off_t page);
643 static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
644 static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
645 static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd);
646 static int dontWaitForSwappedKey(redisClient *c, robj *key);
647 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
648 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
649 static struct redisCommand *lookupCommand(char *name);
650 static void call(redisClient *c, struct redisCommand *cmd);
651 static void resetClient(redisClient *c);
652 static void convertToRealHash(robj *o);
653 static void listTypeConvert(robj *o, int enc);
654 static int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
655 static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
656 static void freePubsubPattern(void *p);
657 static int listMatchPubsubPattern(void *a, void *b);
658 static int compareStringObjects(robj *a, robj *b);
659 static int equalStringObjects(robj *a, robj *b);
660 static void usage();
661 static int rewriteAppendOnlyFileBackground(void);
662 static vmpointer *vmSwapObjectBlocking(robj *val);
663 static int prepareForShutdown();
664 static void touchWatchedKey(redisDb *db, robj *key);
665 static void touchWatchedKeysOnFlush(int dbid);
666 static void unwatchAllKeys(redisClient *c);
667
668 static void authCommand(redisClient *c);
669 static void pingCommand(redisClient *c);
670 static void echoCommand(redisClient *c);
671 static void setCommand(redisClient *c);
672 static void setnxCommand(redisClient *c);
673 static void setexCommand(redisClient *c);
674 static void getCommand(redisClient *c);
675 static void delCommand(redisClient *c);
676 static void existsCommand(redisClient *c);
677 static void incrCommand(redisClient *c);
678 static void decrCommand(redisClient *c);
679 static void incrbyCommand(redisClient *c);
680 static void decrbyCommand(redisClient *c);
681 static void selectCommand(redisClient *c);
682 static void randomkeyCommand(redisClient *c);
683 static void keysCommand(redisClient *c);
684 static void dbsizeCommand(redisClient *c);
685 static void lastsaveCommand(redisClient *c);
686 static void saveCommand(redisClient *c);
687 static void bgsaveCommand(redisClient *c);
688 static void bgrewriteaofCommand(redisClient *c);
689 static void shutdownCommand(redisClient *c);
690 static void moveCommand(redisClient *c);
691 static void renameCommand(redisClient *c);
692 static void renamenxCommand(redisClient *c);
693 static void lpushCommand(redisClient *c);
694 static void rpushCommand(redisClient *c);
695 static void lpushxCommand(redisClient *c);
696 static void rpushxCommand(redisClient *c);
697 static void linsertCommand(redisClient *c);
698 static void lpopCommand(redisClient *c);
699 static void rpopCommand(redisClient *c);
700 static void llenCommand(redisClient *c);
701 static void lindexCommand(redisClient *c);
702 static void lrangeCommand(redisClient *c);
703 static void ltrimCommand(redisClient *c);
704 static void typeCommand(redisClient *c);
705 static void lsetCommand(redisClient *c);
706 static void saddCommand(redisClient *c);
707 static void sremCommand(redisClient *c);
708 static void smoveCommand(redisClient *c);
709 static void sismemberCommand(redisClient *c);
710 static void scardCommand(redisClient *c);
711 static void spopCommand(redisClient *c);
712 static void srandmemberCommand(redisClient *c);
713 static void sinterCommand(redisClient *c);
714 static void sinterstoreCommand(redisClient *c);
715 static void sunionCommand(redisClient *c);
716 static void sunionstoreCommand(redisClient *c);
717 static void sdiffCommand(redisClient *c);
718 static void sdiffstoreCommand(redisClient *c);
719 static void syncCommand(redisClient *c);
720 static void flushdbCommand(redisClient *c);
721 static void flushallCommand(redisClient *c);
722 static void sortCommand(redisClient *c);
723 static void lremCommand(redisClient *c);
724 static void rpoplpushcommand(redisClient *c);
725 static void infoCommand(redisClient *c);
726 static void mgetCommand(redisClient *c);
727 static void monitorCommand(redisClient *c);
728 static void expireCommand(redisClient *c);
729 static void expireatCommand(redisClient *c);
730 static void getsetCommand(redisClient *c);
731 static void ttlCommand(redisClient *c);
732 static void slaveofCommand(redisClient *c);
733 static void debugCommand(redisClient *c);
734 static void msetCommand(redisClient *c);
735 static void msetnxCommand(redisClient *c);
736 static void zaddCommand(redisClient *c);
737 static void zincrbyCommand(redisClient *c);
738 static void zrangeCommand(redisClient *c);
739 static void zrangebyscoreCommand(redisClient *c);
740 static void zcountCommand(redisClient *c);
741 static void zrevrangeCommand(redisClient *c);
742 static void zcardCommand(redisClient *c);
743 static void zremCommand(redisClient *c);
744 static void zscoreCommand(redisClient *c);
745 static void zremrangebyscoreCommand(redisClient *c);
746 static void multiCommand(redisClient *c);
747 static void execCommand(redisClient *c);
748 static void discardCommand(redisClient *c);
749 static void blpopCommand(redisClient *c);
750 static void brpopCommand(redisClient *c);
751 static void appendCommand(redisClient *c);
752 static void substrCommand(redisClient *c);
753 static void zrankCommand(redisClient *c);
754 static void zrevrankCommand(redisClient *c);
755 static void hsetCommand(redisClient *c);
756 static void hsetnxCommand(redisClient *c);
757 static void hgetCommand(redisClient *c);
758 static void hmsetCommand(redisClient *c);
759 static void hmgetCommand(redisClient *c);
760 static void hdelCommand(redisClient *c);
761 static void hlenCommand(redisClient *c);
762 static void zremrangebyrankCommand(redisClient *c);
763 static void zunionstoreCommand(redisClient *c);
764 static void zinterstoreCommand(redisClient *c);
765 static void hkeysCommand(redisClient *c);
766 static void hvalsCommand(redisClient *c);
767 static void hgetallCommand(redisClient *c);
768 static void hexistsCommand(redisClient *c);
769 static void configCommand(redisClient *c);
770 static void hincrbyCommand(redisClient *c);
771 static void subscribeCommand(redisClient *c);
772 static void unsubscribeCommand(redisClient *c);
773 static void psubscribeCommand(redisClient *c);
774 static void punsubscribeCommand(redisClient *c);
775 static void publishCommand(redisClient *c);
776 static void watchCommand(redisClient *c);
777 static void unwatchCommand(redisClient *c);
778
779 /*================================= Globals ================================= */
780
781 /* Global vars */
782 static struct redisServer server; /* server global state */
783 static struct redisCommand *commandTable;
784 static struct redisCommand readonlyCommandTable[] = {
785 {"get",getCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
786 {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
787 {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
788 {"setex",setexCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
789 {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
790 {"substr",substrCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
791 {"del",delCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
792 {"exists",existsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
793 {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
794 {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
795 {"mget",mgetCommand,-2,REDIS_CMD_INLINE,NULL,1,-1,1},
796 {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
797 {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
798 {"rpushx",rpushxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
799 {"lpushx",lpushxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
800 {"linsert",linsertCommand,5,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
801 {"rpop",rpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
802 {"lpop",lpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
803 {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
804 {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
805 {"llen",llenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
806 {"lindex",lindexCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
807 {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
808 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
809 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
810 {"lrem",lremCommand,4,REDIS_CMD_BULK,NULL,1,1,1},
811 {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,2,1},
812 {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
813 {"srem",sremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
814 {"smove",smoveCommand,4,REDIS_CMD_BULK,NULL,1,2,1},
815 {"sismember",sismemberCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
816 {"scard",scardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
817 {"spop",spopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
818 {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
819 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
820 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
821 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
822 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
823 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
824 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
825 {"smembers",sinterCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
826 {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
827 {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
828 {"zrem",zremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
829 {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
830 {"zremrangebyrank",zremrangebyrankCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
831 {"zunionstore",zunionstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
832 {"zinterstore",zinterstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
833 {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
834 {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
835 {"zcount",zcountCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
836 {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
837 {"zcard",zcardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
838 {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
839 {"zrank",zrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
840 {"zrevrank",zrevrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
841 {"hset",hsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
842 {"hsetnx",hsetnxCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
843 {"hget",hgetCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
844 {"hmset",hmsetCommand,-4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
845 {"hmget",hmgetCommand,-3,REDIS_CMD_BULK,NULL,1,1,1},
846 {"hincrby",hincrbyCommand,4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
847 {"hdel",hdelCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
848 {"hlen",hlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
849 {"hkeys",hkeysCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
850 {"hvals",hvalsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
851 {"hgetall",hgetallCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
852 {"hexists",hexistsCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
853 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
854 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
855 {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
856 {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
857 {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
858 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
859 {"select",selectCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
860 {"move",moveCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
861 {"rename",renameCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
862 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
863 {"expire",expireCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
864 {"expireat",expireatCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
865 {"keys",keysCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
866 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
867 {"auth",authCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
868 {"ping",pingCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
869 {"echo",echoCommand,2,REDIS_CMD_BULK,NULL,0,0,0},
870 {"save",saveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
871 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
872 {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
873 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
874 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
875 {"type",typeCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
876 {"multi",multiCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
877 {"exec",execCommand,1,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0},
878 {"discard",discardCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
879 {"sync",syncCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
880 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
881 {"flushall",flushallCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
882 {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
883 {"info",infoCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
884 {"monitor",monitorCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
885 {"ttl",ttlCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
886 {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
887 {"debug",debugCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
888 {"config",configCommand,-2,REDIS_CMD_BULK,NULL,0,0,0},
889 {"subscribe",subscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
890 {"unsubscribe",unsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
891 {"psubscribe",psubscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
892 {"punsubscribe",punsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
893 {"publish",publishCommand,3,REDIS_CMD_BULK|REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0},
894 {"watch",watchCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
895 {"unwatch",unwatchCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}
896 };
897
898 /*============================ Utility functions ============================ */
899
900 /* Glob-style pattern matching. */
901 static int stringmatchlen(const char *pattern, int patternLen,
902 const char *string, int stringLen, int nocase)
903 {
904 while(patternLen) {
905 switch(pattern[0]) {
906 case '*':
907 while (pattern[1] == '*') {
908 pattern++;
909 patternLen--;
910 }
911 if (patternLen == 1)
912 return 1; /* match */
913 while(stringLen) {
914 if (stringmatchlen(pattern+1, patternLen-1,
915 string, stringLen, nocase))
916 return 1; /* match */
917 string++;
918 stringLen--;
919 }
920 return 0; /* no match */
921 break;
922 case '?':
923 if (stringLen == 0)
924 return 0; /* no match */
925 string++;
926 stringLen--;
927 break;
928 case '[':
929 {
930 int not, match;
931
932 pattern++;
933 patternLen--;
934 not = pattern[0] == '^';
935 if (not) {
936 pattern++;
937 patternLen--;
938 }
939 match = 0;
940 while(1) {
941 if (pattern[0] == '\\') {
942 pattern++;
943 patternLen--;
944 if (pattern[0] == string[0])
945 match = 1;
946 } else if (pattern[0] == ']') {
947 break;
948 } else if (patternLen == 0) {
949 pattern--;
950 patternLen++;
951 break;
952 } else if (pattern[1] == '-' && patternLen >= 3) {
953 int start = pattern[0];
954 int end = pattern[2];
955 int c = string[0];
956 if (start > end) {
957 int t = start;
958 start = end;
959 end = t;
960 }
961 if (nocase) {
962 start = tolower(start);
963 end = tolower(end);
964 c = tolower(c);
965 }
966 pattern += 2;
967 patternLen -= 2;
968 if (c >= start && c <= end)
969 match = 1;
970 } else {
971 if (!nocase) {
972 if (pattern[0] == string[0])
973 match = 1;
974 } else {
975 if (tolower((int)pattern[0]) == tolower((int)string[0]))
976 match = 1;
977 }
978 }
979 pattern++;
980 patternLen--;
981 }
982 if (not)
983 match = !match;
984 if (!match)
985 return 0; /* no match */
986 string++;
987 stringLen--;
988 break;
989 }
990 case '\\':
991 if (patternLen >= 2) {
992 pattern++;
993 patternLen--;
994 }
995 /* fall through */
996 default:
997 if (!nocase) {
998 if (pattern[0] != string[0])
999 return 0; /* no match */
1000 } else {
1001 if (tolower((int)pattern[0]) != tolower((int)string[0]))
1002 return 0; /* no match */
1003 }
1004 string++;
1005 stringLen--;
1006 break;
1007 }
1008 pattern++;
1009 patternLen--;
1010 if (stringLen == 0) {
1011 while(*pattern == '*') {
1012 pattern++;
1013 patternLen--;
1014 }
1015 break;
1016 }
1017 }
1018 if (patternLen == 0 && stringLen == 0)
1019 return 1;
1020 return 0;
1021 }
1022
1023 static int stringmatch(const char *pattern, const char *string, int nocase) {
1024 return stringmatchlen(pattern,strlen(pattern),string,strlen(string),nocase);
1025 }
1026
1027 /* Convert a string representing an amount of memory into the number of
1028 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
1029 * (1024*1024*1024).
1030 *
1031 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
1032 * set to 0 */
1033 static long long memtoll(const char *p, int *err) {
1034 const char *u;
1035 char buf[128];
1036 long mul; /* unit multiplier */
1037 long long val;
1038 unsigned int digits;
1039
1040 if (err) *err = 0;
1041 /* Search the first non digit character. */
1042 u = p;
1043 if (*u == '-') u++;
1044 while(*u && isdigit(*u)) u++;
1045 if (*u == '\0' || !strcasecmp(u,"b")) {
1046 mul = 1;
1047 } else if (!strcasecmp(u,"k")) {
1048 mul = 1000;
1049 } else if (!strcasecmp(u,"kb")) {
1050 mul = 1024;
1051 } else if (!strcasecmp(u,"m")) {
1052 mul = 1000*1000;
1053 } else if (!strcasecmp(u,"mb")) {
1054 mul = 1024*1024;
1055 } else if (!strcasecmp(u,"g")) {
1056 mul = 1000L*1000*1000;
1057 } else if (!strcasecmp(u,"gb")) {
1058 mul = 1024L*1024*1024;
1059 } else {
1060 if (err) *err = 1;
1061 mul = 1;
1062 }
1063 digits = u-p;
1064 if (digits >= sizeof(buf)) {
1065 if (err) *err = 1;
1066 return LLONG_MAX;
1067 }
1068 memcpy(buf,p,digits);
1069 buf[digits] = '\0';
1070 val = strtoll(buf,NULL,10);
1071 return val*mul;
1072 }
1073
1074 /* Convert a long long into a string. Returns the number of
1075 * characters needed to represent the number, that can be shorter if passed
1076 * buffer length is not enough to store the whole number. */
1077 static int ll2string(char *s, size_t len, long long value) {
1078 char buf[32], *p;
1079 unsigned long long v;
1080 size_t l;
1081
1082 if (len == 0) return 0;
1083 v = (value < 0) ? -value : value;
1084 p = buf+31; /* point to the last character */
1085 do {
1086 *p-- = '0'+(v%10);
1087 v /= 10;
1088 } while(v);
1089 if (value < 0) *p-- = '-';
1090 p++;
1091 l = 32-(p-buf);
1092 if (l+1 > len) l = len-1; /* Make sure it fits, including the nul term */
1093 memcpy(s,p,l);
1094 s[l] = '\0';
1095 return l;
1096 }
1097
1098 static void redisLog(int level, const char *fmt, ...) {
1099 va_list ap;
1100 FILE *fp;
1101
1102 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
1103 if (!fp) return;
1104
1105 va_start(ap, fmt);
1106 if (level >= server.verbosity) {
1107 char *c = ".-*#";
1108 char buf[64];
1109 time_t now;
1110
1111 now = time(NULL);
1112 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
1113 fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
1114 vfprintf(fp, fmt, ap);
1115 fprintf(fp,"\n");
1116 fflush(fp);
1117 }
1118 va_end(ap);
1119
1120 if (server.logfile) fclose(fp);
1121 }
1122
1123 /*====================== Hash table type implementation ==================== */
1124
1125 /* This is an hash table type that uses the SDS dynamic strings libary as
1126 * keys and radis objects as values (objects can hold SDS strings,
1127 * lists, sets). */
1128
1129 static void dictVanillaFree(void *privdata, void *val)
1130 {
1131 DICT_NOTUSED(privdata);
1132 zfree(val);
1133 }
1134
1135 static void dictListDestructor(void *privdata, void *val)
1136 {
1137 DICT_NOTUSED(privdata);
1138 listRelease((list*)val);
1139 }
1140
1141 static int dictSdsKeyCompare(void *privdata, const void *key1,
1142 const void *key2)
1143 {
1144 int l1,l2;
1145 DICT_NOTUSED(privdata);
1146
1147 l1 = sdslen((sds)key1);
1148 l2 = sdslen((sds)key2);
1149 if (l1 != l2) return 0;
1150 return memcmp(key1, key2, l1) == 0;
1151 }
1152
1153 static void dictRedisObjectDestructor(void *privdata, void *val)
1154 {
1155 DICT_NOTUSED(privdata);
1156
1157 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
1158 decrRefCount(val);
1159 }
1160
1161 static void dictSdsDestructor(void *privdata, void *val)
1162 {
1163 DICT_NOTUSED(privdata);
1164
1165 sdsfree(val);
1166 }
1167
1168 static int dictObjKeyCompare(void *privdata, const void *key1,
1169 const void *key2)
1170 {
1171 const robj *o1 = key1, *o2 = key2;
1172 return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
1173 }
1174
1175 static unsigned int dictObjHash(const void *key) {
1176 const robj *o = key;
1177 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1178 }
1179
1180 static unsigned int dictSdsHash(const void *key) {
1181 return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
1182 }
1183
1184 static int dictEncObjKeyCompare(void *privdata, const void *key1,
1185 const void *key2)
1186 {
1187 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
1188 int cmp;
1189
1190 if (o1->encoding == REDIS_ENCODING_INT &&
1191 o2->encoding == REDIS_ENCODING_INT)
1192 return o1->ptr == o2->ptr;
1193
1194 o1 = getDecodedObject(o1);
1195 o2 = getDecodedObject(o2);
1196 cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
1197 decrRefCount(o1);
1198 decrRefCount(o2);
1199 return cmp;
1200 }
1201
1202 static unsigned int dictEncObjHash(const void *key) {
1203 robj *o = (robj*) key;
1204
1205 if (o->encoding == REDIS_ENCODING_RAW) {
1206 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1207 } else {
1208 if (o->encoding == REDIS_ENCODING_INT) {
1209 char buf[32];
1210 int len;
1211
1212 len = ll2string(buf,32,(long)o->ptr);
1213 return dictGenHashFunction((unsigned char*)buf, len);
1214 } else {
1215 unsigned int hash;
1216
1217 o = getDecodedObject(o);
1218 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1219 decrRefCount(o);
1220 return hash;
1221 }
1222 }
1223 }
1224
1225 /* Sets type */
1226 static dictType setDictType = {
1227 dictEncObjHash, /* hash function */
1228 NULL, /* key dup */
1229 NULL, /* val dup */
1230 dictEncObjKeyCompare, /* key compare */
1231 dictRedisObjectDestructor, /* key destructor */
1232 NULL /* val destructor */
1233 };
1234
1235 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1236 static dictType zsetDictType = {
1237 dictEncObjHash, /* hash function */
1238 NULL, /* key dup */
1239 NULL, /* val dup */
1240 dictEncObjKeyCompare, /* key compare */
1241 dictRedisObjectDestructor, /* key destructor */
1242 dictVanillaFree /* val destructor of malloc(sizeof(double)) */
1243 };
1244
1245 /* Db->dict, keys are sds strings, vals are Redis objects. */
1246 static dictType dbDictType = {
1247 dictSdsHash, /* hash function */
1248 NULL, /* key dup */
1249 NULL, /* val dup */
1250 dictSdsKeyCompare, /* key compare */
1251 dictSdsDestructor, /* key destructor */
1252 dictRedisObjectDestructor /* val destructor */
1253 };
1254
1255 /* Db->expires */
1256 static dictType keyptrDictType = {
1257 dictSdsHash, /* hash function */
1258 NULL, /* key dup */
1259 NULL, /* val dup */
1260 dictSdsKeyCompare, /* key compare */
1261 NULL, /* key destructor */
1262 NULL /* val destructor */
1263 };
1264
1265 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1266 static dictType hashDictType = {
1267 dictEncObjHash, /* hash function */
1268 NULL, /* key dup */
1269 NULL, /* val dup */
1270 dictEncObjKeyCompare, /* key compare */
1271 dictRedisObjectDestructor, /* key destructor */
1272 dictRedisObjectDestructor /* val destructor */
1273 };
1274
1275 /* Keylist hash table type has unencoded redis objects as keys and
1276 * lists as values. It's used for blocking operations (BLPOP) and to
1277 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1278 static dictType keylistDictType = {
1279 dictObjHash, /* hash function */
1280 NULL, /* key dup */
1281 NULL, /* val dup */
1282 dictObjKeyCompare, /* key compare */
1283 dictRedisObjectDestructor, /* key destructor */
1284 dictListDestructor /* val destructor */
1285 };
1286
1287 static void version();
1288
1289 /* ========================= Random utility functions ======================= */
1290
1291 /* Redis generally does not try to recover from out of memory conditions
1292 * when allocating objects or strings, it is not clear if it will be possible
1293 * to report this condition to the client since the networking layer itself
1294 * is based on heap allocation for send buffers, so we simply abort.
1295 * At least the code will be simpler to read... */
1296 static void oom(const char *msg) {
1297 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
1298 sleep(1);
1299 abort();
1300 }
1301
1302 /* ====================== Redis server networking stuff ===================== */
1303 static void closeTimedoutClients(void) {
1304 redisClient *c;
1305 listNode *ln;
1306 time_t now = time(NULL);
1307 listIter li;
1308
1309 listRewind(server.clients,&li);
1310 while ((ln = listNext(&li)) != NULL) {
1311 c = listNodeValue(ln);
1312 if (server.maxidletime &&
1313 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
1314 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
1315 dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
1316 listLength(c->pubsub_patterns) == 0 &&
1317 (now - c->lastinteraction > server.maxidletime))
1318 {
1319 redisLog(REDIS_VERBOSE,"Closing idle client");
1320 freeClient(c);
1321 } else if (c->flags & REDIS_BLOCKED) {
1322 if (c->blockingto != 0 && c->blockingto < now) {
1323 addReply(c,shared.nullmultibulk);
1324 unblockClientWaitingData(c);
1325 }
1326 }
1327 }
1328 }
1329
1330 static int htNeedsResize(dict *dict) {
1331 long long size, used;
1332
1333 size = dictSlots(dict);
1334 used = dictSize(dict);
1335 return (size && used && size > DICT_HT_INITIAL_SIZE &&
1336 (used*100/size < REDIS_HT_MINFILL));
1337 }
1338
1339 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1340 * we resize the hash table to save memory */
1341 static void tryResizeHashTables(void) {
1342 int j;
1343
1344 for (j = 0; j < server.dbnum; j++) {
1345 if (htNeedsResize(server.db[j].dict))
1346 dictResize(server.db[j].dict);
1347 if (htNeedsResize(server.db[j].expires))
1348 dictResize(server.db[j].expires);
1349 }
1350 }
1351
1352 /* Our hash table implementation performs rehashing incrementally while
1353 * we write/read from the hash table. Still if the server is idle, the hash
1354 * table will use two tables for a long time. So we try to use 1 millisecond
1355 * of CPU time at every serverCron() loop in order to rehash some key. */
1356 static void incrementallyRehash(void) {
1357 int j;
1358
1359 for (j = 0; j < server.dbnum; j++) {
1360 if (dictIsRehashing(server.db[j].dict)) {
1361 dictRehashMilliseconds(server.db[j].dict,1);
1362 break; /* already used our millisecond for this loop... */
1363 }
1364 }
1365 }
1366
1367 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1368 void backgroundSaveDoneHandler(int statloc) {
1369 int exitcode = WEXITSTATUS(statloc);
1370 int bysignal = WIFSIGNALED(statloc);
1371
1372 if (!bysignal && exitcode == 0) {
1373 redisLog(REDIS_NOTICE,
1374 "Background saving terminated with success");
1375 server.dirty = 0;
1376 server.lastsave = time(NULL);
1377 } else if (!bysignal && exitcode != 0) {
1378 redisLog(REDIS_WARNING, "Background saving error");
1379 } else {
1380 redisLog(REDIS_WARNING,
1381 "Background saving terminated by signal %d", WTERMSIG(statloc));
1382 rdbRemoveTempFile(server.bgsavechildpid);
1383 }
1384 server.bgsavechildpid = -1;
1385 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1386 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1387 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1388 }
1389
1390 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1391 * Handle this. */
1392 void backgroundRewriteDoneHandler(int statloc) {
1393 int exitcode = WEXITSTATUS(statloc);
1394 int bysignal = WIFSIGNALED(statloc);
1395
1396 if (!bysignal && exitcode == 0) {
1397 int fd;
1398 char tmpfile[256];
1399
1400 redisLog(REDIS_NOTICE,
1401 "Background append only file rewriting terminated with success");
1402 /* Now it's time to flush the differences accumulated by the parent */
1403 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
1404 fd = open(tmpfile,O_WRONLY|O_APPEND);
1405 if (fd == -1) {
1406 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
1407 goto cleanup;
1408 }
1409 /* Flush our data... */
1410 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
1411 (signed) sdslen(server.bgrewritebuf)) {
1412 redisLog(REDIS_WARNING, "Error or short write trying to flush the parent diff of the append log file in the child temp file: %s", strerror(errno));
1413 close(fd);
1414 goto cleanup;
1415 }
1416 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
1417 /* Now our work is to rename the temp file into the stable file. And
1418 * switch the file descriptor used by the server for append only. */
1419 if (rename(tmpfile,server.appendfilename) == -1) {
1420 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
1421 close(fd);
1422 goto cleanup;
1423 }
1424 /* Mission completed... almost */
1425 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
1426 if (server.appendfd != -1) {
1427 /* If append only is actually enabled... */
1428 close(server.appendfd);
1429 server.appendfd = fd;
1430 if (server.appendfsync != APPENDFSYNC_NO) aof_fsync(fd);
1431 server.appendseldb = -1; /* Make sure it will issue SELECT */
1432 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
1433 } else {
1434 /* If append only is disabled we just generate a dump in this
1435 * format. Why not? */
1436 close(fd);
1437 }
1438 } else if (!bysignal && exitcode != 0) {
1439 redisLog(REDIS_WARNING, "Background append only file rewriting error");
1440 } else {
1441 redisLog(REDIS_WARNING,
1442 "Background append only file rewriting terminated by signal %d",
1443 WTERMSIG(statloc));
1444 }
1445 cleanup:
1446 sdsfree(server.bgrewritebuf);
1447 server.bgrewritebuf = sdsempty();
1448 aofRemoveTempFile(server.bgrewritechildpid);
1449 server.bgrewritechildpid = -1;
1450 }
1451
1452 /* This function is called once a background process of some kind terminates,
1453 * as we want to avoid resizing the hash tables when there is a child in order
1454 * to play well with copy-on-write (otherwise when a resize happens lots of
1455 * memory pages are copied). The goal of this function is to update the ability
1456 * for dict.c to resize the hash tables accordingly to the fact we have o not
1457 * running childs. */
1458 static void updateDictResizePolicy(void) {
1459 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
1460 dictEnableResize();
1461 else
1462 dictDisableResize();
1463 }
1464
1465 static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
1466 int j, loops = server.cronloops++;
1467 REDIS_NOTUSED(eventLoop);
1468 REDIS_NOTUSED(id);
1469 REDIS_NOTUSED(clientData);
1470
1471 /* We take a cached value of the unix time in the global state because
1472 * with virtual memory and aging there is to store the current time
1473 * in objects at every object access, and accuracy is not needed.
1474 * To access a global var is faster than calling time(NULL) */
1475 server.unixtime = time(NULL);
1476 /* We have just 21 bits per object for LRU information.
1477 * So we use an (eventually wrapping) LRU clock with minutes resolution.
1478 *
1479 * When we need to select what object to swap, we compute the minimum
1480 * time distance between the current lruclock and the object last access
1481 * lruclock info. Even if clocks will wrap on overflow, there is
1482 * the interesting property that we are sure that at least
1483 * ABS(A-B) minutes passed between current time and timestamp B.
1484 *
1485 * This is not precise but we don't need at all precision, but just
1486 * something statistically reasonable.
1487 */
1488 server.lruclock = (time(NULL)/60)&((1<<21)-1);
1489
1490 /* We received a SIGTERM, shutting down here in a safe way, as it is
1491 * not ok doing so inside the signal handler. */
1492 if (server.shutdown_asap) {
1493 if (prepareForShutdown() == REDIS_OK) exit(0);
1494 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
1495 }
1496
1497 /* Show some info about non-empty databases */
1498 for (j = 0; j < server.dbnum; j++) {
1499 long long size, used, vkeys;
1500
1501 size = dictSlots(server.db[j].dict);
1502 used = dictSize(server.db[j].dict);
1503 vkeys = dictSize(server.db[j].expires);
1504 if (!(loops % 50) && (used || vkeys)) {
1505 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
1506 /* dictPrintStats(server.dict); */
1507 }
1508 }
1509
1510 /* We don't want to resize the hash tables while a bacground saving
1511 * is in progress: the saving child is created using fork() that is
1512 * implemented with a copy-on-write semantic in most modern systems, so
1513 * if we resize the HT while there is the saving child at work actually
1514 * a lot of memory movements in the parent will cause a lot of pages
1515 * copied. */
1516 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
1517 if (!(loops % 10)) tryResizeHashTables();
1518 if (server.activerehashing) incrementallyRehash();
1519 }
1520
1521 /* Show information about connected clients */
1522 if (!(loops % 50)) {
1523 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
1524 listLength(server.clients)-listLength(server.slaves),
1525 listLength(server.slaves),
1526 zmalloc_used_memory());
1527 }
1528
1529 /* Close connections of timedout clients */
1530 if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients)
1531 closeTimedoutClients();
1532
1533 /* Check if a background saving or AOF rewrite in progress terminated */
1534 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
1535 int statloc;
1536 pid_t pid;
1537
1538 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
1539 if (pid == server.bgsavechildpid) {
1540 backgroundSaveDoneHandler(statloc);
1541 } else {
1542 backgroundRewriteDoneHandler(statloc);
1543 }
1544 updateDictResizePolicy();
1545 }
1546 } else {
1547 /* If there is not a background saving in progress check if
1548 * we have to save now */
1549 time_t now = time(NULL);
1550 for (j = 0; j < server.saveparamslen; j++) {
1551 struct saveparam *sp = server.saveparams+j;
1552
1553 if (server.dirty >= sp->changes &&
1554 now-server.lastsave > sp->seconds) {
1555 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
1556 sp->changes, sp->seconds);
1557 rdbSaveBackground(server.dbfilename);
1558 break;
1559 }
1560 }
1561 }
1562
1563 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1564 * will use few CPU cycles if there are few expiring keys, otherwise
1565 * it will get more aggressive to avoid that too much memory is used by
1566 * keys that can be removed from the keyspace. */
1567 for (j = 0; j < server.dbnum; j++) {
1568 int expired;
1569 redisDb *db = server.db+j;
1570
1571 /* Continue to expire if at the end of the cycle more than 25%
1572 * of the keys were expired. */
1573 do {
1574 long num = dictSize(db->expires);
1575 time_t now = time(NULL);
1576
1577 expired = 0;
1578 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
1579 num = REDIS_EXPIRELOOKUPS_PER_CRON;
1580 while (num--) {
1581 dictEntry *de;
1582 time_t t;
1583
1584 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
1585 t = (time_t) dictGetEntryVal(de);
1586 if (now > t) {
1587 sds key = dictGetEntryKey(de);
1588 robj *keyobj = createStringObject(key,sdslen(key));
1589
1590 dbDelete(db,keyobj);
1591 decrRefCount(keyobj);
1592 expired++;
1593 server.stat_expiredkeys++;
1594 }
1595 }
1596 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
1597 }
1598
1599 /* Swap a few keys on disk if we are over the memory limit and VM
1600 * is enbled. Try to free objects from the free list first. */
1601 if (vmCanSwapOut()) {
1602 while (server.vm_enabled && zmalloc_used_memory() >
1603 server.vm_max_memory)
1604 {
1605 int retval;
1606
1607 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
1608 retval = (server.vm_max_threads == 0) ?
1609 vmSwapOneObjectBlocking() :
1610 vmSwapOneObjectThreaded();
1611 if (retval == REDIS_ERR && !(loops % 300) &&
1612 zmalloc_used_memory() >
1613 (server.vm_max_memory+server.vm_max_memory/10))
1614 {
1615 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1616 }
1617 /* Note that when using threade I/O we free just one object,
1618 * because anyway when the I/O thread in charge to swap this
1619 * object out will finish, the handler of completed jobs
1620 * will try to swap more objects if we are still out of memory. */
1621 if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
1622 }
1623 }
1624
1625 /* Check if we should connect to a MASTER */
1626 if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) {
1627 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
1628 if (syncWithMaster() == REDIS_OK) {
1629 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
1630 if (server.appendonly) rewriteAppendOnlyFileBackground();
1631 }
1632 }
1633 return 100;
1634 }
1635
1636 /* This function gets called every time Redis is entering the
1637 * main loop of the event driven library, that is, before to sleep
1638 * for ready file descriptors. */
1639 static void beforeSleep(struct aeEventLoop *eventLoop) {
1640 REDIS_NOTUSED(eventLoop);
1641
1642 /* Awake clients that got all the swapped keys they requested */
1643 if (server.vm_enabled && listLength(server.io_ready_clients)) {
1644 listIter li;
1645 listNode *ln;
1646
1647 listRewind(server.io_ready_clients,&li);
1648 while((ln = listNext(&li))) {
1649 redisClient *c = ln->value;
1650 struct redisCommand *cmd;
1651
1652 /* Resume the client. */
1653 listDelNode(server.io_ready_clients,ln);
1654 c->flags &= (~REDIS_IO_WAIT);
1655 server.vm_blocked_clients--;
1656 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1657 readQueryFromClient, c);
1658 cmd = lookupCommand(c->argv[0]->ptr);
1659 assert(cmd != NULL);
1660 call(c,cmd);
1661 resetClient(c);
1662 /* There may be more data to process in the input buffer. */
1663 if (c->querybuf && sdslen(c->querybuf) > 0)
1664 processInputBuffer(c);
1665 }
1666 }
1667 /* Write the AOF buffer on disk */
1668 flushAppendOnlyFile();
1669 }
1670
1671 static void createSharedObjects(void) {
1672 int j;
1673
1674 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
1675 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
1676 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
1677 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
1678 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
1679 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
1680 shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n"));
1681 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
1682 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
1683 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
1684 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
1685 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
1686 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
1687 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1688 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
1689 "-ERR no such key\r\n"));
1690 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
1691 "-ERR syntax error\r\n"));
1692 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
1693 "-ERR source and destination objects are the same\r\n"));
1694 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
1695 "-ERR index out of range\r\n"));
1696 shared.space = createObject(REDIS_STRING,sdsnew(" "));
1697 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
1698 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
1699 shared.select0 = createStringObject("select 0\r\n",10);
1700 shared.select1 = createStringObject("select 1\r\n",10);
1701 shared.select2 = createStringObject("select 2\r\n",10);
1702 shared.select3 = createStringObject("select 3\r\n",10);
1703 shared.select4 = createStringObject("select 4\r\n",10);
1704 shared.select5 = createStringObject("select 5\r\n",10);
1705 shared.select6 = createStringObject("select 6\r\n",10);
1706 shared.select7 = createStringObject("select 7\r\n",10);
1707 shared.select8 = createStringObject("select 8\r\n",10);
1708 shared.select9 = createStringObject("select 9\r\n",10);
1709 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
1710 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
1711 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
1712 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
1713 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
1714 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
1715 shared.mbulk3 = createStringObject("*3\r\n",4);
1716 shared.mbulk4 = createStringObject("*4\r\n",4);
1717 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
1718 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
1719 shared.integers[j]->encoding = REDIS_ENCODING_INT;
1720 }
1721 }
1722
1723 static void appendServerSaveParams(time_t seconds, int changes) {
1724 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
1725 server.saveparams[server.saveparamslen].seconds = seconds;
1726 server.saveparams[server.saveparamslen].changes = changes;
1727 server.saveparamslen++;
1728 }
1729
1730 static void resetServerSaveParams() {
1731 zfree(server.saveparams);
1732 server.saveparams = NULL;
1733 server.saveparamslen = 0;
1734 }
1735
1736 static void initServerConfig() {
1737 server.dbnum = REDIS_DEFAULT_DBNUM;
1738 server.port = REDIS_SERVERPORT;
1739 server.verbosity = REDIS_VERBOSE;
1740 server.maxidletime = REDIS_MAXIDLETIME;
1741 server.saveparams = NULL;
1742 server.logfile = NULL; /* NULL = log on standard output */
1743 server.bindaddr = NULL;
1744 server.glueoutputbuf = 1;
1745 server.daemonize = 0;
1746 server.appendonly = 0;
1747 server.appendfsync = APPENDFSYNC_EVERYSEC;
1748 server.no_appendfsync_on_rewrite = 0;
1749 server.lastfsync = time(NULL);
1750 server.appendfd = -1;
1751 server.appendseldb = -1; /* Make sure the first time will not match */
1752 server.pidfile = zstrdup("/var/run/redis.pid");
1753 server.dbfilename = zstrdup("dump.rdb");
1754 server.appendfilename = zstrdup("appendonly.aof");
1755 server.requirepass = NULL;
1756 server.rdbcompression = 1;
1757 server.activerehashing = 1;
1758 server.maxclients = 0;
1759 server.blpop_blocked_clients = 0;
1760 server.maxmemory = 0;
1761 server.vm_enabled = 0;
1762 server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
1763 server.vm_page_size = 256; /* 256 bytes per page */
1764 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
1765 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
1766 server.vm_max_threads = 4;
1767 server.vm_blocked_clients = 0;
1768 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
1769 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
1770 server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
1771 server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
1772 server.shutdown_asap = 0;
1773
1774 resetServerSaveParams();
1775
1776 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1777 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1778 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1779 /* Replication related */
1780 server.isslave = 0;
1781 server.masterauth = NULL;
1782 server.masterhost = NULL;
1783 server.masterport = 6379;
1784 server.master = NULL;
1785 server.replstate = REDIS_REPL_NONE;
1786
1787 /* Double constants initialization */
1788 R_Zero = 0.0;
1789 R_PosInf = 1.0/R_Zero;
1790 R_NegInf = -1.0/R_Zero;
1791 R_Nan = R_Zero/R_Zero;
1792 }
1793
1794 static void initServer() {
1795 int j;
1796
1797 signal(SIGHUP, SIG_IGN);
1798 signal(SIGPIPE, SIG_IGN);
1799 setupSigSegvAction();
1800
1801 server.devnull = fopen("/dev/null","w");
1802 if (server.devnull == NULL) {
1803 redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr);
1804 exit(1);
1805 }
1806 server.clients = listCreate();
1807 server.slaves = listCreate();
1808 server.monitors = listCreate();
1809 server.objfreelist = listCreate();
1810 createSharedObjects();
1811 server.el = aeCreateEventLoop();
1812 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
1813 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
1814 if (server.fd == -1) {
1815 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
1816 exit(1);
1817 }
1818 for (j = 0; j < server.dbnum; j++) {
1819 server.db[j].dict = dictCreate(&dbDictType,NULL);
1820 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
1821 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
1822 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
1823 if (server.vm_enabled)
1824 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
1825 server.db[j].id = j;
1826 }
1827 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1828 server.pubsub_patterns = listCreate();
1829 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1830 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
1831 server.cronloops = 0;
1832 server.bgsavechildpid = -1;
1833 server.bgrewritechildpid = -1;
1834 server.bgrewritebuf = sdsempty();
1835 server.aofbuf = sdsempty();
1836 server.lastsave = time(NULL);
1837 server.dirty = 0;
1838 server.stat_numcommands = 0;
1839 server.stat_numconnections = 0;
1840 server.stat_expiredkeys = 0;
1841 server.stat_starttime = time(NULL);
1842 server.unixtime = time(NULL);
1843 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
1844 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
1845 acceptHandler, NULL) == AE_ERR) oom("creating file event");
1846
1847 if (server.appendonly) {
1848 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
1849 if (server.appendfd == -1) {
1850 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1851 strerror(errno));
1852 exit(1);
1853 }
1854 }
1855
1856 if (server.vm_enabled) vmInit();
1857 }
1858
1859 /* Empty the whole database */
1860 static long long emptyDb() {
1861 int j;
1862 long long removed = 0;
1863
1864 for (j = 0; j < server.dbnum; j++) {
1865 removed += dictSize(server.db[j].dict);
1866 dictEmpty(server.db[j].dict);
1867 dictEmpty(server.db[j].expires);
1868 }
1869 return removed;
1870 }
1871
1872 static int yesnotoi(char *s) {
1873 if (!strcasecmp(s,"yes")) return 1;
1874 else if (!strcasecmp(s,"no")) return 0;
1875 else return -1;
1876 }
1877
1878 /* I agree, this is a very rudimental way to load a configuration...
1879 will improve later if the config gets more complex */
1880 static void loadServerConfig(char *filename) {
1881 FILE *fp;
1882 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
1883 int linenum = 0;
1884 sds line = NULL;
1885
1886 if (filename[0] == '-' && filename[1] == '\0')
1887 fp = stdin;
1888 else {
1889 if ((fp = fopen(filename,"r")) == NULL) {
1890 redisLog(REDIS_WARNING, "Fatal error, can't open config file '%s'", filename);
1891 exit(1);
1892 }
1893 }
1894
1895 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1896 sds *argv;
1897 int argc, j;
1898
1899 linenum++;
1900 line = sdsnew(buf);
1901 line = sdstrim(line," \t\r\n");
1902
1903 /* Skip comments and blank lines*/
1904 if (line[0] == '#' || line[0] == '\0') {
1905 sdsfree(line);
1906 continue;
1907 }
1908
1909 /* Split into arguments */
1910 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
1911 sdstolower(argv[0]);
1912
1913 /* Execute config directives */
1914 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
1915 server.maxidletime = atoi(argv[1]);
1916 if (server.maxidletime < 0) {
1917 err = "Invalid timeout value"; goto loaderr;
1918 }
1919 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
1920 server.port = atoi(argv[1]);
1921 if (server.port < 1 || server.port > 65535) {
1922 err = "Invalid port"; goto loaderr;
1923 }
1924 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
1925 server.bindaddr = zstrdup(argv[1]);
1926 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
1927 int seconds = atoi(argv[1]);
1928 int changes = atoi(argv[2]);
1929 if (seconds < 1 || changes < 0) {
1930 err = "Invalid save parameters"; goto loaderr;
1931 }
1932 appendServerSaveParams(seconds,changes);
1933 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
1934 if (chdir(argv[1]) == -1) {
1935 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
1936 argv[1], strerror(errno));
1937 exit(1);
1938 }
1939 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
1940 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
1941 else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
1942 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
1943 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
1944 else {
1945 err = "Invalid log level. Must be one of debug, notice, warning";
1946 goto loaderr;
1947 }
1948 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
1949 FILE *logfp;
1950
1951 server.logfile = zstrdup(argv[1]);
1952 if (!strcasecmp(server.logfile,"stdout")) {
1953 zfree(server.logfile);
1954 server.logfile = NULL;
1955 }
1956 if (server.logfile) {
1957 /* Test if we are able to open the file. The server will not
1958 * be able to abort just for this problem later... */
1959 logfp = fopen(server.logfile,"a");
1960 if (logfp == NULL) {
1961 err = sdscatprintf(sdsempty(),
1962 "Can't open the log file: %s", strerror(errno));
1963 goto loaderr;
1964 }
1965 fclose(logfp);
1966 }
1967 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
1968 server.dbnum = atoi(argv[1]);
1969 if (server.dbnum < 1) {
1970 err = "Invalid number of databases"; goto loaderr;
1971 }
1972 } else if (!strcasecmp(argv[0],"include") && argc == 2) {
1973 loadServerConfig(argv[1]);
1974 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
1975 server.maxclients = atoi(argv[1]);
1976 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
1977 server.maxmemory = memtoll(argv[1],NULL);
1978 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
1979 server.masterhost = sdsnew(argv[1]);
1980 server.masterport = atoi(argv[2]);
1981 server.replstate = REDIS_REPL_CONNECT;
1982 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
1983 server.masterauth = zstrdup(argv[1]);
1984 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
1985 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
1986 err = "argument must be 'yes' or 'no'"; goto loaderr;
1987 }
1988 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
1989 if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
1990 err = "argument must be 'yes' or 'no'"; goto loaderr;
1991 }
1992 } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
1993 if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
1994 err = "argument must be 'yes' or 'no'"; goto loaderr;
1995 }
1996 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
1997 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
1998 err = "argument must be 'yes' or 'no'"; goto loaderr;
1999 }
2000 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
2001 if ((server.appendonly = yesnotoi(argv[1])) == -1) {
2002 err = "argument must be 'yes' or 'no'"; goto loaderr;
2003 }
2004 } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
2005 zfree(server.appendfilename);
2006 server.appendfilename = zstrdup(argv[1]);
2007 } else if (!strcasecmp(argv[0],"no-appendfsync-on-rewrite")
2008 && argc == 2) {
2009 if ((server.no_appendfsync_on_rewrite= yesnotoi(argv[1])) == -1) {
2010 err = "argument must be 'yes' or 'no'"; goto loaderr;
2011 }
2012 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
2013 if (!strcasecmp(argv[1],"no")) {
2014 server.appendfsync = APPENDFSYNC_NO;
2015 } else if (!strcasecmp(argv[1],"always")) {
2016 server.appendfsync = APPENDFSYNC_ALWAYS;
2017 } else if (!strcasecmp(argv[1],"everysec")) {
2018 server.appendfsync = APPENDFSYNC_EVERYSEC;
2019 } else {
2020 err = "argument must be 'no', 'always' or 'everysec'";
2021 goto loaderr;
2022 }
2023 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
2024 server.requirepass = zstrdup(argv[1]);
2025 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
2026 zfree(server.pidfile);
2027 server.pidfile = zstrdup(argv[1]);
2028 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
2029 zfree(server.dbfilename);
2030 server.dbfilename = zstrdup(argv[1]);
2031 } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
2032 if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
2033 err = "argument must be 'yes' or 'no'"; goto loaderr;
2034 }
2035 } else if (!strcasecmp(argv[0],"vm-swap-file") && argc == 2) {
2036 zfree(server.vm_swap_file);
2037 server.vm_swap_file = zstrdup(argv[1]);
2038 } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
2039 server.vm_max_memory = memtoll(argv[1],NULL);
2040 } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
2041 server.vm_page_size = memtoll(argv[1], NULL);
2042 } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
2043 server.vm_pages = memtoll(argv[1], NULL);
2044 } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
2045 server.vm_max_threads = strtoll(argv[1], NULL, 10);
2046 } else if (!strcasecmp(argv[0],"hash-max-zipmap-entries") && argc == 2){
2047 server.hash_max_zipmap_entries = memtoll(argv[1], NULL);
2048 } else if (!strcasecmp(argv[0],"hash-max-zipmap-value") && argc == 2){
2049 server.hash_max_zipmap_value = memtoll(argv[1], NULL);
2050 } else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){
2051 server.list_max_ziplist_entries = memtoll(argv[1], NULL);
2052 } else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2){
2053 server.list_max_ziplist_value = memtoll(argv[1], NULL);
2054 } else {
2055 err = "Bad directive or wrong number of arguments"; goto loaderr;
2056 }
2057 for (j = 0; j < argc; j++)
2058 sdsfree(argv[j]);
2059 zfree(argv);
2060 sdsfree(line);
2061 }
2062 if (fp != stdin) fclose(fp);
2063 return;
2064
2065 loaderr:
2066 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
2067 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
2068 fprintf(stderr, ">>> '%s'\n", line);
2069 fprintf(stderr, "%s\n", err);
2070 exit(1);
2071 }
2072
2073 static void freeClientArgv(redisClient *c) {
2074 int j;
2075
2076 for (j = 0; j < c->argc; j++)
2077 decrRefCount(c->argv[j]);
2078 for (j = 0; j < c->mbargc; j++)
2079 decrRefCount(c->mbargv[j]);
2080 c->argc = 0;
2081 c->mbargc = 0;
2082 }
2083
2084 static void freeClient(redisClient *c) {
2085 listNode *ln;
2086
2087 /* Note that if the client we are freeing is blocked into a blocking
2088 * call, we have to set querybuf to NULL *before* to call
2089 * unblockClientWaitingData() to avoid processInputBuffer() will get
2090 * called. Also it is important to remove the file events after
2091 * this, because this call adds the READABLE event. */
2092 sdsfree(c->querybuf);
2093 c->querybuf = NULL;
2094 if (c->flags & REDIS_BLOCKED)
2095 unblockClientWaitingData(c);
2096
2097 /* UNWATCH all the keys */
2098 unwatchAllKeys(c);
2099 listRelease(c->watched_keys);
2100 /* Unsubscribe from all the pubsub channels */
2101 pubsubUnsubscribeAllChannels(c,0);
2102 pubsubUnsubscribeAllPatterns(c,0);
2103 dictRelease(c->pubsub_channels);
2104 listRelease(c->pubsub_patterns);
2105 /* Obvious cleanup */
2106 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
2107 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2108 listRelease(c->reply);
2109 freeClientArgv(c);
2110 close(c->fd);
2111 /* Remove from the list of clients */
2112 ln = listSearchKey(server.clients,c);
2113 redisAssert(ln != NULL);
2114 listDelNode(server.clients,ln);
2115 /* Remove from the list of clients that are now ready to be restarted
2116 * after waiting for swapped keys */
2117 if (c->flags & REDIS_IO_WAIT && listLength(c->io_keys) == 0) {
2118 ln = listSearchKey(server.io_ready_clients,c);
2119 if (ln) {
2120 listDelNode(server.io_ready_clients,ln);
2121 server.vm_blocked_clients--;
2122 }
2123 }
2124 /* Remove from the list of clients waiting for swapped keys */
2125 while (server.vm_enabled && listLength(c->io_keys)) {
2126 ln = listFirst(c->io_keys);
2127 dontWaitForSwappedKey(c,ln->value);
2128 }
2129 listRelease(c->io_keys);
2130 /* Master/slave cleanup */
2131 if (c->flags & REDIS_SLAVE) {
2132 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
2133 close(c->repldbfd);
2134 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
2135 ln = listSearchKey(l,c);
2136 redisAssert(ln != NULL);
2137 listDelNode(l,ln);
2138 }
2139 if (c->flags & REDIS_MASTER) {
2140 server.master = NULL;
2141 server.replstate = REDIS_REPL_CONNECT;
2142 }
2143 /* Release memory */
2144 zfree(c->argv);
2145 zfree(c->mbargv);
2146 freeClientMultiState(c);
2147 zfree(c);
2148 }
2149
2150 #define GLUEREPLY_UP_TO (1024)
2151 static void glueReplyBuffersIfNeeded(redisClient *c) {
2152 int copylen = 0;
2153 char buf[GLUEREPLY_UP_TO];
2154 listNode *ln;
2155 listIter li;
2156 robj *o;
2157
2158 listRewind(c->reply,&li);
2159 while((ln = listNext(&li))) {
2160 int objlen;
2161
2162 o = ln->value;
2163 objlen = sdslen(o->ptr);
2164 if (copylen + objlen <= GLUEREPLY_UP_TO) {
2165 memcpy(buf+copylen,o->ptr,objlen);
2166 copylen += objlen;
2167 listDelNode(c->reply,ln);
2168 } else {
2169 if (copylen == 0) return;
2170 break;
2171 }
2172 }
2173 /* Now the output buffer is empty, add the new single element */
2174 o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
2175 listAddNodeHead(c->reply,o);
2176 }
2177
2178 static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2179 redisClient *c = privdata;
2180 int nwritten = 0, totwritten = 0, objlen;
2181 robj *o;
2182 REDIS_NOTUSED(el);
2183 REDIS_NOTUSED(mask);
2184
2185 /* Use writev() if we have enough buffers to send */
2186 if (!server.glueoutputbuf &&
2187 listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
2188 !(c->flags & REDIS_MASTER))
2189 {
2190 sendReplyToClientWritev(el, fd, privdata, mask);
2191 return;
2192 }
2193
2194 while(listLength(c->reply)) {
2195 if (server.glueoutputbuf && listLength(c->reply) > 1)
2196 glueReplyBuffersIfNeeded(c);
2197
2198 o = listNodeValue(listFirst(c->reply));
2199 objlen = sdslen(o->ptr);
2200
2201 if (objlen == 0) {
2202 listDelNode(c->reply,listFirst(c->reply));
2203 continue;
2204 }
2205
2206 if (c->flags & REDIS_MASTER) {
2207 /* Don't reply to a master */
2208 nwritten = objlen - c->sentlen;
2209 } else {
2210 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
2211 if (nwritten <= 0) break;
2212 }
2213 c->sentlen += nwritten;
2214 totwritten += nwritten;
2215 /* If we fully sent the object on head go to the next one */
2216 if (c->sentlen == objlen) {
2217 listDelNode(c->reply,listFirst(c->reply));
2218 c->sentlen = 0;
2219 }
2220 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
2221 * bytes, in a single threaded server it's a good idea to serve
2222 * other clients as well, even if a very large request comes from
2223 * super fast link that is always able to accept data (in real world
2224 * scenario think about 'KEYS *' against the loopback interfae) */
2225 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
2226 }
2227 if (nwritten == -1) {
2228 if (errno == EAGAIN) {
2229 nwritten = 0;
2230 } else {
2231 redisLog(REDIS_VERBOSE,
2232 "Error writing to client: %s", strerror(errno));
2233 freeClient(c);
2234 return;
2235 }
2236 }
2237 if (totwritten > 0) c->lastinteraction = time(NULL);
2238 if (listLength(c->reply) == 0) {
2239 c->sentlen = 0;
2240 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2241 }
2242 }
2243
2244 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
2245 {
2246 redisClient *c = privdata;
2247 int nwritten = 0, totwritten = 0, objlen, willwrite;
2248 robj *o;
2249 struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
2250 int offset, ion = 0;
2251 REDIS_NOTUSED(el);
2252 REDIS_NOTUSED(mask);
2253
2254 listNode *node;
2255 while (listLength(c->reply)) {
2256 offset = c->sentlen;
2257 ion = 0;
2258 willwrite = 0;
2259
2260 /* fill-in the iov[] array */
2261 for(node = listFirst(c->reply); node; node = listNextNode(node)) {
2262 o = listNodeValue(node);
2263 objlen = sdslen(o->ptr);
2264
2265 if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
2266 break;
2267
2268 if(ion == REDIS_WRITEV_IOVEC_COUNT)
2269 break; /* no more iovecs */
2270
2271 iov[ion].iov_base = ((char*)o->ptr) + offset;
2272 iov[ion].iov_len = objlen - offset;
2273 willwrite += objlen - offset;
2274 offset = 0; /* just for the first item */
2275 ion++;
2276 }
2277
2278 if(willwrite == 0)
2279 break;
2280
2281 /* write all collected blocks at once */
2282 if((nwritten = writev(fd, iov, ion)) < 0) {
2283 if (errno != EAGAIN) {
2284 redisLog(REDIS_VERBOSE,
2285 "Error writing to client: %s", strerror(errno));
2286 freeClient(c);
2287 return;
2288 }
2289 break;
2290 }
2291
2292 totwritten += nwritten;
2293 offset = c->sentlen;
2294
2295 /* remove written robjs from c->reply */
2296 while (nwritten && listLength(c->reply)) {
2297 o = listNodeValue(listFirst(c->reply));
2298 objlen = sdslen(o->ptr);
2299
2300 if(nwritten >= objlen - offset) {
2301 listDelNode(c->reply, listFirst(c->reply));
2302 nwritten -= objlen - offset;
2303 c->sentlen = 0;
2304 } else {
2305 /* partial write */
2306 c->sentlen += nwritten;
2307 break;
2308 }
2309 offset = 0;
2310 }
2311 }
2312
2313 if (totwritten > 0)
2314 c->lastinteraction = time(NULL);
2315
2316 if (listLength(c->reply) == 0) {
2317 c->sentlen = 0;
2318 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2319 }
2320 }
2321
2322 static int qsortRedisCommands(const void *r1, const void *r2) {
2323 return strcasecmp(
2324 ((struct redisCommand*)r1)->name,
2325 ((struct redisCommand*)r2)->name);
2326 }
2327
2328 static void sortCommandTable() {
2329 /* Copy and sort the read-only version of the command table */
2330 commandTable = (struct redisCommand*)malloc(sizeof(readonlyCommandTable));
2331 memcpy(commandTable,readonlyCommandTable,sizeof(readonlyCommandTable));
2332 qsort(commandTable,
2333 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
2334 sizeof(struct redisCommand),qsortRedisCommands);
2335 }
2336
2337 static struct redisCommand *lookupCommand(char *name) {
2338 struct redisCommand tmp = {name,NULL,0,0,NULL,0,0,0};
2339 return bsearch(
2340 &tmp,
2341 commandTable,
2342 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
2343 sizeof(struct redisCommand),
2344 qsortRedisCommands);
2345 }
2346
2347 /* resetClient prepare the client to process the next command */
2348 static void resetClient(redisClient *c) {
2349 freeClientArgv(c);
2350 c->bulklen = -1;
2351 c->multibulk = 0;
2352 }
2353
2354 /* Call() is the core of Redis execution of a command */
2355 static void call(redisClient *c, struct redisCommand *cmd) {
2356 long long dirty;
2357
2358 dirty = server.dirty;
2359 cmd->proc(c);
2360 dirty = server.dirty-dirty;
2361
2362 if (server.appendonly && dirty)
2363 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
2364 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
2365 listLength(server.slaves))
2366 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
2367 if (listLength(server.monitors))
2368 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
2369 server.stat_numcommands++;
2370 }
2371
2372 /* If this function gets called we already read a whole
2373 * command, argments are in the client argv/argc fields.
2374 * processCommand() execute the command or prepare the
2375 * server for a bulk read from the client.
2376 *
2377 * If 1 is returned the client is still alive and valid and
2378 * and other operations can be performed by the caller. Otherwise
2379 * if 0 is returned the client was destroied (i.e. after QUIT). */
2380 static int processCommand(redisClient *c) {
2381 struct redisCommand *cmd;
2382
2383 /* Free some memory if needed (maxmemory setting) */
2384 if (server.maxmemory) freeMemoryIfNeeded();
2385
2386 /* Handle the multi bulk command type. This is an alternative protocol
2387 * supported by Redis in order to receive commands that are composed of
2388 * multiple binary-safe "bulk" arguments. The latency of processing is
2389 * a bit higher but this allows things like multi-sets, so if this
2390 * protocol is used only for MSET and similar commands this is a big win. */
2391 if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
2392 c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
2393 if (c->multibulk <= 0) {
2394 resetClient(c);
2395 return 1;
2396 } else {
2397 decrRefCount(c->argv[c->argc-1]);
2398 c->argc--;
2399 return 1;
2400 }
2401 } else if (c->multibulk) {
2402 if (c->bulklen == -1) {
2403 if (((char*)c->argv[0]->ptr)[0] != '$') {
2404 addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
2405 resetClient(c);
2406 return 1;
2407 } else {
2408 int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
2409 decrRefCount(c->argv[0]);
2410 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2411 c->argc--;
2412 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2413 resetClient(c);
2414 return 1;
2415 }
2416 c->argc--;
2417 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2418 return 1;
2419 }
2420 } else {
2421 c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
2422 c->mbargv[c->mbargc] = c->argv[0];
2423 c->mbargc++;
2424 c->argc--;
2425 c->multibulk--;
2426 if (c->multibulk == 0) {
2427 robj **auxargv;
2428 int auxargc;
2429
2430 /* Here we need to swap the multi-bulk argc/argv with the
2431 * normal argc/argv of the client structure. */
2432 auxargv = c->argv;
2433 c->argv = c->mbargv;
2434 c->mbargv = auxargv;
2435
2436 auxargc = c->argc;
2437 c->argc = c->mbargc;
2438 c->mbargc = auxargc;
2439
2440 /* We need to set bulklen to something different than -1
2441 * in order for the code below to process the command without
2442 * to try to read the last argument of a bulk command as
2443 * a special argument. */
2444 c->bulklen = 0;
2445 /* continue below and process the command */
2446 } else {
2447 c->bulklen = -1;
2448 return 1;
2449 }
2450 }
2451 }
2452 /* -- end of multi bulk commands processing -- */
2453
2454 /* The QUIT command is handled as a special case. Normal command
2455 * procs are unable to close the client connection safely */
2456 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
2457 freeClient(c);
2458 return 0;
2459 }
2460
2461 /* Now lookup the command and check ASAP about trivial error conditions
2462 * such wrong arity, bad command name and so forth. */
2463 cmd = lookupCommand(c->argv[0]->ptr);
2464 if (!cmd) {
2465 addReplySds(c,
2466 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2467 (char*)c->argv[0]->ptr));
2468 resetClient(c);
2469 return 1;
2470 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
2471 (c->argc < -cmd->arity)) {
2472 addReplySds(c,
2473 sdscatprintf(sdsempty(),
2474 "-ERR wrong number of arguments for '%s' command\r\n",
2475 cmd->name));
2476 resetClient(c);
2477 return 1;
2478 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
2479 /* This is a bulk command, we have to read the last argument yet. */
2480 int bulklen = atoi(c->argv[c->argc-1]->ptr);
2481
2482 decrRefCount(c->argv[c->argc-1]);
2483 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2484 c->argc--;
2485 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2486 resetClient(c);
2487 return 1;
2488 }
2489 c->argc--;
2490 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2491 /* It is possible that the bulk read is already in the
2492 * buffer. Check this condition and handle it accordingly.
2493 * This is just a fast path, alternative to call processInputBuffer().
2494 * It's a good idea since the code is small and this condition
2495 * happens most of the times. */
2496 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
2497 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2498 c->argc++;
2499 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2500 } else {
2501 /* Otherwise return... there is to read the last argument
2502 * from the socket. */
2503 return 1;
2504 }
2505 }
2506 /* Let's try to encode the bulk object to save space. */
2507 if (cmd->flags & REDIS_CMD_BULK)
2508 c->argv[c->argc-1] = tryObjectEncoding(c->argv[c->argc-1]);
2509
2510 /* Check if the user is authenticated */
2511 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
2512 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
2513 resetClient(c);
2514 return 1;
2515 }
2516
2517 /* Handle the maxmemory directive */
2518 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
2519 zmalloc_used_memory() > server.maxmemory)
2520 {
2521 addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2522 resetClient(c);
2523 return 1;
2524 }
2525
2526 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
2527 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
2528 &&
2529 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
2530 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
2531 addReplySds(c,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
2532 resetClient(c);
2533 return 1;
2534 }
2535
2536 /* Exec the command */
2537 if (c->flags & REDIS_MULTI &&
2538 cmd->proc != execCommand && cmd->proc != discardCommand &&
2539 cmd->proc != multiCommand && cmd->proc != watchCommand)
2540 {
2541 queueMultiCommand(c,cmd);
2542 addReply(c,shared.queued);
2543 } else {
2544 if (server.vm_enabled && server.vm_max_threads > 0 &&
2545 blockClientOnSwappedKeys(c,cmd)) return 1;
2546 call(c,cmd);
2547 }
2548
2549 /* Prepare the client for the next command */
2550 resetClient(c);
2551 return 1;
2552 }
2553
2554 static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
2555 listNode *ln;
2556 listIter li;
2557 int outc = 0, j;
2558 robj **outv;
2559 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2560 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2561 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2562 robj *static_outv[REDIS_STATIC_ARGS*3+1];
2563 robj *lenobj;
2564
2565 if (argc <= REDIS_STATIC_ARGS) {
2566 outv = static_outv;
2567 } else {
2568 outv = zmalloc(sizeof(robj*)*(argc*3+1));
2569 }
2570
2571 lenobj = createObject(REDIS_STRING,
2572 sdscatprintf(sdsempty(), "*%d\r\n", argc));
2573 lenobj->refcount = 0;
2574 outv[outc++] = lenobj;
2575 for (j = 0; j < argc; j++) {
2576 lenobj = createObject(REDIS_STRING,
2577 sdscatprintf(sdsempty(),"$%lu\r\n",
2578 (unsigned long) stringObjectLen(argv[j])));
2579 lenobj->refcount = 0;
2580 outv[outc++] = lenobj;
2581 outv[outc++] = argv[j];
2582 outv[outc++] = shared.crlf;
2583 }
2584
2585 /* Increment all the refcounts at start and decrement at end in order to
2586 * be sure to free objects if there is no slave in a replication state
2587 * able to be feed with commands */
2588 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
2589 listRewind(slaves,&li);
2590 while((ln = listNext(&li))) {
2591 redisClient *slave = ln->value;
2592
2593 /* Don't feed slaves that are still waiting for BGSAVE to start */
2594 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
2595
2596 /* Feed all the other slaves, MONITORs and so on */
2597 if (slave->slaveseldb != dictid) {
2598 robj *selectcmd;
2599
2600 switch(dictid) {
2601 case 0: selectcmd = shared.select0; break;
2602 case 1: selectcmd = shared.select1; break;
2603 case 2: selectcmd = shared.select2; break;
2604 case 3: selectcmd = shared.select3; break;
2605 case 4: selectcmd = shared.select4; break;
2606 case 5: selectcmd = shared.select5; break;
2607 case 6: selectcmd = shared.select6; break;
2608 case 7: selectcmd = shared.select7; break;
2609 case 8: selectcmd = shared.select8; break;
2610 case 9: selectcmd = shared.select9; break;
2611 default:
2612 selectcmd = createObject(REDIS_STRING,
2613 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
2614 selectcmd->refcount = 0;
2615 break;
2616 }
2617 addReply(slave,selectcmd);
2618 slave->slaveseldb = dictid;
2619 }
2620 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
2621 }
2622 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
2623 if (outv != static_outv) zfree(outv);
2624 }
2625
2626 static sds sdscatrepr(sds s, char *p, size_t len) {
2627 s = sdscatlen(s,"\"",1);
2628 while(len--) {
2629 switch(*p) {
2630 case '\\':
2631 case '"':
2632 s = sdscatprintf(s,"\\%c",*p);
2633 break;
2634 case '\n': s = sdscatlen(s,"\\n",1); break;
2635 case '\r': s = sdscatlen(s,"\\r",1); break;
2636 case '\t': s = sdscatlen(s,"\\t",1); break;
2637 case '\a': s = sdscatlen(s,"\\a",1); break;
2638 case '\b': s = sdscatlen(s,"\\b",1); break;
2639 default:
2640 if (isprint(*p))
2641 s = sdscatprintf(s,"%c",*p);
2642 else
2643 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
2644 break;
2645 }
2646 p++;
2647 }
2648 return sdscatlen(s,"\"",1);
2649 }
2650
2651 static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc) {
2652 listNode *ln;
2653 listIter li;
2654 int j;
2655 sds cmdrepr = sdsnew("+");
2656 robj *cmdobj;
2657 struct timeval tv;
2658
2659 gettimeofday(&tv,NULL);
2660 cmdrepr = sdscatprintf(cmdrepr,"%ld.%ld ",(long)tv.tv_sec,(long)tv.tv_usec);
2661 if (dictid != 0) cmdrepr = sdscatprintf(cmdrepr,"(db %d) ", dictid);
2662
2663 for (j = 0; j < argc; j++) {
2664 if (argv[j]->encoding == REDIS_ENCODING_INT) {
2665 cmdrepr = sdscatprintf(cmdrepr, "%ld", (long)argv[j]->ptr);
2666 } else {
2667 cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
2668 sdslen(argv[j]->ptr));
2669 }
2670 if (j != argc-1)
2671 cmdrepr = sdscatlen(cmdrepr," ",1);
2672 }
2673 cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
2674 cmdobj = createObject(REDIS_STRING,cmdrepr);
2675
2676 listRewind(monitors,&li);
2677 while((ln = listNext(&li))) {
2678 redisClient *monitor = ln->value;
2679 addReply(monitor,cmdobj);
2680 }
2681 decrRefCount(cmdobj);
2682 }
2683
2684 static void processInputBuffer(redisClient *c) {
2685 again:
2686 /* Before to process the input buffer, make sure the client is not
2687 * waitig for a blocking operation such as BLPOP. Note that the first
2688 * iteration the client is never blocked, otherwise the processInputBuffer
2689 * would not be called at all, but after the execution of the first commands
2690 * in the input buffer the client may be blocked, and the "goto again"
2691 * will try to reiterate. The following line will make it return asap. */
2692 if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
2693 if (c->bulklen == -1) {
2694 /* Read the first line of the query */
2695 char *p = strchr(c->querybuf,'\n');
2696 size_t querylen;
2697
2698 if (p) {
2699 sds query, *argv;
2700 int argc, j;
2701
2702 query = c->querybuf;
2703 c->querybuf = sdsempty();
2704 querylen = 1+(p-(query));
2705 if (sdslen(query) > querylen) {
2706 /* leave data after the first line of the query in the buffer */
2707 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
2708 }
2709 *p = '\0'; /* remove "\n" */
2710 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
2711 sdsupdatelen(query);
2712
2713 /* Now we can split the query in arguments */
2714 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
2715 sdsfree(query);
2716
2717 if (c->argv) zfree(c->argv);
2718 c->argv = zmalloc(sizeof(robj*)*argc);
2719
2720 for (j = 0; j < argc; j++) {
2721 if (sdslen(argv[j])) {
2722 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
2723 c->argc++;
2724 } else {
2725 sdsfree(argv[j]);
2726 }
2727 }
2728 zfree(argv);
2729 if (c->argc) {
2730 /* Execute the command. If the client is still valid
2731 * after processCommand() return and there is something
2732 * on the query buffer try to process the next command. */
2733 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2734 } else {
2735 /* Nothing to process, argc == 0. Just process the query
2736 * buffer if it's not empty or return to the caller */
2737 if (sdslen(c->querybuf)) goto again;
2738 }
2739 return;
2740 } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
2741 redisLog(REDIS_VERBOSE, "Client protocol error");
2742 freeClient(c);
2743 return;
2744 }
2745 } else {
2746 /* Bulk read handling. Note that if we are at this point
2747 the client already sent a command terminated with a newline,
2748 we are reading the bulk data that is actually the last
2749 argument of the command. */
2750 int qbl = sdslen(c->querybuf);
2751
2752 if (c->bulklen <= qbl) {
2753 /* Copy everything but the final CRLF as final argument */
2754 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2755 c->argc++;
2756 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2757 /* Process the command. If the client is still valid after
2758 * the processing and there is more data in the buffer
2759 * try to parse it. */
2760 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2761 return;
2762 }
2763 }
2764 }
2765
2766 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2767 redisClient *c = (redisClient*) privdata;
2768 char buf[REDIS_IOBUF_LEN];
2769 int nread;
2770 REDIS_NOTUSED(el);
2771 REDIS_NOTUSED(mask);
2772
2773 nread = read(fd, buf, REDIS_IOBUF_LEN);
2774 if (nread == -1) {
2775 if (errno == EAGAIN) {
2776 nread = 0;
2777 } else {
2778 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
2779 freeClient(c);
2780 return;
2781 }
2782 } else if (nread == 0) {
2783 redisLog(REDIS_VERBOSE, "Client closed connection");
2784 freeClient(c);
2785 return;
2786 }
2787 if (nread) {
2788 c->querybuf = sdscatlen(c->querybuf, buf, nread);
2789 c->lastinteraction = time(NULL);
2790 } else {
2791 return;
2792 }
2793 processInputBuffer(c);
2794 }
2795
2796 static int selectDb(redisClient *c, int id) {
2797 if (id < 0 || id >= server.dbnum)
2798 return REDIS_ERR;
2799 c->db = &server.db[id];
2800 return REDIS_OK;
2801 }
2802
2803 static void *dupClientReplyValue(void *o) {
2804 incrRefCount((robj*)o);
2805 return o;
2806 }
2807
2808 static int listMatchObjects(void *a, void *b) {
2809 return equalStringObjects(a,b);
2810 }
2811
2812 static redisClient *createClient(int fd) {
2813 redisClient *c = zmalloc(sizeof(*c));
2814
2815 anetNonBlock(NULL,fd);
2816 anetTcpNoDelay(NULL,fd);
2817 if (!c) return NULL;
2818 selectDb(c,0);
2819 c->fd = fd;
2820 c->querybuf = sdsempty();
2821 c->argc = 0;
2822 c->argv = NULL;
2823 c->bulklen = -1;
2824 c->multibulk = 0;
2825 c->mbargc = 0;
2826 c->mbargv = NULL;
2827 c->sentlen = 0;
2828 c->flags = 0;
2829 c->lastinteraction = time(NULL);
2830 c->authenticated = 0;
2831 c->replstate = REDIS_REPL_NONE;
2832 c->reply = listCreate();
2833 listSetFreeMethod(c->reply,decrRefCount);
2834 listSetDupMethod(c->reply,dupClientReplyValue);
2835 c->blocking_keys = NULL;
2836 c->blocking_keys_num = 0;
2837 c->io_keys = listCreate();
2838 c->watched_keys = listCreate();
2839 listSetFreeMethod(c->io_keys,decrRefCount);
2840 c->pubsub_channels = dictCreate(&setDictType,NULL);
2841 c->pubsub_patterns = listCreate();
2842 listSetFreeMethod(c->pubsub_patterns,decrRefCount);
2843 listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
2844 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
2845 readQueryFromClient, c) == AE_ERR) {
2846 freeClient(c);
2847 return NULL;
2848 }
2849 listAddNodeTail(server.clients,c);
2850 initClientMultiState(c);
2851 return c;
2852 }
2853
2854 static void addReply(redisClient *c, robj *obj) {
2855 if (listLength(c->reply) == 0 &&
2856 (c->replstate == REDIS_REPL_NONE ||
2857 c->replstate == REDIS_REPL_ONLINE) &&
2858 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
2859 sendReplyToClient, c) == AE_ERR) return;
2860
2861 if (server.vm_enabled && obj->storage != REDIS_VM_MEMORY) {
2862 obj = dupStringObject(obj);
2863 obj->refcount = 0; /* getDecodedObject() will increment the refcount */
2864 }
2865 listAddNodeTail(c->reply,getDecodedObject(obj));
2866 }
2867
2868 static void addReplySds(redisClient *c, sds s) {
2869 robj *o = createObject(REDIS_STRING,s);
2870 addReply(c,o);
2871 decrRefCount(o);
2872 }
2873
2874 static void addReplyDouble(redisClient *c, double d) {
2875 char buf[128];
2876
2877 snprintf(buf,sizeof(buf),"%.17g",d);
2878 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2879 (unsigned long) strlen(buf),buf));
2880 }
2881
2882 static void addReplyLongLong(redisClient *c, long long ll) {
2883 char buf[128];
2884 size_t len;
2885
2886 if (ll == 0) {
2887 addReply(c,shared.czero);
2888 return;
2889 } else if (ll == 1) {
2890 addReply(c,shared.cone);
2891 return;
2892 }
2893 buf[0] = ':';
2894 len = ll2string(buf+1,sizeof(buf)-1,ll);
2895 buf[len+1] = '\r';
2896 buf[len+2] = '\n';
2897 addReplySds(c,sdsnewlen(buf,len+3));
2898 }
2899
2900 static void addReplyUlong(redisClient *c, unsigned long ul) {
2901 char buf[128];
2902 size_t len;
2903
2904 if (ul == 0) {
2905 addReply(c,shared.czero);
2906 return;
2907 } else if (ul == 1) {
2908 addReply(c,shared.cone);
2909 return;
2910 }
2911 len = snprintf(buf,sizeof(buf),":%lu\r\n",ul);
2912 addReplySds(c,sdsnewlen(buf,len));
2913 }
2914
2915 static void addReplyBulkLen(redisClient *c, robj *obj) {
2916 size_t len, intlen;
2917 char buf[128];
2918
2919 if (obj->encoding == REDIS_ENCODING_RAW) {
2920 len = sdslen(obj->ptr);
2921 } else {
2922 long n = (long)obj->ptr;
2923
2924 /* Compute how many bytes will take this integer as a radix 10 string */
2925 len = 1;
2926 if (n < 0) {
2927 len++;
2928 n = -n;
2929 }
2930 while((n = n/10) != 0) {
2931 len++;
2932 }
2933 }
2934 buf[0] = '$';
2935 intlen = ll2string(buf+1,sizeof(buf)-1,(long long)len);
2936 buf[intlen+1] = '\r';
2937 buf[intlen+2] = '\n';
2938 addReplySds(c,sdsnewlen(buf,intlen+3));
2939 }
2940
2941 static void addReplyBulk(redisClient *c, robj *obj) {
2942 addReplyBulkLen(c,obj);
2943 addReply(c,obj);
2944 addReply(c,shared.crlf);
2945 }
2946
2947 static void addReplyBulkSds(redisClient *c, sds s) {
2948 robj *o = createStringObject(s, sdslen(s));
2949 addReplyBulk(c,o);
2950 decrRefCount(o);
2951 }
2952
2953 /* In the CONFIG command we need to add vanilla C string as bulk replies */
2954 static void addReplyBulkCString(redisClient *c, char *s) {
2955 if (s == NULL) {
2956 addReply(c,shared.nullbulk);
2957 } else {
2958 robj *o = createStringObject(s,strlen(s));
2959 addReplyBulk(c,o);
2960 decrRefCount(o);
2961 }
2962 }
2963
2964 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2965 int cport, cfd;
2966 char cip[128];
2967 redisClient *c;
2968 REDIS_NOTUSED(el);
2969 REDIS_NOTUSED(mask);
2970 REDIS_NOTUSED(privdata);
2971
2972 cfd = anetAccept(server.neterr, fd, cip, &cport);
2973 if (cfd == AE_ERR) {
2974 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
2975 return;
2976 }
2977 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
2978 if ((c = createClient(cfd)) == NULL) {
2979 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2980 close(cfd); /* May be already closed, just ingore errors */
2981 return;
2982 }
2983 /* If maxclient directive is set and this is one client more... close the
2984 * connection. Note that we create the client instead to check before
2985 * for this condition, since now the socket is already set in nonblocking
2986 * mode and we can send an error for free using the Kernel I/O */
2987 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2988 char *err = "-ERR max number of clients reached\r\n";
2989
2990 /* That's a best effort error message, don't check write errors */
2991 if (write(c->fd,err,strlen(err)) == -1) {
2992 /* Nothing to do, Just to avoid the warning... */
2993 }
2994 freeClient(c);
2995 return;
2996 }
2997 server.stat_numconnections++;
2998 }
2999
3000 /* ======================= Redis objects implementation ===================== */
3001
3002 static robj *createObject(int type, void *ptr) {
3003 robj *o;
3004
3005 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
3006 if (listLength(server.objfreelist)) {
3007 listNode *head = listFirst(server.objfreelist);
3008 o = listNodeValue(head);
3009 listDelNode(server.objfreelist,head);
3010 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
3011 } else {
3012 if (server.vm_enabled)
3013 pthread_mutex_unlock(&server.obj_freelist_mutex);
3014 o = zmalloc(sizeof(*o));
3015 }
3016 o->type = type;
3017 o->encoding = REDIS_ENCODING_RAW;
3018 o->ptr = ptr;
3019 o->refcount = 1;
3020 if (server.vm_enabled) {
3021 /* Note that this code may run in the context of an I/O thread
3022 * and accessing server.lruclock in theory is an error
3023 * (no locks). But in practice this is safe, and even if we read
3024 * garbage Redis will not fail. */
3025 o->lru = server.lruclock;
3026 o->storage = REDIS_VM_MEMORY;
3027 }
3028 return o;
3029 }
3030
3031 static robj *createStringObject(char *ptr, size_t len) {
3032 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
3033 }
3034
3035 static robj *createStringObjectFromLongLong(long long value) {
3036 robj *o;
3037 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3038 incrRefCount(shared.integers[value]);
3039 o = shared.integers[value];
3040 } else {
3041 if (value >= LONG_MIN && value <= LONG_MAX) {
3042 o = createObject(REDIS_STRING, NULL);
3043 o->encoding = REDIS_ENCODING_INT;
3044 o->ptr = (void*)((long)value);
3045 } else {
3046 o = createObject(REDIS_STRING,sdsfromlonglong(value));
3047 }
3048 }
3049 return o;
3050 }
3051
3052 static robj *dupStringObject(robj *o) {
3053 assert(o->encoding == REDIS_ENCODING_RAW);
3054 return createStringObject(o->ptr,sdslen(o->ptr));
3055 }
3056
3057 static robj *createListObject(void) {
3058 list *l = listCreate();
3059 robj *o = createObject(REDIS_LIST,l);
3060 listSetFreeMethod(l,decrRefCount);
3061 o->encoding = REDIS_ENCODING_LIST;
3062 return o;
3063 }
3064
3065 static robj *createZiplistObject(void) {
3066 unsigned char *zl = ziplistNew();
3067 robj *o = createObject(REDIS_LIST,zl);
3068 o->encoding = REDIS_ENCODING_ZIPLIST;
3069 return o;
3070 }
3071
3072 static robj *createSetObject(void) {
3073 dict *d = dictCreate(&setDictType,NULL);
3074 return createObject(REDIS_SET,d);
3075 }
3076
3077 static robj *createHashObject(void) {
3078 /* All the Hashes start as zipmaps. Will be automatically converted
3079 * into hash tables if there are enough elements or big elements
3080 * inside. */
3081 unsigned char *zm = zipmapNew();
3082 robj *o = createObject(REDIS_HASH,zm);
3083 o->encoding = REDIS_ENCODING_ZIPMAP;
3084 return o;
3085 }
3086
3087 static robj *createZsetObject(void) {
3088 zset *zs = zmalloc(sizeof(*zs));
3089
3090 zs->dict = dictCreate(&zsetDictType,NULL);
3091 zs->zsl = zslCreate();
3092 return createObject(REDIS_ZSET,zs);
3093 }
3094
3095 static void freeStringObject(robj *o) {
3096 if (o->encoding == REDIS_ENCODING_RAW) {
3097 sdsfree(o->ptr);
3098 }
3099 }
3100
3101 static void freeListObject(robj *o) {
3102 switch (o->encoding) {
3103 case REDIS_ENCODING_LIST:
3104 listRelease((list*) o->ptr);
3105 break;
3106 case REDIS_ENCODING_ZIPLIST:
3107 zfree(o->ptr);
3108 break;
3109 default:
3110 redisPanic("Unknown list encoding type");
3111 }
3112 }
3113
3114 static void freeSetObject(robj *o) {
3115 dictRelease((dict*) o->ptr);
3116 }
3117
3118 static void freeZsetObject(robj *o) {
3119 zset *zs = o->ptr;
3120
3121 dictRelease(zs->dict);
3122 zslFree(zs->zsl);
3123 zfree(zs);
3124 }
3125
3126 static void freeHashObject(robj *o) {
3127 switch (o->encoding) {
3128 case REDIS_ENCODING_HT:
3129 dictRelease((dict*) o->ptr);
3130 break;
3131 case REDIS_ENCODING_ZIPMAP:
3132 zfree(o->ptr);
3133 break;
3134 default:
3135 redisPanic("Unknown hash encoding type");
3136 break;
3137 }
3138 }
3139
3140 static void incrRefCount(robj *o) {
3141 o->refcount++;
3142 }
3143
3144 static void decrRefCount(void *obj) {
3145 robj *o = obj;
3146
3147 /* Object is a swapped out value, or in the process of being loaded. */
3148 if (server.vm_enabled &&
3149 (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
3150 {
3151 vmpointer *vp = obj;
3152 if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(o);
3153 vmMarkPagesFree(vp->page,vp->usedpages);
3154 server.vm_stats_swapped_objects--;
3155 zfree(vp);
3156 return;
3157 }
3158
3159 if (o->refcount <= 0) redisPanic("decrRefCount against refcount <= 0");
3160 /* Object is in memory, or in the process of being swapped out.
3161 *
3162 * If the object is being swapped out, abort the operation on
3163 * decrRefCount even if the refcount does not drop to 0: the object
3164 * is referenced at least two times, as value of the key AND as
3165 * job->val in the iojob. So if we don't invalidate the iojob, when it is
3166 * done but the relevant key was removed in the meantime, the
3167 * complete jobs handler will not find the key about the job and the
3168 * assert will fail. */
3169 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
3170 vmCancelThreadedIOJob(o);
3171 if (--(o->refcount) == 0) {
3172 switch(o->type) {
3173 case REDIS_STRING: freeStringObject(o); break;
3174 case REDIS_LIST: freeListObject(o); break;
3175 case REDIS_SET: freeSetObject(o); break;
3176 case REDIS_ZSET: freeZsetObject(o); break;
3177 case REDIS_HASH: freeHashObject(o); break;
3178 default: redisPanic("Unknown object type"); break;
3179 }
3180 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
3181 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3182 !listAddNodeHead(server.objfreelist,o))
3183 zfree(o);
3184 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
3185 }
3186 }
3187
3188 static int checkType(redisClient *c, robj *o, int type) {
3189 if (o->type != type) {
3190 addReply(c,shared.wrongtypeerr);
3191 return 1;
3192 }
3193 return 0;
3194 }
3195
3196 /* Check if the nul-terminated string 's' can be represented by a long
3197 * (that is, is a number that fits into long without any other space or
3198 * character before or after the digits).
3199 *
3200 * If so, the function returns REDIS_OK and *longval is set to the value
3201 * of the number. Otherwise REDIS_ERR is returned */
3202 static int isStringRepresentableAsLong(sds s, long *longval) {
3203 char buf[32], *endptr;
3204 long value;
3205 int slen;
3206
3207 value = strtol(s, &endptr, 10);
3208 if (endptr[0] != '\0') return REDIS_ERR;
3209 slen = ll2string(buf,32,value);
3210
3211 /* If the number converted back into a string is not identical
3212 * then it's not possible to encode the string as integer */
3213 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
3214 if (longval) *longval = value;
3215 return REDIS_OK;
3216 }
3217
3218 /* Try to encode a string object in order to save space */
3219 static robj *tryObjectEncoding(robj *o) {
3220 long value;
3221 sds s = o->ptr;
3222
3223 if (o->encoding != REDIS_ENCODING_RAW)
3224 return o; /* Already encoded */
3225
3226 /* It's not safe to encode shared objects: shared objects can be shared
3227 * everywhere in the "object space" of Redis. Encoded objects can only
3228 * appear as "values" (and not, for instance, as keys) */
3229 if (o->refcount > 1) return o;
3230
3231 /* Currently we try to encode only strings */
3232 redisAssert(o->type == REDIS_STRING);
3233
3234 /* Check if we can represent this string as a long integer */
3235 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return o;
3236
3237 /* Ok, this object can be encoded */
3238 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3239 decrRefCount(o);
3240 incrRefCount(shared.integers[value]);
3241 return shared.integers[value];
3242 } else {
3243 o->encoding = REDIS_ENCODING_INT;
3244 sdsfree(o->ptr);
3245 o->ptr = (void*) value;
3246 return o;
3247 }
3248 }
3249
3250 /* Get a decoded version of an encoded object (returned as a new object).
3251 * If the object is already raw-encoded just increment the ref count. */
3252 static robj *getDecodedObject(robj *o) {
3253 robj *dec;
3254
3255 if (o->encoding == REDIS_ENCODING_RAW) {
3256 incrRefCount(o);
3257 return o;
3258 }
3259 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
3260 char buf[32];
3261
3262 ll2string(buf,32,(long)o->ptr);
3263 dec = createStringObject(buf,strlen(buf));
3264 return dec;
3265 } else {
3266 redisPanic("Unknown encoding type");
3267 }
3268 }
3269
3270 /* Compare two string objects via strcmp() or alike.
3271 * Note that the objects may be integer-encoded. In such a case we
3272 * use ll2string() to get a string representation of the numbers on the stack
3273 * and compare the strings, it's much faster than calling getDecodedObject().
3274 *
3275 * Important note: if objects are not integer encoded, but binary-safe strings,
3276 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3277 * binary safe. */
3278 static int compareStringObjects(robj *a, robj *b) {
3279 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
3280 char bufa[128], bufb[128], *astr, *bstr;
3281 int bothsds = 1;
3282
3283 if (a == b) return 0;
3284 if (a->encoding != REDIS_ENCODING_RAW) {
3285 ll2string(bufa,sizeof(bufa),(long) a->ptr);
3286 astr = bufa;
3287 bothsds = 0;
3288 } else {
3289 astr = a->ptr;
3290 }
3291 if (b->encoding != REDIS_ENCODING_RAW) {
3292 ll2string(bufb,sizeof(bufb),(long) b->ptr);
3293 bstr = bufb;
3294 bothsds = 0;
3295 } else {
3296 bstr = b->ptr;
3297 }
3298 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
3299 }
3300
3301 /* Equal string objects return 1 if the two objects are the same from the
3302 * point of view of a string comparison, otherwise 0 is returned. Note that
3303 * this function is faster then checking for (compareStringObject(a,b) == 0)
3304 * because it can perform some more optimization. */
3305 static int equalStringObjects(robj *a, robj *b) {
3306 if (a->encoding != REDIS_ENCODING_RAW && b->encoding != REDIS_ENCODING_RAW){
3307 return a->ptr == b->ptr;
3308 } else {
3309 return compareStringObjects(a,b) == 0;
3310 }
3311 }
3312
3313 static size_t stringObjectLen(robj *o) {
3314 redisAssert(o->type == REDIS_STRING);
3315 if (o->encoding == REDIS_ENCODING_RAW) {
3316 return sdslen(o->ptr);
3317 } else {
3318 char buf[32];
3319
3320 return ll2string(buf,32,(long)o->ptr);
3321 }
3322 }
3323
3324 static int getDoubleFromObject(robj *o, double *target) {
3325 double value;
3326 char *eptr;
3327
3328 if (o == NULL) {
3329 value = 0;
3330 } else {
3331 redisAssert(o->type == REDIS_STRING);
3332 if (o->encoding == REDIS_ENCODING_RAW) {
3333 value = strtod(o->ptr, &eptr);
3334 if (eptr[0] != '\0') return REDIS_ERR;
3335 } else if (o->encoding == REDIS_ENCODING_INT) {
3336 value = (long)o->ptr;
3337 } else {
3338 redisPanic("Unknown string encoding");
3339 }
3340 }
3341
3342 *target = value;
3343 return REDIS_OK;
3344 }
3345
3346 static int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg) {
3347 double value;
3348 if (getDoubleFromObject(o, &value) != REDIS_OK) {
3349 if (msg != NULL) {
3350 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3351 } else {
3352 addReplySds(c, sdsnew("-ERR value is not a double\r\n"));
3353 }
3354 return REDIS_ERR;
3355 }
3356
3357 *target = value;
3358 return REDIS_OK;
3359 }
3360
3361 static int getLongLongFromObject(robj *o, long long *target) {
3362 long long value;
3363 char *eptr;
3364
3365 if (o == NULL) {
3366 value = 0;
3367 } else {
3368 redisAssert(o->type == REDIS_STRING);
3369 if (o->encoding == REDIS_ENCODING_RAW) {
3370 value = strtoll(o->ptr, &eptr, 10);
3371 if (eptr[0] != '\0') return REDIS_ERR;
3372 } else if (o->encoding == REDIS_ENCODING_INT) {
3373 value = (long)o->ptr;
3374 } else {
3375 redisPanic("Unknown string encoding");
3376 }
3377 }
3378
3379 *target = value;
3380 return REDIS_OK;
3381 }
3382
3383 static int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg) {
3384 long long value;
3385 if (getLongLongFromObject(o, &value) != REDIS_OK) {
3386 if (msg != NULL) {
3387 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3388 } else {
3389 addReplySds(c, sdsnew("-ERR value is not an integer\r\n"));
3390 }
3391 return REDIS_ERR;
3392 }
3393
3394 *target = value;
3395 return REDIS_OK;
3396 }
3397
3398 static int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg) {
3399 long long value;
3400
3401 if (getLongLongFromObjectOrReply(c, o, &value, msg) != REDIS_OK) return REDIS_ERR;
3402 if (value < LONG_MIN || value > LONG_MAX) {
3403 if (msg != NULL) {
3404 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3405 } else {
3406 addReplySds(c, sdsnew("-ERR value is out of range\r\n"));
3407 }
3408 return REDIS_ERR;
3409 }
3410
3411 *target = value;
3412 return REDIS_OK;
3413 }
3414
3415 /* =========================== Keyspace access API ========================== */
3416
3417 static robj *lookupKey(redisDb *db, robj *key) {
3418 dictEntry *de = dictFind(db->dict,key->ptr);
3419 if (de) {
3420 robj *val = dictGetEntryVal(de);
3421
3422 if (server.vm_enabled) {
3423 if (val->storage == REDIS_VM_MEMORY ||
3424 val->storage == REDIS_VM_SWAPPING)
3425 {
3426 /* If we were swapping the object out, cancel the operation */
3427 if (val->storage == REDIS_VM_SWAPPING)
3428 vmCancelThreadedIOJob(val);
3429 /* Update the access time for the aging algorithm. */
3430 val->lru = server.lruclock;
3431 } else {
3432 int notify = (val->storage == REDIS_VM_LOADING);
3433
3434 /* Our value was swapped on disk. Bring it at home. */
3435 redisAssert(val->type == REDIS_VMPOINTER);
3436 val = vmLoadObject(val);
3437 dictGetEntryVal(de) = val;
3438
3439 /* Clients blocked by the VM subsystem may be waiting for
3440 * this key... */
3441 if (notify) handleClientsBlockedOnSwappedKey(db,key);
3442 }
3443 }
3444 return val;
3445 } else {
3446 return NULL;
3447 }
3448 }
3449
3450 static robj *lookupKeyRead(redisDb *db, robj *key) {
3451 expireIfNeeded(db,key);
3452 return lookupKey(db,key);
3453 }
3454
3455 static robj *lookupKeyWrite(redisDb *db, robj *key) {
3456 deleteIfVolatile(db,key);
3457 touchWatchedKey(db,key);
3458 return lookupKey(db,key);
3459 }
3460
3461 static robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
3462 robj *o = lookupKeyRead(c->db, key);
3463 if (!o) addReply(c,reply);
3464 return o;
3465 }
3466
3467 static robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
3468 robj *o = lookupKeyWrite(c->db, key);
3469 if (!o) addReply(c,reply);
3470 return o;
3471 }
3472
3473 /* Add the key to the DB. If the key already exists REDIS_ERR is returned,
3474 * otherwise REDIS_OK is returned, and the caller should increment the
3475 * refcount of 'val'. */
3476 static int dbAdd(redisDb *db, robj *key, robj *val) {
3477 /* Perform a lookup before adding the key, as we need to copy the
3478 * key value. */
3479 if (dictFind(db->dict, key->ptr) != NULL) {
3480 return REDIS_ERR;
3481 } else {
3482 sds copy = sdsdup(key->ptr);
3483 dictAdd(db->dict, copy, val);
3484 return REDIS_OK;
3485 }
3486 }
3487
3488 /* If the key does not exist, this is just like dbAdd(). Otherwise
3489 * the value associated to the key is replaced with the new one.
3490 *
3491 * On update (key already existed) 0 is returned. Otherwise 1. */
3492 static int dbReplace(redisDb *db, robj *key, robj *val) {
3493 if (dictFind(db->dict,key->ptr) == NULL) {
3494 sds copy = sdsdup(key->ptr);
3495 dictAdd(db->dict, copy, val);
3496 return 1;
3497 } else {
3498 dictReplace(db->dict, key->ptr, val);
3499 return 0;
3500 }
3501 }
3502
3503 static int dbExists(redisDb *db, robj *key) {
3504 return dictFind(db->dict,key->ptr) != NULL;
3505 }
3506
3507 /* Return a random key, in form of a Redis object.
3508 * If there are no keys, NULL is returned.
3509 *
3510 * The function makes sure to return keys not already expired. */
3511 static robj *dbRandomKey(redisDb *db) {
3512 struct dictEntry *de;
3513
3514 while(1) {
3515 sds key;
3516 robj *keyobj;
3517
3518 de = dictGetRandomKey(db->dict);
3519 if (de == NULL) return NULL;
3520
3521 key = dictGetEntryKey(de);
3522 keyobj = createStringObject(key,sdslen(key));
3523 if (dictFind(db->expires,key)) {
3524 if (expireIfNeeded(db,keyobj)) {
3525 decrRefCount(keyobj);
3526 continue; /* search for another key. This expired. */
3527 }
3528 }
3529 return keyobj;
3530 }
3531 }
3532
3533 /* Delete a key, value, and associated expiration entry if any, from the DB */
3534 static int dbDelete(redisDb *db, robj *key) {
3535 /* Deleting an entry from the expires dict will not free the sds of
3536 * the key, because it is shared with the main dictionary. */
3537 if (dictSize(db->expires) > 0) dictDelete(db->expires,key->ptr);
3538 return dictDelete(db->dict,key->ptr) == DICT_OK;
3539 }
3540
3541 /*============================ RDB saving/loading =========================== */
3542
3543 static int rdbSaveType(FILE *fp, unsigned char type) {
3544 if (fwrite(&type,1,1,fp) == 0) return -1;
3545 return 0;
3546 }
3547
3548 static int rdbSaveTime(FILE *fp, time_t t) {
3549 int32_t t32 = (int32_t) t;
3550 if (fwrite(&t32,4,1,fp) == 0) return -1;
3551 return 0;
3552 }
3553
3554 /* check rdbLoadLen() comments for more info */
3555 static int rdbSaveLen(FILE *fp, uint32_t len) {
3556 unsigned char buf[2];
3557
3558 if (len < (1<<6)) {
3559 /* Save a 6 bit len */
3560 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
3561 if (fwrite(buf,1,1,fp) == 0) return -1;
3562 } else if (len < (1<<14)) {
3563 /* Save a 14 bit len */
3564 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
3565 buf[1] = len&0xFF;
3566 if (fwrite(buf,2,1,fp) == 0) return -1;
3567 } else {
3568 /* Save a 32 bit len */
3569 buf[0] = (REDIS_RDB_32BITLEN<<6);
3570 if (fwrite(buf,1,1,fp) == 0) return -1;
3571 len = htonl(len);
3572 if (fwrite(&len,4,1,fp) == 0) return -1;
3573 }
3574 return 0;
3575 }
3576
3577 /* Encode 'value' as an integer if possible (if integer will fit the
3578 * supported range). If the function sucessful encoded the integer
3579 * then the (up to 5 bytes) encoded representation is written in the
3580 * string pointed by 'enc' and the length is returned. Otherwise
3581 * 0 is returned. */
3582 static int rdbEncodeInteger(long long value, unsigned char *enc) {
3583 /* Finally check if it fits in our ranges */
3584 if (value >= -(1<<7) && value <= (1<<7)-1) {
3585 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
3586 enc[1] = value&0xFF;
3587 return 2;
3588 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
3589 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
3590 enc[1] = value&0xFF;
3591 enc[2] = (value>>8)&0xFF;
3592 return 3;
3593 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
3594 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
3595 enc[1] = value&0xFF;
3596 enc[2] = (value>>8)&0xFF;
3597 enc[3] = (value>>16)&0xFF;
3598 enc[4] = (value>>24)&0xFF;
3599 return 5;
3600 } else {
3601 return 0;
3602 }
3603 }
3604
3605 /* String objects in the form "2391" "-100" without any space and with a
3606 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3607 * encoded as integers to save space */
3608 static int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
3609 long long value;
3610 char *endptr, buf[32];
3611
3612 /* Check if it's possible to encode this value as a number */
3613 value = strtoll(s, &endptr, 10);
3614 if (endptr[0] != '\0') return 0;
3615 ll2string(buf,32,value);
3616
3617 /* If the number converted back into a string is not identical
3618 * then it's not possible to encode the string as integer */
3619 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
3620
3621 return rdbEncodeInteger(value,enc);
3622 }
3623
3624 static int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
3625 size_t comprlen, outlen;
3626 unsigned char byte;
3627 void *out;
3628
3629 /* We require at least four bytes compression for this to be worth it */
3630 if (len <= 4) return 0;
3631 outlen = len-4;
3632 if ((out = zmalloc(outlen+1)) == NULL) return 0;
3633 comprlen = lzf_compress(s, len, out, outlen);
3634 if (comprlen == 0) {
3635 zfree(out);
3636 return 0;
3637 }
3638 /* Data compressed! Let's save it on disk */
3639 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
3640 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
3641 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
3642 if (rdbSaveLen(fp,len) == -1) goto writeerr;
3643 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
3644 zfree(out);
3645 return comprlen;
3646
3647 writeerr:
3648 zfree(out);
3649 return -1;
3650 }
3651
3652 /* Save a string objet as [len][data] on disk. If the object is a string
3653 * representation of an integer value we try to safe it in a special form */
3654 static int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
3655 int enclen;
3656
3657 /* Try integer encoding */
3658 if (len <= 11) {
3659 unsigned char buf[5];
3660 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
3661 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3662 return 0;
3663 }
3664 }
3665
3666 /* Try LZF compression - under 20 bytes it's unable to compress even
3667 * aaaaaaaaaaaaaaaaaa so skip it */
3668 if (server.rdbcompression && len > 20) {
3669 int retval;
3670
3671 retval = rdbSaveLzfStringObject(fp,s,len);
3672 if (retval == -1) return -1;
3673 if (retval > 0) return 0;
3674 /* retval == 0 means data can't be compressed, save the old way */
3675 }
3676
3677 /* Store verbatim */
3678 if (rdbSaveLen(fp,len) == -1) return -1;
3679 if (len && fwrite(s,len,1,fp) == 0) return -1;
3680 return 0;
3681 }
3682
3683 /* Save a long long value as either an encoded string or a string. */
3684 static int rdbSaveLongLongAsStringObject(FILE *fp, long long value) {
3685 unsigned char buf[32];
3686 int enclen = rdbEncodeInteger(value,buf);
3687 if (enclen > 0) {
3688 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3689 } else {
3690 /* Encode as string */
3691 enclen = ll2string((char*)buf,32,value);
3692 redisAssert(enclen < 32);
3693 if (rdbSaveLen(fp,enclen) == -1) return -1;
3694 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3695 }
3696 return 0;
3697 }
3698
3699 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3700 static int rdbSaveStringObject(FILE *fp, robj *obj) {
3701 /* Avoid to decode the object, then encode it again, if the
3702 * object is alrady integer encoded. */
3703 if (obj->encoding == REDIS_ENCODING_INT) {
3704 return rdbSaveLongLongAsStringObject(fp,(long)obj->ptr);
3705 } else {
3706 redisAssert(obj->encoding == REDIS_ENCODING_RAW);
3707 return rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
3708 }
3709 }
3710
3711 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3712 * 8 bit integer specifing the length of the representation.
3713 * This 8 bit integer has special values in order to specify the following
3714 * conditions:
3715 * 253: not a number
3716 * 254: + inf
3717 * 255: - inf
3718 */
3719 static int rdbSaveDoubleValue(FILE *fp, double val) {
3720 unsigned char buf[128];
3721 int len;
3722
3723 if (isnan(val)) {
3724 buf[0] = 253;
3725 len = 1;
3726 } else if (!isfinite(val)) {
3727 len = 1;
3728 buf[0] = (val < 0) ? 255 : 254;
3729 } else {
3730 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
3731 /* Check if the float is in a safe range to be casted into a
3732 * long long. We are assuming that long long is 64 bit here.
3733 * Also we are assuming that there are no implementations around where
3734 * double has precision < 52 bit.
3735 *
3736 * Under this assumptions we test if a double is inside an interval
3737 * where casting to long long is safe. Then using two castings we
3738 * make sure the decimal part is zero. If all this is true we use
3739 * integer printing function that is much faster. */
3740 double min = -4503599627370495; /* (2^52)-1 */
3741 double max = 4503599627370496; /* -(2^52) */
3742 if (val > min && val < max && val == ((double)((long long)val)))
3743 ll2string((char*)buf+1,sizeof(buf),(long long)val);
3744 else
3745 #endif
3746 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
3747 buf[0] = strlen((char*)buf+1);
3748 len = buf[0]+1;
3749 }
3750 if (fwrite(buf,len,1,fp) == 0) return -1;
3751 return 0;
3752 }
3753
3754 /* Save a Redis object. */
3755 static int rdbSaveObject(FILE *fp, robj *o) {
3756 if (o->type == REDIS_STRING) {
3757 /* Save a string value */
3758 if (rdbSaveStringObject(fp,o) == -1) return -1;
3759 } else if (o->type == REDIS_LIST) {
3760 /* Save a list value */
3761 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
3762 unsigned char *p;
3763 unsigned char *vstr;
3764 unsigned int vlen;
3765 long long vlong;
3766
3767 if (rdbSaveLen(fp,ziplistLen(o->ptr)) == -1) return -1;
3768 p = ziplistIndex(o->ptr,0);
3769 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
3770 if (vstr) {
3771 if (rdbSaveRawString(fp,vstr,vlen) == -1)
3772 return -1;
3773 } else {
3774 if (rdbSaveLongLongAsStringObject(fp,vlong) == -1)
3775 return -1;
3776 }
3777 p = ziplistNext(o->ptr,p);
3778 }
3779 } else if (o->encoding == REDIS_ENCODING_LIST) {
3780 list *list = o->ptr;
3781 listIter li;
3782 listNode *ln;
3783
3784 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
3785 listRewind(list,&li);
3786 while((ln = listNext(&li))) {
3787 robj *eleobj = listNodeValue(ln);
3788 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3789 }
3790 } else {
3791 redisPanic("Unknown list encoding");
3792 }
3793 } else if (o->type == REDIS_SET) {
3794 /* Save a set value */
3795 dict *set = o->ptr;
3796 dictIterator *di = dictGetIterator(set);
3797 dictEntry *de;
3798
3799 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
3800 while((de = dictNext(di)) != NULL) {
3801 robj *eleobj = dictGetEntryKey(de);
3802
3803 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3804 }
3805 dictReleaseIterator(di);
3806 } else if (o->type == REDIS_ZSET) {
3807 /* Save a set value */
3808 zset *zs = o->ptr;
3809 dictIterator *di = dictGetIterator(zs->dict);
3810 dictEntry *de;
3811
3812 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
3813 while((de = dictNext(di)) != NULL) {
3814 robj *eleobj = dictGetEntryKey(de);
3815 double *score = dictGetEntryVal(de);
3816
3817 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3818 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
3819 }
3820 dictReleaseIterator(di);
3821 } else if (o->type == REDIS_HASH) {
3822 /* Save a hash value */
3823 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3824 unsigned char *p = zipmapRewind(o->ptr);
3825 unsigned int count = zipmapLen(o->ptr);
3826 unsigned char *key, *val;
3827 unsigned int klen, vlen;
3828
3829 if (rdbSaveLen(fp,count) == -1) return -1;
3830 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
3831 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
3832 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
3833 }
3834 } else {
3835 dictIterator *di = dictGetIterator(o->ptr);
3836 dictEntry *de;
3837
3838 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
3839 while((de = dictNext(di)) != NULL) {
3840 robj *key = dictGetEntryKey(de);
3841 robj *val = dictGetEntryVal(de);
3842
3843 if (rdbSaveStringObject(fp,key) == -1) return -1;
3844 if (rdbSaveStringObject(fp,val) == -1) return -1;
3845 }
3846 dictReleaseIterator(di);
3847 }
3848 } else {
3849 redisPanic("Unknown object type");
3850 }
3851 return 0;
3852 }
3853
3854 /* Return the length the object will have on disk if saved with
3855 * the rdbSaveObject() function. Currently we use a trick to get
3856 * this length with very little changes to the code. In the future
3857 * we could switch to a faster solution. */
3858 static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
3859 if (fp == NULL) fp = server.devnull;
3860 rewind(fp);
3861 assert(rdbSaveObject(fp,o) != 1);
3862 return ftello(fp);
3863 }
3864
3865 /* Return the number of pages required to save this object in the swap file */
3866 static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
3867 off_t bytes = rdbSavedObjectLen(o,fp);
3868
3869 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
3870 }
3871
3872 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3873 static int rdbSave(char *filename) {
3874 dictIterator *di = NULL;
3875 dictEntry *de;
3876 FILE *fp;
3877 char tmpfile[256];
3878 int j;
3879 time_t now = time(NULL);
3880
3881 /* Wait for I/O therads to terminate, just in case this is a
3882 * foreground-saving, to avoid seeking the swap file descriptor at the
3883 * same time. */
3884 if (server.vm_enabled)
3885 waitEmptyIOJobsQueue();
3886
3887 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
3888 fp = fopen(tmpfile,"w");
3889 if (!fp) {
3890 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
3891 return REDIS_ERR;
3892 }
3893 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
3894 for (j = 0; j < server.dbnum; j++) {
3895 redisDb *db = server.db+j;
3896 dict *d = db->dict;
3897 if (dictSize(d) == 0) continue;
3898 di = dictGetIterator(d);
3899 if (!di) {
3900 fclose(fp);
3901 return REDIS_ERR;
3902 }
3903
3904 /* Write the SELECT DB opcode */
3905 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
3906 if (rdbSaveLen(fp,j) == -1) goto werr;
3907
3908 /* Iterate this DB writing every entry */
3909 while((de = dictNext(di)) != NULL) {
3910 sds keystr = dictGetEntryKey(de);
3911 robj key, *o = dictGetEntryVal(de);
3912 time_t expiretime;
3913
3914 initStaticStringObject(key,keystr);
3915 expiretime = getExpire(db,&key);
3916
3917 /* Save the expire time */
3918 if (expiretime != -1) {
3919 /* If this key is already expired skip it */
3920 if (expiretime < now) continue;
3921 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
3922 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
3923 }
3924 /* Save the key and associated value. This requires special
3925 * handling if the value is swapped out. */
3926 if (!server.vm_enabled || o->storage == REDIS_VM_MEMORY ||
3927 o->storage == REDIS_VM_SWAPPING) {
3928 /* Save type, key, value */
3929 if (rdbSaveType(fp,o->type) == -1) goto werr;
3930 if (rdbSaveStringObject(fp,&key) == -1) goto werr;
3931 if (rdbSaveObject(fp,o) == -1) goto werr;
3932 } else {
3933 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3934 robj *po;
3935 /* Get a preview of the object in memory */
3936 po = vmPreviewObject(o);
3937 /* Save type, key, value */
3938 if (rdbSaveType(fp,po->type) == -1) goto werr;
3939 if (rdbSaveStringObject(fp,&key) == -1) goto werr;
3940 if (rdbSaveObject(fp,po) == -1) goto werr;
3941 /* Remove the loaded object from memory */
3942 decrRefCount(po);
3943 }
3944 }
3945 dictReleaseIterator(di);
3946 }
3947 /* EOF opcode */
3948 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
3949
3950 /* Make sure data will not remain on the OS's output buffers */
3951 fflush(fp);
3952 fsync(fileno(fp));
3953 fclose(fp);
3954
3955 /* Use RENAME to make sure the DB file is changed atomically only
3956 * if the generate DB file is ok. */
3957 if (rename(tmpfile,filename) == -1) {
3958 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
3959 unlink(tmpfile);
3960 return REDIS_ERR;
3961 }
3962 redisLog(REDIS_NOTICE,"DB saved on disk");
3963 server.dirty = 0;
3964 server.lastsave = time(NULL);
3965 return REDIS_OK;
3966
3967 werr:
3968 fclose(fp);
3969 unlink(tmpfile);
3970 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
3971 if (di) dictReleaseIterator(di);
3972 return REDIS_ERR;
3973 }
3974
3975 static int rdbSaveBackground(char *filename) {
3976 pid_t childpid;
3977
3978 if (server.bgsavechildpid != -1) return REDIS_ERR;
3979 if (server.vm_enabled) waitEmptyIOJobsQueue();
3980 if ((childpid = fork()) == 0) {
3981 /* Child */
3982 if (server.vm_enabled) vmReopenSwapFile();
3983 close(server.fd);
3984 if (rdbSave(filename) == REDIS_OK) {
3985 _exit(0);
3986 } else {
3987 _exit(1);
3988 }
3989 } else {
3990 /* Parent */
3991 if (childpid == -1) {
3992 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
3993 strerror(errno));
3994 return REDIS_ERR;
3995 }
3996 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
3997 server.bgsavechildpid = childpid;
3998 updateDictResizePolicy();
3999 return REDIS_OK;
4000 }
4001 return REDIS_OK; /* unreached */
4002 }
4003
4004 static void rdbRemoveTempFile(pid_t childpid) {
4005 char tmpfile[256];
4006
4007 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
4008 unlink(tmpfile);
4009 }
4010
4011 static int rdbLoadType(FILE *fp) {
4012 unsigned char type;
4013 if (fread(&type,1,1,fp) == 0) return -1;
4014 return type;
4015 }
4016
4017 static time_t rdbLoadTime(FILE *fp) {
4018 int32_t t32;
4019 if (fread(&t32,4,1,fp) == 0) return -1;
4020 return (time_t) t32;
4021 }
4022
4023 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
4024 * of this file for a description of how this are stored on disk.
4025 *
4026 * isencoded is set to 1 if the readed length is not actually a length but
4027 * an "encoding type", check the above comments for more info */
4028 static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
4029 unsigned char buf[2];
4030 uint32_t len;
4031 int type;
4032
4033 if (isencoded) *isencoded = 0;
4034 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
4035 type = (buf[0]&0xC0)>>6;
4036 if (type == REDIS_RDB_6BITLEN) {
4037 /* Read a 6 bit len */
4038 return buf[0]&0x3F;
4039 } else if (type == REDIS_RDB_ENCVAL) {
4040 /* Read a 6 bit len encoding type */
4041 if (isencoded) *isencoded = 1;
4042 return buf[0]&0x3F;
4043 } else if (type == REDIS_RDB_14BITLEN) {
4044 /* Read a 14 bit len */
4045 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
4046 return ((buf[0]&0x3F)<<8)|buf[1];
4047 } else {
4048 /* Read a 32 bit len */
4049 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
4050 return ntohl(len);
4051 }
4052 }
4053
4054 /* Load an integer-encoded object from file 'fp', with the specified
4055 * encoding type 'enctype'. If encode is true the function may return
4056 * an integer-encoded object as reply, otherwise the returned object
4057 * will always be encoded as a raw string. */
4058 static robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
4059 unsigned char enc[4];
4060 long long val;
4061
4062 if (enctype == REDIS_RDB_ENC_INT8) {
4063 if (fread(enc,1,1,fp) == 0) return NULL;
4064 val = (signed char)enc[0];
4065 } else if (enctype == REDIS_RDB_ENC_INT16) {
4066 uint16_t v;
4067 if (fread(enc,2,1,fp) == 0) return NULL;
4068 v = enc[0]|(enc[1]<<8);
4069 val = (int16_t)v;
4070 } else if (enctype == REDIS_RDB_ENC_INT32) {
4071 uint32_t v;
4072 if (fread(enc,4,1,fp) == 0) return NULL;
4073 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
4074 val = (int32_t)v;
4075 } else {
4076 val = 0; /* anti-warning */
4077 redisPanic("Unknown RDB integer encoding type");
4078 }
4079 if (encode)
4080 return createStringObjectFromLongLong(val);
4081 else
4082 return createObject(REDIS_STRING,sdsfromlonglong(val));
4083 }
4084
4085 static robj *rdbLoadLzfStringObject(FILE*fp) {
4086 unsigned int len, clen;
4087 unsigned char *c = NULL;
4088 sds val = NULL;
4089
4090 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4091 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4092 if ((c = zmalloc(clen)) == NULL) goto err;
4093 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
4094 if (fread(c,clen,1,fp) == 0) goto err;
4095 if (lzf_decompress(c,clen,val,len) == 0) goto err;
4096 zfree(c);
4097 return createObject(REDIS_STRING,val);
4098 err:
4099 zfree(c);
4100 sdsfree(val);
4101 return NULL;
4102 }
4103
4104 static robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
4105 int isencoded;
4106 uint32_t len;
4107 sds val;
4108
4109 len = rdbLoadLen(fp,&isencoded);
4110 if (isencoded) {
4111 switch(len) {
4112 case REDIS_RDB_ENC_INT8:
4113 case REDIS_RDB_ENC_INT16:
4114 case REDIS_RDB_ENC_INT32:
4115 return rdbLoadIntegerObject(fp,len,encode);
4116 case REDIS_RDB_ENC_LZF:
4117 return rdbLoadLzfStringObject(fp);
4118 default:
4119 redisPanic("Unknown RDB encoding type");
4120 }
4121 }
4122
4123 if (len == REDIS_RDB_LENERR) return NULL;
4124 val = sdsnewlen(NULL,len);
4125 if (len && fread(val,len,1,fp) == 0) {
4126 sdsfree(val);
4127 return NULL;
4128 }
4129 return createObject(REDIS_STRING,val);
4130 }
4131
4132 static robj *rdbLoadStringObject(FILE *fp) {
4133 return rdbGenericLoadStringObject(fp,0);
4134 }
4135
4136 static robj *rdbLoadEncodedStringObject(FILE *fp) {
4137 return rdbGenericLoadStringObject(fp,1);
4138 }
4139
4140 /* For information about double serialization check rdbSaveDoubleValue() */
4141 static int rdbLoadDoubleValue(FILE *fp, double *val) {
4142 char buf[128];
4143 unsigned char len;
4144
4145 if (fread(&len,1,1,fp) == 0) return -1;
4146 switch(len) {
4147 case 255: *val = R_NegInf; return 0;
4148 case 254: *val = R_PosInf; return 0;
4149 case 253: *val = R_Nan; return 0;
4150 default:
4151 if (fread(buf,len,1,fp) == 0) return -1;
4152 buf[len] = '\0';
4153 sscanf(buf, "%lg", val);
4154 return 0;
4155 }
4156 }
4157
4158 /* Load a Redis object of the specified type from the specified file.
4159 * On success a newly allocated object is returned, otherwise NULL. */
4160 static robj *rdbLoadObject(int type, FILE *fp) {
4161 robj *o, *ele, *dec;
4162 size_t len;
4163
4164 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
4165 if (type == REDIS_STRING) {
4166 /* Read string value */
4167 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4168 o = tryObjectEncoding(o);
4169 } else if (type == REDIS_LIST) {
4170 /* Read list value */
4171 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4172
4173 /* Use a real list when there are too many entries */
4174 if (len > server.list_max_ziplist_entries) {
4175 o = createListObject();
4176 } else {
4177 o = createZiplistObject();
4178 }
4179
4180 /* Load every single element of the list */
4181 while(len--) {
4182 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4183
4184 /* If we are using a ziplist and the value is too big, convert
4185 * the object to a real list. */
4186 if (o->encoding == REDIS_ENCODING_ZIPLIST &&
4187 ele->encoding == REDIS_ENCODING_RAW &&
4188 sdslen(ele->ptr) > server.list_max_ziplist_value)
4189 listTypeConvert(o,REDIS_ENCODING_LIST);
4190
4191 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
4192 dec = getDecodedObject(ele);
4193 o->ptr = ziplistPush(o->ptr,dec->ptr,sdslen(dec->ptr),REDIS_TAIL);
4194 decrRefCount(dec);
4195 decrRefCount(ele);
4196 } else {
4197 ele = tryObjectEncoding(ele);
4198 listAddNodeTail(o->ptr,ele);
4199 }
4200 }
4201 } else if (type == REDIS_SET) {
4202 /* Read list/set value */
4203 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4204 o = createSetObject();
4205 /* It's faster to expand the dict to the right size asap in order
4206 * to avoid rehashing */
4207 if (len > DICT_HT_INITIAL_SIZE)
4208 dictExpand(o->ptr,len);
4209 /* Load every single element of the list/set */
4210 while(len--) {
4211 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4212 ele = tryObjectEncoding(ele);
4213 dictAdd((dict*)o->ptr,ele,NULL);
4214 }
4215 } else if (type == REDIS_ZSET) {
4216 /* Read list/set value */
4217 size_t zsetlen;
4218 zset *zs;
4219
4220 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4221 o = createZsetObject();
4222 zs = o->ptr;
4223 /* Load every single element of the list/set */
4224 while(zsetlen--) {
4225 robj *ele;
4226 double *score = zmalloc(sizeof(double));
4227
4228 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4229 ele = tryObjectEncoding(ele);
4230 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
4231 dictAdd(zs->dict,ele,score);
4232 zslInsert(zs->zsl,*score,ele);
4233 incrRefCount(ele); /* added to skiplist */
4234 }
4235 } else if (type == REDIS_HASH) {
4236 size_t hashlen;
4237
4238 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4239 o = createHashObject();
4240 /* Too many entries? Use an hash table. */
4241 if (hashlen > server.hash_max_zipmap_entries)
4242 convertToRealHash(o);
4243 /* Load every key/value, then set it into the zipmap or hash
4244 * table, as needed. */
4245 while(hashlen--) {
4246 robj *key, *val;
4247
4248 if ((key = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4249 if ((val = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4250 /* If we are using a zipmap and there are too big values
4251 * the object is converted to real hash table encoding. */
4252 if (o->encoding != REDIS_ENCODING_HT &&
4253 ((key->encoding == REDIS_ENCODING_RAW &&
4254 sdslen(key->ptr) > server.hash_max_zipmap_value) ||
4255 (val->encoding == REDIS_ENCODING_RAW &&
4256 sdslen(val->ptr) > server.hash_max_zipmap_value)))
4257 {
4258 convertToRealHash(o);
4259 }
4260
4261 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
4262 unsigned char *zm = o->ptr;
4263 robj *deckey, *decval;
4264
4265 /* We need raw string objects to add them to the zipmap */
4266 deckey = getDecodedObject(key);
4267 decval = getDecodedObject(val);
4268 zm = zipmapSet(zm,deckey->ptr,sdslen(deckey->ptr),
4269 decval->ptr,sdslen(decval->ptr),NULL);
4270 o->ptr = zm;
4271 decrRefCount(deckey);
4272 decrRefCount(decval);
4273 decrRefCount(key);
4274 decrRefCount(val);
4275 } else {
4276 key = tryObjectEncoding(key);
4277 val = tryObjectEncoding(val);
4278 dictAdd((dict*)o->ptr,key,val);
4279 }
4280 }
4281 } else {
4282 redisPanic("Unknown object type");
4283 }
4284 return o;
4285 }
4286
4287 static int rdbLoad(char *filename) {
4288 FILE *fp;
4289 uint32_t dbid;
4290 int type, retval, rdbver;
4291 int swap_all_values = 0;
4292 redisDb *db = server.db+0;
4293 char buf[1024];
4294 time_t expiretime, now = time(NULL);
4295
4296 fp = fopen(filename,"r");
4297 if (!fp) return REDIS_ERR;
4298 if (fread(buf,9,1,fp) == 0) goto eoferr;
4299 buf[9] = '\0';
4300 if (memcmp(buf,"REDIS",5) != 0) {
4301 fclose(fp);
4302 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
4303 return REDIS_ERR;
4304 }
4305 rdbver = atoi(buf+5);
4306 if (rdbver != 1) {
4307 fclose(fp);
4308 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
4309 return REDIS_ERR;
4310 }
4311 while(1) {
4312 robj *key, *val;
4313 int force_swapout;
4314
4315 expiretime = -1;
4316 /* Read type. */
4317 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4318 if (type == REDIS_EXPIRETIME) {
4319 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
4320 /* We read the time so we need to read the object type again */
4321 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4322 }
4323 if (type == REDIS_EOF) break;
4324 /* Handle SELECT DB opcode as a special case */
4325 if (type == REDIS_SELECTDB) {
4326 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
4327 goto eoferr;
4328 if (dbid >= (unsigned)server.dbnum) {
4329 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
4330 exit(1);
4331 }
4332 db = server.db+dbid;
4333 continue;
4334 }
4335 /* Read key */
4336 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
4337 /* Read value */
4338 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
4339 /* Check if the key already expired */
4340 if (expiretime != -1 && expiretime < now) {
4341 decrRefCount(key);
4342 decrRefCount(val);
4343 continue;
4344 }
4345 /* Add the new object in the hash table */
4346 retval = dbAdd(db,key,val);
4347 if (retval == REDIS_ERR) {
4348 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
4349 exit(1);
4350 }
4351 /* Set the expire time if needed */
4352 if (expiretime != -1) setExpire(db,key,expiretime);
4353
4354 /* Handle swapping while loading big datasets when VM is on */
4355
4356 /* If we detecter we are hopeless about fitting something in memory
4357 * we just swap every new key on disk. Directly...
4358 * Note that's important to check for this condition before resorting
4359 * to random sampling, otherwise we may try to swap already
4360 * swapped keys. */
4361 if (swap_all_values) {
4362 dictEntry *de = dictFind(db->dict,key->ptr);
4363
4364 /* de may be NULL since the key already expired */
4365 if (de) {
4366 vmpointer *vp;
4367 val = dictGetEntryVal(de);
4368
4369 if (val->refcount == 1 &&
4370 (vp = vmSwapObjectBlocking(val)) != NULL)
4371 dictGetEntryVal(de) = vp;
4372 }
4373 decrRefCount(key);
4374 continue;
4375 }
4376 decrRefCount(key);
4377
4378 /* Flush data on disk once 32 MB of additional RAM are used... */
4379 force_swapout = 0;
4380 if ((zmalloc_used_memory() - server.vm_max_memory) > 1024*1024*32)
4381 force_swapout = 1;
4382
4383 /* If we have still some hope of having some value fitting memory
4384 * then we try random sampling. */
4385 if (!swap_all_values && server.vm_enabled && force_swapout) {
4386 while (zmalloc_used_memory() > server.vm_max_memory) {
4387 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
4388 }
4389 if (zmalloc_used_memory() > server.vm_max_memory)
4390 swap_all_values = 1; /* We are already using too much mem */
4391 }
4392 }
4393 fclose(fp);
4394 return REDIS_OK;
4395
4396 eoferr: /* unexpected end of file is handled here with a fatal exit */
4397 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
4398 exit(1);
4399 return REDIS_ERR; /* Just to avoid warning */
4400 }
4401
4402 /*================================== Shutdown =============================== */
4403 static int prepareForShutdown() {
4404 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
4405 /* Kill the saving child if there is a background saving in progress.
4406 We want to avoid race conditions, for instance our saving child may
4407 overwrite the synchronous saving did by SHUTDOWN. */
4408 if (server.bgsavechildpid != -1) {
4409 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
4410 kill(server.bgsavechildpid,SIGKILL);
4411 rdbRemoveTempFile(server.bgsavechildpid);
4412 }
4413 if (server.appendonly) {
4414 /* Append only file: fsync() the AOF and exit */
4415 aof_fsync(server.appendfd);
4416 if (server.vm_enabled) unlink(server.vm_swap_file);
4417 } else {
4418 /* Snapshotting. Perform a SYNC SAVE and exit */
4419 if (rdbSave(server.dbfilename) == REDIS_OK) {
4420 if (server.daemonize)
4421 unlink(server.pidfile);
4422 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
4423 } else {
4424 /* Ooops.. error saving! The best we can do is to continue
4425 * operating. Note that if there was a background saving process,
4426 * in the next cron() Redis will be notified that the background
4427 * saving aborted, handling special stuff like slaves pending for
4428 * synchronization... */
4429 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
4430 return REDIS_ERR;
4431 }
4432 }
4433 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
4434 return REDIS_OK;
4435 }
4436
4437 /*================================== Commands =============================== */
4438
4439 static void authCommand(redisClient *c) {
4440 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
4441 c->authenticated = 1;
4442 addReply(c,shared.ok);
4443 } else {
4444 c->authenticated = 0;
4445 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
4446 }
4447 }
4448
4449 static void pingCommand(redisClient *c) {
4450 addReply(c,shared.pong);
4451 }
4452
4453 static void echoCommand(redisClient *c) {
4454 addReplyBulk(c,c->argv[1]);
4455 }
4456
4457 /*=================================== Strings =============================== */
4458
4459 static void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
4460 int retval;
4461 long seconds = 0; /* initialized to avoid an harmness warning */
4462
4463 if (expire) {
4464 if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
4465 return;
4466 if (seconds <= 0) {
4467 addReplySds(c,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4468 return;
4469 }
4470 }
4471
4472 touchWatchedKey(c->db,key);
4473 if (nx) deleteIfVolatile(c->db,key);
4474 retval = dbAdd(c->db,key,val);
4475 if (retval == REDIS_ERR) {
4476 if (!nx) {
4477 dbReplace(c->db,key,val);
4478 incrRefCount(val);
4479 } else {
4480 addReply(c,shared.czero);
4481 return;
4482 }
4483 } else {
4484 incrRefCount(val);
4485 }
4486 server.dirty++;
4487 removeExpire(c->db,key);
4488 if (expire) setExpire(c->db,key,time(NULL)+seconds);
4489 addReply(c, nx ? shared.cone : shared.ok);
4490 }
4491
4492 static void setCommand(redisClient *c) {
4493 setGenericCommand(c,0,c->argv[1],c->argv[2],NULL);
4494 }
4495
4496 static void setnxCommand(redisClient *c) {
4497 setGenericCommand(c,1,c->argv[1],c->argv[2],NULL);
4498 }
4499
4500 static void setexCommand(redisClient *c) {
4501 setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
4502 }
4503
4504 static int getGenericCommand(redisClient *c) {
4505 robj *o;
4506
4507 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
4508 return REDIS_OK;
4509
4510 if (o->type != REDIS_STRING) {
4511 addReply(c,shared.wrongtypeerr);
4512 return REDIS_ERR;
4513 } else {
4514 addReplyBulk(c,o);
4515 return REDIS_OK;
4516 }
4517 }
4518
4519 static void getCommand(redisClient *c) {
4520 getGenericCommand(c);
4521 }
4522
4523 static void getsetCommand(redisClient *c) {
4524 if (getGenericCommand(c) == REDIS_ERR) return;
4525 dbReplace(c->db,c->argv[1],c->argv[2]);
4526 incrRefCount(c->argv[2]);
4527 server.dirty++;
4528 removeExpire(c->db,c->argv[1]);
4529 }
4530
4531 static void mgetCommand(redisClient *c) {
4532 int j;
4533
4534 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
4535 for (j = 1; j < c->argc; j++) {
4536 robj *o = lookupKeyRead(c->db,c->argv[j]);
4537 if (o == NULL) {
4538 addReply(c,shared.nullbulk);
4539 } else {
4540 if (o->type != REDIS_STRING) {
4541 addReply(c,shared.nullbulk);
4542 } else {
4543 addReplyBulk(c,o);
4544 }
4545 }
4546 }
4547 }
4548
4549 static void msetGenericCommand(redisClient *c, int nx) {
4550 int j, busykeys = 0;
4551
4552 if ((c->argc % 2) == 0) {
4553 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
4554 return;
4555 }
4556 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4557 * set nothing at all if at least one already key exists. */
4558 if (nx) {
4559 for (j = 1; j < c->argc; j += 2) {
4560 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
4561 busykeys++;
4562 }
4563 }
4564 }
4565 if (busykeys) {
4566 addReply(c, shared.czero);
4567 return;
4568 }
4569
4570 for (j = 1; j < c->argc; j += 2) {
4571 c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
4572 dbReplace(c->db,c->argv[j],c->argv[j+1]);
4573 incrRefCount(c->argv[j+1]);
4574 removeExpire(c->db,c->argv[j]);
4575 }
4576 server.dirty += (c->argc-1)/2;
4577 addReply(c, nx ? shared.cone : shared.ok);
4578 }
4579
4580 static void msetCommand(redisClient *c) {
4581 msetGenericCommand(c,0);
4582 }
4583
4584 static void msetnxCommand(redisClient *c) {
4585 msetGenericCommand(c,1);
4586 }
4587
4588 static void incrDecrCommand(redisClient *c, long long incr) {
4589 long long value;
4590 robj *o;
4591
4592 o = lookupKeyWrite(c->db,c->argv[1]);
4593 if (o != NULL && checkType(c,o,REDIS_STRING)) return;
4594 if (getLongLongFromObjectOrReply(c,o,&value,NULL) != REDIS_OK) return;
4595
4596 value += incr;
4597 o = createStringObjectFromLongLong(value);
4598 dbReplace(c->db,c->argv[1],o);
4599 server.dirty++;
4600 addReply(c,shared.colon);
4601 addReply(c,o);
4602 addReply(c,shared.crlf);
4603 }
4604
4605 static void incrCommand(redisClient *c) {
4606 incrDecrCommand(c,1);
4607 }
4608
4609 static void decrCommand(redisClient *c) {
4610 incrDecrCommand(c,-1);
4611 }
4612
4613 static void incrbyCommand(redisClient *c) {
4614 long long incr;
4615
4616 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
4617 incrDecrCommand(c,incr);
4618 }
4619
4620 static void decrbyCommand(redisClient *c) {
4621 long long incr;
4622
4623 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
4624 incrDecrCommand(c,-incr);
4625 }
4626
4627 static void appendCommand(redisClient *c) {
4628 int retval;
4629 size_t totlen;
4630 robj *o;
4631
4632 o = lookupKeyWrite(c->db,c->argv[1]);
4633 if (o == NULL) {
4634 /* Create the key */
4635 retval = dbAdd(c->db,c->argv[1],c->argv[2]);
4636 incrRefCount(c->argv[2]);
4637 totlen = stringObjectLen(c->argv[2]);
4638 } else {
4639 if (o->type != REDIS_STRING) {
4640 addReply(c,shared.wrongtypeerr);
4641 return;
4642 }
4643 /* If the object is specially encoded or shared we have to make
4644 * a copy */
4645 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
4646 robj *decoded = getDecodedObject(o);
4647
4648 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
4649 decrRefCount(decoded);
4650 dbReplace(c->db,c->argv[1],o);
4651 }
4652 /* APPEND! */
4653 if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
4654 o->ptr = sdscatlen(o->ptr,
4655 c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
4656 } else {
4657 o->ptr = sdscatprintf(o->ptr, "%ld",
4658 (unsigned long) c->argv[2]->ptr);
4659 }
4660 totlen = sdslen(o->ptr);
4661 }
4662 server.dirty++;
4663 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
4664 }
4665
4666 static void substrCommand(redisClient *c) {
4667 robj *o;
4668 long start = atoi(c->argv[2]->ptr);
4669 long end = atoi(c->argv[3]->ptr);
4670 size_t rangelen, strlen;
4671 sds range;
4672
4673 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4674 checkType(c,o,REDIS_STRING)) return;
4675
4676 o = getDecodedObject(o);
4677 strlen = sdslen(o->ptr);
4678
4679 /* convert negative indexes */
4680 if (start < 0) start = strlen+start;
4681 if (end < 0) end = strlen+end;
4682 if (start < 0) start = 0;
4683 if (end < 0) end = 0;
4684
4685 /* indexes sanity checks */
4686 if (start > end || (size_t)start >= strlen) {
4687 /* Out of range start or start > end result in null reply */
4688 addReply(c,shared.nullbulk);
4689 decrRefCount(o);
4690 return;
4691 }
4692 if ((size_t)end >= strlen) end = strlen-1;
4693 rangelen = (end-start)+1;
4694
4695 /* Return the result */
4696 addReplySds(c,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen));
4697 range = sdsnewlen((char*)o->ptr+start,rangelen);
4698 addReplySds(c,range);
4699 addReply(c,shared.crlf);
4700 decrRefCount(o);
4701 }
4702
4703 /* ========================= Type agnostic commands ========================= */
4704
4705 static void delCommand(redisClient *c) {
4706 int deleted = 0, j;
4707
4708 for (j = 1; j < c->argc; j++) {
4709 if (dbDelete(c->db,c->argv[j])) {
4710 touchWatchedKey(c->db,c->argv[j]);
4711 server.dirty++;
4712 deleted++;
4713 }
4714 }
4715 addReplyLongLong(c,deleted);
4716 }
4717
4718 static void existsCommand(redisClient *c) {
4719 expireIfNeeded(c->db,c->argv[1]);
4720 if (dbExists(c->db,c->argv[1])) {
4721 addReply(c, shared.cone);
4722 } else {
4723 addReply(c, shared.czero);
4724 }
4725 }
4726
4727 static void selectCommand(redisClient *c) {
4728 int id = atoi(c->argv[1]->ptr);
4729
4730 if (selectDb(c,id) == REDIS_ERR) {
4731 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
4732 } else {
4733 addReply(c,shared.ok);
4734 }
4735 }
4736
4737 static void randomkeyCommand(redisClient *c) {
4738 robj *key;
4739
4740 if ((key = dbRandomKey(c->db)) == NULL) {
4741 addReply(c,shared.nullbulk);
4742 return;
4743 }
4744
4745 addReplyBulk(c,key);
4746 decrRefCount(key);
4747 }
4748
4749 static void keysCommand(redisClient *c) {
4750 dictIterator *di;
4751 dictEntry *de;
4752 sds pattern = c->argv[1]->ptr;
4753 int plen = sdslen(pattern);
4754 unsigned long numkeys = 0;
4755 robj *lenobj = createObject(REDIS_STRING,NULL);
4756
4757 di = dictGetIterator(c->db->dict);
4758 addReply(c,lenobj);
4759 decrRefCount(lenobj);
4760 while((de = dictNext(di)) != NULL) {
4761 sds key = dictGetEntryKey(de);
4762 robj *keyobj;
4763
4764 if ((pattern[0] == '*' && pattern[1] == '\0') ||
4765 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
4766 keyobj = createStringObject(key,sdslen(key));
4767 if (expireIfNeeded(c->db,keyobj) == 0) {
4768 addReplyBulk(c,keyobj);
4769 numkeys++;
4770 }
4771 decrRefCount(keyobj);
4772 }
4773 }
4774 dictReleaseIterator(di);
4775 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
4776 }
4777
4778 static void dbsizeCommand(redisClient *c) {
4779 addReplySds(c,
4780 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
4781 }
4782
4783 static void lastsaveCommand(redisClient *c) {
4784 addReplySds(c,
4785 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
4786 }
4787
4788 static void typeCommand(redisClient *c) {
4789 robj *o;
4790 char *type;
4791
4792 o = lookupKeyRead(c->db,c->argv[1]);
4793 if (o == NULL) {
4794 type = "+none";
4795 } else {
4796 switch(o->type) {
4797 case REDIS_STRING: type = "+string"; break;
4798 case REDIS_LIST: type = "+list"; break;
4799 case REDIS_SET: type = "+set"; break;
4800 case REDIS_ZSET: type = "+zset"; break;
4801 case REDIS_HASH: type = "+hash"; break;
4802 default: type = "+unknown"; break;
4803 }
4804 }
4805 addReplySds(c,sdsnew(type));
4806 addReply(c,shared.crlf);
4807 }
4808
4809 static void saveCommand(redisClient *c) {
4810 if (server.bgsavechildpid != -1) {
4811 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
4812 return;
4813 }
4814 if (rdbSave(server.dbfilename) == REDIS_OK) {
4815 addReply(c,shared.ok);
4816 } else {
4817 addReply(c,shared.err);
4818 }
4819 }
4820
4821 static void bgsaveCommand(redisClient *c) {
4822 if (server.bgsavechildpid != -1) {
4823 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
4824 return;
4825 }
4826 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
4827 char *status = "+Background saving started\r\n";
4828 addReplySds(c,sdsnew(status));
4829 } else {
4830 addReply(c,shared.err);
4831 }
4832 }
4833
4834 static void shutdownCommand(redisClient *c) {
4835 if (prepareForShutdown() == REDIS_OK)
4836 exit(0);
4837 addReplySds(c, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
4838 }
4839
4840 static void renameGenericCommand(redisClient *c, int nx) {
4841 robj *o;
4842
4843 /* To use the same key as src and dst is probably an error */
4844 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
4845 addReply(c,shared.sameobjecterr);
4846 return;
4847 }
4848
4849 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
4850 return;
4851
4852 incrRefCount(o);
4853 deleteIfVolatile(c->db,c->argv[2]);
4854 if (dbAdd(c->db,c->argv[2],o) == REDIS_ERR) {
4855 if (nx) {
4856 decrRefCount(o);
4857 addReply(c,shared.czero);
4858 return;
4859 }
4860 dbReplace(c->db,c->argv[2],o);
4861 }
4862 dbDelete(c->db,c->argv[1]);
4863 touchWatchedKey(c->db,c->argv[2]);
4864 server.dirty++;
4865 addReply(c,nx ? shared.cone : shared.ok);
4866 }
4867
4868 static void renameCommand(redisClient *c) {
4869 renameGenericCommand(c,0);
4870 }
4871
4872 static void renamenxCommand(redisClient *c) {
4873 renameGenericCommand(c,1);
4874 }
4875
4876 static void moveCommand(redisClient *c) {
4877 robj *o;
4878 redisDb *src, *dst;
4879 int srcid;
4880
4881 /* Obtain source and target DB pointers */
4882 src = c->db;
4883 srcid = c->db->id;
4884 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
4885 addReply(c,shared.outofrangeerr);
4886 return;
4887 }
4888 dst = c->db;
4889 selectDb(c,srcid); /* Back to the source DB */
4890
4891 /* If the user is moving using as target the same
4892 * DB as the source DB it is probably an error. */
4893 if (src == dst) {
4894 addReply(c,shared.sameobjecterr);
4895 return;
4896 }
4897
4898 /* Check if the element exists and get a reference */
4899 o = lookupKeyWrite(c->db,c->argv[1]);
4900 if (!o) {
4901 addReply(c,shared.czero);
4902 return;
4903 }
4904
4905 /* Try to add the element to the target DB */
4906 deleteIfVolatile(dst,c->argv[1]);
4907 if (dbAdd(dst,c->argv[1],o) == REDIS_ERR) {
4908 addReply(c,shared.czero);
4909 return;
4910 }
4911 incrRefCount(o);
4912
4913 /* OK! key moved, free the entry in the source DB */
4914 dbDelete(src,c->argv[1]);
4915 server.dirty++;
4916 addReply(c,shared.cone);
4917 }
4918
4919 /* =================================== Lists ================================ */
4920
4921
4922 /* Check the argument length to see if it requires us to convert the ziplist
4923 * to a real list. Only check raw-encoded objects because integer encoded
4924 * objects are never too long. */
4925 static void listTypeTryConversion(robj *subject, robj *value) {
4926 if (subject->encoding != REDIS_ENCODING_ZIPLIST) return;
4927 if (value->encoding == REDIS_ENCODING_RAW &&
4928 sdslen(value->ptr) > server.list_max_ziplist_value)
4929 listTypeConvert(subject,REDIS_ENCODING_LIST);
4930 }
4931
4932 static void listTypePush(robj *subject, robj *value, int where) {
4933 /* Check if we need to convert the ziplist */
4934 listTypeTryConversion(subject,value);
4935 if (subject->encoding == REDIS_ENCODING_ZIPLIST &&
4936 ziplistLen(subject->ptr) >= server.list_max_ziplist_entries)
4937 listTypeConvert(subject,REDIS_ENCODING_LIST);
4938
4939 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4940 int pos = (where == REDIS_HEAD) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
4941 value = getDecodedObject(value);
4942 subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),pos);
4943 decrRefCount(value);
4944 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4945 if (where == REDIS_HEAD) {
4946 listAddNodeHead(subject->ptr,value);
4947 } else {
4948 listAddNodeTail(subject->ptr,value);
4949 }
4950 incrRefCount(value);
4951 } else {
4952 redisPanic("Unknown list encoding");
4953 }
4954 }
4955
4956 static robj *listTypePop(robj *subject, int where) {
4957 robj *value = NULL;
4958 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4959 unsigned char *p;
4960 unsigned char *vstr;
4961 unsigned int vlen;
4962 long long vlong;
4963 int pos = (where == REDIS_HEAD) ? 0 : -1;
4964 p = ziplistIndex(subject->ptr,pos);
4965 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
4966 if (vstr) {
4967 value = createStringObject((char*)vstr,vlen);
4968 } else {
4969 value = createStringObjectFromLongLong(vlong);
4970 }
4971 /* We only need to delete an element when it exists */
4972 subject->ptr = ziplistDelete(subject->ptr,&p);
4973 }
4974 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4975 list *list = subject->ptr;
4976 listNode *ln;
4977 if (where == REDIS_HEAD) {
4978 ln = listFirst(list);
4979 } else {
4980 ln = listLast(list);
4981 }
4982 if (ln != NULL) {
4983 value = listNodeValue(ln);
4984 incrRefCount(value);
4985 listDelNode(list,ln);
4986 }
4987 } else {
4988 redisPanic("Unknown list encoding");
4989 }
4990 return value;
4991 }
4992
4993 static unsigned long listTypeLength(robj *subject) {
4994 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4995 return ziplistLen(subject->ptr);
4996 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4997 return listLength((list*)subject->ptr);
4998 } else {
4999 redisPanic("Unknown list encoding");
5000 }
5001 }
5002
5003 /* Structure to hold set iteration abstraction. */
5004 typedef struct {
5005 robj *subject;
5006 unsigned char encoding;
5007 unsigned char direction; /* Iteration direction */
5008 unsigned char *zi;
5009 listNode *ln;
5010 } listTypeIterator;
5011
5012 /* Structure for an entry while iterating over a list. */
5013 typedef struct {
5014 listTypeIterator *li;
5015 unsigned char *zi; /* Entry in ziplist */
5016 listNode *ln; /* Entry in linked list */
5017 } listTypeEntry;
5018
5019 /* Initialize an iterator at the specified index. */
5020 static listTypeIterator *listTypeInitIterator(robj *subject, int index, unsigned char direction) {
5021 listTypeIterator *li = zmalloc(sizeof(listTypeIterator));
5022 li->subject = subject;
5023 li->encoding = subject->encoding;
5024 li->direction = direction;
5025 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
5026 li->zi = ziplistIndex(subject->ptr,index);
5027 } else if (li->encoding == REDIS_ENCODING_LIST) {
5028 li->ln = listIndex(subject->ptr,index);
5029 } else {
5030 redisPanic("Unknown list encoding");
5031 }
5032 return li;
5033 }
5034
5035 /* Clean up the iterator. */
5036 static void listTypeReleaseIterator(listTypeIterator *li) {
5037 zfree(li);
5038 }
5039
5040 /* Stores pointer to current the entry in the provided entry structure
5041 * and advances the position of the iterator. Returns 1 when the current
5042 * entry is in fact an entry, 0 otherwise. */
5043 static int listTypeNext(listTypeIterator *li, listTypeEntry *entry) {
5044 /* Protect from converting when iterating */
5045 redisAssert(li->subject->encoding == li->encoding);
5046
5047 entry->li = li;
5048 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
5049 entry->zi = li->zi;
5050 if (entry->zi != NULL) {
5051 if (li->direction == REDIS_TAIL)
5052 li->zi = ziplistNext(li->subject->ptr,li->zi);
5053 else
5054 li->zi = ziplistPrev(li->subject->ptr,li->zi);
5055 return 1;
5056 }
5057 } else if (li->encoding == REDIS_ENCODING_LIST) {
5058 entry->ln = li->ln;
5059 if (entry->ln != NULL) {
5060 if (li->direction == REDIS_TAIL)
5061 li->ln = li->ln->next;
5062 else
5063 li->ln = li->ln->prev;
5064 return 1;
5065 }
5066 } else {
5067 redisPanic("Unknown list encoding");
5068 }
5069 return 0;
5070 }
5071
5072 /* Return entry or NULL at the current position of the iterator. */
5073 static robj *listTypeGet(listTypeEntry *entry) {
5074 listTypeIterator *li = entry->li;
5075 robj *value = NULL;
5076 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
5077 unsigned char *vstr;
5078 unsigned int vlen;
5079 long long vlong;
5080 redisAssert(entry->zi != NULL);
5081 if (ziplistGet(entry->zi,&vstr,&vlen,&vlong)) {
5082 if (vstr) {
5083 value = createStringObject((char*)vstr,vlen);
5084 } else {
5085 value = createStringObjectFromLongLong(vlong);
5086 }
5087 }
5088 } else if (li->encoding == REDIS_ENCODING_LIST) {
5089 redisAssert(entry->ln != NULL);
5090 value = listNodeValue(entry->ln);
5091 incrRefCount(value);
5092 } else {
5093 redisPanic("Unknown list encoding");
5094 }
5095 return value;
5096 }
5097
5098 static void listTypeInsert(listTypeEntry *entry, robj *value, int where) {
5099 robj *subject = entry->li->subject;
5100 if (entry->li->encoding == REDIS_ENCODING_ZIPLIST) {
5101 value = getDecodedObject(value);
5102 if (where == REDIS_TAIL) {
5103 unsigned char *next = ziplistNext(subject->ptr,entry->zi);
5104
5105 /* When we insert after the current element, but the current element
5106 * is the tail of the list, we need to do a push. */
5107 if (next == NULL) {
5108 subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),REDIS_TAIL);
5109 } else {
5110 subject->ptr = ziplistInsert(subject->ptr,next,value->ptr,sdslen(value->ptr));
5111 }
5112 } else {
5113 subject->ptr = ziplistInsert(subject->ptr,entry->zi,value->ptr,sdslen(value->ptr));
5114 }
5115 decrRefCount(value);
5116 } else if (entry->li->encoding == REDIS_ENCODING_LIST) {
5117 if (where == REDIS_TAIL) {
5118 listInsertNode(subject->ptr,entry->ln,value,AL_START_TAIL);
5119 } else {
5120 listInsertNode(subject->ptr,entry->ln,value,AL_START_HEAD);
5121 }
5122 incrRefCount(value);
5123 } else {
5124 redisPanic("Unknown list encoding");
5125 }
5126 }
5127
5128 /* Compare the given object with the entry at the current position. */
5129 static int listTypeEqual(listTypeEntry *entry, robj *o) {
5130 listTypeIterator *li = entry->li;
5131 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
5132 redisAssert(o->encoding == REDIS_ENCODING_RAW);
5133 return ziplistCompare(entry->zi,o->ptr,sdslen(o->ptr));
5134 } else if (li->encoding == REDIS_ENCODING_LIST) {
5135 return equalStringObjects(o,listNodeValue(entry->ln));
5136 } else {
5137 redisPanic("Unknown list encoding");
5138 }
5139 }
5140
5141 /* Delete the element pointed to. */
5142 static void listTypeDelete(listTypeEntry *entry) {
5143 listTypeIterator *li = entry->li;
5144 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
5145 unsigned char *p = entry->zi;
5146 li->subject->ptr = ziplistDelete(li->subject->ptr,&p);
5147
5148 /* Update position of the iterator depending on the direction */
5149 if (li->direction == REDIS_TAIL)
5150 li->zi = p;
5151 else
5152 li->zi = ziplistPrev(li->subject->ptr,p);
5153 } else if (entry->li->encoding == REDIS_ENCODING_LIST) {
5154 listNode *next;
5155 if (li->direction == REDIS_TAIL)
5156 next = entry->ln->next;
5157 else
5158 next = entry->ln->prev;
5159 listDelNode(li->subject->ptr,entry->ln);
5160 li->ln = next;
5161 } else {
5162 redisPanic("Unknown list encoding");
5163 }
5164 }
5165
5166 static void listTypeConvert(robj *subject, int enc) {
5167 listTypeIterator *li;
5168 listTypeEntry entry;
5169 redisAssert(subject->type == REDIS_LIST);
5170
5171 if (enc == REDIS_ENCODING_LIST) {
5172 list *l = listCreate();
5173 listSetFreeMethod(l,decrRefCount);
5174
5175 /* listTypeGet returns a robj with incremented refcount */
5176 li = listTypeInitIterator(subject,0,REDIS_TAIL);
5177 while (listTypeNext(li,&entry)) listAddNodeTail(l,listTypeGet(&entry));
5178 listTypeReleaseIterator(li);
5179
5180 subject->encoding = REDIS_ENCODING_LIST;
5181 zfree(subject->ptr);
5182 subject->ptr = l;
5183 } else {
5184 redisPanic("Unsupported list conversion");
5185 }
5186 }
5187
5188 static void pushGenericCommand(redisClient *c, int where) {
5189 robj *lobj = lookupKeyWrite(c->db,c->argv[1]);
5190 if (lobj == NULL) {
5191 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
5192 addReply(c,shared.cone);
5193 return;
5194 }
5195 lobj = createZiplistObject();
5196 dbAdd(c->db,c->argv[1],lobj);
5197 } else {
5198 if (lobj->type != REDIS_LIST) {
5199 addReply(c,shared.wrongtypeerr);
5200 return;
5201 }
5202 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
5203 addReply(c,shared.cone);
5204 return;
5205 }
5206 }
5207 listTypePush(lobj,c->argv[2],where);
5208 addReplyLongLong(c,listTypeLength(lobj));
5209 server.dirty++;
5210 }
5211
5212 static void lpushCommand(redisClient *c) {
5213 pushGenericCommand(c,REDIS_HEAD);
5214 }
5215
5216 static void rpushCommand(redisClient *c) {
5217 pushGenericCommand(c,REDIS_TAIL);
5218 }
5219
5220 static void pushxGenericCommand(redisClient *c, robj *refval, robj *val, int where) {
5221 robj *subject;
5222 listTypeIterator *iter;
5223 listTypeEntry entry;
5224 int inserted = 0;
5225
5226 if ((subject = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5227 checkType(c,subject,REDIS_LIST)) return;
5228
5229 if (refval != NULL) {
5230 /* Note: we expect refval to be string-encoded because it is *not* the
5231 * last argument of the multi-bulk LINSERT. */
5232 redisAssert(refval->encoding == REDIS_ENCODING_RAW);
5233
5234 /* We're not sure if this value can be inserted yet, but we cannot
5235 * convert the list inside the iterator. We don't want to loop over
5236 * the list twice (once to see if the value can be inserted and once
5237 * to do the actual insert), so we assume this value can be inserted
5238 * and convert the ziplist to a regular list if necessary. */
5239 listTypeTryConversion(subject,val);
5240
5241 /* Seek refval from head to tail */
5242 iter = listTypeInitIterator(subject,0,REDIS_TAIL);
5243 while (listTypeNext(iter,&entry)) {
5244 if (listTypeEqual(&entry,refval)) {
5245 listTypeInsert(&entry,val,where);
5246 inserted = 1;
5247 break;
5248 }
5249 }
5250 listTypeReleaseIterator(iter);
5251
5252 if (inserted) {
5253 /* Check if the length exceeds the ziplist length threshold. */
5254 if (subject->encoding == REDIS_ENCODING_ZIPLIST &&
5255 ziplistLen(subject->ptr) > server.list_max_ziplist_entries)
5256 listTypeConvert(subject,REDIS_ENCODING_LIST);
5257 server.dirty++;
5258 } else {
5259 /* Notify client of a failed insert */
5260 addReply(c,shared.cnegone);
5261 return;
5262 }
5263 } else {
5264 listTypePush(subject,val,where);
5265 server.dirty++;
5266 }
5267
5268 addReplyUlong(c,listTypeLength(subject));
5269 }
5270
5271 static void lpushxCommand(redisClient *c) {
5272 pushxGenericCommand(c,NULL,c->argv[2],REDIS_HEAD);
5273 }
5274
5275 static void rpushxCommand(redisClient *c) {
5276 pushxGenericCommand(c,NULL,c->argv[2],REDIS_TAIL);
5277 }
5278
5279 static void linsertCommand(redisClient *c) {
5280 if (strcasecmp(c->argv[2]->ptr,"after") == 0) {
5281 pushxGenericCommand(c,c->argv[3],c->argv[4],REDIS_TAIL);
5282 } else if (strcasecmp(c->argv[2]->ptr,"before") == 0) {
5283 pushxGenericCommand(c,c->argv[3],c->argv[4],REDIS_HEAD);
5284 } else {
5285 addReply(c,shared.syntaxerr);
5286 }
5287 }
5288
5289 static void llenCommand(redisClient *c) {
5290 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.czero);
5291 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5292 addReplyUlong(c,listTypeLength(o));
5293 }
5294
5295 static void lindexCommand(redisClient *c) {
5296 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk);
5297 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5298 int index = atoi(c->argv[2]->ptr);
5299 robj *value = NULL;
5300
5301 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5302 unsigned char *p;
5303 unsigned char *vstr;
5304 unsigned int vlen;
5305 long long vlong;
5306 p = ziplistIndex(o->ptr,index);
5307 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
5308 if (vstr) {
5309 value = createStringObject((char*)vstr,vlen);
5310 } else {
5311 value = createStringObjectFromLongLong(vlong);
5312 }
5313 addReplyBulk(c,value);
5314 decrRefCount(value);
5315 } else {
5316 addReply(c,shared.nullbulk);
5317 }
5318 } else if (o->encoding == REDIS_ENCODING_LIST) {
5319 listNode *ln = listIndex(o->ptr,index);
5320 if (ln != NULL) {
5321 value = listNodeValue(ln);
5322 addReplyBulk(c,value);
5323 } else {
5324 addReply(c,shared.nullbulk);
5325 }
5326 } else {
5327 redisPanic("Unknown list encoding");
5328 }
5329 }
5330
5331 static void lsetCommand(redisClient *c) {
5332 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr);
5333 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5334 int index = atoi(c->argv[2]->ptr);
5335 robj *value = c->argv[3];
5336
5337 listTypeTryConversion(o,value);
5338 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5339 unsigned char *p, *zl = o->ptr;
5340 p = ziplistIndex(zl,index);
5341 if (p == NULL) {
5342 addReply(c,shared.outofrangeerr);
5343 } else {
5344 o->ptr = ziplistDelete(o->ptr,&p);
5345 value = getDecodedObject(value);
5346 o->ptr = ziplistInsert(o->ptr,p,value->ptr,sdslen(value->ptr));
5347 decrRefCount(value);
5348 addReply(c,shared.ok);
5349 server.dirty++;
5350 }
5351 } else if (o->encoding == REDIS_ENCODING_LIST) {
5352 listNode *ln = listIndex(o->ptr,index);
5353 if (ln == NULL) {
5354 addReply(c,shared.outofrangeerr);
5355 } else {
5356 decrRefCount((robj*)listNodeValue(ln));
5357 listNodeValue(ln) = value;
5358 incrRefCount(value);
5359 addReply(c,shared.ok);
5360 server.dirty++;
5361 }
5362 } else {
5363 redisPanic("Unknown list encoding");
5364 }
5365 }
5366
5367 static void popGenericCommand(redisClient *c, int where) {
5368 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk);
5369 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5370
5371 robj *value = listTypePop(o,where);
5372 if (value == NULL) {
5373 addReply(c,shared.nullbulk);
5374 } else {
5375 addReplyBulk(c,value);
5376 decrRefCount(value);
5377 if (listTypeLength(o) == 0) dbDelete(c->db,c->argv[1]);
5378 server.dirty++;
5379 }
5380 }
5381
5382 static void lpopCommand(redisClient *c) {
5383 popGenericCommand(c,REDIS_HEAD);
5384 }
5385
5386 static void rpopCommand(redisClient *c) {
5387 popGenericCommand(c,REDIS_TAIL);
5388 }
5389
5390 static void lrangeCommand(redisClient *c) {
5391 robj *o, *value;
5392 int start = atoi(c->argv[2]->ptr);
5393 int end = atoi(c->argv[3]->ptr);
5394 int llen;
5395 int rangelen, j;
5396 listTypeEntry entry;
5397
5398 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
5399 || checkType(c,o,REDIS_LIST)) return;
5400 llen = listTypeLength(o);
5401
5402 /* convert negative indexes */
5403 if (start < 0) start = llen+start;
5404 if (end < 0) end = llen+end;
5405 if (start < 0) start = 0;
5406 if (end < 0) end = 0;
5407
5408 /* indexes sanity checks */
5409 if (start > end || start >= llen) {
5410 /* Out of range start or start > end result in empty list */
5411 addReply(c,shared.emptymultibulk);
5412 return;
5413 }
5414 if (end >= llen) end = llen-1;
5415 rangelen = (end-start)+1;
5416
5417 /* Return the result in form of a multi-bulk reply */
5418 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
5419 listTypeIterator *li = listTypeInitIterator(o,start,REDIS_TAIL);
5420 for (j = 0; j < rangelen; j++) {
5421 redisAssert(listTypeNext(li,&entry));
5422 value = listTypeGet(&entry);
5423 addReplyBulk(c,value);
5424 decrRefCount(value);
5425 }
5426 listTypeReleaseIterator(li);
5427 }
5428
5429 static void ltrimCommand(redisClient *c) {
5430 robj *o;
5431 int start = atoi(c->argv[2]->ptr);
5432 int end = atoi(c->argv[3]->ptr);
5433 int llen;
5434 int j, ltrim, rtrim;
5435 list *list;
5436 listNode *ln;
5437
5438 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
5439 checkType(c,o,REDIS_LIST)) return;
5440 llen = listTypeLength(o);
5441
5442 /* convert negative indexes */
5443 if (start < 0) start = llen+start;
5444 if (end < 0) end = llen+end;
5445 if (start < 0) start = 0;
5446 if (end < 0) end = 0;
5447
5448 /* indexes sanity checks */
5449 if (start > end || start >= llen) {
5450 /* Out of range start or start > end result in empty list */
5451 ltrim = llen;
5452 rtrim = 0;
5453 } else {
5454 if (end >= llen) end = llen-1;
5455 ltrim = start;
5456 rtrim = llen-end-1;
5457 }
5458
5459 /* Remove list elements to perform the trim */
5460 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5461 o->ptr = ziplistDeleteRange(o->ptr,0,ltrim);
5462 o->ptr = ziplistDeleteRange(o->ptr,-rtrim,rtrim);
5463 } else if (o->encoding == REDIS_ENCODING_LIST) {
5464 list = o->ptr;
5465 for (j = 0; j < ltrim; j++) {
5466 ln = listFirst(list);
5467 listDelNode(list,ln);
5468 }
5469 for (j = 0; j < rtrim; j++) {
5470 ln = listLast(list);
5471 listDelNode(list,ln);
5472 }
5473 } else {
5474 redisPanic("Unknown list encoding");
5475 }
5476 if (listTypeLength(o) == 0) dbDelete(c->db,c->argv[1]);
5477 server.dirty++;
5478 addReply(c,shared.ok);
5479 }
5480
5481 static void lremCommand(redisClient *c) {
5482 robj *subject, *obj = c->argv[3];
5483 int toremove = atoi(c->argv[2]->ptr);
5484 int removed = 0;
5485 listTypeEntry entry;
5486
5487 subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero);
5488 if (subject == NULL || checkType(c,subject,REDIS_LIST)) return;
5489
5490 /* Make sure obj is raw when we're dealing with a ziplist */
5491 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
5492 obj = getDecodedObject(obj);
5493
5494 listTypeIterator *li;
5495 if (toremove < 0) {
5496 toremove = -toremove;
5497 li = listTypeInitIterator(subject,-1,REDIS_HEAD);
5498 } else {
5499 li = listTypeInitIterator(subject,0,REDIS_TAIL);
5500 }
5501
5502 while (listTypeNext(li,&entry)) {
5503 if (listTypeEqual(&entry,obj)) {
5504 listTypeDelete(&entry);
5505 server.dirty++;
5506 removed++;
5507 if (toremove && removed == toremove) break;
5508 }
5509 }
5510 listTypeReleaseIterator(li);
5511
5512 /* Clean up raw encoded object */
5513 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
5514 decrRefCount(obj);
5515
5516 if (listTypeLength(subject) == 0) dbDelete(c->db,c->argv[1]);
5517 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
5518 }
5519
5520 /* This is the semantic of this command:
5521 * RPOPLPUSH srclist dstlist:
5522 * IF LLEN(srclist) > 0
5523 * element = RPOP srclist
5524 * LPUSH dstlist element
5525 * RETURN element
5526 * ELSE
5527 * RETURN nil
5528 * END
5529 * END
5530 *
5531 * The idea is to be able to get an element from a list in a reliable way
5532 * since the element is not just returned but pushed against another list
5533 * as well. This command was originally proposed by Ezra Zygmuntowicz.
5534 */
5535 static void rpoplpushcommand(redisClient *c) {
5536 robj *sobj, *value;
5537 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5538 checkType(c,sobj,REDIS_LIST)) return;
5539
5540 if (listTypeLength(sobj) == 0) {
5541 addReply(c,shared.nullbulk);
5542 } else {
5543 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
5544 if (dobj && checkType(c,dobj,REDIS_LIST)) return;
5545 value = listTypePop(sobj,REDIS_TAIL);
5546
5547 /* Add the element to the target list (unless it's directly
5548 * passed to some BLPOP-ing client */
5549 if (!handleClientsWaitingListPush(c,c->argv[2],value)) {
5550 /* Create the list if the key does not exist */
5551 if (!dobj) {
5552 dobj = createZiplistObject();
5553 dbAdd(c->db,c->argv[2],dobj);
5554 }
5555 listTypePush(dobj,value,REDIS_HEAD);
5556 }
5557
5558 /* Send the element to the client as reply as well */
5559 addReplyBulk(c,value);
5560
5561 /* listTypePop returns an object with its refcount incremented */
5562 decrRefCount(value);
5563
5564 /* Delete the source list when it is empty */
5565 if (listTypeLength(sobj) == 0) dbDelete(c->db,c->argv[1]);
5566 server.dirty++;
5567 }
5568 }
5569
5570 /* ==================================== Sets ================================ */
5571
5572 static void saddCommand(redisClient *c) {
5573 robj *set;
5574
5575 set = lookupKeyWrite(c->db,c->argv[1]);
5576 if (set == NULL) {
5577 set = createSetObject();
5578 dbAdd(c->db,c->argv[1],set);
5579 } else {
5580 if (set->type != REDIS_SET) {
5581 addReply(c,shared.wrongtypeerr);
5582 return;
5583 }
5584 }
5585 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
5586 incrRefCount(c->argv[2]);
5587 server.dirty++;
5588 addReply(c,shared.cone);
5589 } else {
5590 addReply(c,shared.czero);
5591 }
5592 }
5593
5594 static void sremCommand(redisClient *c) {
5595 robj *set;
5596
5597 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5598 checkType(c,set,REDIS_SET)) return;
5599
5600 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
5601 server.dirty++;
5602 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
5603 if (dictSize((dict*)set->ptr) == 0) dbDelete(c->db,c->argv[1]);
5604 addReply(c,shared.cone);
5605 } else {
5606 addReply(c,shared.czero);
5607 }
5608 }
5609
5610 static void smoveCommand(redisClient *c) {
5611 robj *srcset, *dstset;
5612
5613 srcset = lookupKeyWrite(c->db,c->argv[1]);
5614 dstset = lookupKeyWrite(c->db,c->argv[2]);
5615
5616 /* If the source key does not exist return 0, if it's of the wrong type
5617 * raise an error */
5618 if (srcset == NULL || srcset->type != REDIS_SET) {
5619 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
5620 return;
5621 }
5622 /* Error if the destination key is not a set as well */
5623 if (dstset && dstset->type != REDIS_SET) {
5624 addReply(c,shared.wrongtypeerr);
5625 return;
5626 }
5627 /* Remove the element from the source set */
5628 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
5629 /* Key not found in the src set! return zero */
5630 addReply(c,shared.czero);
5631 return;
5632 }
5633 if (dictSize((dict*)srcset->ptr) == 0 && srcset != dstset)
5634 dbDelete(c->db,c->argv[1]);
5635 server.dirty++;
5636 /* Add the element to the destination set */
5637 if (!dstset) {
5638 dstset = createSetObject();
5639 dbAdd(c->db,c->argv[2],dstset);
5640 }
5641 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
5642 incrRefCount(c->argv[3]);
5643 addReply(c,shared.cone);
5644 }
5645
5646 static void sismemberCommand(redisClient *c) {
5647 robj *set;
5648
5649 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5650 checkType(c,set,REDIS_SET)) return;
5651
5652 if (dictFind(set->ptr,c->argv[2]))
5653 addReply(c,shared.cone);
5654 else
5655 addReply(c,shared.czero);
5656 }
5657
5658 static void scardCommand(redisClient *c) {
5659 robj *o;
5660 dict *s;
5661
5662 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5663 checkType(c,o,REDIS_SET)) return;
5664
5665 s = o->ptr;
5666 addReplyUlong(c,dictSize(s));
5667 }
5668
5669 static void spopCommand(redisClient *c) {
5670 robj *set;
5671 dictEntry *de;
5672
5673 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5674 checkType(c,set,REDIS_SET)) return;
5675
5676 de = dictGetRandomKey(set->ptr);
5677 if (de == NULL) {
5678 addReply(c,shared.nullbulk);
5679 } else {
5680 robj *ele = dictGetEntryKey(de);
5681
5682 addReplyBulk(c,ele);
5683 dictDelete(set->ptr,ele);
5684 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
5685 if (dictSize((dict*)set->ptr) == 0) dbDelete(c->db,c->argv[1]);
5686 server.dirty++;
5687 }
5688 }
5689
5690 static void srandmemberCommand(redisClient *c) {
5691 robj *set;
5692 dictEntry *de;
5693
5694 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5695 checkType(c,set,REDIS_SET)) return;
5696
5697 de = dictGetRandomKey(set->ptr);
5698 if (de == NULL) {
5699 addReply(c,shared.nullbulk);
5700 } else {
5701 robj *ele = dictGetEntryKey(de);
5702
5703 addReplyBulk(c,ele);
5704 }
5705 }
5706
5707 static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
5708 dict **d1 = (void*) s1, **d2 = (void*) s2;
5709
5710 return dictSize(*d1)-dictSize(*d2);
5711 }
5712
5713 static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
5714 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5715 dictIterator *di;
5716 dictEntry *de;
5717 robj *lenobj = NULL, *dstset = NULL;
5718 unsigned long j, cardinality = 0;
5719
5720 for (j = 0; j < setsnum; j++) {
5721 robj *setobj;
5722
5723 setobj = dstkey ?
5724 lookupKeyWrite(c->db,setskeys[j]) :
5725 lookupKeyRead(c->db,setskeys[j]);
5726 if (!setobj) {
5727 zfree(dv);
5728 if (dstkey) {
5729 if (dbDelete(c->db,dstkey))
5730 server.dirty++;
5731 addReply(c,shared.czero);
5732 } else {
5733 addReply(c,shared.emptymultibulk);
5734 }
5735 return;
5736 }
5737 if (setobj->type != REDIS_SET) {
5738 zfree(dv);
5739 addReply(c,shared.wrongtypeerr);
5740 return;
5741 }
5742 dv[j] = setobj->ptr;
5743 }
5744 /* Sort sets from the smallest to largest, this will improve our
5745 * algorithm's performace */
5746 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
5747
5748 /* The first thing we should output is the total number of elements...
5749 * since this is a multi-bulk write, but at this stage we don't know
5750 * the intersection set size, so we use a trick, append an empty object
5751 * to the output list and save the pointer to later modify it with the
5752 * right length */
5753 if (!dstkey) {
5754 lenobj = createObject(REDIS_STRING,NULL);
5755 addReply(c,lenobj);
5756 decrRefCount(lenobj);
5757 } else {
5758 /* If we have a target key where to store the resulting set
5759 * create this key with an empty set inside */
5760 dstset = createSetObject();
5761 }
5762
5763 /* Iterate all the elements of the first (smallest) set, and test
5764 * the element against all the other sets, if at least one set does
5765 * not include the element it is discarded */
5766 di = dictGetIterator(dv[0]);
5767
5768 while((de = dictNext(di)) != NULL) {
5769 robj *ele;
5770
5771 for (j = 1; j < setsnum; j++)
5772 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
5773 if (j != setsnum)
5774 continue; /* at least one set does not contain the member */
5775 ele = dictGetEntryKey(de);
5776 if (!dstkey) {
5777 addReplyBulk(c,ele);
5778 cardinality++;
5779 } else {
5780 dictAdd(dstset->ptr,ele,NULL);
5781 incrRefCount(ele);
5782 }
5783 }
5784 dictReleaseIterator(di);
5785
5786 if (dstkey) {
5787 /* Store the resulting set into the target, if the intersection
5788 * is not an empty set. */
5789 dbDelete(c->db,dstkey);
5790 if (dictSize((dict*)dstset->ptr) > 0) {
5791 dbAdd(c->db,dstkey,dstset);
5792 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
5793 } else {
5794 decrRefCount(dstset);
5795 addReply(c,shared.czero);
5796 }
5797 server.dirty++;
5798 } else {
5799 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
5800 }
5801 zfree(dv);
5802 }
5803
5804 static void sinterCommand(redisClient *c) {
5805 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
5806 }
5807
5808 static void sinterstoreCommand(redisClient *c) {
5809 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
5810 }
5811
5812 #define REDIS_OP_UNION 0
5813 #define REDIS_OP_DIFF 1
5814 #define REDIS_OP_INTER 2
5815
5816 static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
5817 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5818 dictIterator *di;
5819 dictEntry *de;
5820 robj *dstset = NULL;
5821 int j, cardinality = 0;
5822
5823 for (j = 0; j < setsnum; j++) {
5824 robj *setobj;
5825
5826 setobj = dstkey ?
5827 lookupKeyWrite(c->db,setskeys[j]) :
5828 lookupKeyRead(c->db,setskeys[j]);
5829 if (!setobj) {
5830 dv[j] = NULL;
5831 continue;
5832 }
5833 if (setobj->type != REDIS_SET) {
5834 zfree(dv);
5835 addReply(c,shared.wrongtypeerr);
5836 return;
5837 }
5838 dv[j] = setobj->ptr;
5839 }
5840
5841 /* We need a temp set object to store our union. If the dstkey
5842 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5843 * this set object will be the resulting object to set into the target key*/
5844 dstset = createSetObject();
5845
5846 /* Iterate all the elements of all the sets, add every element a single
5847 * time to the result set */
5848 for (j = 0; j < setsnum; j++) {
5849 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
5850 if (!dv[j]) continue; /* non existing keys are like empty sets */
5851
5852 di = dictGetIterator(dv[j]);
5853
5854 while((de = dictNext(di)) != NULL) {
5855 robj *ele;
5856
5857 /* dictAdd will not add the same element multiple times */
5858 ele = dictGetEntryKey(de);
5859 if (op == REDIS_OP_UNION || j == 0) {
5860 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
5861 incrRefCount(ele);
5862 cardinality++;
5863 }
5864 } else if (op == REDIS_OP_DIFF) {
5865 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
5866 cardinality--;
5867 }
5868 }
5869 }
5870 dictReleaseIterator(di);
5871
5872 /* result set is empty? Exit asap. */
5873 if (op == REDIS_OP_DIFF && cardinality == 0) break;
5874 }
5875
5876 /* Output the content of the resulting set, if not in STORE mode */
5877 if (!dstkey) {
5878 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
5879 di = dictGetIterator(dstset->ptr);
5880 while((de = dictNext(di)) != NULL) {
5881 robj *ele;
5882
5883 ele = dictGetEntryKey(de);
5884 addReplyBulk(c,ele);
5885 }
5886 dictReleaseIterator(di);
5887 decrRefCount(dstset);
5888 } else {
5889 /* If we have a target key where to store the resulting set
5890 * create this key with the result set inside */
5891 dbDelete(c->db,dstkey);
5892 if (dictSize((dict*)dstset->ptr) > 0) {
5893 dbAdd(c->db,dstkey,dstset);
5894 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
5895 } else {
5896 decrRefCount(dstset);
5897 addReply(c,shared.czero);
5898 }
5899 server.dirty++;
5900 }
5901 zfree(dv);
5902 }
5903
5904 static void sunionCommand(redisClient *c) {
5905 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
5906 }
5907
5908 static void sunionstoreCommand(redisClient *c) {
5909 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
5910 }
5911
5912 static void sdiffCommand(redisClient *c) {
5913 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
5914 }
5915
5916 static void sdiffstoreCommand(redisClient *c) {
5917 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
5918 }
5919
5920 /* ==================================== ZSets =============================== */
5921
5922 /* ZSETs are ordered sets using two data structures to hold the same elements
5923 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5924 * data structure.
5925 *
5926 * The elements are added to an hash table mapping Redis objects to scores.
5927 * At the same time the elements are added to a skip list mapping scores
5928 * to Redis objects (so objects are sorted by scores in this "view"). */
5929
5930 /* This skiplist implementation is almost a C translation of the original
5931 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5932 * Alternative to Balanced Trees", modified in three ways:
5933 * a) this implementation allows for repeated values.
5934 * b) the comparison is not just by key (our 'score') but by satellite data.
5935 * c) there is a back pointer, so it's a doubly linked list with the back
5936 * pointers being only at "level 1". This allows to traverse the list
5937 * from tail to head, useful for ZREVRANGE. */
5938
5939 static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
5940 zskiplistNode *zn = zmalloc(sizeof(*zn));
5941
5942 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
5943 if (level > 1)
5944 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
5945 else
5946 zn->span = NULL;
5947 zn->score = score;
5948 zn->obj = obj;
5949 return zn;
5950 }
5951
5952 static zskiplist *zslCreate(void) {
5953 int j;
5954 zskiplist *zsl;
5955
5956 zsl = zmalloc(sizeof(*zsl));
5957 zsl->level = 1;
5958 zsl->length = 0;
5959 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
5960 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
5961 zsl->header->forward[j] = NULL;
5962
5963 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5964 if (j < ZSKIPLIST_MAXLEVEL-1)
5965 zsl->header->span[j] = 0;
5966 }
5967 zsl->header->backward = NULL;
5968 zsl->tail = NULL;
5969 return zsl;
5970 }
5971
5972 static void zslFreeNode(zskiplistNode *node) {
5973 decrRefCount(node->obj);
5974 zfree(node->forward);
5975 zfree(node->span);
5976 zfree(node);
5977 }
5978
5979 static void zslFree(zskiplist *zsl) {
5980 zskiplistNode *node = zsl->header->forward[0], *next;
5981
5982 zfree(zsl->header->forward);
5983 zfree(zsl->header->span);
5984 zfree(zsl->header);
5985 while(node) {
5986 next = node->forward[0];
5987 zslFreeNode(node);
5988 node = next;
5989 }
5990 zfree(zsl);
5991 }
5992
5993 static int zslRandomLevel(void) {
5994 int level = 1;
5995 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
5996 level += 1;
5997 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
5998 }
5999
6000 static void zslInsert(zskiplist *zsl, double score, robj *obj) {
6001 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
6002 unsigned int rank[ZSKIPLIST_MAXLEVEL];
6003 int i, level;
6004
6005 x = zsl->header;
6006 for (i = zsl->level-1; i >= 0; i--) {
6007 /* store rank that is crossed to reach the insert position */
6008 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
6009
6010 while (x->forward[i] &&
6011 (x->forward[i]->score < score ||
6012 (x->forward[i]->score == score &&
6013 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
6014 rank[i] += i > 0 ? x->span[i-1] : 1;
6015 x = x->forward[i];
6016 }
6017 update[i] = x;
6018 }
6019 /* we assume the key is not already inside, since we allow duplicated
6020 * scores, and the re-insertion of score and redis object should never
6021 * happpen since the caller of zslInsert() should test in the hash table
6022 * if the element is already inside or not. */
6023 level = zslRandomLevel();
6024 if (level > zsl->level) {
6025 for (i = zsl->level; i < level; i++) {
6026 rank[i] = 0;
6027 update[i] = zsl->header;
6028 update[i]->span[i-1] = zsl->length;
6029 }
6030 zsl->level = level;
6031 }
6032 x = zslCreateNode(level,score,obj);
6033 for (i = 0; i < level; i++) {
6034 x->forward[i] = update[i]->forward[i];
6035 update[i]->forward[i] = x;
6036
6037 /* update span covered by update[i] as x is inserted here */
6038 if (i > 0) {
6039 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
6040 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
6041 }
6042 }
6043
6044 /* increment span for untouched levels */
6045 for (i = level; i < zsl->level; i++) {
6046 update[i]->span[i-1]++;
6047 }
6048
6049 x->backward = (update[0] == zsl->header) ? NULL : update[0];
6050 if (x->forward[0])
6051 x->forward[0]->backward = x;
6052 else
6053 zsl->tail = x;
6054 zsl->length++;
6055 }
6056
6057 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
6058 void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
6059 int i;
6060 for (i = 0; i < zsl->level; i++) {
6061 if (update[i]->forward[i] == x) {
6062 if (i > 0) {
6063 update[i]->span[i-1] += x->span[i-1] - 1;
6064 }
6065 update[i]->forward[i] = x->forward[i];
6066 } else {
6067 /* invariant: i > 0, because update[0]->forward[0]
6068 * is always equal to x */
6069 update[i]->span[i-1] -= 1;
6070 }
6071 }
6072 if (x->forward[0]) {
6073 x->forward[0]->backward = x->backward;
6074 } else {
6075 zsl->tail = x->backward;
6076 }
6077 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
6078 zsl->level--;
6079 zsl->length--;
6080 }
6081
6082 /* Delete an element with matching score/object from the skiplist. */
6083 static int zslDelete(zskiplist *zsl, double score, robj *obj) {
6084 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
6085 int i;
6086
6087 x = zsl->header;
6088 for (i = zsl->level-1; i >= 0; i--) {
6089 while (x->forward[i] &&
6090 (x->forward[i]->score < score ||
6091 (x->forward[i]->score == score &&
6092 compareStringObjects(x->forward[i]->obj,obj) < 0)))
6093 x = x->forward[i];
6094 update[i] = x;
6095 }
6096 /* We may have multiple elements with the same score, what we need
6097 * is to find the element with both the right score and object. */
6098 x = x->forward[0];
6099 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
6100 zslDeleteNode(zsl, x, update);
6101 zslFreeNode(x);
6102 return 1;
6103 } else {
6104 return 0; /* not found */
6105 }
6106 return 0; /* not found */
6107 }
6108
6109 /* Delete all the elements with score between min and max from the skiplist.
6110 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
6111 * Note that this function takes the reference to the hash table view of the
6112 * sorted set, in order to remove the elements from the hash table too. */
6113 static unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
6114 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
6115 unsigned long removed = 0;
6116 int i;
6117
6118 x = zsl->header;
6119 for (i = zsl->level-1; i >= 0; i--) {
6120 while (x->forward[i] && x->forward[i]->score < min)
6121 x = x->forward[i];
6122 update[i] = x;
6123 }
6124 /* We may have multiple elements with the same score, what we need
6125 * is to find the element with both the right score and object. */
6126 x = x->forward[0];
6127 while (x && x->score <= max) {
6128 zskiplistNode *next = x->forward[0];
6129 zslDeleteNode(zsl, x, update);
6130 dictDelete(dict,x->obj);
6131 zslFreeNode(x);
6132 removed++;
6133 x = next;
6134 }
6135 return removed; /* not found */
6136 }
6137
6138 /* Delete all the elements with rank between start and end from the skiplist.
6139 * Start and end are inclusive. Note that start and end need to be 1-based */
6140 static unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
6141 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
6142 unsigned long traversed = 0, removed = 0;
6143 int i;
6144
6145 x = zsl->header;
6146 for (i = zsl->level-1; i >= 0; i--) {
6147 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
6148 traversed += i > 0 ? x->span[i-1] : 1;
6149 x = x->forward[i];
6150 }
6151 update[i] = x;
6152 }
6153
6154 traversed++;
6155 x = x->forward[0];
6156 while (x && traversed <= end) {
6157 zskiplistNode *next = x->forward[0];
6158 zslDeleteNode(zsl, x, update);
6159 dictDelete(dict,x->obj);
6160 zslFreeNode(x);
6161 removed++;
6162 traversed++;
6163 x = next;
6164 }
6165 return removed;
6166 }
6167
6168 /* Find the first node having a score equal or greater than the specified one.
6169 * Returns NULL if there is no match. */
6170 static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
6171 zskiplistNode *x;
6172 int i;
6173
6174 x = zsl->header;
6175 for (i = zsl->level-1; i >= 0; i--) {
6176 while (x->forward[i] && x->forward[i]->score < score)
6177 x = x->forward[i];
6178 }
6179 /* We may have multiple elements with the same score, what we need
6180 * is to find the element with both the right score and object. */
6181 return x->forward[0];
6182 }
6183
6184 /* Find the rank for an element by both score and key.
6185 * Returns 0 when the element cannot be found, rank otherwise.
6186 * Note that the rank is 1-based due to the span of zsl->header to the
6187 * first element. */
6188 static unsigned long zslistTypeGetRank(zskiplist *zsl, double score, robj *o) {
6189 zskiplistNode *x;
6190 unsigned long rank = 0;
6191 int i;
6192
6193 x = zsl->header;
6194 for (i = zsl->level-1; i >= 0; i--) {
6195 while (x->forward[i] &&
6196 (x->forward[i]->score < score ||
6197 (x->forward[i]->score == score &&
6198 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
6199 rank += i > 0 ? x->span[i-1] : 1;
6200 x = x->forward[i];
6201 }
6202
6203 /* x might be equal to zsl->header, so test if obj is non-NULL */
6204 if (x->obj && equalStringObjects(x->obj,o)) {
6205 return rank;
6206 }
6207 }
6208 return 0;
6209 }
6210
6211 /* Finds an element by its rank. The rank argument needs to be 1-based. */
6212 zskiplistNode* zslistTypeGetElementByRank(zskiplist *zsl, unsigned long rank) {
6213 zskiplistNode *x;
6214 unsigned long traversed = 0;
6215 int i;
6216
6217 x = zsl->header;
6218 for (i = zsl->level-1; i >= 0; i--) {
6219 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
6220 {
6221 traversed += i > 0 ? x->span[i-1] : 1;
6222 x = x->forward[i];
6223 }
6224 if (traversed == rank) {
6225 return x;
6226 }
6227 }
6228 return NULL;
6229 }
6230
6231 /* The actual Z-commands implementations */
6232
6233 /* This generic command implements both ZADD and ZINCRBY.
6234 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
6235 * the increment if the operation is a ZINCRBY (doincrement == 1). */
6236 static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
6237 robj *zsetobj;
6238 zset *zs;
6239 double *score;
6240
6241 if (isnan(scoreval)) {
6242 addReplySds(c,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
6243 return;
6244 }
6245
6246 zsetobj = lookupKeyWrite(c->db,key);
6247 if (zsetobj == NULL) {
6248 zsetobj = createZsetObject();
6249 dbAdd(c->db,key,zsetobj);
6250 } else {
6251 if (zsetobj->type != REDIS_ZSET) {
6252 addReply(c,shared.wrongtypeerr);
6253 return;
6254 }
6255 }
6256 zs = zsetobj->ptr;
6257
6258 /* Ok now since we implement both ZADD and ZINCRBY here the code
6259 * needs to handle the two different conditions. It's all about setting
6260 * '*score', that is, the new score to set, to the right value. */
6261 score = zmalloc(sizeof(double));
6262 if (doincrement) {
6263 dictEntry *de;
6264
6265 /* Read the old score. If the element was not present starts from 0 */
6266 de = dictFind(zs->dict,ele);
6267 if (de) {
6268 double *oldscore = dictGetEntryVal(de);
6269 *score = *oldscore + scoreval;
6270 } else {
6271 *score = scoreval;
6272 }
6273 if (isnan(*score)) {
6274 addReplySds(c,
6275 sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
6276 zfree(score);
6277 /* Note that we don't need to check if the zset may be empty and
6278 * should be removed here, as we can only obtain Nan as score if
6279 * there was already an element in the sorted set. */
6280 return;
6281 }
6282 } else {
6283 *score = scoreval;
6284 }
6285
6286 /* What follows is a simple remove and re-insert operation that is common
6287 * to both ZADD and ZINCRBY... */
6288 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
6289 /* case 1: New element */
6290 incrRefCount(ele); /* added to hash */
6291 zslInsert(zs->zsl,*score,ele);
6292 incrRefCount(ele); /* added to skiplist */
6293 server.dirty++;
6294 if (doincrement)
6295 addReplyDouble(c,*score);
6296 else
6297 addReply(c,shared.cone);
6298 } else {
6299 dictEntry *de;
6300 double *oldscore;
6301
6302 /* case 2: Score update operation */
6303 de = dictFind(zs->dict,ele);
6304 redisAssert(de != NULL);
6305 oldscore = dictGetEntryVal(de);
6306 if (*score != *oldscore) {
6307 int deleted;
6308
6309 /* Remove and insert the element in the skip list with new score */
6310 deleted = zslDelete(zs->zsl,*oldscore,ele);
6311 redisAssert(deleted != 0);
6312 zslInsert(zs->zsl,*score,ele);
6313 incrRefCount(ele);
6314 /* Update the score in the hash table */
6315 dictReplace(zs->dict,ele,score);
6316 server.dirty++;
6317 } else {
6318 zfree(score);
6319 }
6320 if (doincrement)
6321 addReplyDouble(c,*score);
6322 else
6323 addReply(c,shared.czero);
6324 }
6325 }
6326
6327 static void zaddCommand(redisClient *c) {
6328 double scoreval;
6329
6330 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
6331 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
6332 }
6333
6334 static void zincrbyCommand(redisClient *c) {
6335 double scoreval;
6336
6337 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
6338 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
6339 }
6340
6341 static void zremCommand(redisClient *c) {
6342 robj *zsetobj;
6343 zset *zs;
6344 dictEntry *de;
6345 double *oldscore;
6346 int deleted;
6347
6348 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6349 checkType(c,zsetobj,REDIS_ZSET)) return;
6350
6351 zs = zsetobj->ptr;
6352 de = dictFind(zs->dict,c->argv[2]);
6353 if (de == NULL) {
6354 addReply(c,shared.czero);
6355 return;
6356 }
6357 /* Delete from the skiplist */
6358 oldscore = dictGetEntryVal(de);
6359 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
6360 redisAssert(deleted != 0);
6361
6362 /* Delete from the hash table */
6363 dictDelete(zs->dict,c->argv[2]);
6364 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
6365 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
6366 server.dirty++;
6367 addReply(c,shared.cone);
6368 }
6369
6370 static void zremrangebyscoreCommand(redisClient *c) {
6371 double min;
6372 double max;
6373 long deleted;
6374 robj *zsetobj;
6375 zset *zs;
6376
6377 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
6378 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
6379
6380 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6381 checkType(c,zsetobj,REDIS_ZSET)) return;
6382
6383 zs = zsetobj->ptr;
6384 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
6385 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
6386 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
6387 server.dirty += deleted;
6388 addReplyLongLong(c,deleted);
6389 }
6390
6391 static void zremrangebyrankCommand(redisClient *c) {
6392 long start;
6393 long end;
6394 int llen;
6395 long deleted;
6396 robj *zsetobj;
6397 zset *zs;
6398
6399 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6400 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
6401
6402 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6403 checkType(c,zsetobj,REDIS_ZSET)) return;
6404 zs = zsetobj->ptr;
6405 llen = zs->zsl->length;
6406
6407 /* convert negative indexes */
6408 if (start < 0) start = llen+start;
6409 if (end < 0) end = llen+end;
6410 if (start < 0) start = 0;
6411 if (end < 0) end = 0;
6412
6413 /* indexes sanity checks */
6414 if (start > end || start >= llen) {
6415 addReply(c,shared.czero);
6416 return;
6417 }
6418 if (end >= llen) end = llen-1;
6419
6420 /* increment start and end because zsl*Rank functions
6421 * use 1-based rank */
6422 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
6423 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
6424 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
6425 server.dirty += deleted;
6426 addReplyLongLong(c, deleted);
6427 }
6428
6429 typedef struct {
6430 dict *dict;
6431 double weight;
6432 } zsetopsrc;
6433
6434 static int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
6435 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
6436 unsigned long size1, size2;
6437 size1 = d1->dict ? dictSize(d1->dict) : 0;
6438 size2 = d2->dict ? dictSize(d2->dict) : 0;
6439 return size1 - size2;
6440 }
6441
6442 #define REDIS_AGGR_SUM 1
6443 #define REDIS_AGGR_MIN 2
6444 #define REDIS_AGGR_MAX 3
6445 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
6446
6447 inline static void zunionInterAggregate(double *target, double val, int aggregate) {
6448 if (aggregate == REDIS_AGGR_SUM) {
6449 *target = *target + val;
6450 } else if (aggregate == REDIS_AGGR_MIN) {
6451 *target = val < *target ? val : *target;
6452 } else if (aggregate == REDIS_AGGR_MAX) {
6453 *target = val > *target ? val : *target;
6454 } else {
6455 /* safety net */
6456 redisPanic("Unknown ZUNION/INTER aggregate type");
6457 }
6458 }
6459
6460 static void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
6461 int i, j, setnum;
6462 int aggregate = REDIS_AGGR_SUM;
6463 zsetopsrc *src;
6464 robj *dstobj;
6465 zset *dstzset;
6466 dictIterator *di;
6467 dictEntry *de;
6468
6469 /* expect setnum input keys to be given */
6470 setnum = atoi(c->argv[2]->ptr);
6471 if (setnum < 1) {
6472 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
6473 return;
6474 }
6475
6476 /* test if the expected number of keys would overflow */
6477 if (3+setnum > c->argc) {
6478 addReply(c,shared.syntaxerr);
6479 return;
6480 }
6481
6482 /* read keys to be used for input */
6483 src = zmalloc(sizeof(zsetopsrc) * setnum);
6484 for (i = 0, j = 3; i < setnum; i++, j++) {
6485 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
6486 if (!obj) {
6487 src[i].dict = NULL;
6488 } else {
6489 if (obj->type == REDIS_ZSET) {
6490 src[i].dict = ((zset*)obj->ptr)->dict;
6491 } else if (obj->type == REDIS_SET) {
6492 src[i].dict = (obj->ptr);
6493 } else {
6494 zfree(src);
6495 addReply(c,shared.wrongtypeerr);
6496 return;
6497 }
6498 }
6499
6500 /* default all weights to 1 */
6501 src[i].weight = 1.0;
6502 }
6503
6504 /* parse optional extra arguments */
6505 if (j < c->argc) {
6506 int remaining = c->argc - j;
6507
6508 while (remaining) {
6509 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
6510 j++; remaining--;
6511 for (i = 0; i < setnum; i++, j++, remaining--) {
6512 if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK)
6513 return;
6514 }
6515 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
6516 j++; remaining--;
6517 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
6518 aggregate = REDIS_AGGR_SUM;
6519 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
6520 aggregate = REDIS_AGGR_MIN;
6521 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
6522 aggregate = REDIS_AGGR_MAX;
6523 } else {
6524 zfree(src);
6525 addReply(c,shared.syntaxerr);
6526 return;
6527 }
6528 j++; remaining--;
6529 } else {
6530 zfree(src);
6531 addReply(c,shared.syntaxerr);
6532 return;
6533 }
6534 }
6535 }
6536
6537 /* sort sets from the smallest to largest, this will improve our
6538 * algorithm's performance */
6539 qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);
6540
6541 dstobj = createZsetObject();
6542 dstzset = dstobj->ptr;
6543
6544 if (op == REDIS_OP_INTER) {
6545 /* skip going over all entries if the smallest zset is NULL or empty */
6546 if (src[0].dict && dictSize(src[0].dict) > 0) {
6547 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6548 * from small to large, all src[i > 0].dict are non-empty too */
6549 di = dictGetIterator(src[0].dict);
6550 while((de = dictNext(di)) != NULL) {
6551 double *score = zmalloc(sizeof(double)), value;
6552 *score = src[0].weight * zunionInterDictValue(de);
6553
6554 for (j = 1; j < setnum; j++) {
6555 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
6556 if (other) {
6557 value = src[j].weight * zunionInterDictValue(other);
6558 zunionInterAggregate(score, value, aggregate);
6559 } else {
6560 break;
6561 }
6562 }
6563
6564 /* skip entry when not present in every source dict */
6565 if (j != setnum) {
6566 zfree(score);
6567 } else {
6568 robj *o = dictGetEntryKey(de);
6569 dictAdd(dstzset->dict,o,score);
6570 incrRefCount(o); /* added to dictionary */
6571 zslInsert(dstzset->zsl,*score,o);
6572 incrRefCount(o); /* added to skiplist */
6573 }
6574 }
6575 dictReleaseIterator(di);
6576 }
6577 } else if (op == REDIS_OP_UNION) {
6578 for (i = 0; i < setnum; i++) {
6579 if (!src[i].dict) continue;
6580
6581 di = dictGetIterator(src[i].dict);
6582 while((de = dictNext(di)) != NULL) {
6583 /* skip key when already processed */
6584 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
6585
6586 double *score = zmalloc(sizeof(double)), value;
6587 *score = src[i].weight * zunionInterDictValue(de);
6588
6589 /* because the zsets are sorted by size, its only possible
6590 * for sets at larger indices to hold this entry */
6591 for (j = (i+1); j < setnum; j++) {
6592 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
6593 if (other) {
6594 value = src[j].weight * zunionInterDictValue(other);
6595 zunionInterAggregate(score, value, aggregate);
6596 }
6597 }
6598
6599 robj *o = dictGetEntryKey(de);
6600 dictAdd(dstzset->dict,o,score);
6601 incrRefCount(o); /* added to dictionary */
6602 zslInsert(dstzset->zsl,*score,o);
6603 incrRefCount(o); /* added to skiplist */
6604 }
6605 dictReleaseIterator(di);
6606 }
6607 } else {
6608 /* unknown operator */
6609 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
6610 }
6611
6612 dbDelete(c->db,dstkey);
6613 if (dstzset->zsl->length) {
6614 dbAdd(c->db,dstkey,dstobj);
6615 addReplyLongLong(c, dstzset->zsl->length);
6616 server.dirty++;
6617 } else {
6618 decrRefCount(dstobj);
6619 addReply(c, shared.czero);
6620 }
6621 zfree(src);
6622 }
6623
6624 static void zunionstoreCommand(redisClient *c) {
6625 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
6626 }
6627
6628 static void zinterstoreCommand(redisClient *c) {
6629 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
6630 }
6631
6632 static void zrangeGenericCommand(redisClient *c, int reverse) {
6633 robj *o;
6634 long start;
6635 long end;
6636 int withscores = 0;
6637 int llen;
6638 int rangelen, j;
6639 zset *zsetobj;
6640 zskiplist *zsl;
6641 zskiplistNode *ln;
6642 robj *ele;
6643
6644 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6645 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
6646
6647 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
6648 withscores = 1;
6649 } else if (c->argc >= 5) {
6650 addReply(c,shared.syntaxerr);
6651 return;
6652 }
6653
6654 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6655 || checkType(c,o,REDIS_ZSET)) return;
6656 zsetobj = o->ptr;
6657 zsl = zsetobj->zsl;
6658 llen = zsl->length;
6659
6660 /* convert negative indexes */
6661 if (start < 0) start = llen+start;
6662 if (end < 0) end = llen+end;
6663 if (start < 0) start = 0;
6664 if (end < 0) end = 0;
6665
6666 /* indexes sanity checks */
6667 if (start > end || start >= llen) {
6668 /* Out of range start or start > end result in empty list */
6669 addReply(c,shared.emptymultibulk);
6670 return;
6671 }
6672 if (end >= llen) end = llen-1;
6673 rangelen = (end-start)+1;
6674
6675 /* check if starting point is trivial, before searching
6676 * the element in log(N) time */
6677 if (reverse) {
6678 ln = start == 0 ? zsl->tail : zslistTypeGetElementByRank(zsl, llen-start);
6679 } else {
6680 ln = start == 0 ?
6681 zsl->header->forward[0] : zslistTypeGetElementByRank(zsl, start+1);
6682 }
6683
6684 /* Return the result in form of a multi-bulk reply */
6685 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
6686 withscores ? (rangelen*2) : rangelen));
6687 for (j = 0; j < rangelen; j++) {
6688 ele = ln->obj;
6689 addReplyBulk(c,ele);
6690 if (withscores)
6691 addReplyDouble(c,ln->score);
6692 ln = reverse ? ln->backward : ln->forward[0];
6693 }
6694 }
6695
6696 static void zrangeCommand(redisClient *c) {
6697 zrangeGenericCommand(c,0);
6698 }
6699
6700 static void zrevrangeCommand(redisClient *c) {
6701 zrangeGenericCommand(c,1);
6702 }
6703
6704 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
6705 * If justcount is non-zero, just the count is returned. */
6706 static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
6707 robj *o;
6708 double min, max;
6709 int minex = 0, maxex = 0; /* are min or max exclusive? */
6710 int offset = 0, limit = -1;
6711 int withscores = 0;
6712 int badsyntax = 0;
6713
6714 /* Parse the min-max interval. If one of the values is prefixed
6715 * by the "(" character, it's considered "open". For instance
6716 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6717 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6718 if (((char*)c->argv[2]->ptr)[0] == '(') {
6719 min = strtod((char*)c->argv[2]->ptr+1,NULL);
6720 minex = 1;
6721 } else {
6722 min = strtod(c->argv[2]->ptr,NULL);
6723 }
6724 if (((char*)c->argv[3]->ptr)[0] == '(') {
6725 max = strtod((char*)c->argv[3]->ptr+1,NULL);
6726 maxex = 1;
6727 } else {
6728 max = strtod(c->argv[3]->ptr,NULL);
6729 }
6730
6731 /* Parse "WITHSCORES": note that if the command was called with
6732 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6733 * enter the following paths to parse WITHSCORES and LIMIT. */
6734 if (c->argc == 5 || c->argc == 8) {
6735 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
6736 withscores = 1;
6737 else
6738 badsyntax = 1;
6739 }
6740 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
6741 badsyntax = 1;
6742 if (badsyntax) {
6743 addReplySds(c,
6744 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
6745 return;
6746 }
6747
6748 /* Parse "LIMIT" */
6749 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
6750 addReply(c,shared.syntaxerr);
6751 return;
6752 } else if (c->argc == (7 + withscores)) {
6753 offset = atoi(c->argv[5]->ptr);
6754 limit = atoi(c->argv[6]->ptr);
6755 if (offset < 0) offset = 0;
6756 }
6757
6758 /* Ok, lookup the key and get the range */
6759 o = lookupKeyRead(c->db,c->argv[1]);
6760 if (o == NULL) {
6761 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
6762 } else {
6763 if (o->type != REDIS_ZSET) {
6764 addReply(c,shared.wrongtypeerr);
6765 } else {
6766 zset *zsetobj = o->ptr;
6767 zskiplist *zsl = zsetobj->zsl;
6768 zskiplistNode *ln;
6769 robj *ele, *lenobj = NULL;
6770 unsigned long rangelen = 0;
6771
6772 /* Get the first node with the score >= min, or with
6773 * score > min if 'minex' is true. */
6774 ln = zslFirstWithScore(zsl,min);
6775 while (minex && ln && ln->score == min) ln = ln->forward[0];
6776
6777 if (ln == NULL) {
6778 /* No element matching the speciifed interval */
6779 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
6780 return;
6781 }
6782
6783 /* We don't know in advance how many matching elements there
6784 * are in the list, so we push this object that will represent
6785 * the multi-bulk length in the output buffer, and will "fix"
6786 * it later */
6787 if (!justcount) {
6788 lenobj = createObject(REDIS_STRING,NULL);
6789 addReply(c,lenobj);
6790 decrRefCount(lenobj);
6791 }
6792
6793 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
6794 if (offset) {
6795 offset--;
6796 ln = ln->forward[0];
6797 continue;
6798 }
6799 if (limit == 0) break;
6800 if (!justcount) {
6801 ele = ln->obj;
6802 addReplyBulk(c,ele);
6803 if (withscores)
6804 addReplyDouble(c,ln->score);
6805 }
6806 ln = ln->forward[0];
6807 rangelen++;
6808 if (limit > 0) limit--;
6809 }
6810 if (justcount) {
6811 addReplyLongLong(c,(long)rangelen);
6812 } else {
6813 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
6814 withscores ? (rangelen*2) : rangelen);
6815 }
6816 }
6817 }
6818 }
6819
6820 static void zrangebyscoreCommand(redisClient *c) {
6821 genericZrangebyscoreCommand(c,0);
6822 }
6823
6824 static void zcountCommand(redisClient *c) {
6825 genericZrangebyscoreCommand(c,1);
6826 }
6827
6828 static void zcardCommand(redisClient *c) {
6829 robj *o;
6830 zset *zs;
6831
6832 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6833 checkType(c,o,REDIS_ZSET)) return;
6834
6835 zs = o->ptr;
6836 addReplyUlong(c,zs->zsl->length);
6837 }
6838
6839 static void zscoreCommand(redisClient *c) {
6840 robj *o;
6841 zset *zs;
6842 dictEntry *de;
6843
6844 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6845 checkType(c,o,REDIS_ZSET)) return;
6846
6847 zs = o->ptr;
6848 de = dictFind(zs->dict,c->argv[2]);
6849 if (!de) {
6850 addReply(c,shared.nullbulk);
6851 } else {
6852 double *score = dictGetEntryVal(de);
6853
6854 addReplyDouble(c,*score);
6855 }
6856 }
6857
6858 static void zrankGenericCommand(redisClient *c, int reverse) {
6859 robj *o;
6860 zset *zs;
6861 zskiplist *zsl;
6862 dictEntry *de;
6863 unsigned long rank;
6864 double *score;
6865
6866 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6867 checkType(c,o,REDIS_ZSET)) return;
6868
6869 zs = o->ptr;
6870 zsl = zs->zsl;
6871 de = dictFind(zs->dict,c->argv[2]);
6872 if (!de) {
6873 addReply(c,shared.nullbulk);
6874 return;
6875 }
6876
6877 score = dictGetEntryVal(de);
6878 rank = zslistTypeGetRank(zsl, *score, c->argv[2]);
6879 if (rank) {
6880 if (reverse) {
6881 addReplyLongLong(c, zsl->length - rank);
6882 } else {
6883 addReplyLongLong(c, rank-1);
6884 }
6885 } else {
6886 addReply(c,shared.nullbulk);
6887 }
6888 }
6889
6890 static void zrankCommand(redisClient *c) {
6891 zrankGenericCommand(c, 0);
6892 }
6893
6894 static void zrevrankCommand(redisClient *c) {
6895 zrankGenericCommand(c, 1);
6896 }
6897
6898 /* ========================= Hashes utility functions ======================= */
6899 #define REDIS_HASH_KEY 1
6900 #define REDIS_HASH_VALUE 2
6901
6902 /* Check the length of a number of objects to see if we need to convert a
6903 * zipmap to a real hash. Note that we only check string encoded objects
6904 * as their string length can be queried in constant time. */
6905 static void hashTypeTryConversion(robj *subject, robj **argv, int start, int end) {
6906 int i;
6907 if (subject->encoding != REDIS_ENCODING_ZIPMAP) return;
6908
6909 for (i = start; i <= end; i++) {
6910 if (argv[i]->encoding == REDIS_ENCODING_RAW &&
6911 sdslen(argv[i]->ptr) > server.hash_max_zipmap_value)
6912 {
6913 convertToRealHash(subject);
6914 return;
6915 }
6916 }
6917 }
6918
6919 /* Encode given objects in-place when the hash uses a dict. */
6920 static void hashTypeTryObjectEncoding(robj *subject, robj **o1, robj **o2) {
6921 if (subject->encoding == REDIS_ENCODING_HT) {
6922 if (o1) *o1 = tryObjectEncoding(*o1);
6923 if (o2) *o2 = tryObjectEncoding(*o2);
6924 }
6925 }
6926
6927 /* Get the value from a hash identified by key. Returns either a string
6928 * object or NULL if the value cannot be found. The refcount of the object
6929 * is always increased by 1 when the value was found. */
6930 static robj *hashTypeGet(robj *o, robj *key) {
6931 robj *value = NULL;
6932 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6933 unsigned char *v;
6934 unsigned int vlen;
6935 key = getDecodedObject(key);
6936 if (zipmapGet(o->ptr,key->ptr,sdslen(key->ptr),&v,&vlen)) {
6937 value = createStringObject((char*)v,vlen);
6938 }
6939 decrRefCount(key);
6940 } else {
6941 dictEntry *de = dictFind(o->ptr,key);
6942 if (de != NULL) {
6943 value = dictGetEntryVal(de);
6944 incrRefCount(value);
6945 }
6946 }
6947 return value;
6948 }
6949
6950 /* Test if the key exists in the given hash. Returns 1 if the key
6951 * exists and 0 when it doesn't. */
6952 static int hashTypeExists(robj *o, robj *key) {
6953 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6954 key = getDecodedObject(key);
6955 if (zipmapExists(o->ptr,key->ptr,sdslen(key->ptr))) {
6956 decrRefCount(key);
6957 return 1;
6958 }
6959 decrRefCount(key);
6960 } else {
6961 if (dictFind(o->ptr,key) != NULL) {
6962 return 1;
6963 }
6964 }
6965 return 0;
6966 }
6967
6968 /* Add an element, discard the old if the key already exists.
6969 * Return 0 on insert and 1 on update. */
6970 static int hashTypeSet(robj *o, robj *key, robj *value) {
6971 int update = 0;
6972 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6973 key = getDecodedObject(key);
6974 value = getDecodedObject(value);
6975 o->ptr = zipmapSet(o->ptr,
6976 key->ptr,sdslen(key->ptr),
6977 value->ptr,sdslen(value->ptr), &update);
6978 decrRefCount(key);
6979 decrRefCount(value);
6980
6981 /* Check if the zipmap needs to be upgraded to a real hash table */
6982 if (zipmapLen(o->ptr) > server.hash_max_zipmap_entries)
6983 convertToRealHash(o);
6984 } else {
6985 if (dictReplace(o->ptr,key,value)) {
6986 /* Insert */
6987 incrRefCount(key);
6988 } else {
6989 /* Update */
6990 update = 1;
6991 }
6992 incrRefCount(value);
6993 }
6994 return update;
6995 }
6996
6997 /* Delete an element from a hash.
6998 * Return 1 on deleted and 0 on not found. */
6999 static int hashTypeDelete(robj *o, robj *key) {
7000 int deleted = 0;
7001 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
7002 key = getDecodedObject(key);
7003 o->ptr = zipmapDel(o->ptr,key->ptr,sdslen(key->ptr), &deleted);
7004 decrRefCount(key);
7005 } else {
7006 deleted = dictDelete((dict*)o->ptr,key) == DICT_OK;
7007 /* Always check if the dictionary needs a resize after a delete. */
7008 if (deleted && htNeedsResize(o->ptr)) dictResize(o->ptr);
7009 }
7010 return deleted;
7011 }
7012
7013 /* Return the number of elements in a hash. */
7014 static unsigned long hashTypeLength(robj *o) {
7015 return (o->encoding == REDIS_ENCODING_ZIPMAP) ?
7016 zipmapLen((unsigned char*)o->ptr) : dictSize((dict*)o->ptr);
7017 }
7018
7019 /* Structure to hold hash iteration abstration. Note that iteration over
7020 * hashes involves both fields and values. Because it is possible that
7021 * not both are required, store pointers in the iterator to avoid
7022 * unnecessary memory allocation for fields/values. */
7023 typedef struct {
7024 int encoding;
7025 unsigned char *zi;
7026 unsigned char *zk, *zv;
7027 unsigned int zklen, zvlen;
7028
7029 dictIterator *di;
7030 dictEntry *de;
7031 } hashTypeIterator;
7032
7033 static hashTypeIterator *hashTypeInitIterator(robj *subject) {
7034 hashTypeIterator *hi = zmalloc(sizeof(hashTypeIterator));
7035 hi->encoding = subject->encoding;
7036 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
7037 hi->zi = zipmapRewind(subject->ptr);
7038 } else if (hi->encoding == REDIS_ENCODING_HT) {
7039 hi->di = dictGetIterator(subject->ptr);
7040 } else {
7041 redisAssert(NULL);
7042 }
7043 return hi;
7044 }
7045
7046 static void hashTypeReleaseIterator(hashTypeIterator *hi) {
7047 if (hi->encoding == REDIS_ENCODING_HT) {
7048 dictReleaseIterator(hi->di);
7049 }
7050 zfree(hi);
7051 }
7052
7053 /* Move to the next entry in the hash. Return REDIS_OK when the next entry
7054 * could be found and REDIS_ERR when the iterator reaches the end. */
7055 static int hashTypeNext(hashTypeIterator *hi) {
7056 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
7057 if ((hi->zi = zipmapNext(hi->zi, &hi->zk, &hi->zklen,
7058 &hi->zv, &hi->zvlen)) == NULL) return REDIS_ERR;
7059 } else {
7060 if ((hi->de = dictNext(hi->di)) == NULL) return REDIS_ERR;
7061 }
7062 return REDIS_OK;
7063 }
7064
7065 /* Get key or value object at current iteration position.
7066 * This increases the refcount of the field object by 1. */
7067 static robj *hashTypeCurrent(hashTypeIterator *hi, int what) {
7068 robj *o;
7069 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
7070 if (what & REDIS_HASH_KEY) {
7071 o = createStringObject((char*)hi->zk,hi->zklen);
7072 } else {
7073 o = createStringObject((char*)hi->zv,hi->zvlen);
7074 }
7075 } else {
7076 if (what & REDIS_HASH_KEY) {
7077 o = dictGetEntryKey(hi->de);
7078 } else {
7079 o = dictGetEntryVal(hi->de);
7080 }
7081 incrRefCount(o);
7082 }
7083 return o;
7084 }
7085
7086 static robj *hashTypeLookupWriteOrCreate(redisClient *c, robj *key) {
7087 robj *o = lookupKeyWrite(c->db,key);
7088 if (o == NULL) {
7089 o = createHashObject();
7090 dbAdd(c->db,key,o);
7091 } else {
7092 if (o->type != REDIS_HASH) {
7093 addReply(c,shared.wrongtypeerr);
7094 return NULL;
7095 }
7096 }
7097 return o;
7098 }
7099
7100 /* ============================= Hash commands ============================== */
7101 static void hsetCommand(redisClient *c) {
7102 int update;
7103 robj *o;
7104
7105 if ((o = hashTypeLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
7106 hashTypeTryConversion(o,c->argv,2,3);
7107 hashTypeTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
7108 update = hashTypeSet(o,c->argv[2],c->argv[3]);
7109 addReply(c, update ? shared.czero : shared.cone);
7110 server.dirty++;
7111 }
7112
7113 static void hsetnxCommand(redisClient *c) {
7114 robj *o;
7115 if ((o = hashTypeLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
7116 hashTypeTryConversion(o,c->argv,2,3);
7117
7118 if (hashTypeExists(o, c->argv[2])) {
7119 addReply(c, shared.czero);
7120 } else {
7121 hashTypeTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
7122 hashTypeSet(o,c->argv[2],c->argv[3]);
7123 addReply(c, shared.cone);
7124 server.dirty++;
7125 }
7126 }
7127
7128 static void hmsetCommand(redisClient *c) {
7129 int i;
7130 robj *o;
7131
7132 if ((c->argc % 2) == 1) {
7133 addReplySds(c,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
7134 return;
7135 }
7136
7137 if ((o = hashTypeLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
7138 hashTypeTryConversion(o,c->argv,2,c->argc-1);
7139 for (i = 2; i < c->argc; i += 2) {
7140 hashTypeTryObjectEncoding(o,&c->argv[i], &c->argv[i+1]);
7141 hashTypeSet(o,c->argv[i],c->argv[i+1]);
7142 }
7143 addReply(c, shared.ok);
7144 server.dirty++;
7145 }
7146
7147 static void hincrbyCommand(redisClient *c) {
7148 long long value, incr;
7149 robj *o, *current, *new;
7150
7151 if (getLongLongFromObjectOrReply(c,c->argv[3],&incr,NULL) != REDIS_OK) return;
7152 if ((o = hashTypeLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
7153 if ((current = hashTypeGet(o,c->argv[2])) != NULL) {
7154 if (getLongLongFromObjectOrReply(c,current,&value,
7155 "hash value is not an integer") != REDIS_OK) {
7156 decrRefCount(current);
7157 return;
7158 }
7159 decrRefCount(current);
7160 } else {
7161 value = 0;
7162 }
7163
7164 value += incr;
7165 new = createStringObjectFromLongLong(value);
7166 hashTypeTryObjectEncoding(o,&c->argv[2],NULL);
7167 hashTypeSet(o,c->argv[2],new);
7168 decrRefCount(new);
7169 addReplyLongLong(c,value);
7170 server.dirty++;
7171 }
7172
7173 static void hgetCommand(redisClient *c) {
7174 robj *o, *value;
7175 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
7176 checkType(c,o,REDIS_HASH)) return;
7177
7178 if ((value = hashTypeGet(o,c->argv[2])) != NULL) {
7179 addReplyBulk(c,value);
7180 decrRefCount(value);
7181 } else {
7182 addReply(c,shared.nullbulk);
7183 }
7184 }
7185
7186 static void hmgetCommand(redisClient *c) {
7187 int i;
7188 robj *o, *value;
7189 o = lookupKeyRead(c->db,c->argv[1]);
7190 if (o != NULL && o->type != REDIS_HASH) {
7191 addReply(c,shared.wrongtypeerr);
7192 }
7193
7194 /* Note the check for o != NULL happens inside the loop. This is
7195 * done because objects that cannot be found are considered to be
7196 * an empty hash. The reply should then be a series of NULLs. */
7197 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-2));
7198 for (i = 2; i < c->argc; i++) {
7199 if (o != NULL && (value = hashTypeGet(o,c->argv[i])) != NULL) {
7200 addReplyBulk(c,value);
7201 decrRefCount(value);
7202 } else {
7203 addReply(c,shared.nullbulk);
7204 }
7205 }
7206 }
7207
7208 static void hdelCommand(redisClient *c) {
7209 robj *o;
7210 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
7211 checkType(c,o,REDIS_HASH)) return;
7212
7213 if (hashTypeDelete(o,c->argv[2])) {
7214 if (hashTypeLength(o) == 0) dbDelete(c->db,c->argv[1]);
7215 addReply(c,shared.cone);
7216 server.dirty++;
7217 } else {
7218 addReply(c,shared.czero);
7219 }
7220 }
7221
7222 static void hlenCommand(redisClient *c) {
7223 robj *o;
7224 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
7225 checkType(c,o,REDIS_HASH)) return;
7226
7227 addReplyUlong(c,hashTypeLength(o));
7228 }
7229
7230 static void genericHgetallCommand(redisClient *c, int flags) {
7231 robj *o, *lenobj, *obj;
7232 unsigned long count = 0;
7233 hashTypeIterator *hi;
7234
7235 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
7236 || checkType(c,o,REDIS_HASH)) return;
7237
7238 lenobj = createObject(REDIS_STRING,NULL);
7239 addReply(c,lenobj);
7240 decrRefCount(lenobj);
7241
7242 hi = hashTypeInitIterator(o);
7243 while (hashTypeNext(hi) != REDIS_ERR) {
7244 if (flags & REDIS_HASH_KEY) {
7245 obj = hashTypeCurrent(hi,REDIS_HASH_KEY);
7246 addReplyBulk(c,obj);
7247 decrRefCount(obj);
7248 count++;
7249 }
7250 if (flags & REDIS_HASH_VALUE) {
7251 obj = hashTypeCurrent(hi,REDIS_HASH_VALUE);
7252 addReplyBulk(c,obj);
7253 decrRefCount(obj);
7254 count++;
7255 }
7256 }
7257 hashTypeReleaseIterator(hi);
7258
7259 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",count);
7260 }
7261
7262 static void hkeysCommand(redisClient *c) {
7263 genericHgetallCommand(c,REDIS_HASH_KEY);
7264 }
7265
7266 static void hvalsCommand(redisClient *c) {
7267 genericHgetallCommand(c,REDIS_HASH_VALUE);
7268 }
7269
7270 static void hgetallCommand(redisClient *c) {
7271 genericHgetallCommand(c,REDIS_HASH_KEY|REDIS_HASH_VALUE);
7272 }
7273
7274 static void hexistsCommand(redisClient *c) {
7275 robj *o;
7276 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
7277 checkType(c,o,REDIS_HASH)) return;
7278
7279 addReply(c, hashTypeExists(o,c->argv[2]) ? shared.cone : shared.czero);
7280 }
7281
7282 static void convertToRealHash(robj *o) {
7283 unsigned char *key, *val, *p, *zm = o->ptr;
7284 unsigned int klen, vlen;
7285 dict *dict = dictCreate(&hashDictType,NULL);
7286
7287 assert(o->type == REDIS_HASH && o->encoding != REDIS_ENCODING_HT);
7288 p = zipmapRewind(zm);
7289 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
7290 robj *keyobj, *valobj;
7291
7292 keyobj = createStringObject((char*)key,klen);
7293 valobj = createStringObject((char*)val,vlen);
7294 keyobj = tryObjectEncoding(keyobj);
7295 valobj = tryObjectEncoding(valobj);
7296 dictAdd(dict,keyobj,valobj);
7297 }
7298 o->encoding = REDIS_ENCODING_HT;
7299 o->ptr = dict;
7300 zfree(zm);
7301 }
7302
7303 /* ========================= Non type-specific commands ==================== */
7304
7305 static void flushdbCommand(redisClient *c) {
7306 server.dirty += dictSize(c->db->dict);
7307 touchWatchedKeysOnFlush(c->db->id);
7308 dictEmpty(c->db->dict);
7309 dictEmpty(c->db->expires);
7310 addReply(c,shared.ok);
7311 }
7312
7313 static void flushallCommand(redisClient *c) {
7314 touchWatchedKeysOnFlush(-1);
7315 server.dirty += emptyDb();
7316 addReply(c,shared.ok);
7317 if (server.bgsavechildpid != -1) {
7318 kill(server.bgsavechildpid,SIGKILL);
7319 rdbRemoveTempFile(server.bgsavechildpid);
7320 }
7321 rdbSave(server.dbfilename);
7322 server.dirty++;
7323 }
7324
7325 static redisSortOperation *createSortOperation(int type, robj *pattern) {
7326 redisSortOperation *so = zmalloc(sizeof(*so));
7327 so->type = type;
7328 so->pattern = pattern;
7329 return so;
7330 }
7331
7332 /* Return the value associated to the key with a name obtained
7333 * substituting the first occurence of '*' in 'pattern' with 'subst'.
7334 * The returned object will always have its refcount increased by 1
7335 * when it is non-NULL. */
7336 static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
7337 char *p, *f;
7338 sds spat, ssub;
7339 robj keyobj, fieldobj, *o;
7340 int prefixlen, sublen, postfixlen, fieldlen;
7341 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
7342 struct {
7343 long len;
7344 long free;
7345 char buf[REDIS_SORTKEY_MAX+1];
7346 } keyname, fieldname;
7347
7348 /* If the pattern is "#" return the substitution object itself in order
7349 * to implement the "SORT ... GET #" feature. */
7350 spat = pattern->ptr;
7351 if (spat[0] == '#' && spat[1] == '\0') {
7352 incrRefCount(subst);
7353 return subst;
7354 }
7355
7356 /* The substitution object may be specially encoded. If so we create
7357 * a decoded object on the fly. Otherwise getDecodedObject will just
7358 * increment the ref count, that we'll decrement later. */
7359 subst = getDecodedObject(subst);
7360
7361 ssub = subst->ptr;
7362 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
7363 p = strchr(spat,'*');
7364 if (!p) {
7365 decrRefCount(subst);
7366 return NULL;
7367 }
7368
7369 /* Find out if we're dealing with a hash dereference. */
7370 if ((f = strstr(p+1, "->")) != NULL) {
7371 fieldlen = sdslen(spat)-(f-spat);
7372 /* this also copies \0 character */
7373 memcpy(fieldname.buf,f+2,fieldlen-1);
7374 fieldname.len = fieldlen-2;
7375 } else {
7376 fieldlen = 0;
7377 }
7378
7379 prefixlen = p-spat;
7380 sublen = sdslen(ssub);
7381 postfixlen = sdslen(spat)-(prefixlen+1)-fieldlen;
7382 memcpy(keyname.buf,spat,prefixlen);
7383 memcpy(keyname.buf+prefixlen,ssub,sublen);
7384 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
7385 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
7386 keyname.len = prefixlen+sublen+postfixlen;
7387 decrRefCount(subst);
7388
7389 /* Lookup substituted key */
7390 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2));
7391 o = lookupKeyRead(db,&keyobj);
7392 if (o == NULL) return NULL;
7393
7394 if (fieldlen > 0) {
7395 if (o->type != REDIS_HASH || fieldname.len < 1) return NULL;
7396
7397 /* Retrieve value from hash by the field name. This operation
7398 * already increases the refcount of the returned object. */
7399 initStaticStringObject(fieldobj,((char*)&fieldname)+(sizeof(long)*2));
7400 o = hashTypeGet(o, &fieldobj);
7401 } else {
7402 if (o->type != REDIS_STRING) return NULL;
7403
7404 /* Every object that this function returns needs to have its refcount
7405 * increased. sortCommand decreases it again. */
7406 incrRefCount(o);
7407 }
7408
7409 return o;
7410 }
7411
7412 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
7413 * the additional parameter is not standard but a BSD-specific we have to
7414 * pass sorting parameters via the global 'server' structure */
7415 static int sortCompare(const void *s1, const void *s2) {
7416 const redisSortObject *so1 = s1, *so2 = s2;
7417 int cmp;
7418
7419 if (!server.sort_alpha) {
7420 /* Numeric sorting. Here it's trivial as we precomputed scores */
7421 if (so1->u.score > so2->u.score) {
7422 cmp = 1;
7423 } else if (so1->u.score < so2->u.score) {
7424 cmp = -1;
7425 } else {
7426 cmp = 0;
7427 }
7428 } else {
7429 /* Alphanumeric sorting */
7430 if (server.sort_bypattern) {
7431 if (!so1->u.cmpobj || !so2->u.cmpobj) {
7432 /* At least one compare object is NULL */
7433 if (so1->u.cmpobj == so2->u.cmpobj)
7434 cmp = 0;
7435 else if (so1->u.cmpobj == NULL)
7436 cmp = -1;
7437 else
7438 cmp = 1;
7439 } else {
7440 /* We have both the objects, use strcoll */
7441 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
7442 }
7443 } else {
7444 /* Compare elements directly. */
7445 cmp = compareStringObjects(so1->obj,so2->obj);
7446 }
7447 }
7448 return server.sort_desc ? -cmp : cmp;
7449 }
7450
7451 /* The SORT command is the most complex command in Redis. Warning: this code
7452 * is optimized for speed and a bit less for readability */
7453 static void sortCommand(redisClient *c) {
7454 list *operations;
7455 unsigned int outputlen = 0;
7456 int desc = 0, alpha = 0;
7457 int limit_start = 0, limit_count = -1, start, end;
7458 int j, dontsort = 0, vectorlen;
7459 int getop = 0; /* GET operation counter */
7460 robj *sortval, *sortby = NULL, *storekey = NULL;
7461 redisSortObject *vector; /* Resulting vector to sort */
7462
7463 /* Lookup the key to sort. It must be of the right types */
7464 sortval = lookupKeyRead(c->db,c->argv[1]);
7465 if (sortval == NULL) {
7466 addReply(c,shared.emptymultibulk);
7467 return;
7468 }
7469 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
7470 sortval->type != REDIS_ZSET)
7471 {
7472 addReply(c,shared.wrongtypeerr);
7473 return;
7474 }
7475
7476 /* Create a list of operations to perform for every sorted element.
7477 * Operations can be GET/DEL/INCR/DECR */
7478 operations = listCreate();
7479 listSetFreeMethod(operations,zfree);
7480 j = 2;
7481
7482 /* Now we need to protect sortval incrementing its count, in the future
7483 * SORT may have options able to overwrite/delete keys during the sorting
7484 * and the sorted key itself may get destroied */
7485 incrRefCount(sortval);
7486
7487 /* The SORT command has an SQL-alike syntax, parse it */
7488 while(j < c->argc) {
7489 int leftargs = c->argc-j-1;
7490 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
7491 desc = 0;
7492 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
7493 desc = 1;
7494 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
7495 alpha = 1;
7496 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
7497 limit_start = atoi(c->argv[j+1]->ptr);
7498 limit_count = atoi(c->argv[j+2]->ptr);
7499 j+=2;
7500 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
7501 storekey = c->argv[j+1];
7502 j++;
7503 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
7504 sortby = c->argv[j+1];
7505 /* If the BY pattern does not contain '*', i.e. it is constant,
7506 * we don't need to sort nor to lookup the weight keys. */
7507 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
7508 j++;
7509 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
7510 listAddNodeTail(operations,createSortOperation(
7511 REDIS_SORT_GET,c->argv[j+1]));
7512 getop++;
7513 j++;
7514 } else {
7515 decrRefCount(sortval);
7516 listRelease(operations);
7517 addReply(c,shared.syntaxerr);
7518 return;
7519 }
7520 j++;
7521 }
7522
7523 /* Load the sorting vector with all the objects to sort */
7524 switch(sortval->type) {
7525 case REDIS_LIST: vectorlen = listTypeLength(sortval); break;
7526 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
7527 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
7528 default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
7529 }
7530 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
7531 j = 0;
7532
7533 if (sortval->type == REDIS_LIST) {
7534 listTypeIterator *li = listTypeInitIterator(sortval,0,REDIS_TAIL);
7535 listTypeEntry entry;
7536 while(listTypeNext(li,&entry)) {
7537 vector[j].obj = listTypeGet(&entry);
7538 vector[j].u.score = 0;
7539 vector[j].u.cmpobj = NULL;
7540 j++;
7541 }
7542 listTypeReleaseIterator(li);
7543 } else {
7544 dict *set;
7545 dictIterator *di;
7546 dictEntry *setele;
7547
7548 if (sortval->type == REDIS_SET) {
7549 set = sortval->ptr;
7550 } else {
7551 zset *zs = sortval->ptr;
7552 set = zs->dict;
7553 }
7554
7555 di = dictGetIterator(set);
7556 while((setele = dictNext(di)) != NULL) {
7557 vector[j].obj = dictGetEntryKey(setele);
7558 vector[j].u.score = 0;
7559 vector[j].u.cmpobj = NULL;
7560 j++;
7561 }
7562 dictReleaseIterator(di);
7563 }
7564 redisAssert(j == vectorlen);
7565
7566 /* Now it's time to load the right scores in the sorting vector */
7567 if (dontsort == 0) {
7568 for (j = 0; j < vectorlen; j++) {
7569 robj *byval;
7570 if (sortby) {
7571 /* lookup value to sort by */
7572 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
7573 if (!byval) continue;
7574 } else {
7575 /* use object itself to sort by */
7576 byval = vector[j].obj;
7577 }
7578
7579 if (alpha) {
7580 if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
7581 } else {
7582 if (byval->encoding == REDIS_ENCODING_RAW) {
7583 vector[j].u.score = strtod(byval->ptr,NULL);
7584 } else if (byval->encoding == REDIS_ENCODING_INT) {
7585 /* Don't need to decode the object if it's
7586 * integer-encoded (the only encoding supported) so
7587 * far. We can just cast it */
7588 vector[j].u.score = (long)byval->ptr;
7589 } else {
7590 redisAssert(1 != 1);
7591 }
7592 }
7593
7594 /* when the object was retrieved using lookupKeyByPattern,
7595 * its refcount needs to be decreased. */
7596 if (sortby) {
7597 decrRefCount(byval);
7598 }
7599 }
7600 }
7601
7602 /* We are ready to sort the vector... perform a bit of sanity check
7603 * on the LIMIT option too. We'll use a partial version of quicksort. */
7604 start = (limit_start < 0) ? 0 : limit_start;
7605 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
7606 if (start >= vectorlen) {
7607 start = vectorlen-1;
7608 end = vectorlen-2;
7609 }
7610 if (end >= vectorlen) end = vectorlen-1;
7611
7612 if (dontsort == 0) {
7613 server.sort_desc = desc;
7614 server.sort_alpha = alpha;
7615 server.sort_bypattern = sortby ? 1 : 0;
7616 if (sortby && (start != 0 || end != vectorlen-1))
7617 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
7618 else
7619 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
7620 }
7621
7622 /* Send command output to the output buffer, performing the specified
7623 * GET/DEL/INCR/DECR operations if any. */
7624 outputlen = getop ? getop*(end-start+1) : end-start+1;
7625 if (storekey == NULL) {
7626 /* STORE option not specified, sent the sorting result to client */
7627 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
7628 for (j = start; j <= end; j++) {
7629 listNode *ln;
7630 listIter li;
7631
7632 if (!getop) addReplyBulk(c,vector[j].obj);
7633 listRewind(operations,&li);
7634 while((ln = listNext(&li))) {
7635 redisSortOperation *sop = ln->value;
7636 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7637 vector[j].obj);
7638
7639 if (sop->type == REDIS_SORT_GET) {
7640 if (!val) {
7641 addReply(c,shared.nullbulk);
7642 } else {
7643 addReplyBulk(c,val);
7644 decrRefCount(val);
7645 }
7646 } else {
7647 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
7648 }
7649 }
7650 }
7651 } else {
7652 robj *sobj = createZiplistObject();
7653
7654 /* STORE option specified, set the sorting result as a List object */
7655 for (j = start; j <= end; j++) {
7656 listNode *ln;
7657 listIter li;
7658
7659 if (!getop) {
7660 listTypePush(sobj,vector[j].obj,REDIS_TAIL);
7661 } else {
7662 listRewind(operations,&li);
7663 while((ln = listNext(&li))) {
7664 redisSortOperation *sop = ln->value;
7665 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7666 vector[j].obj);
7667
7668 if (sop->type == REDIS_SORT_GET) {
7669 if (!val) val = createStringObject("",0);
7670
7671 /* listTypePush does an incrRefCount, so we should take care
7672 * care of the incremented refcount caused by either
7673 * lookupKeyByPattern or createStringObject("",0) */
7674 listTypePush(sobj,val,REDIS_TAIL);
7675 decrRefCount(val);
7676 } else {
7677 /* always fails */
7678 redisAssert(sop->type == REDIS_SORT_GET);
7679 }
7680 }
7681 }
7682 }
7683 dbReplace(c->db,storekey,sobj);
7684 /* Note: we add 1 because the DB is dirty anyway since even if the
7685 * SORT result is empty a new key is set and maybe the old content
7686 * replaced. */
7687 server.dirty += 1+outputlen;
7688 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
7689 }
7690
7691 /* Cleanup */
7692 if (sortval->type == REDIS_LIST)
7693 for (j = 0; j < vectorlen; j++)
7694 decrRefCount(vector[j].obj);
7695 decrRefCount(sortval);
7696 listRelease(operations);
7697 for (j = 0; j < vectorlen; j++) {
7698 if (alpha && vector[j].u.cmpobj)
7699 decrRefCount(vector[j].u.cmpobj);
7700 }
7701 zfree(vector);
7702 }
7703
7704 /* Convert an amount of bytes into a human readable string in the form
7705 * of 100B, 2G, 100M, 4K, and so forth. */
7706 static void bytesToHuman(char *s, unsigned long long n) {
7707 double d;
7708
7709 if (n < 1024) {
7710 /* Bytes */
7711 sprintf(s,"%lluB",n);
7712 return;
7713 } else if (n < (1024*1024)) {
7714 d = (double)n/(1024);
7715 sprintf(s,"%.2fK",d);
7716 } else if (n < (1024LL*1024*1024)) {
7717 d = (double)n/(1024*1024);
7718 sprintf(s,"%.2fM",d);
7719 } else if (n < (1024LL*1024*1024*1024)) {
7720 d = (double)n/(1024LL*1024*1024);
7721 sprintf(s,"%.2fG",d);
7722 }
7723 }
7724
7725 /* Create the string returned by the INFO command. This is decoupled
7726 * by the INFO command itself as we need to report the same information
7727 * on memory corruption problems. */
7728 static sds genRedisInfoString(void) {
7729 sds info;
7730 time_t uptime = time(NULL)-server.stat_starttime;
7731 int j;
7732 char hmem[64];
7733
7734 bytesToHuman(hmem,zmalloc_used_memory());
7735 info = sdscatprintf(sdsempty(),
7736 "redis_version:%s\r\n"
7737 "redis_git_sha1:%s\r\n"
7738 "redis_git_dirty:%d\r\n"
7739 "arch_bits:%s\r\n"
7740 "multiplexing_api:%s\r\n"
7741 "process_id:%ld\r\n"
7742 "uptime_in_seconds:%ld\r\n"
7743 "uptime_in_days:%ld\r\n"
7744 "connected_clients:%d\r\n"
7745 "connected_slaves:%d\r\n"
7746 "blocked_clients:%d\r\n"
7747 "used_memory:%zu\r\n"
7748 "used_memory_human:%s\r\n"
7749 "changes_since_last_save:%lld\r\n"
7750 "bgsave_in_progress:%d\r\n"
7751 "last_save_time:%ld\r\n"
7752 "bgrewriteaof_in_progress:%d\r\n"
7753 "total_connections_received:%lld\r\n"
7754 "total_commands_processed:%lld\r\n"
7755 "expired_keys:%lld\r\n"
7756 "hash_max_zipmap_entries:%zu\r\n"
7757 "hash_max_zipmap_value:%zu\r\n"
7758 "pubsub_channels:%ld\r\n"
7759 "pubsub_patterns:%u\r\n"
7760 "vm_enabled:%d\r\n"
7761 "role:%s\r\n"
7762 ,REDIS_VERSION,
7763 REDIS_GIT_SHA1,
7764 strtol(REDIS_GIT_DIRTY,NULL,10) > 0,
7765 (sizeof(long) == 8) ? "64" : "32",
7766 aeGetApiName(),
7767 (long) getpid(),
7768 uptime,
7769 uptime/(3600*24),
7770 listLength(server.clients)-listLength(server.slaves),
7771 listLength(server.slaves),
7772 server.blpop_blocked_clients,
7773 zmalloc_used_memory(),
7774 hmem,
7775 server.dirty,
7776 server.bgsavechildpid != -1,
7777 server.lastsave,
7778 server.bgrewritechildpid != -1,
7779 server.stat_numconnections,
7780 server.stat_numcommands,
7781 server.stat_expiredkeys,
7782 server.hash_max_zipmap_entries,
7783 server.hash_max_zipmap_value,
7784 dictSize(server.pubsub_channels),
7785 listLength(server.pubsub_patterns),
7786 server.vm_enabled != 0,
7787 server.masterhost == NULL ? "master" : "slave"
7788 );
7789 if (server.masterhost) {
7790 info = sdscatprintf(info,
7791 "master_host:%s\r\n"
7792 "master_port:%d\r\n"
7793 "master_link_status:%s\r\n"
7794 "master_last_io_seconds_ago:%d\r\n"
7795 ,server.masterhost,
7796 server.masterport,
7797 (server.replstate == REDIS_REPL_CONNECTED) ?
7798 "up" : "down",
7799 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
7800 );
7801 }
7802 if (server.vm_enabled) {
7803 lockThreadedIO();
7804 info = sdscatprintf(info,
7805 "vm_conf_max_memory:%llu\r\n"
7806 "vm_conf_page_size:%llu\r\n"
7807 "vm_conf_pages:%llu\r\n"
7808 "vm_stats_used_pages:%llu\r\n"
7809 "vm_stats_swapped_objects:%llu\r\n"
7810 "vm_stats_swappin_count:%llu\r\n"
7811 "vm_stats_swappout_count:%llu\r\n"
7812 "vm_stats_io_newjobs_len:%lu\r\n"
7813 "vm_stats_io_processing_len:%lu\r\n"
7814 "vm_stats_io_processed_len:%lu\r\n"
7815 "vm_stats_io_active_threads:%lu\r\n"
7816 "vm_stats_blocked_clients:%lu\r\n"
7817 ,(unsigned long long) server.vm_max_memory,
7818 (unsigned long long) server.vm_page_size,
7819 (unsigned long long) server.vm_pages,
7820 (unsigned long long) server.vm_stats_used_pages,
7821 (unsigned long long) server.vm_stats_swapped_objects,
7822 (unsigned long long) server.vm_stats_swapins,
7823 (unsigned long long) server.vm_stats_swapouts,
7824 (unsigned long) listLength(server.io_newjobs),
7825 (unsigned long) listLength(server.io_processing),
7826 (unsigned long) listLength(server.io_processed),
7827 (unsigned long) server.io_active_threads,
7828 (unsigned long) server.vm_blocked_clients
7829 );
7830 unlockThreadedIO();
7831 }
7832 for (j = 0; j < server.dbnum; j++) {
7833 long long keys, vkeys;
7834
7835 keys = dictSize(server.db[j].dict);
7836 vkeys = dictSize(server.db[j].expires);
7837 if (keys || vkeys) {
7838 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
7839 j, keys, vkeys);
7840 }
7841 }
7842 return info;
7843 }
7844
7845 static void infoCommand(redisClient *c) {
7846 sds info = genRedisInfoString();
7847 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
7848 (unsigned long)sdslen(info)));
7849 addReplySds(c,info);
7850 addReply(c,shared.crlf);
7851 }
7852
7853 static void monitorCommand(redisClient *c) {
7854 /* ignore MONITOR if aleady slave or in monitor mode */
7855 if (c->flags & REDIS_SLAVE) return;
7856
7857 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
7858 c->slaveseldb = 0;
7859 listAddNodeTail(server.monitors,c);
7860 addReply(c,shared.ok);
7861 }
7862
7863 /* ================================= Expire ================================= */
7864 static int removeExpire(redisDb *db, robj *key) {
7865 /* An expire may only be removed if there is a corresponding entry in the
7866 * main dict. Otherwise, the key will never be freed. */
7867 redisAssert(dictFind(db->dict,key->ptr) != NULL);
7868 if (dictDelete(db->expires,key->ptr) == DICT_OK) {
7869 return 1;
7870 } else {
7871 return 0;
7872 }
7873 }
7874
7875 static int setExpire(redisDb *db, robj *key, time_t when) {
7876 dictEntry *de;
7877
7878 /* Reuse the sds from the main dict in the expire dict */
7879 redisAssert((de = dictFind(db->dict,key->ptr)) != NULL);
7880 if (dictAdd(db->expires,dictGetEntryKey(de),(void*)when) == DICT_ERR) {
7881 return 0;
7882 } else {
7883 return 1;
7884 }
7885 }
7886
7887 /* Return the expire time of the specified key, or -1 if no expire
7888 * is associated with this key (i.e. the key is non volatile) */
7889 static time_t getExpire(redisDb *db, robj *key) {
7890 dictEntry *de;
7891
7892 /* No expire? return ASAP */
7893 if (dictSize(db->expires) == 0 ||
7894 (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
7895
7896 /* The entry was found in the expire dict, this means it should also
7897 * be present in the main dict (safety check). */
7898 redisAssert(dictFind(db->dict,key->ptr) != NULL);
7899 return (time_t) dictGetEntryVal(de);
7900 }
7901
7902 static int expireIfNeeded(redisDb *db, robj *key) {
7903 time_t when = getExpire(db,key);
7904 if (when < 0) return 0;
7905
7906 /* Return when this key has not expired */
7907 if (time(NULL) <= when) return 0;
7908
7909 /* Delete the key */
7910 server.stat_expiredkeys++;
7911 server.dirty++;
7912 return dbDelete(db,key);
7913 }
7914
7915 static int deleteIfVolatile(redisDb *db, robj *key) {
7916 if (getExpire(db,key) < 0) return 0;
7917
7918 /* Delete the key */
7919 server.stat_expiredkeys++;
7920 server.dirty++;
7921 return dbDelete(db,key);
7922 }
7923
7924 static void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
7925 dictEntry *de;
7926 time_t seconds;
7927
7928 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
7929
7930 seconds -= offset;
7931
7932 de = dictFind(c->db->dict,key->ptr);
7933 if (de == NULL) {
7934 addReply(c,shared.czero);
7935 return;
7936 }
7937 if (seconds <= 0) {
7938 if (dbDelete(c->db,key)) server.dirty++;
7939 addReply(c, shared.cone);
7940 return;
7941 } else {
7942 time_t when = time(NULL)+seconds;
7943 if (setExpire(c->db,key,when)) {
7944 addReply(c,shared.cone);
7945 server.dirty++;
7946 } else {
7947 addReply(c,shared.czero);
7948 }
7949 return;
7950 }
7951 }
7952
7953 static void expireCommand(redisClient *c) {
7954 expireGenericCommand(c,c->argv[1],c->argv[2],0);
7955 }
7956
7957 static void expireatCommand(redisClient *c) {
7958 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
7959 }
7960
7961 static void ttlCommand(redisClient *c) {
7962 time_t expire;
7963 int ttl = -1;
7964
7965 expire = getExpire(c->db,c->argv[1]);
7966 if (expire != -1) {
7967 ttl = (int) (expire-time(NULL));
7968 if (ttl < 0) ttl = -1;
7969 }
7970 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
7971 }
7972
7973 /* ================================ MULTI/EXEC ============================== */
7974
7975 /* Client state initialization for MULTI/EXEC */
7976 static void initClientMultiState(redisClient *c) {
7977 c->mstate.commands = NULL;
7978 c->mstate.count = 0;
7979 }
7980
7981 /* Release all the resources associated with MULTI/EXEC state */
7982 static void freeClientMultiState(redisClient *c) {
7983 int j;
7984
7985 for (j = 0; j < c->mstate.count; j++) {
7986 int i;
7987 multiCmd *mc = c->mstate.commands+j;
7988
7989 for (i = 0; i < mc->argc; i++)
7990 decrRefCount(mc->argv[i]);
7991 zfree(mc->argv);
7992 }
7993 zfree(c->mstate.commands);
7994 }
7995
7996 /* Add a new command into the MULTI commands queue */
7997 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
7998 multiCmd *mc;
7999 int j;
8000
8001 c->mstate.commands = zrealloc(c->mstate.commands,
8002 sizeof(multiCmd)*(c->mstate.count+1));
8003 mc = c->mstate.commands+c->mstate.count;
8004 mc->cmd = cmd;
8005 mc->argc = c->argc;
8006 mc->argv = zmalloc(sizeof(robj*)*c->argc);
8007 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
8008 for (j = 0; j < c->argc; j++)
8009 incrRefCount(mc->argv[j]);
8010 c->mstate.count++;
8011 }
8012
8013 static void multiCommand(redisClient *c) {
8014 if (c->flags & REDIS_MULTI) {
8015 addReplySds(c,sdsnew("-ERR MULTI calls can not be nested\r\n"));
8016 return;
8017 }
8018 c->flags |= REDIS_MULTI;
8019 addReply(c,shared.ok);
8020 }
8021
8022 static void discardCommand(redisClient *c) {
8023 if (!(c->flags & REDIS_MULTI)) {
8024 addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
8025 return;
8026 }
8027
8028 freeClientMultiState(c);
8029 initClientMultiState(c);
8030 c->flags &= (~REDIS_MULTI);
8031 unwatchAllKeys(c);
8032 addReply(c,shared.ok);
8033 }
8034
8035 /* Send a MULTI command to all the slaves and AOF file. Check the execCommand
8036 * implememntation for more information. */
8037 static void execCommandReplicateMulti(redisClient *c) {
8038 struct redisCommand *cmd;
8039 robj *multistring = createStringObject("MULTI",5);
8040
8041 cmd = lookupCommand("multi");
8042 if (server.appendonly)
8043 feedAppendOnlyFile(cmd,c->db->id,&multistring,1);
8044 if (listLength(server.slaves))
8045 replicationFeedSlaves(server.slaves,c->db->id,&multistring,1);
8046 decrRefCount(multistring);
8047 }
8048
8049 static void execCommand(redisClient *c) {
8050 int j;
8051 robj **orig_argv;
8052 int orig_argc;
8053
8054 if (!(c->flags & REDIS_MULTI)) {
8055 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
8056 return;
8057 }
8058
8059 /* Check if we need to abort the EXEC if some WATCHed key was touched.
8060 * A failed EXEC will return a multi bulk nil object. */
8061 if (c->flags & REDIS_DIRTY_CAS) {
8062 freeClientMultiState(c);
8063 initClientMultiState(c);
8064 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
8065 unwatchAllKeys(c);
8066 addReply(c,shared.nullmultibulk);
8067 return;
8068 }
8069
8070 /* Replicate a MULTI request now that we are sure the block is executed.
8071 * This way we'll deliver the MULTI/..../EXEC block as a whole and
8072 * both the AOF and the replication link will have the same consistency
8073 * and atomicity guarantees. */
8074 execCommandReplicateMulti(c);
8075
8076 /* Exec all the queued commands */
8077 unwatchAllKeys(c); /* Unwatch ASAP otherwise we'll waste CPU cycles */
8078 orig_argv = c->argv;
8079 orig_argc = c->argc;
8080 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
8081 for (j = 0; j < c->mstate.count; j++) {
8082 c->argc = c->mstate.commands[j].argc;
8083 c->argv = c->mstate.commands[j].argv;
8084 call(c,c->mstate.commands[j].cmd);
8085 }
8086 c->argv = orig_argv;
8087 c->argc = orig_argc;
8088 freeClientMultiState(c);
8089 initClientMultiState(c);
8090 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
8091 /* Make sure the EXEC command is always replicated / AOF, since we
8092 * always send the MULTI command (we can't know beforehand if the
8093 * next operations will contain at least a modification to the DB). */
8094 server.dirty++;
8095 }
8096
8097 /* =========================== Blocking Operations ========================= */
8098
8099 /* Currently Redis blocking operations support is limited to list POP ops,
8100 * so the current implementation is not fully generic, but it is also not
8101 * completely specific so it will not require a rewrite to support new
8102 * kind of blocking operations in the future.
8103 *
8104 * Still it's important to note that list blocking operations can be already
8105 * used as a notification mechanism in order to implement other blocking
8106 * operations at application level, so there must be a very strong evidence
8107 * of usefulness and generality before new blocking operations are implemented.
8108 *
8109 * This is how the current blocking POP works, we use BLPOP as example:
8110 * - If the user calls BLPOP and the key exists and contains a non empty list
8111 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
8112 * if there is not to block.
8113 * - If instead BLPOP is called and the key does not exists or the list is
8114 * empty we need to block. In order to do so we remove the notification for
8115 * new data to read in the client socket (so that we'll not serve new
8116 * requests if the blocking request is not served). Also we put the client
8117 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
8118 * blocking for this keys.
8119 * - If a PUSH operation against a key with blocked clients waiting is
8120 * performed, we serve the first in the list: basically instead to push
8121 * the new element inside the list we return it to the (first / oldest)
8122 * blocking client, unblock the client, and remove it form the list.
8123 *
8124 * The above comment and the source code should be enough in order to understand
8125 * the implementation and modify / fix it later.
8126 */
8127
8128 /* Set a client in blocking mode for the specified key, with the specified
8129 * timeout */
8130 static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
8131 dictEntry *de;
8132 list *l;
8133 int j;
8134
8135 c->blocking_keys = zmalloc(sizeof(robj*)*numkeys);
8136 c->blocking_keys_num = numkeys;
8137 c->blockingto = timeout;
8138 for (j = 0; j < numkeys; j++) {
8139 /* Add the key in the client structure, to map clients -> keys */
8140 c->blocking_keys[j] = keys[j];
8141 incrRefCount(keys[j]);
8142
8143 /* And in the other "side", to map keys -> clients */
8144 de = dictFind(c->db->blocking_keys,keys[j]);
8145 if (de == NULL) {
8146 int retval;
8147
8148 /* For every key we take a list of clients blocked for it */
8149 l = listCreate();
8150 retval = dictAdd(c->db->blocking_keys,keys[j],l);
8151 incrRefCount(keys[j]);
8152 assert(retval == DICT_OK);
8153 } else {
8154 l = dictGetEntryVal(de);
8155 }
8156 listAddNodeTail(l,c);
8157 }
8158 /* Mark the client as a blocked client */
8159 c->flags |= REDIS_BLOCKED;
8160 server.blpop_blocked_clients++;
8161 }
8162
8163 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
8164 static void unblockClientWaitingData(redisClient *c) {
8165 dictEntry *de;
8166 list *l;
8167 int j;
8168
8169 assert(c->blocking_keys != NULL);
8170 /* The client may wait for multiple keys, so unblock it for every key. */
8171 for (j = 0; j < c->blocking_keys_num; j++) {
8172 /* Remove this client from the list of clients waiting for this key. */
8173 de = dictFind(c->db->blocking_keys,c->blocking_keys[j]);
8174 assert(de != NULL);
8175 l = dictGetEntryVal(de);
8176 listDelNode(l,listSearchKey(l,c));
8177 /* If the list is empty we need to remove it to avoid wasting memory */
8178 if (listLength(l) == 0)
8179 dictDelete(c->db->blocking_keys,c->blocking_keys[j]);
8180 decrRefCount(c->blocking_keys[j]);
8181 }
8182 /* Cleanup the client structure */
8183 zfree(c->blocking_keys);
8184 c->blocking_keys = NULL;
8185 c->flags &= (~REDIS_BLOCKED);
8186 server.blpop_blocked_clients--;
8187 /* We want to process data if there is some command waiting
8188 * in the input buffer. Note that this is safe even if
8189 * unblockClientWaitingData() gets called from freeClient() because
8190 * freeClient() will be smart enough to call this function
8191 * *after* c->querybuf was set to NULL. */
8192 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
8193 }
8194
8195 /* This should be called from any function PUSHing into lists.
8196 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
8197 * 'ele' is the element pushed.
8198 *
8199 * If the function returns 0 there was no client waiting for a list push
8200 * against this key.
8201 *
8202 * If the function returns 1 there was a client waiting for a list push
8203 * against this key, the element was passed to this client thus it's not
8204 * needed to actually add it to the list and the caller should return asap. */
8205 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
8206 struct dictEntry *de;
8207 redisClient *receiver;
8208 list *l;
8209 listNode *ln;
8210
8211 de = dictFind(c->db->blocking_keys,key);
8212 if (de == NULL) return 0;
8213 l = dictGetEntryVal(de);
8214 ln = listFirst(l);
8215 assert(ln != NULL);
8216 receiver = ln->value;
8217
8218 addReplySds(receiver,sdsnew("*2\r\n"));
8219 addReplyBulk(receiver,key);
8220 addReplyBulk(receiver,ele);
8221 unblockClientWaitingData(receiver);
8222 return 1;
8223 }
8224
8225 /* Blocking RPOP/LPOP */
8226 static void blockingPopGenericCommand(redisClient *c, int where) {
8227 robj *o;
8228 time_t timeout;
8229 int j;
8230
8231 for (j = 1; j < c->argc-1; j++) {
8232 o = lookupKeyWrite(c->db,c->argv[j]);
8233 if (o != NULL) {
8234 if (o->type != REDIS_LIST) {
8235 addReply(c,shared.wrongtypeerr);
8236 return;
8237 } else {
8238 list *list = o->ptr;
8239 if (listLength(list) != 0) {
8240 /* If the list contains elements fall back to the usual
8241 * non-blocking POP operation */
8242 robj *argv[2], **orig_argv;
8243 int orig_argc;
8244
8245 /* We need to alter the command arguments before to call
8246 * popGenericCommand() as the command takes a single key. */
8247 orig_argv = c->argv;
8248 orig_argc = c->argc;
8249 argv[1] = c->argv[j];
8250 c->argv = argv;
8251 c->argc = 2;
8252
8253 /* Also the return value is different, we need to output
8254 * the multi bulk reply header and the key name. The
8255 * "real" command will add the last element (the value)
8256 * for us. If this souds like an hack to you it's just
8257 * because it is... */
8258 addReplySds(c,sdsnew("*2\r\n"));
8259 addReplyBulk(c,argv[1]);
8260 popGenericCommand(c,where);
8261
8262 /* Fix the client structure with the original stuff */
8263 c->argv = orig_argv;
8264 c->argc = orig_argc;
8265 return;
8266 }
8267 }
8268 }
8269 }
8270 /* If the list is empty or the key does not exists we must block */
8271 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
8272 if (timeout > 0) timeout += time(NULL);
8273 blockForKeys(c,c->argv+1,c->argc-2,timeout);
8274 }
8275
8276 static void blpopCommand(redisClient *c) {
8277 blockingPopGenericCommand(c,REDIS_HEAD);
8278 }
8279
8280 static void brpopCommand(redisClient *c) {
8281 blockingPopGenericCommand(c,REDIS_TAIL);
8282 }
8283
8284 /* =============================== Replication ============================= */
8285
8286 static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
8287 ssize_t nwritten, ret = size;
8288 time_t start = time(NULL);
8289
8290 timeout++;
8291 while(size) {
8292 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
8293 nwritten = write(fd,ptr,size);
8294 if (nwritten == -1) return -1;
8295 ptr += nwritten;
8296 size -= nwritten;
8297 }
8298 if ((time(NULL)-start) > timeout) {
8299 errno = ETIMEDOUT;
8300 return -1;
8301 }
8302 }
8303 return ret;
8304 }
8305
8306 static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
8307 ssize_t nread, totread = 0;
8308 time_t start = time(NULL);
8309
8310 timeout++;
8311 while(size) {
8312 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
8313 nread = read(fd,ptr,size);
8314 if (nread == -1) return -1;
8315 ptr += nread;
8316 size -= nread;
8317 totread += nread;
8318 }
8319 if ((time(NULL)-start) > timeout) {
8320 errno = ETIMEDOUT;
8321 return -1;
8322 }
8323 }
8324 return totread;
8325 }
8326
8327 static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
8328 ssize_t nread = 0;
8329
8330 size--;
8331 while(size) {
8332 char c;
8333
8334 if (syncRead(fd,&c,1,timeout) == -1) return -1;
8335 if (c == '\n') {
8336 *ptr = '\0';
8337 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
8338 return nread;
8339 } else {
8340 *ptr++ = c;
8341 *ptr = '\0';
8342 nread++;
8343 }
8344 }
8345 return nread;
8346 }
8347
8348 static void syncCommand(redisClient *c) {
8349 /* ignore SYNC if aleady slave or in monitor mode */
8350 if (c->flags & REDIS_SLAVE) return;
8351
8352 /* SYNC can't be issued when the server has pending data to send to
8353 * the client about already issued commands. We need a fresh reply
8354 * buffer registering the differences between the BGSAVE and the current
8355 * dataset, so that we can copy to other slaves if needed. */
8356 if (listLength(c->reply) != 0) {
8357 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
8358 return;
8359 }
8360
8361 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
8362 /* Here we need to check if there is a background saving operation
8363 * in progress, or if it is required to start one */
8364 if (server.bgsavechildpid != -1) {
8365 /* Ok a background save is in progress. Let's check if it is a good
8366 * one for replication, i.e. if there is another slave that is
8367 * registering differences since the server forked to save */
8368 redisClient *slave;
8369 listNode *ln;
8370 listIter li;
8371
8372 listRewind(server.slaves,&li);
8373 while((ln = listNext(&li))) {
8374 slave = ln->value;
8375 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
8376 }
8377 if (ln) {
8378 /* Perfect, the server is already registering differences for
8379 * another slave. Set the right state, and copy the buffer. */
8380 listRelease(c->reply);
8381 c->reply = listDup(slave->reply);
8382 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8383 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
8384 } else {
8385 /* No way, we need to wait for the next BGSAVE in order to
8386 * register differences */
8387 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
8388 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
8389 }
8390 } else {
8391 /* Ok we don't have a BGSAVE in progress, let's start one */
8392 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
8393 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
8394 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
8395 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
8396 return;
8397 }
8398 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8399 }
8400 c->repldbfd = -1;
8401 c->flags |= REDIS_SLAVE;
8402 c->slaveseldb = 0;
8403 listAddNodeTail(server.slaves,c);
8404 return;
8405 }
8406
8407 static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
8408 redisClient *slave = privdata;
8409 REDIS_NOTUSED(el);
8410 REDIS_NOTUSED(mask);
8411 char buf[REDIS_IOBUF_LEN];
8412 ssize_t nwritten, buflen;
8413
8414 if (slave->repldboff == 0) {
8415 /* Write the bulk write count before to transfer the DB. In theory here
8416 * we don't know how much room there is in the output buffer of the
8417 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
8418 * operations) will never be smaller than the few bytes we need. */
8419 sds bulkcount;
8420
8421 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
8422 slave->repldbsize);
8423 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
8424 {
8425 sdsfree(bulkcount);
8426 freeClient(slave);
8427 return;
8428 }
8429 sdsfree(bulkcount);
8430 }
8431 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
8432 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
8433 if (buflen <= 0) {
8434 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
8435 (buflen == 0) ? "premature EOF" : strerror(errno));
8436 freeClient(slave);
8437 return;
8438 }
8439 if ((nwritten = write(fd,buf,buflen)) == -1) {
8440 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
8441 strerror(errno));
8442 freeClient(slave);
8443 return;
8444 }
8445 slave->repldboff += nwritten;
8446 if (slave->repldboff == slave->repldbsize) {
8447 close(slave->repldbfd);
8448 slave->repldbfd = -1;
8449 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8450 slave->replstate = REDIS_REPL_ONLINE;
8451 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
8452 sendReplyToClient, slave) == AE_ERR) {
8453 freeClient(slave);
8454 return;
8455 }
8456 addReplySds(slave,sdsempty());
8457 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
8458 }
8459 }
8460
8461 /* This function is called at the end of every backgrond saving.
8462 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
8463 * otherwise REDIS_ERR is passed to the function.
8464 *
8465 * The goal of this function is to handle slaves waiting for a successful
8466 * background saving in order to perform non-blocking synchronization. */
8467 static void updateSlavesWaitingBgsave(int bgsaveerr) {
8468 listNode *ln;
8469 int startbgsave = 0;
8470 listIter li;
8471
8472 listRewind(server.slaves,&li);
8473 while((ln = listNext(&li))) {
8474 redisClient *slave = ln->value;
8475
8476 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
8477 startbgsave = 1;
8478 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8479 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
8480 struct redis_stat buf;
8481
8482 if (bgsaveerr != REDIS_OK) {
8483 freeClient(slave);
8484 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
8485 continue;
8486 }
8487 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
8488 redis_fstat(slave->repldbfd,&buf) == -1) {
8489 freeClient(slave);
8490 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
8491 continue;
8492 }
8493 slave->repldboff = 0;
8494 slave->repldbsize = buf.st_size;
8495 slave->replstate = REDIS_REPL_SEND_BULK;
8496 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8497 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
8498 freeClient(slave);
8499 continue;
8500 }
8501 }
8502 }
8503 if (startbgsave) {
8504 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
8505 listIter li;
8506
8507 listRewind(server.slaves,&li);
8508 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
8509 while((ln = listNext(&li))) {
8510 redisClient *slave = ln->value;
8511
8512 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
8513 freeClient(slave);
8514 }
8515 }
8516 }
8517 }
8518
8519 static int syncWithMaster(void) {
8520 char buf[1024], tmpfile[256], authcmd[1024];
8521 long dumpsize;
8522 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
8523 int dfd, maxtries = 5;
8524
8525 if (fd == -1) {
8526 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
8527 strerror(errno));
8528 return REDIS_ERR;
8529 }
8530
8531 /* AUTH with the master if required. */
8532 if(server.masterauth) {
8533 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
8534 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
8535 close(fd);
8536 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
8537 strerror(errno));
8538 return REDIS_ERR;
8539 }
8540 /* Read the AUTH result. */
8541 if (syncReadLine(fd,buf,1024,3600) == -1) {
8542 close(fd);
8543 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
8544 strerror(errno));
8545 return REDIS_ERR;
8546 }
8547 if (buf[0] != '+') {
8548 close(fd);
8549 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
8550 return REDIS_ERR;
8551 }
8552 }
8553
8554 /* Issue the SYNC command */
8555 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
8556 close(fd);
8557 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
8558 strerror(errno));
8559 return REDIS_ERR;
8560 }
8561 /* Read the bulk write count */
8562 if (syncReadLine(fd,buf,1024,3600) == -1) {
8563 close(fd);
8564 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
8565 strerror(errno));
8566 return REDIS_ERR;
8567 }
8568 if (buf[0] != '$') {
8569 close(fd);
8570 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8571 return REDIS_ERR;
8572 }
8573 dumpsize = strtol(buf+1,NULL,10);
8574 redisLog(REDIS_NOTICE,"Receiving %ld bytes data dump from MASTER",dumpsize);
8575 /* Read the bulk write data on a temp file */
8576 while(maxtries--) {
8577 snprintf(tmpfile,256,
8578 "temp-%d.%ld.rdb",(int)time(NULL),(long int)getpid());
8579 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
8580 if (dfd != -1) break;
8581 sleep(1);
8582 }
8583 if (dfd == -1) {
8584 close(fd);
8585 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
8586 return REDIS_ERR;
8587 }
8588 while(dumpsize) {
8589 int nread, nwritten;
8590
8591 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
8592 if (nread == -1) {
8593 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
8594 strerror(errno));
8595 close(fd);
8596 close(dfd);
8597 return REDIS_ERR;
8598 }
8599 nwritten = write(dfd,buf,nread);
8600 if (nwritten == -1) {
8601 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
8602 close(fd);
8603 close(dfd);
8604 return REDIS_ERR;
8605 }
8606 dumpsize -= nread;
8607 }
8608 close(dfd);
8609 if (rename(tmpfile,server.dbfilename) == -1) {
8610 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
8611 unlink(tmpfile);
8612 close(fd);
8613 return REDIS_ERR;
8614 }
8615 emptyDb();
8616 if (rdbLoad(server.dbfilename) != REDIS_OK) {
8617 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
8618 close(fd);
8619 return REDIS_ERR;
8620 }
8621 server.master = createClient(fd);
8622 server.master->flags |= REDIS_MASTER;
8623 server.master->authenticated = 1;
8624 server.replstate = REDIS_REPL_CONNECTED;
8625 return REDIS_OK;
8626 }
8627
8628 static void slaveofCommand(redisClient *c) {
8629 if (!strcasecmp(c->argv[1]->ptr,"no") &&
8630 !strcasecmp(c->argv[2]->ptr,"one")) {
8631 if (server.masterhost) {
8632 sdsfree(server.masterhost);
8633 server.masterhost = NULL;
8634 if (server.master) freeClient(server.master);
8635 server.replstate = REDIS_REPL_NONE;
8636 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
8637 }
8638 } else {
8639 sdsfree(server.masterhost);
8640 server.masterhost = sdsdup(c->argv[1]->ptr);
8641 server.masterport = atoi(c->argv[2]->ptr);
8642 if (server.master) freeClient(server.master);
8643 server.replstate = REDIS_REPL_CONNECT;
8644 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
8645 server.masterhost, server.masterport);
8646 }
8647 addReply(c,shared.ok);
8648 }
8649
8650 /* ============================ Maxmemory directive ======================== */
8651
8652 /* Try to free one object form the pre-allocated objects free list.
8653 * This is useful under low mem conditions as by default we take 1 million
8654 * free objects allocated. On success REDIS_OK is returned, otherwise
8655 * REDIS_ERR. */
8656 static int tryFreeOneObjectFromFreelist(void) {
8657 robj *o;
8658
8659 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
8660 if (listLength(server.objfreelist)) {
8661 listNode *head = listFirst(server.objfreelist);
8662 o = listNodeValue(head);
8663 listDelNode(server.objfreelist,head);
8664 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8665 zfree(o);
8666 return REDIS_OK;
8667 } else {
8668 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8669 return REDIS_ERR;
8670 }
8671 }
8672
8673 /* This function gets called when 'maxmemory' is set on the config file to limit
8674 * the max memory used by the server, and we are out of memory.
8675 * This function will try to, in order:
8676 *
8677 * - Free objects from the free list
8678 * - Try to remove keys with an EXPIRE set
8679 *
8680 * It is not possible to free enough memory to reach used-memory < maxmemory
8681 * the server will start refusing commands that will enlarge even more the
8682 * memory usage.
8683 */
8684 static void freeMemoryIfNeeded(void) {
8685 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
8686 int j, k, freed = 0;
8687
8688 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
8689 for (j = 0; j < server.dbnum; j++) {
8690 int minttl = -1;
8691 robj *minkey = NULL;
8692 struct dictEntry *de;
8693
8694 if (dictSize(server.db[j].expires)) {
8695 freed = 1;
8696 /* From a sample of three keys drop the one nearest to
8697 * the natural expire */
8698 for (k = 0; k < 3; k++) {
8699 time_t t;
8700
8701 de = dictGetRandomKey(server.db[j].expires);
8702 t = (time_t) dictGetEntryVal(de);
8703 if (minttl == -1 || t < minttl) {
8704 minkey = dictGetEntryKey(de);
8705 minttl = t;
8706 }
8707 }
8708 dbDelete(server.db+j,minkey);
8709 }
8710 }
8711 if (!freed) return; /* nothing to free... */
8712 }
8713 }
8714
8715 /* ============================== Append Only file ========================== */
8716
8717 /* Called when the user switches from "appendonly yes" to "appendonly no"
8718 * at runtime using the CONFIG command. */
8719 static void stopAppendOnly(void) {
8720 flushAppendOnlyFile();
8721 aof_fsync(server.appendfd);
8722 close(server.appendfd);
8723
8724 server.appendfd = -1;
8725 server.appendseldb = -1;
8726 server.appendonly = 0;
8727 /* rewrite operation in progress? kill it, wait child exit */
8728 if (server.bgsavechildpid != -1) {
8729 int statloc;
8730
8731 if (kill(server.bgsavechildpid,SIGKILL) != -1)
8732 wait3(&statloc,0,NULL);
8733 /* reset the buffer accumulating changes while the child saves */
8734 sdsfree(server.bgrewritebuf);
8735 server.bgrewritebuf = sdsempty();
8736 server.bgsavechildpid = -1;
8737 }
8738 }
8739
8740 /* Called when the user switches from "appendonly no" to "appendonly yes"
8741 * at runtime using the CONFIG command. */
8742 static int startAppendOnly(void) {
8743 server.appendonly = 1;
8744 server.lastfsync = time(NULL);
8745 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
8746 if (server.appendfd == -1) {
8747 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno));
8748 return REDIS_ERR;
8749 }
8750 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
8751 server.appendonly = 0;
8752 close(server.appendfd);
8753 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, I can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.",strerror(errno));
8754 return REDIS_ERR;
8755 }
8756 return REDIS_OK;
8757 }
8758
8759 /* Write the append only file buffer on disk.
8760 *
8761 * Since we are required to write the AOF before replying to the client,
8762 * and the only way the client socket can get a write is entering when the
8763 * the event loop, we accumulate all the AOF writes in a memory
8764 * buffer and write it on disk using this function just before entering
8765 * the event loop again. */
8766 static void flushAppendOnlyFile(void) {
8767 time_t now;
8768 ssize_t nwritten;
8769
8770 if (sdslen(server.aofbuf) == 0) return;
8771
8772 /* We want to perform a single write. This should be guaranteed atomic
8773 * at least if the filesystem we are writing is a real physical one.
8774 * While this will save us against the server being killed I don't think
8775 * there is much to do about the whole server stopping for power problems
8776 * or alike */
8777 nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf));
8778 if (nwritten != (signed)sdslen(server.aofbuf)) {
8779 /* Ooops, we are in troubles. The best thing to do for now is
8780 * aborting instead of giving the illusion that everything is
8781 * working as expected. */
8782 if (nwritten == -1) {
8783 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
8784 } else {
8785 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
8786 }
8787 exit(1);
8788 }
8789 sdsfree(server.aofbuf);
8790 server.aofbuf = sdsempty();
8791
8792 /* Don't Fsync if no-appendfsync-on-rewrite is set to yes and we have
8793 * childs performing heavy I/O on disk. */
8794 if (server.no_appendfsync_on_rewrite &&
8795 (server.bgrewritechildpid != -1 || server.bgsavechildpid != -1))
8796 return;
8797 /* Fsync if needed */
8798 now = time(NULL);
8799 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
8800 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
8801 now-server.lastfsync > 1))
8802 {
8803 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8804 * flushing metadata. */
8805 aof_fsync(server.appendfd); /* Let's try to get this data on the disk */
8806 server.lastfsync = now;
8807 }
8808 }
8809
8810 static sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) {
8811 int j;
8812 buf = sdscatprintf(buf,"*%d\r\n",argc);
8813 for (j = 0; j < argc; j++) {
8814 robj *o = getDecodedObject(argv[j]);
8815 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
8816 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
8817 buf = sdscatlen(buf,"\r\n",2);
8818 decrRefCount(o);
8819 }
8820 return buf;
8821 }
8822
8823 static sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) {
8824 int argc = 3;
8825 long when;
8826 robj *argv[3];
8827
8828 /* Make sure we can use strtol */
8829 seconds = getDecodedObject(seconds);
8830 when = time(NULL)+strtol(seconds->ptr,NULL,10);
8831 decrRefCount(seconds);
8832
8833 argv[0] = createStringObject("EXPIREAT",8);
8834 argv[1] = key;
8835 argv[2] = createObject(REDIS_STRING,
8836 sdscatprintf(sdsempty(),"%ld",when));
8837 buf = catAppendOnlyGenericCommand(buf, argc, argv);
8838 decrRefCount(argv[0]);
8839 decrRefCount(argv[2]);
8840 return buf;
8841 }
8842
8843 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
8844 sds buf = sdsempty();
8845 robj *tmpargv[3];
8846
8847 /* The DB this command was targetting is not the same as the last command
8848 * we appendend. To issue a SELECT command is needed. */
8849 if (dictid != server.appendseldb) {
8850 char seldb[64];
8851
8852 snprintf(seldb,sizeof(seldb),"%d",dictid);
8853 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
8854 (unsigned long)strlen(seldb),seldb);
8855 server.appendseldb = dictid;
8856 }
8857
8858 if (cmd->proc == expireCommand) {
8859 /* Translate EXPIRE into EXPIREAT */
8860 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8861 } else if (cmd->proc == setexCommand) {
8862 /* Translate SETEX to SET and EXPIREAT */
8863 tmpargv[0] = createStringObject("SET",3);
8864 tmpargv[1] = argv[1];
8865 tmpargv[2] = argv[3];
8866 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
8867 decrRefCount(tmpargv[0]);
8868 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8869 } else {
8870 buf = catAppendOnlyGenericCommand(buf,argc,argv);
8871 }
8872
8873 /* Append to the AOF buffer. This will be flushed on disk just before
8874 * of re-entering the event loop, so before the client will get a
8875 * positive reply about the operation performed. */
8876 server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf));
8877
8878 /* If a background append only file rewriting is in progress we want to
8879 * accumulate the differences between the child DB and the current one
8880 * in a buffer, so that when the child process will do its work we
8881 * can append the differences to the new append only file. */
8882 if (server.bgrewritechildpid != -1)
8883 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
8884
8885 sdsfree(buf);
8886 }
8887
8888 /* In Redis commands are always executed in the context of a client, so in
8889 * order to load the append only file we need to create a fake client. */
8890 static struct redisClient *createFakeClient(void) {
8891 struct redisClient *c = zmalloc(sizeof(*c));
8892
8893 selectDb(c,0);
8894 c->fd = -1;
8895 c->querybuf = sdsempty();
8896 c->argc = 0;
8897 c->argv = NULL;
8898 c->flags = 0;
8899 /* We set the fake client as a slave waiting for the synchronization
8900 * so that Redis will not try to send replies to this client. */
8901 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
8902 c->reply = listCreate();
8903 listSetFreeMethod(c->reply,decrRefCount);
8904 listSetDupMethod(c->reply,dupClientReplyValue);
8905 initClientMultiState(c);
8906 return c;
8907 }
8908
8909 static void freeFakeClient(struct redisClient *c) {
8910 sdsfree(c->querybuf);
8911 listRelease(c->reply);
8912 freeClientMultiState(c);
8913 zfree(c);
8914 }
8915
8916 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
8917 * error (the append only file is zero-length) REDIS_ERR is returned. On
8918 * fatal error an error message is logged and the program exists. */
8919 int loadAppendOnlyFile(char *filename) {
8920 struct redisClient *fakeClient;
8921 FILE *fp = fopen(filename,"r");
8922 struct redis_stat sb;
8923 int appendonly = server.appendonly;
8924
8925 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
8926 return REDIS_ERR;
8927
8928 if (fp == NULL) {
8929 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
8930 exit(1);
8931 }
8932
8933 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8934 * to the same file we're about to read. */
8935 server.appendonly = 0;
8936
8937 fakeClient = createFakeClient();
8938 while(1) {
8939 int argc, j;
8940 unsigned long len;
8941 robj **argv;
8942 char buf[128];
8943 sds argsds;
8944 struct redisCommand *cmd;
8945 int force_swapout;
8946
8947 if (fgets(buf,sizeof(buf),fp) == NULL) {
8948 if (feof(fp))
8949 break;
8950 else
8951 goto readerr;
8952 }
8953 if (buf[0] != '*') goto fmterr;
8954 argc = atoi(buf+1);
8955 argv = zmalloc(sizeof(robj*)*argc);
8956 for (j = 0; j < argc; j++) {
8957 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
8958 if (buf[0] != '$') goto fmterr;
8959 len = strtol(buf+1,NULL,10);
8960 argsds = sdsnewlen(NULL,len);
8961 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
8962 argv[j] = createObject(REDIS_STRING,argsds);
8963 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
8964 }
8965
8966 /* Command lookup */
8967 cmd = lookupCommand(argv[0]->ptr);
8968 if (!cmd) {
8969 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
8970 exit(1);
8971 }
8972 /* Try object encoding */
8973 if (cmd->flags & REDIS_CMD_BULK)
8974 argv[argc-1] = tryObjectEncoding(argv[argc-1]);
8975 /* Run the command in the context of a fake client */
8976 fakeClient->argc = argc;
8977 fakeClient->argv = argv;
8978 cmd->proc(fakeClient);
8979 /* Discard the reply objects list from the fake client */
8980 while(listLength(fakeClient->reply))
8981 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
8982 /* Clean up, ready for the next command */
8983 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
8984 zfree(argv);
8985 /* Handle swapping while loading big datasets when VM is on */
8986 force_swapout = 0;
8987 if ((zmalloc_used_memory() - server.vm_max_memory) > 1024*1024*32)
8988 force_swapout = 1;
8989
8990 if (server.vm_enabled && force_swapout) {
8991 while (zmalloc_used_memory() > server.vm_max_memory) {
8992 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
8993 }
8994 }
8995 }
8996
8997 /* This point can only be reached when EOF is reached without errors.
8998 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8999 if (fakeClient->flags & REDIS_MULTI) goto readerr;
9000
9001 fclose(fp);
9002 freeFakeClient(fakeClient);
9003 server.appendonly = appendonly;
9004 return REDIS_OK;
9005
9006 readerr:
9007 if (feof(fp)) {
9008 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
9009 } else {
9010 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
9011 }
9012 exit(1);
9013 fmterr:
9014 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
9015 exit(1);
9016 }
9017
9018 /* Write binary-safe string into a file in the bulkformat
9019 * $<count>\r\n<payload>\r\n */
9020 static int fwriteBulkString(FILE *fp, char *s, unsigned long len) {
9021 char cbuf[128];
9022 int clen;
9023 cbuf[0] = '$';
9024 clen = 1+ll2string(cbuf+1,sizeof(cbuf)-1,len);
9025 cbuf[clen++] = '\r';
9026 cbuf[clen++] = '\n';
9027 if (fwrite(cbuf,clen,1,fp) == 0) return 0;
9028 if (len > 0 && fwrite(s,len,1,fp) == 0) return 0;
9029 if (fwrite("\r\n",2,1,fp) == 0) return 0;
9030 return 1;
9031 }
9032
9033 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
9034 static int fwriteBulkDouble(FILE *fp, double d) {
9035 char buf[128], dbuf[128];
9036
9037 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
9038 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
9039 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
9040 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
9041 return 1;
9042 }
9043
9044 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
9045 static int fwriteBulkLongLong(FILE *fp, long long l) {
9046 char bbuf[128], lbuf[128];
9047 unsigned int blen, llen;
9048 llen = ll2string(lbuf,32,l);
9049 blen = snprintf(bbuf,sizeof(bbuf),"$%u\r\n%s\r\n",llen,lbuf);
9050 if (fwrite(bbuf,blen,1,fp) == 0) return 0;
9051 return 1;
9052 }
9053
9054 /* Delegate writing an object to writing a bulk string or bulk long long. */
9055 static int fwriteBulkObject(FILE *fp, robj *obj) {
9056 /* Avoid using getDecodedObject to help copy-on-write (we are often
9057 * in a child process when this function is called). */
9058 if (obj->encoding == REDIS_ENCODING_INT) {
9059 return fwriteBulkLongLong(fp,(long)obj->ptr);
9060 } else if (obj->encoding == REDIS_ENCODING_RAW) {
9061 return fwriteBulkString(fp,obj->ptr,sdslen(obj->ptr));
9062 } else {
9063 redisPanic("Unknown string encoding");
9064 }
9065 }
9066
9067 /* Write a sequence of commands able to fully rebuild the dataset into
9068 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
9069 static int rewriteAppendOnlyFile(char *filename) {
9070 dictIterator *di = NULL;
9071 dictEntry *de;
9072 FILE *fp;
9073 char tmpfile[256];
9074 int j;
9075 time_t now = time(NULL);
9076
9077 /* Note that we have to use a different temp name here compared to the
9078 * one used by rewriteAppendOnlyFileBackground() function. */
9079 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
9080 fp = fopen(tmpfile,"w");
9081 if (!fp) {
9082 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
9083 return REDIS_ERR;
9084 }
9085 for (j = 0; j < server.dbnum; j++) {
9086 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
9087 redisDb *db = server.db+j;
9088 dict *d = db->dict;
9089 if (dictSize(d) == 0) continue;
9090 di = dictGetIterator(d);
9091 if (!di) {
9092 fclose(fp);
9093 return REDIS_ERR;
9094 }
9095
9096 /* SELECT the new DB */
9097 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
9098 if (fwriteBulkLongLong(fp,j) == 0) goto werr;
9099
9100 /* Iterate this DB writing every entry */
9101 while((de = dictNext(di)) != NULL) {
9102 sds keystr = dictGetEntryKey(de);
9103 robj key, *o;
9104 time_t expiretime;
9105 int swapped;
9106
9107 keystr = dictGetEntryKey(de);
9108 o = dictGetEntryVal(de);
9109 initStaticStringObject(key,keystr);
9110 /* If the value for this key is swapped, load a preview in memory.
9111 * We use a "swapped" flag to remember if we need to free the
9112 * value object instead to just increment the ref count anyway
9113 * in order to avoid copy-on-write of pages if we are forked() */
9114 if (!server.vm_enabled || o->storage == REDIS_VM_MEMORY ||
9115 o->storage == REDIS_VM_SWAPPING) {
9116 swapped = 0;
9117 } else {
9118 o = vmPreviewObject(o);
9119 swapped = 1;
9120 }
9121 expiretime = getExpire(db,&key);
9122
9123 /* Save the key and associated value */
9124 if (o->type == REDIS_STRING) {
9125 /* Emit a SET command */
9126 char cmd[]="*3\r\n$3\r\nSET\r\n";
9127 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9128 /* Key and value */
9129 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9130 if (fwriteBulkObject(fp,o) == 0) goto werr;
9131 } else if (o->type == REDIS_LIST) {
9132 /* Emit the RPUSHes needed to rebuild the list */
9133 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
9134 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
9135 unsigned char *zl = o->ptr;
9136 unsigned char *p = ziplistIndex(zl,0);
9137 unsigned char *vstr;
9138 unsigned int vlen;
9139 long long vlong;
9140
9141 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
9142 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9143 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9144 if (vstr) {
9145 if (fwriteBulkString(fp,(char*)vstr,vlen) == 0)
9146 goto werr;
9147 } else {
9148 if (fwriteBulkLongLong(fp,vlong) == 0)
9149 goto werr;
9150 }
9151 p = ziplistNext(zl,p);
9152 }
9153 } else if (o->encoding == REDIS_ENCODING_LIST) {
9154 list *list = o->ptr;
9155 listNode *ln;
9156 listIter li;
9157
9158 listRewind(list,&li);
9159 while((ln = listNext(&li))) {
9160 robj *eleobj = listNodeValue(ln);
9161
9162 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9163 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9164 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9165 }
9166 } else {
9167 redisPanic("Unknown list encoding");
9168 }
9169 } else if (o->type == REDIS_SET) {
9170 /* Emit the SADDs needed to rebuild the set */
9171 dict *set = o->ptr;
9172 dictIterator *di = dictGetIterator(set);
9173 dictEntry *de;
9174
9175 while((de = dictNext(di)) != NULL) {
9176 char cmd[]="*3\r\n$4\r\nSADD\r\n";
9177 robj *eleobj = dictGetEntryKey(de);
9178
9179 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9180 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9181 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9182 }
9183 dictReleaseIterator(di);
9184 } else if (o->type == REDIS_ZSET) {
9185 /* Emit the ZADDs needed to rebuild the sorted set */
9186 zset *zs = o->ptr;
9187 dictIterator *di = dictGetIterator(zs->dict);
9188 dictEntry *de;
9189
9190 while((de = dictNext(di)) != NULL) {
9191 char cmd[]="*4\r\n$4\r\nZADD\r\n";
9192 robj *eleobj = dictGetEntryKey(de);
9193 double *score = dictGetEntryVal(de);
9194
9195 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9196 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9197 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
9198 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9199 }
9200 dictReleaseIterator(di);
9201 } else if (o->type == REDIS_HASH) {
9202 char cmd[]="*4\r\n$4\r\nHSET\r\n";
9203
9204 /* Emit the HSETs needed to rebuild the hash */
9205 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9206 unsigned char *p = zipmapRewind(o->ptr);
9207 unsigned char *field, *val;
9208 unsigned int flen, vlen;
9209
9210 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
9211 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9212 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9213 if (fwriteBulkString(fp,(char*)field,flen) == -1)
9214 return -1;
9215 if (fwriteBulkString(fp,(char*)val,vlen) == -1)
9216 return -1;
9217 }
9218 } else {
9219 dictIterator *di = dictGetIterator(o->ptr);
9220 dictEntry *de;
9221
9222 while((de = dictNext(di)) != NULL) {
9223 robj *field = dictGetEntryKey(de);
9224 robj *val = dictGetEntryVal(de);
9225
9226 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9227 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9228 if (fwriteBulkObject(fp,field) == -1) return -1;
9229 if (fwriteBulkObject(fp,val) == -1) return -1;
9230 }
9231 dictReleaseIterator(di);
9232 }
9233 } else {
9234 redisPanic("Unknown object type");
9235 }
9236 /* Save the expire time */
9237 if (expiretime != -1) {
9238 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
9239 /* If this key is already expired skip it */
9240 if (expiretime < now) continue;
9241 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9242 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9243 if (fwriteBulkLongLong(fp,expiretime) == 0) goto werr;
9244 }
9245 if (swapped) decrRefCount(o);
9246 }
9247 dictReleaseIterator(di);
9248 }
9249
9250 /* Make sure data will not remain on the OS's output buffers */
9251 fflush(fp);
9252 aof_fsync(fileno(fp));
9253 fclose(fp);
9254
9255 /* Use RENAME to make sure the DB file is changed atomically only
9256 * if the generate DB file is ok. */
9257 if (rename(tmpfile,filename) == -1) {
9258 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
9259 unlink(tmpfile);
9260 return REDIS_ERR;
9261 }
9262 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
9263 return REDIS_OK;
9264
9265 werr:
9266 fclose(fp);
9267 unlink(tmpfile);
9268 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
9269 if (di) dictReleaseIterator(di);
9270 return REDIS_ERR;
9271 }
9272
9273 /* This is how rewriting of the append only file in background works:
9274 *
9275 * 1) The user calls BGREWRITEAOF
9276 * 2) Redis calls this function, that forks():
9277 * 2a) the child rewrite the append only file in a temp file.
9278 * 2b) the parent accumulates differences in server.bgrewritebuf.
9279 * 3) When the child finished '2a' exists.
9280 * 4) The parent will trap the exit code, if it's OK, will append the
9281 * data accumulated into server.bgrewritebuf into the temp file, and
9282 * finally will rename(2) the temp file in the actual file name.
9283 * The the new file is reopened as the new append only file. Profit!
9284 */
9285 static int rewriteAppendOnlyFileBackground(void) {
9286 pid_t childpid;
9287
9288 if (server.bgrewritechildpid != -1) return REDIS_ERR;
9289 if (server.vm_enabled) waitEmptyIOJobsQueue();
9290 if ((childpid = fork()) == 0) {
9291 /* Child */
9292 char tmpfile[256];
9293
9294 if (server.vm_enabled) vmReopenSwapFile();
9295 close(server.fd);
9296 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
9297 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
9298 _exit(0);
9299 } else {
9300 _exit(1);
9301 }
9302 } else {
9303 /* Parent */
9304 if (childpid == -1) {
9305 redisLog(REDIS_WARNING,
9306 "Can't rewrite append only file in background: fork: %s",
9307 strerror(errno));
9308 return REDIS_ERR;
9309 }
9310 redisLog(REDIS_NOTICE,
9311 "Background append only file rewriting started by pid %d",childpid);
9312 server.bgrewritechildpid = childpid;
9313 updateDictResizePolicy();
9314 /* We set appendseldb to -1 in order to force the next call to the
9315 * feedAppendOnlyFile() to issue a SELECT command, so the differences
9316 * accumulated by the parent into server.bgrewritebuf will start
9317 * with a SELECT statement and it will be safe to merge. */
9318 server.appendseldb = -1;
9319 return REDIS_OK;
9320 }
9321 return REDIS_OK; /* unreached */
9322 }
9323
9324 static void bgrewriteaofCommand(redisClient *c) {
9325 if (server.bgrewritechildpid != -1) {
9326 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
9327 return;
9328 }
9329 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
9330 char *status = "+Background append only file rewriting started\r\n";
9331 addReplySds(c,sdsnew(status));
9332 } else {
9333 addReply(c,shared.err);
9334 }
9335 }
9336
9337 static void aofRemoveTempFile(pid_t childpid) {
9338 char tmpfile[256];
9339
9340 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
9341 unlink(tmpfile);
9342 }
9343
9344 /* Virtual Memory is composed mainly of two subsystems:
9345 * - Blocking Virutal Memory
9346 * - Threaded Virtual Memory I/O
9347 * The two parts are not fully decoupled, but functions are split among two
9348 * different sections of the source code (delimited by comments) in order to
9349 * make more clear what functionality is about the blocking VM and what about
9350 * the threaded (not blocking) VM.
9351 *
9352 * Redis VM design:
9353 *
9354 * Redis VM is a blocking VM (one that blocks reading swapped values from
9355 * disk into memory when a value swapped out is needed in memory) that is made
9356 * unblocking by trying to examine the command argument vector in order to
9357 * load in background values that will likely be needed in order to exec
9358 * the command. The command is executed only once all the relevant keys
9359 * are loaded into memory.
9360 *
9361 * This basically is almost as simple of a blocking VM, but almost as parallel
9362 * as a fully non-blocking VM.
9363 */
9364
9365 /* =================== Virtual Memory - Blocking Side ====================== */
9366
9367 /* Create a VM pointer object. This kind of objects are used in place of
9368 * values in the key -> value hash table, for swapped out objects. */
9369 static vmpointer *createVmPointer(int vtype) {
9370 vmpointer *vp = zmalloc(sizeof(vmpointer));
9371
9372 vp->type = REDIS_VMPOINTER;
9373 vp->storage = REDIS_VM_SWAPPED;
9374 vp->vtype = vtype;
9375 return vp;
9376 }
9377
9378 static void vmInit(void) {
9379 off_t totsize;
9380 int pipefds[2];
9381 size_t stacksize;
9382 struct flock fl;
9383
9384 if (server.vm_max_threads != 0)
9385 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
9386
9387 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
9388 /* Try to open the old swap file, otherwise create it */
9389 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
9390 server.vm_fp = fopen(server.vm_swap_file,"w+b");
9391 }
9392 if (server.vm_fp == NULL) {
9393 redisLog(REDIS_WARNING,
9394 "Can't open the swap file: %s. Exiting.",
9395 strerror(errno));
9396 exit(1);
9397 }
9398 server.vm_fd = fileno(server.vm_fp);
9399 /* Lock the swap file for writing, this is useful in order to avoid
9400 * another instance to use the same swap file for a config error. */
9401 fl.l_type = F_WRLCK;
9402 fl.l_whence = SEEK_SET;
9403 fl.l_start = fl.l_len = 0;
9404 if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
9405 redisLog(REDIS_WARNING,
9406 "Can't lock the swap file at '%s': %s. Make sure it is not used by another Redis instance.", server.vm_swap_file, strerror(errno));
9407 exit(1);
9408 }
9409 /* Initialize */
9410 server.vm_next_page = 0;
9411 server.vm_near_pages = 0;
9412 server.vm_stats_used_pages = 0;
9413 server.vm_stats_swapped_objects = 0;
9414 server.vm_stats_swapouts = 0;
9415 server.vm_stats_swapins = 0;
9416 totsize = server.vm_pages*server.vm_page_size;
9417 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
9418 if (ftruncate(server.vm_fd,totsize) == -1) {
9419 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
9420 strerror(errno));
9421 exit(1);
9422 } else {
9423 redisLog(REDIS_NOTICE,"Swap file allocated with success");
9424 }
9425 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
9426 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
9427 (long long) (server.vm_pages+7)/8, server.vm_pages);
9428 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
9429
9430 /* Initialize threaded I/O (used by Virtual Memory) */
9431 server.io_newjobs = listCreate();
9432 server.io_processing = listCreate();
9433 server.io_processed = listCreate();
9434 server.io_ready_clients = listCreate();
9435 pthread_mutex_init(&server.io_mutex,NULL);
9436 pthread_mutex_init(&server.obj_freelist_mutex,NULL);
9437 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
9438 server.io_active_threads = 0;
9439 if (pipe(pipefds) == -1) {
9440 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
9441 ,strerror(errno));
9442 exit(1);
9443 }
9444 server.io_ready_pipe_read = pipefds[0];
9445 server.io_ready_pipe_write = pipefds[1];
9446 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
9447 /* LZF requires a lot of stack */
9448 pthread_attr_init(&server.io_threads_attr);
9449 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
9450 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
9451 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
9452 /* Listen for events in the threaded I/O pipe */
9453 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
9454 vmThreadedIOCompletedJob, NULL) == AE_ERR)
9455 oom("creating file event");
9456 }
9457
9458 /* Mark the page as used */
9459 static void vmMarkPageUsed(off_t page) {
9460 off_t byte = page/8;
9461 int bit = page&7;
9462 redisAssert(vmFreePage(page) == 1);
9463 server.vm_bitmap[byte] |= 1<<bit;
9464 }
9465
9466 /* Mark N contiguous pages as used, with 'page' being the first. */
9467 static void vmMarkPagesUsed(off_t page, off_t count) {
9468 off_t j;
9469
9470 for (j = 0; j < count; j++)
9471 vmMarkPageUsed(page+j);
9472 server.vm_stats_used_pages += count;
9473 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
9474 (long long)count, (long long)page);
9475 }
9476
9477 /* Mark the page as free */
9478 static void vmMarkPageFree(off_t page) {
9479 off_t byte = page/8;
9480 int bit = page&7;
9481 redisAssert(vmFreePage(page) == 0);
9482 server.vm_bitmap[byte] &= ~(1<<bit);
9483 }
9484
9485 /* Mark N contiguous pages as free, with 'page' being the first. */
9486 static void vmMarkPagesFree(off_t page, off_t count) {
9487 off_t j;
9488
9489 for (j = 0; j < count; j++)
9490 vmMarkPageFree(page+j);
9491 server.vm_stats_used_pages -= count;
9492 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
9493 (long long)count, (long long)page);
9494 }
9495
9496 /* Test if the page is free */
9497 static int vmFreePage(off_t page) {
9498 off_t byte = page/8;
9499 int bit = page&7;
9500 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
9501 }
9502
9503 /* Find N contiguous free pages storing the first page of the cluster in *first.
9504 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
9505 * REDIS_ERR is returned.
9506 *
9507 * This function uses a simple algorithm: we try to allocate
9508 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
9509 * again from the start of the swap file searching for free spaces.
9510 *
9511 * If it looks pretty clear that there are no free pages near our offset
9512 * we try to find less populated places doing a forward jump of
9513 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
9514 * without hurry, and then we jump again and so forth...
9515 *
9516 * This function can be improved using a free list to avoid to guess
9517 * too much, since we could collect data about freed pages.
9518 *
9519 * note: I implemented this function just after watching an episode of
9520 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
9521 */
9522 static int vmFindContiguousPages(off_t *first, off_t n) {
9523 off_t base, offset = 0, since_jump = 0, numfree = 0;
9524
9525 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
9526 server.vm_near_pages = 0;
9527 server.vm_next_page = 0;
9528 }
9529 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
9530 base = server.vm_next_page;
9531
9532 while(offset < server.vm_pages) {
9533 off_t this = base+offset;
9534
9535 /* If we overflow, restart from page zero */
9536 if (this >= server.vm_pages) {
9537 this -= server.vm_pages;
9538 if (this == 0) {
9539 /* Just overflowed, what we found on tail is no longer
9540 * interesting, as it's no longer contiguous. */
9541 numfree = 0;
9542 }
9543 }
9544 if (vmFreePage(this)) {
9545 /* This is a free page */
9546 numfree++;
9547 /* Already got N free pages? Return to the caller, with success */
9548 if (numfree == n) {
9549 *first = this-(n-1);
9550 server.vm_next_page = this+1;
9551 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
9552 return REDIS_OK;
9553 }
9554 } else {
9555 /* The current one is not a free page */
9556 numfree = 0;
9557 }
9558
9559 /* Fast-forward if the current page is not free and we already
9560 * searched enough near this place. */
9561 since_jump++;
9562 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
9563 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
9564 since_jump = 0;
9565 /* Note that even if we rewind after the jump, we are don't need
9566 * to make sure numfree is set to zero as we only jump *if* it
9567 * is set to zero. */
9568 } else {
9569 /* Otherwise just check the next page */
9570 offset++;
9571 }
9572 }
9573 return REDIS_ERR;
9574 }
9575
9576 /* Write the specified object at the specified page of the swap file */
9577 static int vmWriteObjectOnSwap(robj *o, off_t page) {
9578 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9579 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9580 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9581 redisLog(REDIS_WARNING,
9582 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
9583 strerror(errno));
9584 return REDIS_ERR;
9585 }
9586 rdbSaveObject(server.vm_fp,o);
9587 fflush(server.vm_fp);
9588 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9589 return REDIS_OK;
9590 }
9591
9592 /* Transfers the 'val' object to disk. Store all the information
9593 * a 'vmpointer' object containing all the information needed to load the
9594 * object back later is returned.
9595 *
9596 * If we can't find enough contiguous empty pages to swap the object on disk
9597 * NULL is returned. */
9598 static vmpointer *vmSwapObjectBlocking(robj *val) {
9599 off_t pages = rdbSavedObjectPages(val,NULL);
9600 off_t page;
9601 vmpointer *vp;
9602
9603 assert(val->storage == REDIS_VM_MEMORY);
9604 assert(val->refcount == 1);
9605 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return NULL;
9606 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return NULL;
9607
9608 vp = createVmPointer(val->type);
9609 vp->page = page;
9610 vp->usedpages = pages;
9611 decrRefCount(val); /* Deallocate the object from memory. */
9612 vmMarkPagesUsed(page,pages);
9613 redisLog(REDIS_DEBUG,"VM: object %p swapped out at %lld (%lld pages)",
9614 (void*) val,
9615 (unsigned long long) page, (unsigned long long) pages);
9616 server.vm_stats_swapped_objects++;
9617 server.vm_stats_swapouts++;
9618 return vp;
9619 }
9620
9621 static robj *vmReadObjectFromSwap(off_t page, int type) {
9622 robj *o;
9623
9624 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9625 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9626 redisLog(REDIS_WARNING,
9627 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
9628 strerror(errno));
9629 _exit(1);
9630 }
9631 o = rdbLoadObject(type,server.vm_fp);
9632 if (o == NULL) {
9633 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
9634 _exit(1);
9635 }
9636 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9637 return o;
9638 }
9639
9640 /* Load the specified object from swap to memory.
9641 * The newly allocated object is returned.
9642 *
9643 * If preview is true the unserialized object is returned to the caller but
9644 * the pages are not marked as freed, nor the vp object is freed. */
9645 static robj *vmGenericLoadObject(vmpointer *vp, int preview) {
9646 robj *val;
9647
9648 redisAssert(vp->type == REDIS_VMPOINTER &&
9649 (vp->storage == REDIS_VM_SWAPPED || vp->storage == REDIS_VM_LOADING));
9650 val = vmReadObjectFromSwap(vp->page,vp->vtype);
9651 if (!preview) {
9652 redisLog(REDIS_DEBUG, "VM: object %p loaded from disk", (void*)vp);
9653 vmMarkPagesFree(vp->page,vp->usedpages);
9654 zfree(vp);
9655 server.vm_stats_swapped_objects--;
9656 } else {
9657 redisLog(REDIS_DEBUG, "VM: object %p previewed from disk", (void*)vp);
9658 }
9659 server.vm_stats_swapins++;
9660 return val;
9661 }
9662
9663 /* Plain object loading, from swap to memory.
9664 *
9665 * 'o' is actually a redisVmPointer structure that will be freed by the call.
9666 * The return value is the loaded object. */
9667 static robj *vmLoadObject(robj *o) {
9668 /* If we are loading the object in background, stop it, we
9669 * need to load this object synchronously ASAP. */
9670 if (o->storage == REDIS_VM_LOADING)
9671 vmCancelThreadedIOJob(o);
9672 return vmGenericLoadObject((vmpointer*)o,0);
9673 }
9674
9675 /* Just load the value on disk, without to modify the key.
9676 * This is useful when we want to perform some operation on the value
9677 * without to really bring it from swap to memory, like while saving the
9678 * dataset or rewriting the append only log. */
9679 static robj *vmPreviewObject(robj *o) {
9680 return vmGenericLoadObject((vmpointer*)o,1);
9681 }
9682
9683 /* How a good candidate is this object for swapping?
9684 * The better candidate it is, the greater the returned value.
9685 *
9686 * Currently we try to perform a fast estimation of the object size in
9687 * memory, and combine it with aging informations.
9688 *
9689 * Basically swappability = idle-time * log(estimated size)
9690 *
9691 * Bigger objects are preferred over smaller objects, but not
9692 * proportionally, this is why we use the logarithm. This algorithm is
9693 * just a first try and will probably be tuned later. */
9694 static double computeObjectSwappability(robj *o) {
9695 /* actual age can be >= minage, but not < minage. As we use wrapping
9696 * 21 bit clocks with minutes resolution for the LRU. */
9697 time_t minage = abs(server.lruclock - o->lru);
9698 long asize = 0, elesize;
9699 robj *ele;
9700 list *l;
9701 listNode *ln;
9702 dict *d;
9703 struct dictEntry *de;
9704 int z;
9705
9706 if (minage <= 0) return 0;
9707 switch(o->type) {
9708 case REDIS_STRING:
9709 if (o->encoding != REDIS_ENCODING_RAW) {
9710 asize = sizeof(*o);
9711 } else {
9712 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
9713 }
9714 break;
9715 case REDIS_LIST:
9716 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
9717 asize = sizeof(*o)+ziplistSize(o->ptr);
9718 } else {
9719 l = o->ptr;
9720 ln = listFirst(l);
9721 asize = sizeof(list);
9722 if (ln) {
9723 ele = ln->value;
9724 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9725 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
9726 asize += (sizeof(listNode)+elesize)*listLength(l);
9727 }
9728 }
9729 break;
9730 case REDIS_SET:
9731 case REDIS_ZSET:
9732 z = (o->type == REDIS_ZSET);
9733 d = z ? ((zset*)o->ptr)->dict : o->ptr;
9734
9735 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9736 if (z) asize += sizeof(zset)-sizeof(dict);
9737 if (dictSize(d)) {
9738 de = dictGetRandomKey(d);
9739 ele = dictGetEntryKey(de);
9740 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9741 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
9742 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9743 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
9744 }
9745 break;
9746 case REDIS_HASH:
9747 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9748 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
9749 unsigned int len = zipmapLen((unsigned char*)o->ptr);
9750 unsigned int klen, vlen;
9751 unsigned char *key, *val;
9752
9753 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
9754 klen = 0;
9755 vlen = 0;
9756 }
9757 asize = len*(klen+vlen+3);
9758 } else if (o->encoding == REDIS_ENCODING_HT) {
9759 d = o->ptr;
9760 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9761 if (dictSize(d)) {
9762 de = dictGetRandomKey(d);
9763 ele = dictGetEntryKey(de);
9764 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9765 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
9766 ele = dictGetEntryVal(de);
9767 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9768 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
9769 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9770 }
9771 }
9772 break;
9773 }
9774 return (double)minage*log(1+asize);
9775 }
9776
9777 /* Try to swap an object that's a good candidate for swapping.
9778 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
9779 * to swap any object at all.
9780 *
9781 * If 'usethreaded' is true, Redis will try to swap the object in background
9782 * using I/O threads. */
9783 static int vmSwapOneObject(int usethreads) {
9784 int j, i;
9785 struct dictEntry *best = NULL;
9786 double best_swappability = 0;
9787 redisDb *best_db = NULL;
9788 robj *val;
9789 sds key;
9790
9791 for (j = 0; j < server.dbnum; j++) {
9792 redisDb *db = server.db+j;
9793 /* Why maxtries is set to 100?
9794 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9795 * are swappable objects */
9796 int maxtries = 100;
9797
9798 if (dictSize(db->dict) == 0) continue;
9799 for (i = 0; i < 5; i++) {
9800 dictEntry *de;
9801 double swappability;
9802
9803 if (maxtries) maxtries--;
9804 de = dictGetRandomKey(db->dict);
9805 val = dictGetEntryVal(de);
9806 /* Only swap objects that are currently in memory.
9807 *
9808 * Also don't swap shared objects: not a good idea in general and
9809 * we need to ensure that the main thread does not touch the
9810 * object while the I/O thread is using it, but we can't
9811 * control other keys without adding additional mutex. */
9812 if (val->storage != REDIS_VM_MEMORY || val->refcount != 1) {
9813 if (maxtries) i--; /* don't count this try */
9814 continue;
9815 }
9816 swappability = computeObjectSwappability(val);
9817 if (!best || swappability > best_swappability) {
9818 best = de;
9819 best_swappability = swappability;
9820 best_db = db;
9821 }
9822 }
9823 }
9824 if (best == NULL) return REDIS_ERR;
9825 key = dictGetEntryKey(best);
9826 val = dictGetEntryVal(best);
9827
9828 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
9829 key, best_swappability);
9830
9831 /* Swap it */
9832 if (usethreads) {
9833 robj *keyobj = createStringObject(key,sdslen(key));
9834 vmSwapObjectThreaded(keyobj,val,best_db);
9835 decrRefCount(keyobj);
9836 return REDIS_OK;
9837 } else {
9838 vmpointer *vp;
9839
9840 if ((vp = vmSwapObjectBlocking(val)) != NULL) {
9841 dictGetEntryVal(best) = vp;
9842 return REDIS_OK;
9843 } else {
9844 return REDIS_ERR;
9845 }
9846 }
9847 }
9848
9849 static int vmSwapOneObjectBlocking() {
9850 return vmSwapOneObject(0);
9851 }
9852
9853 static int vmSwapOneObjectThreaded() {
9854 return vmSwapOneObject(1);
9855 }
9856
9857 /* Return true if it's safe to swap out objects in a given moment.
9858 * Basically we don't want to swap objects out while there is a BGSAVE
9859 * or a BGAEOREWRITE running in backgroud. */
9860 static int vmCanSwapOut(void) {
9861 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
9862 }
9863
9864 /* =================== Virtual Memory - Threaded I/O ======================= */
9865
9866 static void freeIOJob(iojob *j) {
9867 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
9868 j->type == REDIS_IOJOB_DO_SWAP ||
9869 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
9870 {
9871 /* we fix the storage type, otherwise decrRefCount() will try to
9872 * kill the I/O thread Job (that does no longer exists). */
9873 if (j->val->storage == REDIS_VM_SWAPPING)
9874 j->val->storage = REDIS_VM_MEMORY;
9875 decrRefCount(j->val);
9876 }
9877 decrRefCount(j->key);
9878 zfree(j);
9879 }
9880
9881 /* Every time a thread finished a Job, it writes a byte into the write side
9882 * of an unix pipe in order to "awake" the main thread, and this function
9883 * is called. */
9884 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
9885 int mask)
9886 {
9887 char buf[1];
9888 int retval, processed = 0, toprocess = -1, trytoswap = 1;
9889 REDIS_NOTUSED(el);
9890 REDIS_NOTUSED(mask);
9891 REDIS_NOTUSED(privdata);
9892
9893 /* For every byte we read in the read side of the pipe, there is one
9894 * I/O job completed to process. */
9895 while((retval = read(fd,buf,1)) == 1) {
9896 iojob *j;
9897 listNode *ln;
9898 struct dictEntry *de;
9899
9900 redisLog(REDIS_DEBUG,"Processing I/O completed job");
9901
9902 /* Get the processed element (the oldest one) */
9903 lockThreadedIO();
9904 assert(listLength(server.io_processed) != 0);
9905 if (toprocess == -1) {
9906 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
9907 if (toprocess <= 0) toprocess = 1;
9908 }
9909 ln = listFirst(server.io_processed);
9910 j = ln->value;
9911 listDelNode(server.io_processed,ln);
9912 unlockThreadedIO();
9913 /* If this job is marked as canceled, just ignore it */
9914 if (j->canceled) {
9915 freeIOJob(j);
9916 continue;
9917 }
9918 /* Post process it in the main thread, as there are things we
9919 * can do just here to avoid race conditions and/or invasive locks */
9920 redisLog(REDIS_DEBUG,"COMPLETED Job type: %d, ID %p, key: %s", j->type, (void*)j->id, (unsigned char*)j->key->ptr);
9921 de = dictFind(j->db->dict,j->key->ptr);
9922 redisAssert(de != NULL);
9923 if (j->type == REDIS_IOJOB_LOAD) {
9924 redisDb *db;
9925 vmpointer *vp = dictGetEntryVal(de);
9926
9927 /* Key loaded, bring it at home */
9928 vmMarkPagesFree(vp->page,vp->usedpages);
9929 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
9930 (unsigned char*) j->key->ptr);
9931 server.vm_stats_swapped_objects--;
9932 server.vm_stats_swapins++;
9933 dictGetEntryVal(de) = j->val;
9934 incrRefCount(j->val);
9935 db = j->db;
9936 /* Handle clients waiting for this key to be loaded. */
9937 handleClientsBlockedOnSwappedKey(db,j->key);
9938 freeIOJob(j);
9939 zfree(vp);
9940 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9941 /* Now we know the amount of pages required to swap this object.
9942 * Let's find some space for it, and queue this task again
9943 * rebranded as REDIS_IOJOB_DO_SWAP. */
9944 if (!vmCanSwapOut() ||
9945 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
9946 {
9947 /* Ooops... no space or we can't swap as there is
9948 * a fork()ed Redis trying to save stuff on disk. */
9949 j->val->storage = REDIS_VM_MEMORY; /* undo operation */
9950 freeIOJob(j);
9951 } else {
9952 /* Note that we need to mark this pages as used now,
9953 * if the job will be canceled, we'll mark them as freed
9954 * again. */
9955 vmMarkPagesUsed(j->page,j->pages);
9956 j->type = REDIS_IOJOB_DO_SWAP;
9957 lockThreadedIO();
9958 queueIOJob(j);
9959 unlockThreadedIO();
9960 }
9961 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9962 vmpointer *vp;
9963
9964 /* Key swapped. We can finally free some memory. */
9965 if (j->val->storage != REDIS_VM_SWAPPING) {
9966 vmpointer *vp = (vmpointer*) j->id;
9967 printf("storage: %d\n",vp->storage);
9968 printf("key->name: %s\n",(char*)j->key->ptr);
9969 printf("val: %p\n",(void*)j->val);
9970 printf("val->type: %d\n",j->val->type);
9971 printf("val->ptr: %s\n",(char*)j->val->ptr);
9972 }
9973 redisAssert(j->val->storage == REDIS_VM_SWAPPING);
9974 vp = createVmPointer(j->val->type);
9975 vp->page = j->page;
9976 vp->usedpages = j->pages;
9977 dictGetEntryVal(de) = vp;
9978 /* Fix the storage otherwise decrRefCount will attempt to
9979 * remove the associated I/O job */
9980 j->val->storage = REDIS_VM_MEMORY;
9981 decrRefCount(j->val);
9982 redisLog(REDIS_DEBUG,
9983 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9984 (unsigned char*) j->key->ptr,
9985 (unsigned long long) j->page, (unsigned long long) j->pages);
9986 server.vm_stats_swapped_objects++;
9987 server.vm_stats_swapouts++;
9988 freeIOJob(j);
9989 /* Put a few more swap requests in queue if we are still
9990 * out of memory */
9991 if (trytoswap && vmCanSwapOut() &&
9992 zmalloc_used_memory() > server.vm_max_memory)
9993 {
9994 int more = 1;
9995 while(more) {
9996 lockThreadedIO();
9997 more = listLength(server.io_newjobs) <
9998 (unsigned) server.vm_max_threads;
9999 unlockThreadedIO();
10000 /* Don't waste CPU time if swappable objects are rare. */
10001 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
10002 trytoswap = 0;
10003 break;
10004 }
10005 }
10006 }
10007 }
10008 processed++;
10009 if (processed == toprocess) return;
10010 }
10011 if (retval < 0 && errno != EAGAIN) {
10012 redisLog(REDIS_WARNING,
10013 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
10014 strerror(errno));
10015 }
10016 }
10017
10018 static void lockThreadedIO(void) {
10019 pthread_mutex_lock(&server.io_mutex);
10020 }
10021
10022 static void unlockThreadedIO(void) {
10023 pthread_mutex_unlock(&server.io_mutex);
10024 }
10025
10026 /* Remove the specified object from the threaded I/O queue if still not
10027 * processed, otherwise make sure to flag it as canceled. */
10028 static void vmCancelThreadedIOJob(robj *o) {
10029 list *lists[3] = {
10030 server.io_newjobs, /* 0 */
10031 server.io_processing, /* 1 */
10032 server.io_processed /* 2 */
10033 };
10034 int i;
10035
10036 assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
10037 again:
10038 lockThreadedIO();
10039 /* Search for a matching object in one of the queues */
10040 for (i = 0; i < 3; i++) {
10041 listNode *ln;
10042 listIter li;
10043
10044 listRewind(lists[i],&li);
10045 while ((ln = listNext(&li)) != NULL) {
10046 iojob *job = ln->value;
10047
10048 if (job->canceled) continue; /* Skip this, already canceled. */
10049 if (job->id == o) {
10050 redisLog(REDIS_DEBUG,"*** CANCELED %p (key %s) (type %d) (LIST ID %d)\n",
10051 (void*)job, (char*)job->key->ptr, job->type, i);
10052 /* Mark the pages as free since the swap didn't happened
10053 * or happened but is now discarded. */
10054 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
10055 vmMarkPagesFree(job->page,job->pages);
10056 /* Cancel the job. It depends on the list the job is
10057 * living in. */
10058 switch(i) {
10059 case 0: /* io_newjobs */
10060 /* If the job was yet not processed the best thing to do
10061 * is to remove it from the queue at all */
10062 freeIOJob(job);
10063 listDelNode(lists[i],ln);
10064 break;
10065 case 1: /* io_processing */
10066 /* Oh Shi- the thread is messing with the Job:
10067 *
10068 * Probably it's accessing the object if this is a
10069 * PREPARE_SWAP or DO_SWAP job.
10070 * If it's a LOAD job it may be reading from disk and
10071 * if we don't wait for the job to terminate before to
10072 * cancel it, maybe in a few microseconds data can be
10073 * corrupted in this pages. So the short story is:
10074 *
10075 * Better to wait for the job to move into the
10076 * next queue (processed)... */
10077
10078 /* We try again and again until the job is completed. */
10079 unlockThreadedIO();
10080 /* But let's wait some time for the I/O thread
10081 * to finish with this job. After all this condition
10082 * should be very rare. */
10083 usleep(1);
10084 goto again;
10085 case 2: /* io_processed */
10086 /* The job was already processed, that's easy...
10087 * just mark it as canceled so that we'll ignore it
10088 * when processing completed jobs. */
10089 job->canceled = 1;
10090 break;
10091 }
10092 /* Finally we have to adjust the storage type of the object
10093 * in order to "UNDO" the operaiton. */
10094 if (o->storage == REDIS_VM_LOADING)
10095 o->storage = REDIS_VM_SWAPPED;
10096 else if (o->storage == REDIS_VM_SWAPPING)
10097 o->storage = REDIS_VM_MEMORY;
10098 unlockThreadedIO();
10099 redisLog(REDIS_DEBUG,"*** DONE");
10100 return;
10101 }
10102 }
10103 }
10104 unlockThreadedIO();
10105 printf("Not found: %p\n", (void*)o);
10106 redisAssert(1 != 1); /* We should never reach this */
10107 }
10108
10109 static void *IOThreadEntryPoint(void *arg) {
10110 iojob *j;
10111 listNode *ln;
10112 REDIS_NOTUSED(arg);
10113
10114 pthread_detach(pthread_self());
10115 while(1) {
10116 /* Get a new job to process */
10117 lockThreadedIO();
10118 if (listLength(server.io_newjobs) == 0) {
10119 /* No new jobs in queue, exit. */
10120 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
10121 (long) pthread_self());
10122 server.io_active_threads--;
10123 unlockThreadedIO();
10124 return NULL;
10125 }
10126 ln = listFirst(server.io_newjobs);
10127 j = ln->value;
10128 listDelNode(server.io_newjobs,ln);
10129 /* Add the job in the processing queue */
10130 j->thread = pthread_self();
10131 listAddNodeTail(server.io_processing,j);
10132 ln = listLast(server.io_processing); /* We use ln later to remove it */
10133 unlockThreadedIO();
10134 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
10135 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
10136
10137 /* Process the Job */
10138 if (j->type == REDIS_IOJOB_LOAD) {
10139 vmpointer *vp = (vmpointer*)j->id;
10140 j->val = vmReadObjectFromSwap(j->page,vp->vtype);
10141 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
10142 FILE *fp = fopen("/dev/null","w+");
10143 j->pages = rdbSavedObjectPages(j->val,fp);
10144 fclose(fp);
10145 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
10146 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
10147 j->canceled = 1;
10148 }
10149
10150 /* Done: insert the job into the processed queue */
10151 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
10152 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
10153 lockThreadedIO();
10154 listDelNode(server.io_processing,ln);
10155 listAddNodeTail(server.io_processed,j);
10156 unlockThreadedIO();
10157
10158 /* Signal the main thread there is new stuff to process */
10159 assert(write(server.io_ready_pipe_write,"x",1) == 1);
10160 }
10161 return NULL; /* never reached */
10162 }
10163
10164 static void spawnIOThread(void) {
10165 pthread_t thread;
10166 sigset_t mask, omask;
10167 int err;
10168
10169 sigemptyset(&mask);
10170 sigaddset(&mask,SIGCHLD);
10171 sigaddset(&mask,SIGHUP);
10172 sigaddset(&mask,SIGPIPE);
10173 pthread_sigmask(SIG_SETMASK, &mask, &omask);
10174 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
10175 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
10176 strerror(err));
10177 usleep(1000000);
10178 }
10179 pthread_sigmask(SIG_SETMASK, &omask, NULL);
10180 server.io_active_threads++;
10181 }
10182
10183 /* We need to wait for the last thread to exit before we are able to
10184 * fork() in order to BGSAVE or BGREWRITEAOF. */
10185 static void waitEmptyIOJobsQueue(void) {
10186 while(1) {
10187 int io_processed_len;
10188
10189 lockThreadedIO();
10190 if (listLength(server.io_newjobs) == 0 &&
10191 listLength(server.io_processing) == 0 &&
10192 server.io_active_threads == 0)
10193 {
10194 unlockThreadedIO();
10195 return;
10196 }
10197 /* While waiting for empty jobs queue condition we post-process some
10198 * finshed job, as I/O threads may be hanging trying to write against
10199 * the io_ready_pipe_write FD but there are so much pending jobs that
10200 * it's blocking. */
10201 io_processed_len = listLength(server.io_processed);
10202 unlockThreadedIO();
10203 if (io_processed_len) {
10204 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
10205 usleep(1000); /* 1 millisecond */
10206 } else {
10207 usleep(10000); /* 10 milliseconds */
10208 }
10209 }
10210 }
10211
10212 static void vmReopenSwapFile(void) {
10213 /* Note: we don't close the old one as we are in the child process
10214 * and don't want to mess at all with the original file object. */
10215 server.vm_fp = fopen(server.vm_swap_file,"r+b");
10216 if (server.vm_fp == NULL) {
10217 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
10218 server.vm_swap_file);
10219 _exit(1);
10220 }
10221 server.vm_fd = fileno(server.vm_fp);
10222 }
10223
10224 /* This function must be called while with threaded IO locked */
10225 static void queueIOJob(iojob *j) {
10226 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
10227 (void*)j, j->type, (char*)j->key->ptr);
10228 listAddNodeTail(server.io_newjobs,j);
10229 if (server.io_active_threads < server.vm_max_threads)
10230 spawnIOThread();
10231 }
10232
10233 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
10234 iojob *j;
10235
10236 j = zmalloc(sizeof(*j));
10237 j->type = REDIS_IOJOB_PREPARE_SWAP;
10238 j->db = db;
10239 j->key = key;
10240 incrRefCount(key);
10241 j->id = j->val = val;
10242 incrRefCount(val);
10243 j->canceled = 0;
10244 j->thread = (pthread_t) -1;
10245 val->storage = REDIS_VM_SWAPPING;
10246
10247 lockThreadedIO();
10248 queueIOJob(j);
10249 unlockThreadedIO();
10250 return REDIS_OK;
10251 }
10252
10253 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
10254
10255 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
10256 * If there is not already a job loading the key, it is craeted.
10257 * The key is added to the io_keys list in the client structure, and also
10258 * in the hash table mapping swapped keys to waiting clients, that is,
10259 * server.io_waited_keys. */
10260 static int waitForSwappedKey(redisClient *c, robj *key) {
10261 struct dictEntry *de;
10262 robj *o;
10263 list *l;
10264
10265 /* If the key does not exist or is already in RAM we don't need to
10266 * block the client at all. */
10267 de = dictFind(c->db->dict,key->ptr);
10268 if (de == NULL) return 0;
10269 o = dictGetEntryVal(de);
10270 if (o->storage == REDIS_VM_MEMORY) {
10271 return 0;
10272 } else if (o->storage == REDIS_VM_SWAPPING) {
10273 /* We were swapping the key, undo it! */
10274 vmCancelThreadedIOJob(o);
10275 return 0;
10276 }
10277
10278 /* OK: the key is either swapped, or being loaded just now. */
10279
10280 /* Add the key to the list of keys this client is waiting for.
10281 * This maps clients to keys they are waiting for. */
10282 listAddNodeTail(c->io_keys,key);
10283 incrRefCount(key);
10284
10285 /* Add the client to the swapped keys => clients waiting map. */
10286 de = dictFind(c->db->io_keys,key);
10287 if (de == NULL) {
10288 int retval;
10289
10290 /* For every key we take a list of clients blocked for it */
10291 l = listCreate();
10292 retval = dictAdd(c->db->io_keys,key,l);
10293 incrRefCount(key);
10294 assert(retval == DICT_OK);
10295 } else {
10296 l = dictGetEntryVal(de);
10297 }
10298 listAddNodeTail(l,c);
10299
10300 /* Are we already loading the key from disk? If not create a job */
10301 if (o->storage == REDIS_VM_SWAPPED) {
10302 iojob *j;
10303 vmpointer *vp = (vmpointer*)o;
10304
10305 o->storage = REDIS_VM_LOADING;
10306 j = zmalloc(sizeof(*j));
10307 j->type = REDIS_IOJOB_LOAD;
10308 j->db = c->db;
10309 j->id = (robj*)vp;
10310 j->key = key;
10311 incrRefCount(key);
10312 j->page = vp->page;
10313 j->val = NULL;
10314 j->canceled = 0;
10315 j->thread = (pthread_t) -1;
10316 lockThreadedIO();
10317 queueIOJob(j);
10318 unlockThreadedIO();
10319 }
10320 return 1;
10321 }
10322
10323 /* Preload keys for any command with first, last and step values for
10324 * the command keys prototype, as defined in the command table. */
10325 static void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10326 int j, last;
10327 if (cmd->vm_firstkey == 0) return;
10328 last = cmd->vm_lastkey;
10329 if (last < 0) last = argc+last;
10330 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
10331 redisAssert(j < argc);
10332 waitForSwappedKey(c,argv[j]);
10333 }
10334 }
10335
10336 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
10337 * Note that the number of keys to preload is user-defined, so we need to
10338 * apply a sanity check against argc. */
10339 static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10340 int i, num;
10341 REDIS_NOTUSED(cmd);
10342
10343 num = atoi(argv[2]->ptr);
10344 if (num > (argc-3)) return;
10345 for (i = 0; i < num; i++) {
10346 waitForSwappedKey(c,argv[3+i]);
10347 }
10348 }
10349
10350 /* Preload keys needed to execute the entire MULTI/EXEC block.
10351 *
10352 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
10353 * and will block the client when any command requires a swapped out value. */
10354 static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10355 int i, margc;
10356 struct redisCommand *mcmd;
10357 robj **margv;
10358 REDIS_NOTUSED(cmd);
10359 REDIS_NOTUSED(argc);
10360 REDIS_NOTUSED(argv);
10361
10362 if (!(c->flags & REDIS_MULTI)) return;
10363 for (i = 0; i < c->mstate.count; i++) {
10364 mcmd = c->mstate.commands[i].cmd;
10365 margc = c->mstate.commands[i].argc;
10366 margv = c->mstate.commands[i].argv;
10367
10368 if (mcmd->vm_preload_proc != NULL) {
10369 mcmd->vm_preload_proc(c,mcmd,margc,margv);
10370 } else {
10371 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
10372 }
10373 }
10374 }
10375
10376 /* Is this client attempting to run a command against swapped keys?
10377 * If so, block it ASAP, load the keys in background, then resume it.
10378 *
10379 * The important idea about this function is that it can fail! If keys will
10380 * still be swapped when the client is resumed, this key lookups will
10381 * just block loading keys from disk. In practical terms this should only
10382 * happen with SORT BY command or if there is a bug in this function.
10383 *
10384 * Return 1 if the client is marked as blocked, 0 if the client can
10385 * continue as the keys it is going to access appear to be in memory. */
10386 static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
10387 if (cmd->vm_preload_proc != NULL) {
10388 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
10389 } else {
10390 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
10391 }
10392
10393 /* If the client was blocked for at least one key, mark it as blocked. */
10394 if (listLength(c->io_keys)) {
10395 c->flags |= REDIS_IO_WAIT;
10396 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
10397 server.vm_blocked_clients++;
10398 return 1;
10399 } else {
10400 return 0;
10401 }
10402 }
10403
10404 /* Remove the 'key' from the list of blocked keys for a given client.
10405 *
10406 * The function returns 1 when there are no longer blocking keys after
10407 * the current one was removed (and the client can be unblocked). */
10408 static int dontWaitForSwappedKey(redisClient *c, robj *key) {
10409 list *l;
10410 listNode *ln;
10411 listIter li;
10412 struct dictEntry *de;
10413
10414 /* Remove the key from the list of keys this client is waiting for. */
10415 listRewind(c->io_keys,&li);
10416 while ((ln = listNext(&li)) != NULL) {
10417 if (equalStringObjects(ln->value,key)) {
10418 listDelNode(c->io_keys,ln);
10419 break;
10420 }
10421 }
10422 assert(ln != NULL);
10423
10424 /* Remove the client form the key => waiting clients map. */
10425 de = dictFind(c->db->io_keys,key);
10426 assert(de != NULL);
10427 l = dictGetEntryVal(de);
10428 ln = listSearchKey(l,c);
10429 assert(ln != NULL);
10430 listDelNode(l,ln);
10431 if (listLength(l) == 0)
10432 dictDelete(c->db->io_keys,key);
10433
10434 return listLength(c->io_keys) == 0;
10435 }
10436
10437 /* Every time we now a key was loaded back in memory, we handle clients
10438 * waiting for this key if any. */
10439 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
10440 struct dictEntry *de;
10441 list *l;
10442 listNode *ln;
10443 int len;
10444
10445 de = dictFind(db->io_keys,key);
10446 if (!de) return;
10447
10448 l = dictGetEntryVal(de);
10449 len = listLength(l);
10450 /* Note: we can't use something like while(listLength(l)) as the list
10451 * can be freed by the calling function when we remove the last element. */
10452 while (len--) {
10453 ln = listFirst(l);
10454 redisClient *c = ln->value;
10455
10456 if (dontWaitForSwappedKey(c,key)) {
10457 /* Put the client in the list of clients ready to go as we
10458 * loaded all the keys about it. */
10459 listAddNodeTail(server.io_ready_clients,c);
10460 }
10461 }
10462 }
10463
10464 /* =========================== Remote Configuration ========================= */
10465
10466 static void configSetCommand(redisClient *c) {
10467 robj *o = getDecodedObject(c->argv[3]);
10468 long long ll;
10469
10470 if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
10471 zfree(server.dbfilename);
10472 server.dbfilename = zstrdup(o->ptr);
10473 } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
10474 zfree(server.requirepass);
10475 server.requirepass = zstrdup(o->ptr);
10476 } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
10477 zfree(server.masterauth);
10478 server.masterauth = zstrdup(o->ptr);
10479 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
10480 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10481 ll < 0) goto badfmt;
10482 server.maxmemory = ll;
10483 } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
10484 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10485 ll < 0 || ll > LONG_MAX) goto badfmt;
10486 server.maxidletime = ll;
10487 } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
10488 if (!strcasecmp(o->ptr,"no")) {
10489 server.appendfsync = APPENDFSYNC_NO;
10490 } else if (!strcasecmp(o->ptr,"everysec")) {
10491 server.appendfsync = APPENDFSYNC_EVERYSEC;
10492 } else if (!strcasecmp(o->ptr,"always")) {
10493 server.appendfsync = APPENDFSYNC_ALWAYS;
10494 } else {
10495 goto badfmt;
10496 }
10497 } else if (!strcasecmp(c->argv[2]->ptr,"no-appendfsync-on-rewrite")) {
10498 int yn = yesnotoi(o->ptr);
10499
10500 if (yn == -1) goto badfmt;
10501 server.no_appendfsync_on_rewrite = yn;
10502 } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
10503 int old = server.appendonly;
10504 int new = yesnotoi(o->ptr);
10505
10506 if (new == -1) goto badfmt;
10507 if (old != new) {
10508 if (new == 0) {
10509 stopAppendOnly();
10510 } else {
10511 if (startAppendOnly() == REDIS_ERR) {
10512 addReplySds(c,sdscatprintf(sdsempty(),
10513 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
10514 decrRefCount(o);
10515 return;
10516 }
10517 }
10518 }
10519 } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
10520 int vlen, j;
10521 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
10522
10523 /* Perform sanity check before setting the new config:
10524 * - Even number of args
10525 * - Seconds >= 1, changes >= 0 */
10526 if (vlen & 1) {
10527 sdsfreesplitres(v,vlen);
10528 goto badfmt;
10529 }
10530 for (j = 0; j < vlen; j++) {
10531 char *eptr;
10532 long val;
10533
10534 val = strtoll(v[j], &eptr, 10);
10535 if (eptr[0] != '\0' ||
10536 ((j & 1) == 0 && val < 1) ||
10537 ((j & 1) == 1 && val < 0)) {
10538 sdsfreesplitres(v,vlen);
10539 goto badfmt;
10540 }
10541 }
10542 /* Finally set the new config */
10543 resetServerSaveParams();
10544 for (j = 0; j < vlen; j += 2) {
10545 time_t seconds;
10546 int changes;
10547
10548 seconds = strtoll(v[j],NULL,10);
10549 changes = strtoll(v[j+1],NULL,10);
10550 appendServerSaveParams(seconds, changes);
10551 }
10552 sdsfreesplitres(v,vlen);
10553 } else {
10554 addReplySds(c,sdscatprintf(sdsempty(),
10555 "-ERR not supported CONFIG parameter %s\r\n",
10556 (char*)c->argv[2]->ptr));
10557 decrRefCount(o);
10558 return;
10559 }
10560 decrRefCount(o);
10561 addReply(c,shared.ok);
10562 return;
10563
10564 badfmt: /* Bad format errors */
10565 addReplySds(c,sdscatprintf(sdsempty(),
10566 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
10567 (char*)o->ptr,
10568 (char*)c->argv[2]->ptr));
10569 decrRefCount(o);
10570 }
10571
10572 static void configGetCommand(redisClient *c) {
10573 robj *o = getDecodedObject(c->argv[2]);
10574 robj *lenobj = createObject(REDIS_STRING,NULL);
10575 char *pattern = o->ptr;
10576 int matches = 0;
10577
10578 addReply(c,lenobj);
10579 decrRefCount(lenobj);
10580
10581 if (stringmatch(pattern,"dbfilename",0)) {
10582 addReplyBulkCString(c,"dbfilename");
10583 addReplyBulkCString(c,server.dbfilename);
10584 matches++;
10585 }
10586 if (stringmatch(pattern,"requirepass",0)) {
10587 addReplyBulkCString(c,"requirepass");
10588 addReplyBulkCString(c,server.requirepass);
10589 matches++;
10590 }
10591 if (stringmatch(pattern,"masterauth",0)) {
10592 addReplyBulkCString(c,"masterauth");
10593 addReplyBulkCString(c,server.masterauth);
10594 matches++;
10595 }
10596 if (stringmatch(pattern,"maxmemory",0)) {
10597 char buf[128];
10598
10599 ll2string(buf,128,server.maxmemory);
10600 addReplyBulkCString(c,"maxmemory");
10601 addReplyBulkCString(c,buf);
10602 matches++;
10603 }
10604 if (stringmatch(pattern,"timeout",0)) {
10605 char buf[128];
10606
10607 ll2string(buf,128,server.maxidletime);
10608 addReplyBulkCString(c,"timeout");
10609 addReplyBulkCString(c,buf);
10610 matches++;
10611 }
10612 if (stringmatch(pattern,"appendonly",0)) {
10613 addReplyBulkCString(c,"appendonly");
10614 addReplyBulkCString(c,server.appendonly ? "yes" : "no");
10615 matches++;
10616 }
10617 if (stringmatch(pattern,"no-appendfsync-on-rewrite",0)) {
10618 addReplyBulkCString(c,"no-appendfsync-on-rewrite");
10619 addReplyBulkCString(c,server.no_appendfsync_on_rewrite ? "yes" : "no");
10620 matches++;
10621 }
10622 if (stringmatch(pattern,"appendfsync",0)) {
10623 char *policy;
10624
10625 switch(server.appendfsync) {
10626 case APPENDFSYNC_NO: policy = "no"; break;
10627 case APPENDFSYNC_EVERYSEC: policy = "everysec"; break;
10628 case APPENDFSYNC_ALWAYS: policy = "always"; break;
10629 default: policy = "unknown"; break; /* too harmless to panic */
10630 }
10631 addReplyBulkCString(c,"appendfsync");
10632 addReplyBulkCString(c,policy);
10633 matches++;
10634 }
10635 if (stringmatch(pattern,"save",0)) {
10636 sds buf = sdsempty();
10637 int j;
10638
10639 for (j = 0; j < server.saveparamslen; j++) {
10640 buf = sdscatprintf(buf,"%ld %d",
10641 server.saveparams[j].seconds,
10642 server.saveparams[j].changes);
10643 if (j != server.saveparamslen-1)
10644 buf = sdscatlen(buf," ",1);
10645 }
10646 addReplyBulkCString(c,"save");
10647 addReplyBulkCString(c,buf);
10648 sdsfree(buf);
10649 matches++;
10650 }
10651 decrRefCount(o);
10652 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",matches*2);
10653 }
10654
10655 static void configCommand(redisClient *c) {
10656 if (!strcasecmp(c->argv[1]->ptr,"set")) {
10657 if (c->argc != 4) goto badarity;
10658 configSetCommand(c);
10659 } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
10660 if (c->argc != 3) goto badarity;
10661 configGetCommand(c);
10662 } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
10663 if (c->argc != 2) goto badarity;
10664 server.stat_numcommands = 0;
10665 server.stat_numconnections = 0;
10666 server.stat_expiredkeys = 0;
10667 server.stat_starttime = time(NULL);
10668 addReply(c,shared.ok);
10669 } else {
10670 addReplySds(c,sdscatprintf(sdsempty(),
10671 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10672 }
10673 return;
10674
10675 badarity:
10676 addReplySds(c,sdscatprintf(sdsempty(),
10677 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10678 (char*) c->argv[1]->ptr));
10679 }
10680
10681 /* =========================== Pubsub implementation ======================== */
10682
10683 static void freePubsubPattern(void *p) {
10684 pubsubPattern *pat = p;
10685
10686 decrRefCount(pat->pattern);
10687 zfree(pat);
10688 }
10689
10690 static int listMatchPubsubPattern(void *a, void *b) {
10691 pubsubPattern *pa = a, *pb = b;
10692
10693 return (pa->client == pb->client) &&
10694 (equalStringObjects(pa->pattern,pb->pattern));
10695 }
10696
10697 /* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10698 * 0 if the client was already subscribed to that channel. */
10699 static int pubsubSubscribeChannel(redisClient *c, robj *channel) {
10700 struct dictEntry *de;
10701 list *clients = NULL;
10702 int retval = 0;
10703
10704 /* Add the channel to the client -> channels hash table */
10705 if (dictAdd(c->pubsub_channels,channel,NULL) == DICT_OK) {
10706 retval = 1;
10707 incrRefCount(channel);
10708 /* Add the client to the channel -> list of clients hash table */
10709 de = dictFind(server.pubsub_channels,channel);
10710 if (de == NULL) {
10711 clients = listCreate();
10712 dictAdd(server.pubsub_channels,channel,clients);
10713 incrRefCount(channel);
10714 } else {
10715 clients = dictGetEntryVal(de);
10716 }
10717 listAddNodeTail(clients,c);
10718 }
10719 /* Notify the client */
10720 addReply(c,shared.mbulk3);
10721 addReply(c,shared.subscribebulk);
10722 addReplyBulk(c,channel);
10723 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10724 return retval;
10725 }
10726
10727 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10728 * 0 if the client was not subscribed to the specified channel. */
10729 static int pubsubUnsubscribeChannel(redisClient *c, robj *channel, int notify) {
10730 struct dictEntry *de;
10731 list *clients;
10732 listNode *ln;
10733 int retval = 0;
10734
10735 /* Remove the channel from the client -> channels hash table */
10736 incrRefCount(channel); /* channel may be just a pointer to the same object
10737 we have in the hash tables. Protect it... */
10738 if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
10739 retval = 1;
10740 /* Remove the client from the channel -> clients list hash table */
10741 de = dictFind(server.pubsub_channels,channel);
10742 assert(de != NULL);
10743 clients = dictGetEntryVal(de);
10744 ln = listSearchKey(clients,c);
10745 assert(ln != NULL);
10746 listDelNode(clients,ln);
10747 if (listLength(clients) == 0) {
10748 /* Free the list and associated hash entry at all if this was
10749 * the latest client, so that it will be possible to abuse
10750 * Redis PUBSUB creating millions of channels. */
10751 dictDelete(server.pubsub_channels,channel);
10752 }
10753 }
10754 /* Notify the client */
10755 if (notify) {
10756 addReply(c,shared.mbulk3);
10757 addReply(c,shared.unsubscribebulk);
10758 addReplyBulk(c,channel);
10759 addReplyLongLong(c,dictSize(c->pubsub_channels)+
10760 listLength(c->pubsub_patterns));
10761
10762 }
10763 decrRefCount(channel); /* it is finally safe to release it */
10764 return retval;
10765 }
10766
10767 /* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10768 static int pubsubSubscribePattern(redisClient *c, robj *pattern) {
10769 int retval = 0;
10770
10771 if (listSearchKey(c->pubsub_patterns,pattern) == NULL) {
10772 retval = 1;
10773 pubsubPattern *pat;
10774 listAddNodeTail(c->pubsub_patterns,pattern);
10775 incrRefCount(pattern);
10776 pat = zmalloc(sizeof(*pat));
10777 pat->pattern = getDecodedObject(pattern);
10778 pat->client = c;
10779 listAddNodeTail(server.pubsub_patterns,pat);
10780 }
10781 /* Notify the client */
10782 addReply(c,shared.mbulk3);
10783 addReply(c,shared.psubscribebulk);
10784 addReplyBulk(c,pattern);
10785 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10786 return retval;
10787 }
10788
10789 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10790 * 0 if the client was not subscribed to the specified channel. */
10791 static int pubsubUnsubscribePattern(redisClient *c, robj *pattern, int notify) {
10792 listNode *ln;
10793 pubsubPattern pat;
10794 int retval = 0;
10795
10796 incrRefCount(pattern); /* Protect the object. May be the same we remove */
10797 if ((ln = listSearchKey(c->pubsub_patterns,pattern)) != NULL) {
10798 retval = 1;
10799 listDelNode(c->pubsub_patterns,ln);
10800 pat.client = c;
10801 pat.pattern = pattern;
10802 ln = listSearchKey(server.pubsub_patterns,&pat);
10803 listDelNode(server.pubsub_patterns,ln);
10804 }
10805 /* Notify the client */
10806 if (notify) {
10807 addReply(c,shared.mbulk3);
10808 addReply(c,shared.punsubscribebulk);
10809 addReplyBulk(c,pattern);
10810 addReplyLongLong(c,dictSize(c->pubsub_channels)+
10811 listLength(c->pubsub_patterns));
10812 }
10813 decrRefCount(pattern);
10814 return retval;
10815 }
10816
10817 /* Unsubscribe from all the channels. Return the number of channels the
10818 * client was subscribed from. */
10819 static int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
10820 dictIterator *di = dictGetIterator(c->pubsub_channels);
10821 dictEntry *de;
10822 int count = 0;
10823
10824 while((de = dictNext(di)) != NULL) {
10825 robj *channel = dictGetEntryKey(de);
10826
10827 count += pubsubUnsubscribeChannel(c,channel,notify);
10828 }
10829 dictReleaseIterator(di);
10830 return count;
10831 }
10832
10833 /* Unsubscribe from all the patterns. Return the number of patterns the
10834 * client was subscribed from. */
10835 static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify) {
10836 listNode *ln;
10837 listIter li;
10838 int count = 0;
10839
10840 listRewind(c->pubsub_patterns,&li);
10841 while ((ln = listNext(&li)) != NULL) {
10842 robj *pattern = ln->value;
10843
10844 count += pubsubUnsubscribePattern(c,pattern,notify);
10845 }
10846 return count;
10847 }
10848
10849 /* Publish a message */
10850 static int pubsubPublishMessage(robj *channel, robj *message) {
10851 int receivers = 0;
10852 struct dictEntry *de;
10853 listNode *ln;
10854 listIter li;
10855
10856 /* Send to clients listening for that channel */
10857 de = dictFind(server.pubsub_channels,channel);
10858 if (de) {
10859 list *list = dictGetEntryVal(de);
10860 listNode *ln;
10861 listIter li;
10862
10863 listRewind(list,&li);
10864 while ((ln = listNext(&li)) != NULL) {
10865 redisClient *c = ln->value;
10866
10867 addReply(c,shared.mbulk3);
10868 addReply(c,shared.messagebulk);
10869 addReplyBulk(c,channel);
10870 addReplyBulk(c,message);
10871 receivers++;
10872 }
10873 }
10874 /* Send to clients listening to matching channels */
10875 if (listLength(server.pubsub_patterns)) {
10876 listRewind(server.pubsub_patterns,&li);
10877 channel = getDecodedObject(channel);
10878 while ((ln = listNext(&li)) != NULL) {
10879 pubsubPattern *pat = ln->value;
10880
10881 if (stringmatchlen((char*)pat->pattern->ptr,
10882 sdslen(pat->pattern->ptr),
10883 (char*)channel->ptr,
10884 sdslen(channel->ptr),0)) {
10885 addReply(pat->client,shared.mbulk4);
10886 addReply(pat->client,shared.pmessagebulk);
10887 addReplyBulk(pat->client,pat->pattern);
10888 addReplyBulk(pat->client,channel);
10889 addReplyBulk(pat->client,message);
10890 receivers++;
10891 }
10892 }
10893 decrRefCount(channel);
10894 }
10895 return receivers;
10896 }
10897
10898 static void subscribeCommand(redisClient *c) {
10899 int j;
10900
10901 for (j = 1; j < c->argc; j++)
10902 pubsubSubscribeChannel(c,c->argv[j]);
10903 }
10904
10905 static void unsubscribeCommand(redisClient *c) {
10906 if (c->argc == 1) {
10907 pubsubUnsubscribeAllChannels(c,1);
10908 return;
10909 } else {
10910 int j;
10911
10912 for (j = 1; j < c->argc; j++)
10913 pubsubUnsubscribeChannel(c,c->argv[j],1);
10914 }
10915 }
10916
10917 static void psubscribeCommand(redisClient *c) {
10918 int j;
10919
10920 for (j = 1; j < c->argc; j++)
10921 pubsubSubscribePattern(c,c->argv[j]);
10922 }
10923
10924 static void punsubscribeCommand(redisClient *c) {
10925 if (c->argc == 1) {
10926 pubsubUnsubscribeAllPatterns(c,1);
10927 return;
10928 } else {
10929 int j;
10930
10931 for (j = 1; j < c->argc; j++)
10932 pubsubUnsubscribePattern(c,c->argv[j],1);
10933 }
10934 }
10935
10936 static void publishCommand(redisClient *c) {
10937 int receivers = pubsubPublishMessage(c->argv[1],c->argv[2]);
10938 addReplyLongLong(c,receivers);
10939 }
10940
10941 /* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
10942 *
10943 * The implementation uses a per-DB hash table mapping keys to list of clients
10944 * WATCHing those keys, so that given a key that is going to be modified
10945 * we can mark all the associated clients as dirty.
10946 *
10947 * Also every client contains a list of WATCHed keys so that's possible to
10948 * un-watch such keys when the client is freed or when UNWATCH is called. */
10949
10950 /* In the client->watched_keys list we need to use watchedKey structures
10951 * as in order to identify a key in Redis we need both the key name and the
10952 * DB */
10953 typedef struct watchedKey {
10954 robj *key;
10955 redisDb *db;
10956 } watchedKey;
10957
10958 /* Watch for the specified key */
10959 static void watchForKey(redisClient *c, robj *key) {
10960 list *clients = NULL;
10961 listIter li;
10962 listNode *ln;
10963 watchedKey *wk;
10964
10965 /* Check if we are already watching for this key */
10966 listRewind(c->watched_keys,&li);
10967 while((ln = listNext(&li))) {
10968 wk = listNodeValue(ln);
10969 if (wk->db == c->db && equalStringObjects(key,wk->key))
10970 return; /* Key already watched */
10971 }
10972 /* This key is not already watched in this DB. Let's add it */
10973 clients = dictFetchValue(c->db->watched_keys,key);
10974 if (!clients) {
10975 clients = listCreate();
10976 dictAdd(c->db->watched_keys,key,clients);
10977 incrRefCount(key);
10978 }
10979 listAddNodeTail(clients,c);
10980 /* Add the new key to the lits of keys watched by this client */
10981 wk = zmalloc(sizeof(*wk));
10982 wk->key = key;
10983 wk->db = c->db;
10984 incrRefCount(key);
10985 listAddNodeTail(c->watched_keys,wk);
10986 }
10987
10988 /* Unwatch all the keys watched by this client. To clean the EXEC dirty
10989 * flag is up to the caller. */
10990 static void unwatchAllKeys(redisClient *c) {
10991 listIter li;
10992 listNode *ln;
10993
10994 if (listLength(c->watched_keys) == 0) return;
10995 listRewind(c->watched_keys,&li);
10996 while((ln = listNext(&li))) {
10997 list *clients;
10998 watchedKey *wk;
10999
11000 /* Lookup the watched key -> clients list and remove the client
11001 * from the list */
11002 wk = listNodeValue(ln);
11003 clients = dictFetchValue(wk->db->watched_keys, wk->key);
11004 assert(clients != NULL);
11005 listDelNode(clients,listSearchKey(clients,c));
11006 /* Kill the entry at all if this was the only client */
11007 if (listLength(clients) == 0)
11008 dictDelete(wk->db->watched_keys, wk->key);
11009 /* Remove this watched key from the client->watched list */
11010 listDelNode(c->watched_keys,ln);
11011 decrRefCount(wk->key);
11012 zfree(wk);
11013 }
11014 }
11015
11016 /* "Touch" a key, so that if this key is being WATCHed by some client the
11017 * next EXEC will fail. */
11018 static void touchWatchedKey(redisDb *db, robj *key) {
11019 list *clients;
11020 listIter li;
11021 listNode *ln;
11022
11023 if (dictSize(db->watched_keys) == 0) return;
11024 clients = dictFetchValue(db->watched_keys, key);
11025 if (!clients) return;
11026
11027 /* Mark all the clients watching this key as REDIS_DIRTY_CAS */
11028 /* Check if we are already watching for this key */
11029 listRewind(clients,&li);
11030 while((ln = listNext(&li))) {
11031 redisClient *c = listNodeValue(ln);
11032
11033 c->flags |= REDIS_DIRTY_CAS;
11034 }
11035 }
11036
11037 /* On FLUSHDB or FLUSHALL all the watched keys that are present before the
11038 * flush but will be deleted as effect of the flushing operation should
11039 * be touched. "dbid" is the DB that's getting the flush. -1 if it is
11040 * a FLUSHALL operation (all the DBs flushed). */
11041 static void touchWatchedKeysOnFlush(int dbid) {
11042 listIter li1, li2;
11043 listNode *ln;
11044
11045 /* For every client, check all the waited keys */
11046 listRewind(server.clients,&li1);
11047 while((ln = listNext(&li1))) {
11048 redisClient *c = listNodeValue(ln);
11049 listRewind(c->watched_keys,&li2);
11050 while((ln = listNext(&li2))) {
11051 watchedKey *wk = listNodeValue(ln);
11052
11053 /* For every watched key matching the specified DB, if the
11054 * key exists, mark the client as dirty, as the key will be
11055 * removed. */
11056 if (dbid == -1 || wk->db->id == dbid) {
11057 if (dictFind(wk->db->dict, wk->key->ptr) != NULL)
11058 c->flags |= REDIS_DIRTY_CAS;
11059 }
11060 }
11061 }
11062 }
11063
11064 static void watchCommand(redisClient *c) {
11065 int j;
11066
11067 if (c->flags & REDIS_MULTI) {
11068 addReplySds(c,sdsnew("-ERR WATCH inside MULTI is not allowed\r\n"));
11069 return;
11070 }
11071 for (j = 1; j < c->argc; j++)
11072 watchForKey(c,c->argv[j]);
11073 addReply(c,shared.ok);
11074 }
11075
11076 static void unwatchCommand(redisClient *c) {
11077 unwatchAllKeys(c);
11078 c->flags &= (~REDIS_DIRTY_CAS);
11079 addReply(c,shared.ok);
11080 }
11081
11082 /* ================================= Debugging ============================== */
11083
11084 /* Compute the sha1 of string at 's' with 'len' bytes long.
11085 * The SHA1 is then xored againt the string pointed by digest.
11086 * Since xor is commutative, this operation is used in order to
11087 * "add" digests relative to unordered elements.
11088 *
11089 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
11090 static void xorDigest(unsigned char *digest, void *ptr, size_t len) {
11091 SHA1_CTX ctx;
11092 unsigned char hash[20], *s = ptr;
11093 int j;
11094
11095 SHA1Init(&ctx);
11096 SHA1Update(&ctx,s,len);
11097 SHA1Final(hash,&ctx);
11098
11099 for (j = 0; j < 20; j++)
11100 digest[j] ^= hash[j];
11101 }
11102
11103 static void xorObjectDigest(unsigned char *digest, robj *o) {
11104 o = getDecodedObject(o);
11105 xorDigest(digest,o->ptr,sdslen(o->ptr));
11106 decrRefCount(o);
11107 }
11108
11109 /* This function instead of just computing the SHA1 and xoring it
11110 * against diget, also perform the digest of "digest" itself and
11111 * replace the old value with the new one.
11112 *
11113 * So the final digest will be:
11114 *
11115 * digest = SHA1(digest xor SHA1(data))
11116 *
11117 * This function is used every time we want to preserve the order so
11118 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
11119 *
11120 * Also note that mixdigest("foo") followed by mixdigest("bar")
11121 * will lead to a different digest compared to "fo", "obar".
11122 */
11123 static void mixDigest(unsigned char *digest, void *ptr, size_t len) {
11124 SHA1_CTX ctx;
11125 char *s = ptr;
11126
11127 xorDigest(digest,s,len);
11128 SHA1Init(&ctx);
11129 SHA1Update(&ctx,digest,20);
11130 SHA1Final(digest,&ctx);
11131 }
11132
11133 static void mixObjectDigest(unsigned char *digest, robj *o) {
11134 o = getDecodedObject(o);
11135 mixDigest(digest,o->ptr,sdslen(o->ptr));
11136 decrRefCount(o);
11137 }
11138
11139 /* Compute the dataset digest. Since keys, sets elements, hashes elements
11140 * are not ordered, we use a trick: every aggregate digest is the xor
11141 * of the digests of their elements. This way the order will not change
11142 * the result. For list instead we use a feedback entering the output digest
11143 * as input in order to ensure that a different ordered list will result in
11144 * a different digest. */
11145 static void computeDatasetDigest(unsigned char *final) {
11146 unsigned char digest[20];
11147 char buf[128];
11148 dictIterator *di = NULL;
11149 dictEntry *de;
11150 int j;
11151 uint32_t aux;
11152
11153 memset(final,0,20); /* Start with a clean result */
11154
11155 for (j = 0; j < server.dbnum; j++) {
11156 redisDb *db = server.db+j;
11157
11158 if (dictSize(db->dict) == 0) continue;
11159 di = dictGetIterator(db->dict);
11160
11161 /* hash the DB id, so the same dataset moved in a different
11162 * DB will lead to a different digest */
11163 aux = htonl(j);
11164 mixDigest(final,&aux,sizeof(aux));
11165
11166 /* Iterate this DB writing every entry */
11167 while((de = dictNext(di)) != NULL) {
11168 sds key;
11169 robj *keyobj, *o;
11170 time_t expiretime;
11171
11172 memset(digest,0,20); /* This key-val digest */
11173 key = dictGetEntryKey(de);
11174 keyobj = createStringObject(key,sdslen(key));
11175
11176 mixDigest(digest,key,sdslen(key));
11177
11178 /* Make sure the key is loaded if VM is active */
11179 o = lookupKeyRead(db,keyobj);
11180
11181 aux = htonl(o->type);
11182 mixDigest(digest,&aux,sizeof(aux));
11183 expiretime = getExpire(db,keyobj);
11184
11185 /* Save the key and associated value */
11186 if (o->type == REDIS_STRING) {
11187 mixObjectDigest(digest,o);
11188 } else if (o->type == REDIS_LIST) {
11189 listTypeIterator *li = listTypeInitIterator(o,0,REDIS_TAIL);
11190 listTypeEntry entry;
11191 while(listTypeNext(li,&entry)) {
11192 robj *eleobj = listTypeGet(&entry);
11193 mixObjectDigest(digest,eleobj);
11194 decrRefCount(eleobj);
11195 }
11196 listTypeReleaseIterator(li);
11197 } else if (o->type == REDIS_SET) {
11198 dict *set = o->ptr;
11199 dictIterator *di = dictGetIterator(set);
11200 dictEntry *de;
11201
11202 while((de = dictNext(di)) != NULL) {
11203 robj *eleobj = dictGetEntryKey(de);
11204
11205 xorObjectDigest(digest,eleobj);
11206 }
11207 dictReleaseIterator(di);
11208 } else if (o->type == REDIS_ZSET) {
11209 zset *zs = o->ptr;
11210 dictIterator *di = dictGetIterator(zs->dict);
11211 dictEntry *de;
11212
11213 while((de = dictNext(di)) != NULL) {
11214 robj *eleobj = dictGetEntryKey(de);
11215 double *score = dictGetEntryVal(de);
11216 unsigned char eledigest[20];
11217
11218 snprintf(buf,sizeof(buf),"%.17g",*score);
11219 memset(eledigest,0,20);
11220 mixObjectDigest(eledigest,eleobj);
11221 mixDigest(eledigest,buf,strlen(buf));
11222 xorDigest(digest,eledigest,20);
11223 }
11224 dictReleaseIterator(di);
11225 } else if (o->type == REDIS_HASH) {
11226 hashTypeIterator *hi;
11227 robj *obj;
11228
11229 hi = hashTypeInitIterator(o);
11230 while (hashTypeNext(hi) != REDIS_ERR) {
11231 unsigned char eledigest[20];
11232
11233 memset(eledigest,0,20);
11234 obj = hashTypeCurrent(hi,REDIS_HASH_KEY);
11235 mixObjectDigest(eledigest,obj);
11236 decrRefCount(obj);
11237 obj = hashTypeCurrent(hi,REDIS_HASH_VALUE);
11238 mixObjectDigest(eledigest,obj);
11239 decrRefCount(obj);
11240 xorDigest(digest,eledigest,20);
11241 }
11242 hashTypeReleaseIterator(hi);
11243 } else {
11244 redisPanic("Unknown object type");
11245 }
11246 /* If the key has an expire, add it to the mix */
11247 if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
11248 /* We can finally xor the key-val digest to the final digest */
11249 xorDigest(final,digest,20);
11250 decrRefCount(keyobj);
11251 }
11252 dictReleaseIterator(di);
11253 }
11254 }
11255
11256 static void debugCommand(redisClient *c) {
11257 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
11258 *((char*)-1) = 'x';
11259 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
11260 if (rdbSave(server.dbfilename) != REDIS_OK) {
11261 addReply(c,shared.err);
11262 return;
11263 }
11264 emptyDb();
11265 if (rdbLoad(server.dbfilename) != REDIS_OK) {
11266 addReply(c,shared.err);
11267 return;
11268 }
11269 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
11270 addReply(c,shared.ok);
11271 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
11272 emptyDb();
11273 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
11274 addReply(c,shared.err);
11275 return;
11276 }
11277 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
11278 addReply(c,shared.ok);
11279 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
11280 dictEntry *de = dictFind(c->db->dict,c->argv[2]->ptr);
11281 robj *val;
11282
11283 if (!de) {
11284 addReply(c,shared.nokeyerr);
11285 return;
11286 }
11287 val = dictGetEntryVal(de);
11288 if (!server.vm_enabled || (val->storage == REDIS_VM_MEMORY ||
11289 val->storage == REDIS_VM_SWAPPING)) {
11290 char *strenc;
11291 char buf[128];
11292
11293 if (val->encoding < (sizeof(strencoding)/sizeof(char*))) {
11294 strenc = strencoding[val->encoding];
11295 } else {
11296 snprintf(buf,64,"unknown encoding %d\n", val->encoding);
11297 strenc = buf;
11298 }
11299 addReplySds(c,sdscatprintf(sdsempty(),
11300 "+Value at:%p refcount:%d "
11301 "encoding:%s serializedlength:%lld\r\n",
11302 (void*)val, val->refcount,
11303 strenc, (long long) rdbSavedObjectLen(val,NULL)));
11304 } else {
11305 vmpointer *vp = (vmpointer*) val;
11306 addReplySds(c,sdscatprintf(sdsempty(),
11307 "+Value swapped at: page %llu "
11308 "using %llu pages\r\n",
11309 (unsigned long long) vp->page,
11310 (unsigned long long) vp->usedpages));
11311 }
11312 } else if (!strcasecmp(c->argv[1]->ptr,"swapin") && c->argc == 3) {
11313 lookupKeyRead(c->db,c->argv[2]);
11314 addReply(c,shared.ok);
11315 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
11316 dictEntry *de = dictFind(c->db->dict,c->argv[2]->ptr);
11317 robj *val;
11318 vmpointer *vp;
11319
11320 if (!server.vm_enabled) {
11321 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
11322 return;
11323 }
11324 if (!de) {
11325 addReply(c,shared.nokeyerr);
11326 return;
11327 }
11328 val = dictGetEntryVal(de);
11329 /* Swap it */
11330 if (val->storage != REDIS_VM_MEMORY) {
11331 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
11332 } else if (val->refcount != 1) {
11333 addReplySds(c,sdsnew("-ERR Object is shared\r\n"));
11334 } else if ((vp = vmSwapObjectBlocking(val)) != NULL) {
11335 dictGetEntryVal(de) = vp;
11336 addReply(c,shared.ok);
11337 } else {
11338 addReply(c,shared.err);
11339 }
11340 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
11341 long keys, j;
11342 robj *key, *val;
11343 char buf[128];
11344
11345 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
11346 return;
11347 for (j = 0; j < keys; j++) {
11348 snprintf(buf,sizeof(buf),"key:%lu",j);
11349 key = createStringObject(buf,strlen(buf));
11350 if (lookupKeyRead(c->db,key) != NULL) {
11351 decrRefCount(key);
11352 continue;
11353 }
11354 snprintf(buf,sizeof(buf),"value:%lu",j);
11355 val = createStringObject(buf,strlen(buf));
11356 dbAdd(c->db,key,val);
11357 decrRefCount(key);
11358 }
11359 addReply(c,shared.ok);
11360 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
11361 unsigned char digest[20];
11362 sds d = sdsnew("+");
11363 int j;
11364
11365 computeDatasetDigest(digest);
11366 for (j = 0; j < 20; j++)
11367 d = sdscatprintf(d, "%02x",digest[j]);
11368
11369 d = sdscatlen(d,"\r\n",2);
11370 addReplySds(c,d);
11371 } else {
11372 addReplySds(c,sdsnew(
11373 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
11374 }
11375 }
11376
11377 static void _redisAssert(char *estr, char *file, int line) {
11378 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
11379 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
11380 #ifdef HAVE_BACKTRACE
11381 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
11382 *((char*)-1) = 'x';
11383 #endif
11384 }
11385
11386 static void _redisPanic(char *msg, char *file, int line) {
11387 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
11388 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
11389 #ifdef HAVE_BACKTRACE
11390 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
11391 *((char*)-1) = 'x';
11392 #endif
11393 }
11394
11395 /* =================================== Main! ================================ */
11396
11397 #ifdef __linux__
11398 int linuxOvercommitMemoryValue(void) {
11399 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
11400 char buf[64];
11401
11402 if (!fp) return -1;
11403 if (fgets(buf,64,fp) == NULL) {
11404 fclose(fp);
11405 return -1;
11406 }
11407 fclose(fp);
11408
11409 return atoi(buf);
11410 }
11411
11412 void linuxOvercommitMemoryWarning(void) {
11413 if (linuxOvercommitMemoryValue() == 0) {
11414 redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.");
11415 }
11416 }
11417 #endif /* __linux__ */
11418
11419 static void daemonize(void) {
11420 int fd;
11421 FILE *fp;
11422
11423 if (fork() != 0) exit(0); /* parent exits */
11424 setsid(); /* create a new session */
11425
11426 /* Every output goes to /dev/null. If Redis is daemonized but
11427 * the 'logfile' is set to 'stdout' in the configuration file
11428 * it will not log at all. */
11429 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
11430 dup2(fd, STDIN_FILENO);
11431 dup2(fd, STDOUT_FILENO);
11432 dup2(fd, STDERR_FILENO);
11433 if (fd > STDERR_FILENO) close(fd);
11434 }
11435 /* Try to write the pid file */
11436 fp = fopen(server.pidfile,"w");
11437 if (fp) {
11438 fprintf(fp,"%d\n",getpid());
11439 fclose(fp);
11440 }
11441 }
11442
11443 static void version() {
11444 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
11445 REDIS_GIT_SHA1, atoi(REDIS_GIT_DIRTY) > 0);
11446 exit(0);
11447 }
11448
11449 static void usage() {
11450 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
11451 fprintf(stderr," ./redis-server - (read config from stdin)\n");
11452 exit(1);
11453 }
11454
11455 int main(int argc, char **argv) {
11456 time_t start;
11457
11458 initServerConfig();
11459 sortCommandTable();
11460 if (argc == 2) {
11461 if (strcmp(argv[1], "-v") == 0 ||
11462 strcmp(argv[1], "--version") == 0) version();
11463 if (strcmp(argv[1], "--help") == 0) usage();
11464 resetServerSaveParams();
11465 loadServerConfig(argv[1]);
11466 } else if ((argc > 2)) {
11467 usage();
11468 } else {
11469 redisLog(REDIS_WARNING,"Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf'");
11470 }
11471 if (server.daemonize) daemonize();
11472 initServer();
11473 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
11474 #ifdef __linux__
11475 linuxOvercommitMemoryWarning();
11476 #endif
11477 start = time(NULL);
11478 if (server.appendonly) {
11479 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
11480 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
11481 } else {
11482 if (rdbLoad(server.dbfilename) == REDIS_OK)
11483 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
11484 }
11485 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
11486 aeSetBeforeSleepProc(server.el,beforeSleep);
11487 aeMain(server.el);
11488 aeDeleteEventLoop(server.el);
11489 return 0;
11490 }
11491
11492 /* ============================= Backtrace support ========================= */
11493
11494 #ifdef HAVE_BACKTRACE
11495 static char *findFuncName(void *pointer, unsigned long *offset);
11496
11497 static void *getMcontextEip(ucontext_t *uc) {
11498 #if defined(__FreeBSD__)
11499 return (void*) uc->uc_mcontext.mc_eip;
11500 #elif defined(__dietlibc__)
11501 return (void*) uc->uc_mcontext.eip;
11502 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
11503 #if __x86_64__
11504 return (void*) uc->uc_mcontext->__ss.__rip;
11505 #else
11506 return (void*) uc->uc_mcontext->__ss.__eip;
11507 #endif
11508 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
11509 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
11510 return (void*) uc->uc_mcontext->__ss.__rip;
11511 #else
11512 return (void*) uc->uc_mcontext->__ss.__eip;
11513 #endif
11514 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
11515 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
11516 #elif defined(__ia64__) /* Linux IA64 */
11517 return (void*) uc->uc_mcontext.sc_ip;
11518 #else
11519 return NULL;
11520 #endif
11521 }
11522
11523 static void segvHandler(int sig, siginfo_t *info, void *secret) {
11524 void *trace[100];
11525 char **messages = NULL;
11526 int i, trace_size = 0;
11527 unsigned long offset=0;
11528 ucontext_t *uc = (ucontext_t*) secret;
11529 sds infostring;
11530 REDIS_NOTUSED(info);
11531
11532 redisLog(REDIS_WARNING,
11533 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
11534 infostring = genRedisInfoString();
11535 redisLog(REDIS_WARNING, "%s",infostring);
11536 /* It's not safe to sdsfree() the returned string under memory
11537 * corruption conditions. Let it leak as we are going to abort */
11538
11539 trace_size = backtrace(trace, 100);
11540 /* overwrite sigaction with caller's address */
11541 if (getMcontextEip(uc) != NULL) {
11542 trace[1] = getMcontextEip(uc);
11543 }
11544 messages = backtrace_symbols(trace, trace_size);
11545
11546 for (i=1; i<trace_size; ++i) {
11547 char *fn = findFuncName(trace[i], &offset), *p;
11548
11549 p = strchr(messages[i],'+');
11550 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
11551 redisLog(REDIS_WARNING,"%s", messages[i]);
11552 } else {
11553 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
11554 }
11555 }
11556 /* free(messages); Don't call free() with possibly corrupted memory. */
11557 _exit(0);
11558 }
11559
11560 static void sigtermHandler(int sig) {
11561 REDIS_NOTUSED(sig);
11562
11563 redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
11564 server.shutdown_asap = 1;
11565 }
11566
11567 static void setupSigSegvAction(void) {
11568 struct sigaction act;
11569
11570 sigemptyset (&act.sa_mask);
11571 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
11572 * is used. Otherwise, sa_handler is used */
11573 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
11574 act.sa_sigaction = segvHandler;
11575 sigaction (SIGSEGV, &act, NULL);
11576 sigaction (SIGBUS, &act, NULL);
11577 sigaction (SIGFPE, &act, NULL);
11578 sigaction (SIGILL, &act, NULL);
11579 sigaction (SIGBUS, &act, NULL);
11580
11581 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
11582 act.sa_handler = sigtermHandler;
11583 sigaction (SIGTERM, &act, NULL);
11584 return;
11585 }
11586
11587 #include "staticsymbols.h"
11588 /* This function try to convert a pointer into a function name. It's used in
11589 * oreder to provide a backtrace under segmentation fault that's able to
11590 * display functions declared as static (otherwise the backtrace is useless). */
11591 static char *findFuncName(void *pointer, unsigned long *offset){
11592 int i, ret = -1;
11593 unsigned long off, minoff = 0;
11594
11595 /* Try to match against the Symbol with the smallest offset */
11596 for (i=0; symsTable[i].pointer; i++) {
11597 unsigned long lp = (unsigned long) pointer;
11598
11599 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
11600 off=lp-symsTable[i].pointer;
11601 if (ret < 0 || off < minoff) {
11602 minoff=off;
11603 ret=i;
11604 }
11605 }
11606 }
11607 if (ret == -1) return NULL;
11608 *offset = minoff;
11609 return symsTable[ret].name;
11610 }
11611 #else /* HAVE_BACKTRACE */
11612 static void setupSigSegvAction(void) {
11613 }
11614 #endif /* HAVE_BACKTRACE */
11615
11616
11617
11618 /* The End */
11619
11620
11621