]> git.saurik.com Git - redis.git/blob - redis.c
25068618a053ff643abca6ef9f87eefba9952f25
[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
125 /* Objects encoding. Some kind of objects like Strings and Hashes can be
126 * internally represented in multiple ways. The 'encoding' field of the object
127 * is set to one of this fields for this object. */
128 #define REDIS_ENCODING_RAW 0 /* Raw representation */
129 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
130 #define REDIS_ENCODING_HT 2 /* Encoded as hash table */
131 #define REDIS_ENCODING_ZIPMAP 3 /* Encoded as zipmap */
132 #define REDIS_ENCODING_LIST 4 /* Encoded as zipmap */
133 #define REDIS_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
134
135 static char* strencoding[] = {
136 "raw", "int", "zipmap", "hashtable"
137 };
138
139 /* Object types only used for dumping to disk */
140 #define REDIS_EXPIRETIME 253
141 #define REDIS_SELECTDB 254
142 #define REDIS_EOF 255
143
144 /* Defines related to the dump file format. To store 32 bits lengths for short
145 * keys requires a lot of space, so we check the most significant 2 bits of
146 * the first byte to interpreter the length:
147 *
148 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
149 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
150 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
151 * 11|000000 this means: specially encoded object will follow. The six bits
152 * number specify the kind of object that follows.
153 * See the REDIS_RDB_ENC_* defines.
154 *
155 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
156 * values, will fit inside. */
157 #define REDIS_RDB_6BITLEN 0
158 #define REDIS_RDB_14BITLEN 1
159 #define REDIS_RDB_32BITLEN 2
160 #define REDIS_RDB_ENCVAL 3
161 #define REDIS_RDB_LENERR UINT_MAX
162
163 /* When a length of a string object stored on disk has the first two bits
164 * set, the remaining two bits specify a special encoding for the object
165 * accordingly to the following defines: */
166 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
167 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
168 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
169 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
170
171 /* Virtual memory object->where field. */
172 #define REDIS_VM_MEMORY 0 /* The object is on memory */
173 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
174 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
175 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
176
177 /* Virtual memory static configuration stuff.
178 * Check vmFindContiguousPages() to know more about this magic numbers. */
179 #define REDIS_VM_MAX_NEAR_PAGES 65536
180 #define REDIS_VM_MAX_RANDOM_JUMP 4096
181 #define REDIS_VM_MAX_THREADS 32
182 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
183 /* The following is the *percentage* of completed I/O jobs to process when the
184 * handelr is called. While Virtual Memory I/O operations are performed by
185 * threads, this operations must be processed by the main thread when completed
186 * in order to take effect. */
187 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
188
189 /* Client flags */
190 #define REDIS_SLAVE 1 /* This client is a slave server */
191 #define REDIS_MASTER 2 /* This client is a master server */
192 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
193 #define REDIS_MULTI 8 /* This client is in a MULTI context */
194 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
195 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
196 #define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
197
198 /* Slave replication state - slave side */
199 #define REDIS_REPL_NONE 0 /* No active replication */
200 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
201 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
202
203 /* Slave replication state - from the point of view of master
204 * Note that in SEND_BULK and ONLINE state the slave receives new updates
205 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
206 * to start the next background saving in order to send updates to it. */
207 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
208 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
209 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
210 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
211
212 /* List related stuff */
213 #define REDIS_HEAD 0
214 #define REDIS_TAIL 1
215
216 /* Sort operations */
217 #define REDIS_SORT_GET 0
218 #define REDIS_SORT_ASC 1
219 #define REDIS_SORT_DESC 2
220 #define REDIS_SORTKEY_MAX 1024
221
222 /* Log levels */
223 #define REDIS_DEBUG 0
224 #define REDIS_VERBOSE 1
225 #define REDIS_NOTICE 2
226 #define REDIS_WARNING 3
227
228 /* Anti-warning macro... */
229 #define REDIS_NOTUSED(V) ((void) V)
230
231 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
232 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
233
234 /* Append only defines */
235 #define APPENDFSYNC_NO 0
236 #define APPENDFSYNC_ALWAYS 1
237 #define APPENDFSYNC_EVERYSEC 2
238
239 /* Hashes related defaults */
240 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
241 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
242
243 /* We can print the stacktrace, so our assert is defined this way: */
244 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
245 #define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
246 static void _redisAssert(char *estr, char *file, int line);
247 static void _redisPanic(char *msg, char *file, int line);
248
249 /*================================= Data types ============================== */
250
251 /* A redis object, that is a type able to hold a string / list / set */
252
253 /* The VM object structure */
254 struct redisObjectVM {
255 off_t page; /* the page at witch the object is stored on disk */
256 off_t usedpages; /* number of pages used on disk */
257 time_t atime; /* Last access time */
258 } vm;
259
260 /* The actual Redis Object */
261 typedef struct redisObject {
262 void *ptr;
263 unsigned char type;
264 unsigned char encoding;
265 unsigned char storage; /* If this object is a key, where is the value?
266 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
267 unsigned char vtype; /* If this object is a key, and value is swapped out,
268 * this is the type of the swapped out object. */
269 int refcount;
270 /* VM fields, this are only allocated if VM is active, otherwise the
271 * object allocation function will just allocate
272 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
273 * Redis without VM active will not have any overhead. */
274 struct redisObjectVM vm;
275 } robj;
276
277 /* Macro used to initalize a Redis object allocated on the stack.
278 * Note that this macro is taken near the structure definition to make sure
279 * we'll update it when the structure is changed, to avoid bugs like
280 * bug #85 introduced exactly in this way. */
281 #define initStaticStringObject(_var,_ptr) do { \
282 _var.refcount = 1; \
283 _var.type = REDIS_STRING; \
284 _var.encoding = REDIS_ENCODING_RAW; \
285 _var.ptr = _ptr; \
286 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
287 } while(0);
288
289 typedef struct redisDb {
290 dict *dict; /* The keyspace for this DB */
291 dict *expires; /* Timeout of keys with a timeout set */
292 dict *blocking_keys; /* Keys with clients waiting for data (BLPOP) */
293 dict *io_keys; /* Keys with clients waiting for VM I/O */
294 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
295 int id;
296 } redisDb;
297
298 /* Client MULTI/EXEC state */
299 typedef struct multiCmd {
300 robj **argv;
301 int argc;
302 struct redisCommand *cmd;
303 } multiCmd;
304
305 typedef struct multiState {
306 multiCmd *commands; /* Array of MULTI commands */
307 int count; /* Total number of MULTI commands */
308 } multiState;
309
310 /* With multiplexing we need to take per-clinet state.
311 * Clients are taken in a liked list. */
312 typedef struct redisClient {
313 int fd;
314 redisDb *db;
315 int dictid;
316 sds querybuf;
317 robj **argv, **mbargv;
318 int argc, mbargc;
319 int bulklen; /* bulk read len. -1 if not in bulk read mode */
320 int multibulk; /* multi bulk command format active */
321 list *reply;
322 int sentlen;
323 time_t lastinteraction; /* time of the last interaction, used for timeout */
324 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
325 int slaveseldb; /* slave selected db, if this client is a slave */
326 int authenticated; /* when requirepass is non-NULL */
327 int replstate; /* replication state if this is a slave */
328 int repldbfd; /* replication DB file descriptor */
329 long repldboff; /* replication DB file offset */
330 off_t repldbsize; /* replication DB file size */
331 multiState mstate; /* MULTI/EXEC state */
332 robj **blocking_keys; /* The key we are waiting to terminate a blocking
333 * operation such as BLPOP. Otherwise NULL. */
334 int blocking_keys_num; /* Number of blocking keys */
335 time_t blockingto; /* Blocking operation timeout. If UNIX current time
336 * is >= blockingto then the operation timed out. */
337 list *io_keys; /* Keys this client is waiting to be loaded from the
338 * swap file in order to continue. */
339 list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */
340 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
341 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
342 } redisClient;
343
344 struct saveparam {
345 time_t seconds;
346 int changes;
347 };
348
349 /* Global server state structure */
350 struct redisServer {
351 int port;
352 int fd;
353 redisDb *db;
354 long long dirty; /* changes to DB from the last save */
355 list *clients;
356 list *slaves, *monitors;
357 char neterr[ANET_ERR_LEN];
358 aeEventLoop *el;
359 int cronloops; /* number of times the cron function run */
360 list *objfreelist; /* A list of freed objects to avoid malloc() */
361 time_t lastsave; /* Unix time of last save succeeede */
362 /* Fields used only for stats */
363 time_t stat_starttime; /* server start time */
364 long long stat_numcommands; /* number of processed commands */
365 long long stat_numconnections; /* number of connections received */
366 long long stat_expiredkeys; /* number of expired keys */
367 /* Configuration */
368 int verbosity;
369 int glueoutputbuf;
370 int maxidletime;
371 int dbnum;
372 int daemonize;
373 int appendonly;
374 int appendfsync;
375 int shutdown_asap;
376 time_t lastfsync;
377 int appendfd;
378 int appendseldb;
379 char *pidfile;
380 pid_t bgsavechildpid;
381 pid_t bgrewritechildpid;
382 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
383 sds aofbuf; /* AOF buffer, written before entering the event loop */
384 struct saveparam *saveparams;
385 int saveparamslen;
386 char *logfile;
387 char *bindaddr;
388 char *dbfilename;
389 char *appendfilename;
390 char *requirepass;
391 int rdbcompression;
392 int activerehashing;
393 /* Replication related */
394 int isslave;
395 char *masterauth;
396 char *masterhost;
397 int masterport;
398 redisClient *master; /* client that is master for this slave */
399 int replstate;
400 unsigned int maxclients;
401 unsigned long long maxmemory;
402 unsigned int blpop_blocked_clients;
403 unsigned int vm_blocked_clients;
404 /* Sort parameters - qsort_r() is only available under BSD so we
405 * have to take this state global, in order to pass it to sortCompare() */
406 int sort_desc;
407 int sort_alpha;
408 int sort_bypattern;
409 /* Virtual memory configuration */
410 int vm_enabled;
411 char *vm_swap_file;
412 off_t vm_page_size;
413 off_t vm_pages;
414 unsigned long long vm_max_memory;
415 /* Hashes config */
416 size_t hash_max_zipmap_entries;
417 size_t hash_max_zipmap_value;
418 /* Virtual memory state */
419 FILE *vm_fp;
420 int vm_fd;
421 off_t vm_next_page; /* Next probably empty page */
422 off_t vm_near_pages; /* Number of pages allocated sequentially */
423 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
424 time_t unixtime; /* Unix time sampled every second. */
425 /* Virtual memory I/O threads stuff */
426 /* An I/O thread process an element taken from the io_jobs queue and
427 * put the result of the operation in the io_done list. While the
428 * job is being processed, it's put on io_processing queue. */
429 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
430 list *io_processing; /* List of VM I/O jobs being processed */
431 list *io_processed; /* List of VM I/O jobs already processed */
432 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
433 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
434 pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
435 pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
436 pthread_attr_t io_threads_attr; /* attributes for threads creation */
437 int io_active_threads; /* Number of running I/O threads */
438 int vm_max_threads; /* Max number of I/O threads running at the same time */
439 /* Our main thread is blocked on the event loop, locking for sockets ready
440 * to be read or written, so when a threaded I/O operation is ready to be
441 * processed by the main thread, the I/O thread will use a unix pipe to
442 * awake the main thread. The followings are the two pipe FDs. */
443 int io_ready_pipe_read;
444 int io_ready_pipe_write;
445 /* Virtual memory stats */
446 unsigned long long vm_stats_used_pages;
447 unsigned long long vm_stats_swapped_objects;
448 unsigned long long vm_stats_swapouts;
449 unsigned long long vm_stats_swapins;
450 /* Pubsub */
451 dict *pubsub_channels; /* Map channels to list of subscribed clients */
452 list *pubsub_patterns; /* A list of pubsub_patterns */
453 /* Misc */
454 FILE *devnull;
455 };
456
457 typedef struct pubsubPattern {
458 redisClient *client;
459 robj *pattern;
460 } pubsubPattern;
461
462 typedef void redisCommandProc(redisClient *c);
463 typedef void redisVmPreloadProc(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
464 struct redisCommand {
465 char *name;
466 redisCommandProc *proc;
467 int arity;
468 int flags;
469 /* Use a function to determine which keys need to be loaded
470 * in the background prior to executing this command. Takes precedence
471 * over vm_firstkey and others, ignored when NULL */
472 redisVmPreloadProc *vm_preload_proc;
473 /* What keys should be loaded in background when calling this command? */
474 int vm_firstkey; /* The first argument that's a key (0 = no keys) */
475 int vm_lastkey; /* THe last argument that's a key */
476 int vm_keystep; /* The step between first and last key */
477 };
478
479 struct redisFunctionSym {
480 char *name;
481 unsigned long pointer;
482 };
483
484 typedef struct _redisSortObject {
485 robj *obj;
486 union {
487 double score;
488 robj *cmpobj;
489 } u;
490 } redisSortObject;
491
492 typedef struct _redisSortOperation {
493 int type;
494 robj *pattern;
495 } redisSortOperation;
496
497 /* ZSETs use a specialized version of Skiplists */
498
499 typedef struct zskiplistNode {
500 struct zskiplistNode **forward;
501 struct zskiplistNode *backward;
502 unsigned int *span;
503 double score;
504 robj *obj;
505 } zskiplistNode;
506
507 typedef struct zskiplist {
508 struct zskiplistNode *header, *tail;
509 unsigned long length;
510 int level;
511 } zskiplist;
512
513 typedef struct zset {
514 dict *dict;
515 zskiplist *zsl;
516 } zset;
517
518 /* Our shared "common" objects */
519
520 #define REDIS_SHARED_INTEGERS 10000
521 struct sharedObjectsStruct {
522 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
523 *colon, *nullbulk, *nullmultibulk, *queued,
524 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
525 *outofrangeerr, *plus,
526 *select0, *select1, *select2, *select3, *select4,
527 *select5, *select6, *select7, *select8, *select9,
528 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk, *mbulk3,
529 *mbulk4, *psubscribebulk, *punsubscribebulk,
530 *integers[REDIS_SHARED_INTEGERS];
531 } shared;
532
533 /* Global vars that are actally used as constants. The following double
534 * values are used for double on-disk serialization, and are initialized
535 * at runtime to avoid strange compiler optimizations. */
536
537 static double R_Zero, R_PosInf, R_NegInf, R_Nan;
538
539 /* VM threaded I/O request message */
540 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
541 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
542 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
543 typedef struct iojob {
544 int type; /* Request type, REDIS_IOJOB_* */
545 redisDb *db;/* Redis database */
546 robj *key; /* This I/O request is about swapping this key */
547 robj *val; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
548 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
549 off_t page; /* Swap page where to read/write the object */
550 off_t pages; /* Swap pages needed to save object. PREPARE_SWAP return val */
551 int canceled; /* True if this command was canceled by blocking side of VM */
552 pthread_t thread; /* ID of the thread processing this entry */
553 } iojob;
554
555 /*================================ Prototypes =============================== */
556
557 static void freeStringObject(robj *o);
558 static void freeListObject(robj *o);
559 static void freeSetObject(robj *o);
560 static void decrRefCount(void *o);
561 static robj *createObject(int type, void *ptr);
562 static void freeClient(redisClient *c);
563 static int rdbLoad(char *filename);
564 static void addReply(redisClient *c, robj *obj);
565 static void addReplySds(redisClient *c, sds s);
566 static void incrRefCount(robj *o);
567 static int rdbSaveBackground(char *filename);
568 static robj *createStringObject(char *ptr, size_t len);
569 static robj *dupStringObject(robj *o);
570 static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
571 static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
572 static void flushAppendOnlyFile(void);
573 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
574 static int syncWithMaster(void);
575 static robj *tryObjectEncoding(robj *o);
576 static robj *getDecodedObject(robj *o);
577 static int removeExpire(redisDb *db, robj *key);
578 static int expireIfNeeded(redisDb *db, robj *key);
579 static int deleteIfVolatile(redisDb *db, robj *key);
580 static int deleteIfSwapped(redisDb *db, robj *key);
581 static int deleteKey(redisDb *db, robj *key);
582 static time_t getExpire(redisDb *db, robj *key);
583 static int setExpire(redisDb *db, robj *key, time_t when);
584 static void updateSlavesWaitingBgsave(int bgsaveerr);
585 static void freeMemoryIfNeeded(void);
586 static int processCommand(redisClient *c);
587 static void setupSigSegvAction(void);
588 static void rdbRemoveTempFile(pid_t childpid);
589 static void aofRemoveTempFile(pid_t childpid);
590 static size_t stringObjectLen(robj *o);
591 static void processInputBuffer(redisClient *c);
592 static zskiplist *zslCreate(void);
593 static void zslFree(zskiplist *zsl);
594 static void zslInsert(zskiplist *zsl, double score, robj *obj);
595 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
596 static void initClientMultiState(redisClient *c);
597 static void freeClientMultiState(redisClient *c);
598 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
599 static void unblockClientWaitingData(redisClient *c);
600 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
601 static void vmInit(void);
602 static void vmMarkPagesFree(off_t page, off_t count);
603 static robj *vmLoadObject(robj *key);
604 static robj *vmPreviewObject(robj *key);
605 static int vmSwapOneObjectBlocking(void);
606 static int vmSwapOneObjectThreaded(void);
607 static int vmCanSwapOut(void);
608 static int tryFreeOneObjectFromFreelist(void);
609 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
610 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
611 static void vmCancelThreadedIOJob(robj *o);
612 static void lockThreadedIO(void);
613 static void unlockThreadedIO(void);
614 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
615 static void freeIOJob(iojob *j);
616 static void queueIOJob(iojob *j);
617 static int vmWriteObjectOnSwap(robj *o, off_t page);
618 static robj *vmReadObjectFromSwap(off_t page, int type);
619 static void waitEmptyIOJobsQueue(void);
620 static void vmReopenSwapFile(void);
621 static int vmFreePage(off_t page);
622 static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
623 static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
624 static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd);
625 static int dontWaitForSwappedKey(redisClient *c, robj *key);
626 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
627 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
628 static struct redisCommand *lookupCommand(char *name);
629 static void call(redisClient *c, struct redisCommand *cmd);
630 static void resetClient(redisClient *c);
631 static void convertToRealHash(robj *o);
632 static int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
633 static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
634 static void freePubsubPattern(void *p);
635 static int listMatchPubsubPattern(void *a, void *b);
636 static int compareStringObjects(robj *a, robj *b);
637 static int equalStringObjects(robj *a, robj *b);
638 static void usage();
639 static int rewriteAppendOnlyFileBackground(void);
640 static int vmSwapObjectBlocking(robj *key, robj *val);
641 static int prepareForShutdown();
642 static void touchWatchedKey(redisDb *db, robj *key);
643 static void touchWatchedKeysOnFlush(int dbid);
644 static void unwatchAllKeys(redisClient *c);
645
646 static void authCommand(redisClient *c);
647 static void pingCommand(redisClient *c);
648 static void echoCommand(redisClient *c);
649 static void setCommand(redisClient *c);
650 static void setnxCommand(redisClient *c);
651 static void setexCommand(redisClient *c);
652 static void getCommand(redisClient *c);
653 static void delCommand(redisClient *c);
654 static void existsCommand(redisClient *c);
655 static void incrCommand(redisClient *c);
656 static void decrCommand(redisClient *c);
657 static void incrbyCommand(redisClient *c);
658 static void decrbyCommand(redisClient *c);
659 static void selectCommand(redisClient *c);
660 static void randomkeyCommand(redisClient *c);
661 static void keysCommand(redisClient *c);
662 static void dbsizeCommand(redisClient *c);
663 static void lastsaveCommand(redisClient *c);
664 static void saveCommand(redisClient *c);
665 static void bgsaveCommand(redisClient *c);
666 static void bgrewriteaofCommand(redisClient *c);
667 static void shutdownCommand(redisClient *c);
668 static void moveCommand(redisClient *c);
669 static void renameCommand(redisClient *c);
670 static void renamenxCommand(redisClient *c);
671 static void lpushCommand(redisClient *c);
672 static void rpushCommand(redisClient *c);
673 static void lpopCommand(redisClient *c);
674 static void rpopCommand(redisClient *c);
675 static void llenCommand(redisClient *c);
676 static void lindexCommand(redisClient *c);
677 static void lrangeCommand(redisClient *c);
678 static void ltrimCommand(redisClient *c);
679 static void typeCommand(redisClient *c);
680 static void lsetCommand(redisClient *c);
681 static void saddCommand(redisClient *c);
682 static void sremCommand(redisClient *c);
683 static void smoveCommand(redisClient *c);
684 static void sismemberCommand(redisClient *c);
685 static void scardCommand(redisClient *c);
686 static void spopCommand(redisClient *c);
687 static void srandmemberCommand(redisClient *c);
688 static void sinterCommand(redisClient *c);
689 static void sinterstoreCommand(redisClient *c);
690 static void sunionCommand(redisClient *c);
691 static void sunionstoreCommand(redisClient *c);
692 static void sdiffCommand(redisClient *c);
693 static void sdiffstoreCommand(redisClient *c);
694 static void syncCommand(redisClient *c);
695 static void flushdbCommand(redisClient *c);
696 static void flushallCommand(redisClient *c);
697 static void sortCommand(redisClient *c);
698 static void lremCommand(redisClient *c);
699 static void rpoplpushcommand(redisClient *c);
700 static void infoCommand(redisClient *c);
701 static void mgetCommand(redisClient *c);
702 static void monitorCommand(redisClient *c);
703 static void expireCommand(redisClient *c);
704 static void expireatCommand(redisClient *c);
705 static void getsetCommand(redisClient *c);
706 static void ttlCommand(redisClient *c);
707 static void slaveofCommand(redisClient *c);
708 static void debugCommand(redisClient *c);
709 static void msetCommand(redisClient *c);
710 static void msetnxCommand(redisClient *c);
711 static void zaddCommand(redisClient *c);
712 static void zincrbyCommand(redisClient *c);
713 static void zrangeCommand(redisClient *c);
714 static void zrangebyscoreCommand(redisClient *c);
715 static void zcountCommand(redisClient *c);
716 static void zrevrangeCommand(redisClient *c);
717 static void zcardCommand(redisClient *c);
718 static void zremCommand(redisClient *c);
719 static void zscoreCommand(redisClient *c);
720 static void zremrangebyscoreCommand(redisClient *c);
721 static void multiCommand(redisClient *c);
722 static void execCommand(redisClient *c);
723 static void discardCommand(redisClient *c);
724 static void blpopCommand(redisClient *c);
725 static void brpopCommand(redisClient *c);
726 static void appendCommand(redisClient *c);
727 static void substrCommand(redisClient *c);
728 static void zrankCommand(redisClient *c);
729 static void zrevrankCommand(redisClient *c);
730 static void hsetCommand(redisClient *c);
731 static void hsetnxCommand(redisClient *c);
732 static void hgetCommand(redisClient *c);
733 static void hmsetCommand(redisClient *c);
734 static void hmgetCommand(redisClient *c);
735 static void hdelCommand(redisClient *c);
736 static void hlenCommand(redisClient *c);
737 static void zremrangebyrankCommand(redisClient *c);
738 static void zunionstoreCommand(redisClient *c);
739 static void zinterstoreCommand(redisClient *c);
740 static void hkeysCommand(redisClient *c);
741 static void hvalsCommand(redisClient *c);
742 static void hgetallCommand(redisClient *c);
743 static void hexistsCommand(redisClient *c);
744 static void configCommand(redisClient *c);
745 static void hincrbyCommand(redisClient *c);
746 static void subscribeCommand(redisClient *c);
747 static void unsubscribeCommand(redisClient *c);
748 static void psubscribeCommand(redisClient *c);
749 static void punsubscribeCommand(redisClient *c);
750 static void publishCommand(redisClient *c);
751 static void watchCommand(redisClient *c);
752 static void unwatchCommand(redisClient *c);
753
754 /*================================= Globals ================================= */
755
756 /* Global vars */
757 static struct redisServer server; /* server global state */
758 static struct redisCommand *commandTable;
759 static struct redisCommand readonlyCommandTable[] = {
760 {"get",getCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
761 {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
762 {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
763 {"setex",setexCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
764 {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
765 {"substr",substrCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
766 {"del",delCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
767 {"exists",existsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
768 {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
769 {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
770 {"mget",mgetCommand,-2,REDIS_CMD_INLINE,NULL,1,-1,1},
771 {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
772 {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
773 {"rpop",rpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
774 {"lpop",lpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
775 {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
776 {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
777 {"llen",llenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
778 {"lindex",lindexCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
779 {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
780 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
781 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
782 {"lrem",lremCommand,4,REDIS_CMD_BULK,NULL,1,1,1},
783 {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,2,1},
784 {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
785 {"srem",sremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
786 {"smove",smoveCommand,4,REDIS_CMD_BULK,NULL,1,2,1},
787 {"sismember",sismemberCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
788 {"scard",scardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
789 {"spop",spopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
790 {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
791 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
792 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
793 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
794 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
795 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
796 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
797 {"smembers",sinterCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
798 {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
799 {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
800 {"zrem",zremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
801 {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
802 {"zremrangebyrank",zremrangebyrankCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
803 {"zunionstore",zunionstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
804 {"zinterstore",zinterstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
805 {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
806 {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
807 {"zcount",zcountCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
808 {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
809 {"zcard",zcardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
810 {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
811 {"zrank",zrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
812 {"zrevrank",zrevrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
813 {"hset",hsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
814 {"hsetnx",hsetnxCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
815 {"hget",hgetCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
816 {"hmset",hmsetCommand,-4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
817 {"hmget",hmgetCommand,-3,REDIS_CMD_BULK,NULL,1,1,1},
818 {"hincrby",hincrbyCommand,4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
819 {"hdel",hdelCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
820 {"hlen",hlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
821 {"hkeys",hkeysCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
822 {"hvals",hvalsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
823 {"hgetall",hgetallCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
824 {"hexists",hexistsCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
825 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
826 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
827 {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
828 {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
829 {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
830 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
831 {"select",selectCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
832 {"move",moveCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
833 {"rename",renameCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
834 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
835 {"expire",expireCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
836 {"expireat",expireatCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
837 {"keys",keysCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
838 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
839 {"auth",authCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
840 {"ping",pingCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
841 {"echo",echoCommand,2,REDIS_CMD_BULK,NULL,0,0,0},
842 {"save",saveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
843 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
844 {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
845 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
846 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
847 {"type",typeCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
848 {"multi",multiCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
849 {"exec",execCommand,1,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0},
850 {"discard",discardCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
851 {"sync",syncCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
852 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
853 {"flushall",flushallCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
854 {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
855 {"info",infoCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
856 {"monitor",monitorCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
857 {"ttl",ttlCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
858 {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
859 {"debug",debugCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
860 {"config",configCommand,-2,REDIS_CMD_BULK,NULL,0,0,0},
861 {"subscribe",subscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
862 {"unsubscribe",unsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
863 {"psubscribe",psubscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
864 {"punsubscribe",punsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
865 {"publish",publishCommand,3,REDIS_CMD_BULK|REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0},
866 {"watch",watchCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
867 {"unwatch",unwatchCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}
868 };
869
870 /*============================ Utility functions ============================ */
871
872 /* Glob-style pattern matching. */
873 static int stringmatchlen(const char *pattern, int patternLen,
874 const char *string, int stringLen, int nocase)
875 {
876 while(patternLen) {
877 switch(pattern[0]) {
878 case '*':
879 while (pattern[1] == '*') {
880 pattern++;
881 patternLen--;
882 }
883 if (patternLen == 1)
884 return 1; /* match */
885 while(stringLen) {
886 if (stringmatchlen(pattern+1, patternLen-1,
887 string, stringLen, nocase))
888 return 1; /* match */
889 string++;
890 stringLen--;
891 }
892 return 0; /* no match */
893 break;
894 case '?':
895 if (stringLen == 0)
896 return 0; /* no match */
897 string++;
898 stringLen--;
899 break;
900 case '[':
901 {
902 int not, match;
903
904 pattern++;
905 patternLen--;
906 not = pattern[0] == '^';
907 if (not) {
908 pattern++;
909 patternLen--;
910 }
911 match = 0;
912 while(1) {
913 if (pattern[0] == '\\') {
914 pattern++;
915 patternLen--;
916 if (pattern[0] == string[0])
917 match = 1;
918 } else if (pattern[0] == ']') {
919 break;
920 } else if (patternLen == 0) {
921 pattern--;
922 patternLen++;
923 break;
924 } else if (pattern[1] == '-' && patternLen >= 3) {
925 int start = pattern[0];
926 int end = pattern[2];
927 int c = string[0];
928 if (start > end) {
929 int t = start;
930 start = end;
931 end = t;
932 }
933 if (nocase) {
934 start = tolower(start);
935 end = tolower(end);
936 c = tolower(c);
937 }
938 pattern += 2;
939 patternLen -= 2;
940 if (c >= start && c <= end)
941 match = 1;
942 } else {
943 if (!nocase) {
944 if (pattern[0] == string[0])
945 match = 1;
946 } else {
947 if (tolower((int)pattern[0]) == tolower((int)string[0]))
948 match = 1;
949 }
950 }
951 pattern++;
952 patternLen--;
953 }
954 if (not)
955 match = !match;
956 if (!match)
957 return 0; /* no match */
958 string++;
959 stringLen--;
960 break;
961 }
962 case '\\':
963 if (patternLen >= 2) {
964 pattern++;
965 patternLen--;
966 }
967 /* fall through */
968 default:
969 if (!nocase) {
970 if (pattern[0] != string[0])
971 return 0; /* no match */
972 } else {
973 if (tolower((int)pattern[0]) != tolower((int)string[0]))
974 return 0; /* no match */
975 }
976 string++;
977 stringLen--;
978 break;
979 }
980 pattern++;
981 patternLen--;
982 if (stringLen == 0) {
983 while(*pattern == '*') {
984 pattern++;
985 patternLen--;
986 }
987 break;
988 }
989 }
990 if (patternLen == 0 && stringLen == 0)
991 return 1;
992 return 0;
993 }
994
995 static int stringmatch(const char *pattern, const char *string, int nocase) {
996 return stringmatchlen(pattern,strlen(pattern),string,strlen(string),nocase);
997 }
998
999 /* Convert a string representing an amount of memory into the number of
1000 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
1001 * (1024*1024*1024).
1002 *
1003 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
1004 * set to 0 */
1005 static long long memtoll(const char *p, int *err) {
1006 const char *u;
1007 char buf[128];
1008 long mul; /* unit multiplier */
1009 long long val;
1010 unsigned int digits;
1011
1012 if (err) *err = 0;
1013 /* Search the first non digit character. */
1014 u = p;
1015 if (*u == '-') u++;
1016 while(*u && isdigit(*u)) u++;
1017 if (*u == '\0' || !strcasecmp(u,"b")) {
1018 mul = 1;
1019 } else if (!strcasecmp(u,"k")) {
1020 mul = 1000;
1021 } else if (!strcasecmp(u,"kb")) {
1022 mul = 1024;
1023 } else if (!strcasecmp(u,"m")) {
1024 mul = 1000*1000;
1025 } else if (!strcasecmp(u,"mb")) {
1026 mul = 1024*1024;
1027 } else if (!strcasecmp(u,"g")) {
1028 mul = 1000L*1000*1000;
1029 } else if (!strcasecmp(u,"gb")) {
1030 mul = 1024L*1024*1024;
1031 } else {
1032 if (err) *err = 1;
1033 mul = 1;
1034 }
1035 digits = u-p;
1036 if (digits >= sizeof(buf)) {
1037 if (err) *err = 1;
1038 return LLONG_MAX;
1039 }
1040 memcpy(buf,p,digits);
1041 buf[digits] = '\0';
1042 val = strtoll(buf,NULL,10);
1043 return val*mul;
1044 }
1045
1046 /* Convert a long long into a string. Returns the number of
1047 * characters needed to represent the number, that can be shorter if passed
1048 * buffer length is not enough to store the whole number. */
1049 static int ll2string(char *s, size_t len, long long value) {
1050 char buf[32], *p;
1051 unsigned long long v;
1052 size_t l;
1053
1054 if (len == 0) return 0;
1055 v = (value < 0) ? -value : value;
1056 p = buf+31; /* point to the last character */
1057 do {
1058 *p-- = '0'+(v%10);
1059 v /= 10;
1060 } while(v);
1061 if (value < 0) *p-- = '-';
1062 p++;
1063 l = 32-(p-buf);
1064 if (l+1 > len) l = len-1; /* Make sure it fits, including the nul term */
1065 memcpy(s,p,l);
1066 s[l] = '\0';
1067 return l;
1068 }
1069
1070 static void redisLog(int level, const char *fmt, ...) {
1071 va_list ap;
1072 FILE *fp;
1073
1074 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
1075 if (!fp) return;
1076
1077 va_start(ap, fmt);
1078 if (level >= server.verbosity) {
1079 char *c = ".-*#";
1080 char buf[64];
1081 time_t now;
1082
1083 now = time(NULL);
1084 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
1085 fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
1086 vfprintf(fp, fmt, ap);
1087 fprintf(fp,"\n");
1088 fflush(fp);
1089 }
1090 va_end(ap);
1091
1092 if (server.logfile) fclose(fp);
1093 }
1094
1095 /*====================== Hash table type implementation ==================== */
1096
1097 /* This is an hash table type that uses the SDS dynamic strings libary as
1098 * keys and radis objects as values (objects can hold SDS strings,
1099 * lists, sets). */
1100
1101 static void dictVanillaFree(void *privdata, void *val)
1102 {
1103 DICT_NOTUSED(privdata);
1104 zfree(val);
1105 }
1106
1107 static void dictListDestructor(void *privdata, void *val)
1108 {
1109 DICT_NOTUSED(privdata);
1110 listRelease((list*)val);
1111 }
1112
1113 static int sdsDictKeyCompare(void *privdata, const void *key1,
1114 const void *key2)
1115 {
1116 int l1,l2;
1117 DICT_NOTUSED(privdata);
1118
1119 l1 = sdslen((sds)key1);
1120 l2 = sdslen((sds)key2);
1121 if (l1 != l2) return 0;
1122 return memcmp(key1, key2, l1) == 0;
1123 }
1124
1125 static void dictRedisObjectDestructor(void *privdata, void *val)
1126 {
1127 DICT_NOTUSED(privdata);
1128
1129 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
1130 decrRefCount(val);
1131 }
1132
1133 static int dictObjKeyCompare(void *privdata, const void *key1,
1134 const void *key2)
1135 {
1136 const robj *o1 = key1, *o2 = key2;
1137 return sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1138 }
1139
1140 static unsigned int dictObjHash(const void *key) {
1141 const robj *o = key;
1142 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1143 }
1144
1145 static int dictEncObjKeyCompare(void *privdata, const void *key1,
1146 const void *key2)
1147 {
1148 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
1149 int cmp;
1150
1151 if (o1->encoding == REDIS_ENCODING_INT &&
1152 o2->encoding == REDIS_ENCODING_INT)
1153 return o1->ptr == o2->ptr;
1154
1155 o1 = getDecodedObject(o1);
1156 o2 = getDecodedObject(o2);
1157 cmp = sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1158 decrRefCount(o1);
1159 decrRefCount(o2);
1160 return cmp;
1161 }
1162
1163 static unsigned int dictEncObjHash(const void *key) {
1164 robj *o = (robj*) key;
1165
1166 if (o->encoding == REDIS_ENCODING_RAW) {
1167 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1168 } else {
1169 if (o->encoding == REDIS_ENCODING_INT) {
1170 char buf[32];
1171 int len;
1172
1173 len = ll2string(buf,32,(long)o->ptr);
1174 return dictGenHashFunction((unsigned char*)buf, len);
1175 } else {
1176 unsigned int hash;
1177
1178 o = getDecodedObject(o);
1179 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1180 decrRefCount(o);
1181 return hash;
1182 }
1183 }
1184 }
1185
1186 /* Sets type and expires */
1187 static dictType setDictType = {
1188 dictEncObjHash, /* hash function */
1189 NULL, /* key dup */
1190 NULL, /* val dup */
1191 dictEncObjKeyCompare, /* key compare */
1192 dictRedisObjectDestructor, /* key destructor */
1193 NULL /* val destructor */
1194 };
1195
1196 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1197 static dictType zsetDictType = {
1198 dictEncObjHash, /* hash function */
1199 NULL, /* key dup */
1200 NULL, /* val dup */
1201 dictEncObjKeyCompare, /* key compare */
1202 dictRedisObjectDestructor, /* key destructor */
1203 dictVanillaFree /* val destructor of malloc(sizeof(double)) */
1204 };
1205
1206 /* Db->dict */
1207 static dictType dbDictType = {
1208 dictObjHash, /* hash function */
1209 NULL, /* key dup */
1210 NULL, /* val dup */
1211 dictObjKeyCompare, /* key compare */
1212 dictRedisObjectDestructor, /* key destructor */
1213 dictRedisObjectDestructor /* val destructor */
1214 };
1215
1216 /* Db->expires */
1217 static dictType keyptrDictType = {
1218 dictObjHash, /* hash function */
1219 NULL, /* key dup */
1220 NULL, /* val dup */
1221 dictObjKeyCompare, /* key compare */
1222 dictRedisObjectDestructor, /* key destructor */
1223 NULL /* val destructor */
1224 };
1225
1226 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1227 static dictType hashDictType = {
1228 dictEncObjHash, /* hash function */
1229 NULL, /* key dup */
1230 NULL, /* val dup */
1231 dictEncObjKeyCompare, /* key compare */
1232 dictRedisObjectDestructor, /* key destructor */
1233 dictRedisObjectDestructor /* val destructor */
1234 };
1235
1236 /* Keylist hash table type has unencoded redis objects as keys and
1237 * lists as values. It's used for blocking operations (BLPOP) and to
1238 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1239 static dictType keylistDictType = {
1240 dictObjHash, /* hash function */
1241 NULL, /* key dup */
1242 NULL, /* val dup */
1243 dictObjKeyCompare, /* key compare */
1244 dictRedisObjectDestructor, /* key destructor */
1245 dictListDestructor /* val destructor */
1246 };
1247
1248 static void version();
1249
1250 /* ========================= Random utility functions ======================= */
1251
1252 /* Redis generally does not try to recover from out of memory conditions
1253 * when allocating objects or strings, it is not clear if it will be possible
1254 * to report this condition to the client since the networking layer itself
1255 * is based on heap allocation for send buffers, so we simply abort.
1256 * At least the code will be simpler to read... */
1257 static void oom(const char *msg) {
1258 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
1259 sleep(1);
1260 abort();
1261 }
1262
1263 /* ====================== Redis server networking stuff ===================== */
1264 static void closeTimedoutClients(void) {
1265 redisClient *c;
1266 listNode *ln;
1267 time_t now = time(NULL);
1268 listIter li;
1269
1270 listRewind(server.clients,&li);
1271 while ((ln = listNext(&li)) != NULL) {
1272 c = listNodeValue(ln);
1273 if (server.maxidletime &&
1274 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
1275 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
1276 dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
1277 listLength(c->pubsub_patterns) == 0 &&
1278 (now - c->lastinteraction > server.maxidletime))
1279 {
1280 redisLog(REDIS_VERBOSE,"Closing idle client");
1281 freeClient(c);
1282 } else if (c->flags & REDIS_BLOCKED) {
1283 if (c->blockingto != 0 && c->blockingto < now) {
1284 addReply(c,shared.nullmultibulk);
1285 unblockClientWaitingData(c);
1286 }
1287 }
1288 }
1289 }
1290
1291 static int htNeedsResize(dict *dict) {
1292 long long size, used;
1293
1294 size = dictSlots(dict);
1295 used = dictSize(dict);
1296 return (size && used && size > DICT_HT_INITIAL_SIZE &&
1297 (used*100/size < REDIS_HT_MINFILL));
1298 }
1299
1300 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1301 * we resize the hash table to save memory */
1302 static void tryResizeHashTables(void) {
1303 int j;
1304
1305 for (j = 0; j < server.dbnum; j++) {
1306 if (htNeedsResize(server.db[j].dict))
1307 dictResize(server.db[j].dict);
1308 if (htNeedsResize(server.db[j].expires))
1309 dictResize(server.db[j].expires);
1310 }
1311 }
1312
1313 /* Our hash table implementation performs rehashing incrementally while
1314 * we write/read from the hash table. Still if the server is idle, the hash
1315 * table will use two tables for a long time. So we try to use 1 millisecond
1316 * of CPU time at every serverCron() loop in order to rehash some key. */
1317 static void incrementallyRehash(void) {
1318 int j;
1319
1320 for (j = 0; j < server.dbnum; j++) {
1321 if (dictIsRehashing(server.db[j].dict)) {
1322 dictRehashMilliseconds(server.db[j].dict,1);
1323 break; /* already used our millisecond for this loop... */
1324 }
1325 }
1326 }
1327
1328 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1329 void backgroundSaveDoneHandler(int statloc) {
1330 int exitcode = WEXITSTATUS(statloc);
1331 int bysignal = WIFSIGNALED(statloc);
1332
1333 if (!bysignal && exitcode == 0) {
1334 redisLog(REDIS_NOTICE,
1335 "Background saving terminated with success");
1336 server.dirty = 0;
1337 server.lastsave = time(NULL);
1338 } else if (!bysignal && exitcode != 0) {
1339 redisLog(REDIS_WARNING, "Background saving error");
1340 } else {
1341 redisLog(REDIS_WARNING,
1342 "Background saving terminated by signal %d", WTERMSIG(statloc));
1343 rdbRemoveTempFile(server.bgsavechildpid);
1344 }
1345 server.bgsavechildpid = -1;
1346 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1347 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1348 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1349 }
1350
1351 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1352 * Handle this. */
1353 void backgroundRewriteDoneHandler(int statloc) {
1354 int exitcode = WEXITSTATUS(statloc);
1355 int bysignal = WIFSIGNALED(statloc);
1356
1357 if (!bysignal && exitcode == 0) {
1358 int fd;
1359 char tmpfile[256];
1360
1361 redisLog(REDIS_NOTICE,
1362 "Background append only file rewriting terminated with success");
1363 /* Now it's time to flush the differences accumulated by the parent */
1364 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
1365 fd = open(tmpfile,O_WRONLY|O_APPEND);
1366 if (fd == -1) {
1367 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
1368 goto cleanup;
1369 }
1370 /* Flush our data... */
1371 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
1372 (signed) sdslen(server.bgrewritebuf)) {
1373 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));
1374 close(fd);
1375 goto cleanup;
1376 }
1377 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
1378 /* Now our work is to rename the temp file into the stable file. And
1379 * switch the file descriptor used by the server for append only. */
1380 if (rename(tmpfile,server.appendfilename) == -1) {
1381 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
1382 close(fd);
1383 goto cleanup;
1384 }
1385 /* Mission completed... almost */
1386 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
1387 if (server.appendfd != -1) {
1388 /* If append only is actually enabled... */
1389 close(server.appendfd);
1390 server.appendfd = fd;
1391 fsync(fd);
1392 server.appendseldb = -1; /* Make sure it will issue SELECT */
1393 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
1394 } else {
1395 /* If append only is disabled we just generate a dump in this
1396 * format. Why not? */
1397 close(fd);
1398 }
1399 } else if (!bysignal && exitcode != 0) {
1400 redisLog(REDIS_WARNING, "Background append only file rewriting error");
1401 } else {
1402 redisLog(REDIS_WARNING,
1403 "Background append only file rewriting terminated by signal %d",
1404 WTERMSIG(statloc));
1405 }
1406 cleanup:
1407 sdsfree(server.bgrewritebuf);
1408 server.bgrewritebuf = sdsempty();
1409 aofRemoveTempFile(server.bgrewritechildpid);
1410 server.bgrewritechildpid = -1;
1411 }
1412
1413 /* This function is called once a background process of some kind terminates,
1414 * as we want to avoid resizing the hash tables when there is a child in order
1415 * to play well with copy-on-write (otherwise when a resize happens lots of
1416 * memory pages are copied). The goal of this function is to update the ability
1417 * for dict.c to resize the hash tables accordingly to the fact we have o not
1418 * running childs. */
1419 static void updateDictResizePolicy(void) {
1420 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
1421 dictEnableResize();
1422 else
1423 dictDisableResize();
1424 }
1425
1426 static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
1427 int j, loops = server.cronloops++;
1428 REDIS_NOTUSED(eventLoop);
1429 REDIS_NOTUSED(id);
1430 REDIS_NOTUSED(clientData);
1431
1432 /* We take a cached value of the unix time in the global state because
1433 * with virtual memory and aging there is to store the current time
1434 * in objects at every object access, and accuracy is not needed.
1435 * To access a global var is faster than calling time(NULL) */
1436 server.unixtime = time(NULL);
1437
1438 /* We received a SIGTERM, shutting down here in a safe way, as it is
1439 * not ok doing so inside the signal handler. */
1440 if (server.shutdown_asap) {
1441 if (prepareForShutdown() == REDIS_OK) exit(0);
1442 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
1443 }
1444
1445 /* Show some info about non-empty databases */
1446 for (j = 0; j < server.dbnum; j++) {
1447 long long size, used, vkeys;
1448
1449 size = dictSlots(server.db[j].dict);
1450 used = dictSize(server.db[j].dict);
1451 vkeys = dictSize(server.db[j].expires);
1452 if (!(loops % 50) && (used || vkeys)) {
1453 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
1454 /* dictPrintStats(server.dict); */
1455 }
1456 }
1457
1458 /* We don't want to resize the hash tables while a bacground saving
1459 * is in progress: the saving child is created using fork() that is
1460 * implemented with a copy-on-write semantic in most modern systems, so
1461 * if we resize the HT while there is the saving child at work actually
1462 * a lot of memory movements in the parent will cause a lot of pages
1463 * copied. */
1464 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
1465 if (!(loops % 10)) tryResizeHashTables();
1466 if (server.activerehashing) incrementallyRehash();
1467 }
1468
1469 /* Show information about connected clients */
1470 if (!(loops % 50)) {
1471 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
1472 listLength(server.clients)-listLength(server.slaves),
1473 listLength(server.slaves),
1474 zmalloc_used_memory());
1475 }
1476
1477 /* Close connections of timedout clients */
1478 if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients)
1479 closeTimedoutClients();
1480
1481 /* Check if a background saving or AOF rewrite in progress terminated */
1482 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
1483 int statloc;
1484 pid_t pid;
1485
1486 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
1487 if (pid == server.bgsavechildpid) {
1488 backgroundSaveDoneHandler(statloc);
1489 } else {
1490 backgroundRewriteDoneHandler(statloc);
1491 }
1492 updateDictResizePolicy();
1493 }
1494 } else {
1495 /* If there is not a background saving in progress check if
1496 * we have to save now */
1497 time_t now = time(NULL);
1498 for (j = 0; j < server.saveparamslen; j++) {
1499 struct saveparam *sp = server.saveparams+j;
1500
1501 if (server.dirty >= sp->changes &&
1502 now-server.lastsave > sp->seconds) {
1503 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
1504 sp->changes, sp->seconds);
1505 rdbSaveBackground(server.dbfilename);
1506 break;
1507 }
1508 }
1509 }
1510
1511 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1512 * will use few CPU cycles if there are few expiring keys, otherwise
1513 * it will get more aggressive to avoid that too much memory is used by
1514 * keys that can be removed from the keyspace. */
1515 for (j = 0; j < server.dbnum; j++) {
1516 int expired;
1517 redisDb *db = server.db+j;
1518
1519 /* Continue to expire if at the end of the cycle more than 25%
1520 * of the keys were expired. */
1521 do {
1522 long num = dictSize(db->expires);
1523 time_t now = time(NULL);
1524
1525 expired = 0;
1526 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
1527 num = REDIS_EXPIRELOOKUPS_PER_CRON;
1528 while (num--) {
1529 dictEntry *de;
1530 time_t t;
1531
1532 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
1533 t = (time_t) dictGetEntryVal(de);
1534 if (now > t) {
1535 deleteKey(db,dictGetEntryKey(de));
1536 expired++;
1537 server.stat_expiredkeys++;
1538 }
1539 }
1540 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
1541 }
1542
1543 /* Swap a few keys on disk if we are over the memory limit and VM
1544 * is enbled. Try to free objects from the free list first. */
1545 if (vmCanSwapOut()) {
1546 while (server.vm_enabled && zmalloc_used_memory() >
1547 server.vm_max_memory)
1548 {
1549 int retval;
1550
1551 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
1552 retval = (server.vm_max_threads == 0) ?
1553 vmSwapOneObjectBlocking() :
1554 vmSwapOneObjectThreaded();
1555 if (retval == REDIS_ERR && !(loops % 300) &&
1556 zmalloc_used_memory() >
1557 (server.vm_max_memory+server.vm_max_memory/10))
1558 {
1559 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1560 }
1561 /* Note that when using threade I/O we free just one object,
1562 * because anyway when the I/O thread in charge to swap this
1563 * object out will finish, the handler of completed jobs
1564 * will try to swap more objects if we are still out of memory. */
1565 if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
1566 }
1567 }
1568
1569 /* Check if we should connect to a MASTER */
1570 if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) {
1571 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
1572 if (syncWithMaster() == REDIS_OK) {
1573 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
1574 if (server.appendonly) rewriteAppendOnlyFileBackground();
1575 }
1576 }
1577 return 100;
1578 }
1579
1580 /* This function gets called every time Redis is entering the
1581 * main loop of the event driven library, that is, before to sleep
1582 * for ready file descriptors. */
1583 static void beforeSleep(struct aeEventLoop *eventLoop) {
1584 REDIS_NOTUSED(eventLoop);
1585
1586 /* Awake clients that got all the swapped keys they requested */
1587 if (server.vm_enabled && listLength(server.io_ready_clients)) {
1588 listIter li;
1589 listNode *ln;
1590
1591 listRewind(server.io_ready_clients,&li);
1592 while((ln = listNext(&li))) {
1593 redisClient *c = ln->value;
1594 struct redisCommand *cmd;
1595
1596 /* Resume the client. */
1597 listDelNode(server.io_ready_clients,ln);
1598 c->flags &= (~REDIS_IO_WAIT);
1599 server.vm_blocked_clients--;
1600 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1601 readQueryFromClient, c);
1602 cmd = lookupCommand(c->argv[0]->ptr);
1603 assert(cmd != NULL);
1604 call(c,cmd);
1605 resetClient(c);
1606 /* There may be more data to process in the input buffer. */
1607 if (c->querybuf && sdslen(c->querybuf) > 0)
1608 processInputBuffer(c);
1609 }
1610 }
1611 /* Write the AOF buffer on disk */
1612 flushAppendOnlyFile();
1613 }
1614
1615 static void createSharedObjects(void) {
1616 int j;
1617
1618 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
1619 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
1620 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
1621 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
1622 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
1623 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
1624 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
1625 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
1626 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
1627 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
1628 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
1629 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
1630 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1631 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
1632 "-ERR no such key\r\n"));
1633 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
1634 "-ERR syntax error\r\n"));
1635 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
1636 "-ERR source and destination objects are the same\r\n"));
1637 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
1638 "-ERR index out of range\r\n"));
1639 shared.space = createObject(REDIS_STRING,sdsnew(" "));
1640 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
1641 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
1642 shared.select0 = createStringObject("select 0\r\n",10);
1643 shared.select1 = createStringObject("select 1\r\n",10);
1644 shared.select2 = createStringObject("select 2\r\n",10);
1645 shared.select3 = createStringObject("select 3\r\n",10);
1646 shared.select4 = createStringObject("select 4\r\n",10);
1647 shared.select5 = createStringObject("select 5\r\n",10);
1648 shared.select6 = createStringObject("select 6\r\n",10);
1649 shared.select7 = createStringObject("select 7\r\n",10);
1650 shared.select8 = createStringObject("select 8\r\n",10);
1651 shared.select9 = createStringObject("select 9\r\n",10);
1652 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
1653 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
1654 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
1655 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
1656 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
1657 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
1658 shared.mbulk3 = createStringObject("*3\r\n",4);
1659 shared.mbulk4 = createStringObject("*4\r\n",4);
1660 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
1661 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
1662 shared.integers[j]->encoding = REDIS_ENCODING_INT;
1663 }
1664 }
1665
1666 static void appendServerSaveParams(time_t seconds, int changes) {
1667 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
1668 server.saveparams[server.saveparamslen].seconds = seconds;
1669 server.saveparams[server.saveparamslen].changes = changes;
1670 server.saveparamslen++;
1671 }
1672
1673 static void resetServerSaveParams() {
1674 zfree(server.saveparams);
1675 server.saveparams = NULL;
1676 server.saveparamslen = 0;
1677 }
1678
1679 static void initServerConfig() {
1680 server.dbnum = REDIS_DEFAULT_DBNUM;
1681 server.port = REDIS_SERVERPORT;
1682 server.verbosity = REDIS_VERBOSE;
1683 server.maxidletime = REDIS_MAXIDLETIME;
1684 server.saveparams = NULL;
1685 server.logfile = NULL; /* NULL = log on standard output */
1686 server.bindaddr = NULL;
1687 server.glueoutputbuf = 1;
1688 server.daemonize = 0;
1689 server.appendonly = 0;
1690 server.appendfsync = APPENDFSYNC_EVERYSEC;
1691 server.lastfsync = time(NULL);
1692 server.appendfd = -1;
1693 server.appendseldb = -1; /* Make sure the first time will not match */
1694 server.pidfile = zstrdup("/var/run/redis.pid");
1695 server.dbfilename = zstrdup("dump.rdb");
1696 server.appendfilename = zstrdup("appendonly.aof");
1697 server.requirepass = NULL;
1698 server.rdbcompression = 1;
1699 server.activerehashing = 1;
1700 server.maxclients = 0;
1701 server.blpop_blocked_clients = 0;
1702 server.maxmemory = 0;
1703 server.vm_enabled = 0;
1704 server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
1705 server.vm_page_size = 256; /* 256 bytes per page */
1706 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
1707 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
1708 server.vm_max_threads = 4;
1709 server.vm_blocked_clients = 0;
1710 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
1711 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
1712 server.shutdown_asap = 0;
1713
1714 resetServerSaveParams();
1715
1716 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1717 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1718 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1719 /* Replication related */
1720 server.isslave = 0;
1721 server.masterauth = NULL;
1722 server.masterhost = NULL;
1723 server.masterport = 6379;
1724 server.master = NULL;
1725 server.replstate = REDIS_REPL_NONE;
1726
1727 /* Double constants initialization */
1728 R_Zero = 0.0;
1729 R_PosInf = 1.0/R_Zero;
1730 R_NegInf = -1.0/R_Zero;
1731 R_Nan = R_Zero/R_Zero;
1732 }
1733
1734 static void initServer() {
1735 int j;
1736
1737 signal(SIGHUP, SIG_IGN);
1738 signal(SIGPIPE, SIG_IGN);
1739 setupSigSegvAction();
1740
1741 server.devnull = fopen("/dev/null","w");
1742 if (server.devnull == NULL) {
1743 redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr);
1744 exit(1);
1745 }
1746 server.clients = listCreate();
1747 server.slaves = listCreate();
1748 server.monitors = listCreate();
1749 server.objfreelist = listCreate();
1750 createSharedObjects();
1751 server.el = aeCreateEventLoop();
1752 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
1753 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
1754 if (server.fd == -1) {
1755 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
1756 exit(1);
1757 }
1758 for (j = 0; j < server.dbnum; j++) {
1759 server.db[j].dict = dictCreate(&dbDictType,NULL);
1760 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
1761 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
1762 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
1763 if (server.vm_enabled)
1764 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
1765 server.db[j].id = j;
1766 }
1767 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1768 server.pubsub_patterns = listCreate();
1769 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1770 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
1771 server.cronloops = 0;
1772 server.bgsavechildpid = -1;
1773 server.bgrewritechildpid = -1;
1774 server.bgrewritebuf = sdsempty();
1775 server.aofbuf = sdsempty();
1776 server.lastsave = time(NULL);
1777 server.dirty = 0;
1778 server.stat_numcommands = 0;
1779 server.stat_numconnections = 0;
1780 server.stat_expiredkeys = 0;
1781 server.stat_starttime = time(NULL);
1782 server.unixtime = time(NULL);
1783 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
1784 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
1785 acceptHandler, NULL) == AE_ERR) oom("creating file event");
1786
1787 if (server.appendonly) {
1788 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
1789 if (server.appendfd == -1) {
1790 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1791 strerror(errno));
1792 exit(1);
1793 }
1794 }
1795
1796 if (server.vm_enabled) vmInit();
1797 }
1798
1799 /* Empty the whole database */
1800 static long long emptyDb() {
1801 int j;
1802 long long removed = 0;
1803
1804 for (j = 0; j < server.dbnum; j++) {
1805 removed += dictSize(server.db[j].dict);
1806 dictEmpty(server.db[j].dict);
1807 dictEmpty(server.db[j].expires);
1808 }
1809 return removed;
1810 }
1811
1812 static int yesnotoi(char *s) {
1813 if (!strcasecmp(s,"yes")) return 1;
1814 else if (!strcasecmp(s,"no")) return 0;
1815 else return -1;
1816 }
1817
1818 /* I agree, this is a very rudimental way to load a configuration...
1819 will improve later if the config gets more complex */
1820 static void loadServerConfig(char *filename) {
1821 FILE *fp;
1822 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
1823 int linenum = 0;
1824 sds line = NULL;
1825
1826 if (filename[0] == '-' && filename[1] == '\0')
1827 fp = stdin;
1828 else {
1829 if ((fp = fopen(filename,"r")) == NULL) {
1830 redisLog(REDIS_WARNING, "Fatal error, can't open config file '%s'", filename);
1831 exit(1);
1832 }
1833 }
1834
1835 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1836 sds *argv;
1837 int argc, j;
1838
1839 linenum++;
1840 line = sdsnew(buf);
1841 line = sdstrim(line," \t\r\n");
1842
1843 /* Skip comments and blank lines*/
1844 if (line[0] == '#' || line[0] == '\0') {
1845 sdsfree(line);
1846 continue;
1847 }
1848
1849 /* Split into arguments */
1850 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
1851 sdstolower(argv[0]);
1852
1853 /* Execute config directives */
1854 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
1855 server.maxidletime = atoi(argv[1]);
1856 if (server.maxidletime < 0) {
1857 err = "Invalid timeout value"; goto loaderr;
1858 }
1859 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
1860 server.port = atoi(argv[1]);
1861 if (server.port < 1 || server.port > 65535) {
1862 err = "Invalid port"; goto loaderr;
1863 }
1864 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
1865 server.bindaddr = zstrdup(argv[1]);
1866 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
1867 int seconds = atoi(argv[1]);
1868 int changes = atoi(argv[2]);
1869 if (seconds < 1 || changes < 0) {
1870 err = "Invalid save parameters"; goto loaderr;
1871 }
1872 appendServerSaveParams(seconds,changes);
1873 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
1874 if (chdir(argv[1]) == -1) {
1875 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
1876 argv[1], strerror(errno));
1877 exit(1);
1878 }
1879 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
1880 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
1881 else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
1882 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
1883 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
1884 else {
1885 err = "Invalid log level. Must be one of debug, notice, warning";
1886 goto loaderr;
1887 }
1888 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
1889 FILE *logfp;
1890
1891 server.logfile = zstrdup(argv[1]);
1892 if (!strcasecmp(server.logfile,"stdout")) {
1893 zfree(server.logfile);
1894 server.logfile = NULL;
1895 }
1896 if (server.logfile) {
1897 /* Test if we are able to open the file. The server will not
1898 * be able to abort just for this problem later... */
1899 logfp = fopen(server.logfile,"a");
1900 if (logfp == NULL) {
1901 err = sdscatprintf(sdsempty(),
1902 "Can't open the log file: %s", strerror(errno));
1903 goto loaderr;
1904 }
1905 fclose(logfp);
1906 }
1907 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
1908 server.dbnum = atoi(argv[1]);
1909 if (server.dbnum < 1) {
1910 err = "Invalid number of databases"; goto loaderr;
1911 }
1912 } else if (!strcasecmp(argv[0],"include") && argc == 2) {
1913 loadServerConfig(argv[1]);
1914 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
1915 server.maxclients = atoi(argv[1]);
1916 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
1917 server.maxmemory = memtoll(argv[1],NULL);
1918 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
1919 server.masterhost = sdsnew(argv[1]);
1920 server.masterport = atoi(argv[2]);
1921 server.replstate = REDIS_REPL_CONNECT;
1922 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
1923 server.masterauth = zstrdup(argv[1]);
1924 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
1925 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
1926 err = "argument must be 'yes' or 'no'"; goto loaderr;
1927 }
1928 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
1929 if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
1930 err = "argument must be 'yes' or 'no'"; goto loaderr;
1931 }
1932 } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
1933 if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
1934 err = "argument must be 'yes' or 'no'"; goto loaderr;
1935 }
1936 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
1937 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
1938 err = "argument must be 'yes' or 'no'"; goto loaderr;
1939 }
1940 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
1941 if ((server.appendonly = yesnotoi(argv[1])) == -1) {
1942 err = "argument must be 'yes' or 'no'"; goto loaderr;
1943 }
1944 } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
1945 zfree(server.appendfilename);
1946 server.appendfilename = zstrdup(argv[1]);
1947 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
1948 if (!strcasecmp(argv[1],"no")) {
1949 server.appendfsync = APPENDFSYNC_NO;
1950 } else if (!strcasecmp(argv[1],"always")) {
1951 server.appendfsync = APPENDFSYNC_ALWAYS;
1952 } else if (!strcasecmp(argv[1],"everysec")) {
1953 server.appendfsync = APPENDFSYNC_EVERYSEC;
1954 } else {
1955 err = "argument must be 'no', 'always' or 'everysec'";
1956 goto loaderr;
1957 }
1958 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
1959 server.requirepass = zstrdup(argv[1]);
1960 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
1961 zfree(server.pidfile);
1962 server.pidfile = zstrdup(argv[1]);
1963 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
1964 zfree(server.dbfilename);
1965 server.dbfilename = zstrdup(argv[1]);
1966 } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
1967 if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
1968 err = "argument must be 'yes' or 'no'"; goto loaderr;
1969 }
1970 } else if (!strcasecmp(argv[0],"vm-swap-file") && argc == 2) {
1971 zfree(server.vm_swap_file);
1972 server.vm_swap_file = zstrdup(argv[1]);
1973 } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
1974 server.vm_max_memory = memtoll(argv[1],NULL);
1975 } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
1976 server.vm_page_size = memtoll(argv[1], NULL);
1977 } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
1978 server.vm_pages = memtoll(argv[1], NULL);
1979 } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
1980 server.vm_max_threads = strtoll(argv[1], NULL, 10);
1981 } else if (!strcasecmp(argv[0],"hash-max-zipmap-entries") && argc == 2){
1982 server.hash_max_zipmap_entries = memtoll(argv[1], NULL);
1983 } else if (!strcasecmp(argv[0],"hash-max-zipmap-value") && argc == 2){
1984 server.hash_max_zipmap_value = memtoll(argv[1], NULL);
1985 } else {
1986 err = "Bad directive or wrong number of arguments"; goto loaderr;
1987 }
1988 for (j = 0; j < argc; j++)
1989 sdsfree(argv[j]);
1990 zfree(argv);
1991 sdsfree(line);
1992 }
1993 if (fp != stdin) fclose(fp);
1994 return;
1995
1996 loaderr:
1997 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
1998 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
1999 fprintf(stderr, ">>> '%s'\n", line);
2000 fprintf(stderr, "%s\n", err);
2001 exit(1);
2002 }
2003
2004 static void freeClientArgv(redisClient *c) {
2005 int j;
2006
2007 for (j = 0; j < c->argc; j++)
2008 decrRefCount(c->argv[j]);
2009 for (j = 0; j < c->mbargc; j++)
2010 decrRefCount(c->mbargv[j]);
2011 c->argc = 0;
2012 c->mbargc = 0;
2013 }
2014
2015 static void freeClient(redisClient *c) {
2016 listNode *ln;
2017
2018 /* Note that if the client we are freeing is blocked into a blocking
2019 * call, we have to set querybuf to NULL *before* to call
2020 * unblockClientWaitingData() to avoid processInputBuffer() will get
2021 * called. Also it is important to remove the file events after
2022 * this, because this call adds the READABLE event. */
2023 sdsfree(c->querybuf);
2024 c->querybuf = NULL;
2025 if (c->flags & REDIS_BLOCKED)
2026 unblockClientWaitingData(c);
2027
2028 /* UNWATCH all the keys */
2029 unwatchAllKeys(c);
2030 listRelease(c->watched_keys);
2031 /* Unsubscribe from all the pubsub channels */
2032 pubsubUnsubscribeAllChannels(c,0);
2033 pubsubUnsubscribeAllPatterns(c,0);
2034 dictRelease(c->pubsub_channels);
2035 listRelease(c->pubsub_patterns);
2036 /* Obvious cleanup */
2037 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
2038 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2039 listRelease(c->reply);
2040 freeClientArgv(c);
2041 close(c->fd);
2042 /* Remove from the list of clients */
2043 ln = listSearchKey(server.clients,c);
2044 redisAssert(ln != NULL);
2045 listDelNode(server.clients,ln);
2046 /* Remove from the list of clients that are now ready to be restarted
2047 * after waiting for swapped keys */
2048 if (c->flags & REDIS_IO_WAIT && listLength(c->io_keys) == 0) {
2049 ln = listSearchKey(server.io_ready_clients,c);
2050 if (ln) {
2051 listDelNode(server.io_ready_clients,ln);
2052 server.vm_blocked_clients--;
2053 }
2054 }
2055 /* Remove from the list of clients waiting for swapped keys */
2056 while (server.vm_enabled && listLength(c->io_keys)) {
2057 ln = listFirst(c->io_keys);
2058 dontWaitForSwappedKey(c,ln->value);
2059 }
2060 listRelease(c->io_keys);
2061 /* Master/slave cleanup */
2062 if (c->flags & REDIS_SLAVE) {
2063 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
2064 close(c->repldbfd);
2065 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
2066 ln = listSearchKey(l,c);
2067 redisAssert(ln != NULL);
2068 listDelNode(l,ln);
2069 }
2070 if (c->flags & REDIS_MASTER) {
2071 server.master = NULL;
2072 server.replstate = REDIS_REPL_CONNECT;
2073 }
2074 /* Release memory */
2075 zfree(c->argv);
2076 zfree(c->mbargv);
2077 freeClientMultiState(c);
2078 zfree(c);
2079 }
2080
2081 #define GLUEREPLY_UP_TO (1024)
2082 static void glueReplyBuffersIfNeeded(redisClient *c) {
2083 int copylen = 0;
2084 char buf[GLUEREPLY_UP_TO];
2085 listNode *ln;
2086 listIter li;
2087 robj *o;
2088
2089 listRewind(c->reply,&li);
2090 while((ln = listNext(&li))) {
2091 int objlen;
2092
2093 o = ln->value;
2094 objlen = sdslen(o->ptr);
2095 if (copylen + objlen <= GLUEREPLY_UP_TO) {
2096 memcpy(buf+copylen,o->ptr,objlen);
2097 copylen += objlen;
2098 listDelNode(c->reply,ln);
2099 } else {
2100 if (copylen == 0) return;
2101 break;
2102 }
2103 }
2104 /* Now the output buffer is empty, add the new single element */
2105 o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
2106 listAddNodeHead(c->reply,o);
2107 }
2108
2109 static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2110 redisClient *c = privdata;
2111 int nwritten = 0, totwritten = 0, objlen;
2112 robj *o;
2113 REDIS_NOTUSED(el);
2114 REDIS_NOTUSED(mask);
2115
2116 /* Use writev() if we have enough buffers to send */
2117 if (!server.glueoutputbuf &&
2118 listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
2119 !(c->flags & REDIS_MASTER))
2120 {
2121 sendReplyToClientWritev(el, fd, privdata, mask);
2122 return;
2123 }
2124
2125 while(listLength(c->reply)) {
2126 if (server.glueoutputbuf && listLength(c->reply) > 1)
2127 glueReplyBuffersIfNeeded(c);
2128
2129 o = listNodeValue(listFirst(c->reply));
2130 objlen = sdslen(o->ptr);
2131
2132 if (objlen == 0) {
2133 listDelNode(c->reply,listFirst(c->reply));
2134 continue;
2135 }
2136
2137 if (c->flags & REDIS_MASTER) {
2138 /* Don't reply to a master */
2139 nwritten = objlen - c->sentlen;
2140 } else {
2141 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
2142 if (nwritten <= 0) break;
2143 }
2144 c->sentlen += nwritten;
2145 totwritten += nwritten;
2146 /* If we fully sent the object on head go to the next one */
2147 if (c->sentlen == objlen) {
2148 listDelNode(c->reply,listFirst(c->reply));
2149 c->sentlen = 0;
2150 }
2151 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
2152 * bytes, in a single threaded server it's a good idea to serve
2153 * other clients as well, even if a very large request comes from
2154 * super fast link that is always able to accept data (in real world
2155 * scenario think about 'KEYS *' against the loopback interfae) */
2156 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
2157 }
2158 if (nwritten == -1) {
2159 if (errno == EAGAIN) {
2160 nwritten = 0;
2161 } else {
2162 redisLog(REDIS_VERBOSE,
2163 "Error writing to client: %s", strerror(errno));
2164 freeClient(c);
2165 return;
2166 }
2167 }
2168 if (totwritten > 0) c->lastinteraction = time(NULL);
2169 if (listLength(c->reply) == 0) {
2170 c->sentlen = 0;
2171 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2172 }
2173 }
2174
2175 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
2176 {
2177 redisClient *c = privdata;
2178 int nwritten = 0, totwritten = 0, objlen, willwrite;
2179 robj *o;
2180 struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
2181 int offset, ion = 0;
2182 REDIS_NOTUSED(el);
2183 REDIS_NOTUSED(mask);
2184
2185 listNode *node;
2186 while (listLength(c->reply)) {
2187 offset = c->sentlen;
2188 ion = 0;
2189 willwrite = 0;
2190
2191 /* fill-in the iov[] array */
2192 for(node = listFirst(c->reply); node; node = listNextNode(node)) {
2193 o = listNodeValue(node);
2194 objlen = sdslen(o->ptr);
2195
2196 if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
2197 break;
2198
2199 if(ion == REDIS_WRITEV_IOVEC_COUNT)
2200 break; /* no more iovecs */
2201
2202 iov[ion].iov_base = ((char*)o->ptr) + offset;
2203 iov[ion].iov_len = objlen - offset;
2204 willwrite += objlen - offset;
2205 offset = 0; /* just for the first item */
2206 ion++;
2207 }
2208
2209 if(willwrite == 0)
2210 break;
2211
2212 /* write all collected blocks at once */
2213 if((nwritten = writev(fd, iov, ion)) < 0) {
2214 if (errno != EAGAIN) {
2215 redisLog(REDIS_VERBOSE,
2216 "Error writing to client: %s", strerror(errno));
2217 freeClient(c);
2218 return;
2219 }
2220 break;
2221 }
2222
2223 totwritten += nwritten;
2224 offset = c->sentlen;
2225
2226 /* remove written robjs from c->reply */
2227 while (nwritten && listLength(c->reply)) {
2228 o = listNodeValue(listFirst(c->reply));
2229 objlen = sdslen(o->ptr);
2230
2231 if(nwritten >= objlen - offset) {
2232 listDelNode(c->reply, listFirst(c->reply));
2233 nwritten -= objlen - offset;
2234 c->sentlen = 0;
2235 } else {
2236 /* partial write */
2237 c->sentlen += nwritten;
2238 break;
2239 }
2240 offset = 0;
2241 }
2242 }
2243
2244 if (totwritten > 0)
2245 c->lastinteraction = time(NULL);
2246
2247 if (listLength(c->reply) == 0) {
2248 c->sentlen = 0;
2249 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2250 }
2251 }
2252
2253 static int qsortRedisCommands(const void *r1, const void *r2) {
2254 return strcasecmp(
2255 ((struct redisCommand*)r1)->name,
2256 ((struct redisCommand*)r2)->name);
2257 }
2258
2259 static void sortCommandTable() {
2260 /* Copy and sort the read-only version of the command table */
2261 commandTable = (struct redisCommand*)malloc(sizeof(readonlyCommandTable));
2262 memcpy(commandTable,readonlyCommandTable,sizeof(readonlyCommandTable));
2263 qsort(commandTable,
2264 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
2265 sizeof(struct redisCommand),qsortRedisCommands);
2266 }
2267
2268 static struct redisCommand *lookupCommand(char *name) {
2269 struct redisCommand tmp = {name,NULL,0,0,NULL,0,0,0};
2270 return bsearch(
2271 &tmp,
2272 commandTable,
2273 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
2274 sizeof(struct redisCommand),
2275 qsortRedisCommands);
2276 }
2277
2278 /* resetClient prepare the client to process the next command */
2279 static void resetClient(redisClient *c) {
2280 freeClientArgv(c);
2281 c->bulklen = -1;
2282 c->multibulk = 0;
2283 }
2284
2285 /* Call() is the core of Redis execution of a command */
2286 static void call(redisClient *c, struct redisCommand *cmd) {
2287 long long dirty;
2288
2289 dirty = server.dirty;
2290 cmd->proc(c);
2291 dirty = server.dirty-dirty;
2292
2293 if (server.appendonly && dirty)
2294 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
2295 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
2296 listLength(server.slaves))
2297 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
2298 if (listLength(server.monitors))
2299 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
2300 server.stat_numcommands++;
2301 }
2302
2303 /* If this function gets called we already read a whole
2304 * command, argments are in the client argv/argc fields.
2305 * processCommand() execute the command or prepare the
2306 * server for a bulk read from the client.
2307 *
2308 * If 1 is returned the client is still alive and valid and
2309 * and other operations can be performed by the caller. Otherwise
2310 * if 0 is returned the client was destroied (i.e. after QUIT). */
2311 static int processCommand(redisClient *c) {
2312 struct redisCommand *cmd;
2313
2314 /* Free some memory if needed (maxmemory setting) */
2315 if (server.maxmemory) freeMemoryIfNeeded();
2316
2317 /* Handle the multi bulk command type. This is an alternative protocol
2318 * supported by Redis in order to receive commands that are composed of
2319 * multiple binary-safe "bulk" arguments. The latency of processing is
2320 * a bit higher but this allows things like multi-sets, so if this
2321 * protocol is used only for MSET and similar commands this is a big win. */
2322 if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
2323 c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
2324 if (c->multibulk <= 0) {
2325 resetClient(c);
2326 return 1;
2327 } else {
2328 decrRefCount(c->argv[c->argc-1]);
2329 c->argc--;
2330 return 1;
2331 }
2332 } else if (c->multibulk) {
2333 if (c->bulklen == -1) {
2334 if (((char*)c->argv[0]->ptr)[0] != '$') {
2335 addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
2336 resetClient(c);
2337 return 1;
2338 } else {
2339 int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
2340 decrRefCount(c->argv[0]);
2341 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2342 c->argc--;
2343 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2344 resetClient(c);
2345 return 1;
2346 }
2347 c->argc--;
2348 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2349 return 1;
2350 }
2351 } else {
2352 c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
2353 c->mbargv[c->mbargc] = c->argv[0];
2354 c->mbargc++;
2355 c->argc--;
2356 c->multibulk--;
2357 if (c->multibulk == 0) {
2358 robj **auxargv;
2359 int auxargc;
2360
2361 /* Here we need to swap the multi-bulk argc/argv with the
2362 * normal argc/argv of the client structure. */
2363 auxargv = c->argv;
2364 c->argv = c->mbargv;
2365 c->mbargv = auxargv;
2366
2367 auxargc = c->argc;
2368 c->argc = c->mbargc;
2369 c->mbargc = auxargc;
2370
2371 /* We need to set bulklen to something different than -1
2372 * in order for the code below to process the command without
2373 * to try to read the last argument of a bulk command as
2374 * a special argument. */
2375 c->bulklen = 0;
2376 /* continue below and process the command */
2377 } else {
2378 c->bulklen = -1;
2379 return 1;
2380 }
2381 }
2382 }
2383 /* -- end of multi bulk commands processing -- */
2384
2385 /* The QUIT command is handled as a special case. Normal command
2386 * procs are unable to close the client connection safely */
2387 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
2388 freeClient(c);
2389 return 0;
2390 }
2391
2392 /* Now lookup the command and check ASAP about trivial error conditions
2393 * such wrong arity, bad command name and so forth. */
2394 cmd = lookupCommand(c->argv[0]->ptr);
2395 if (!cmd) {
2396 addReplySds(c,
2397 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2398 (char*)c->argv[0]->ptr));
2399 resetClient(c);
2400 return 1;
2401 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
2402 (c->argc < -cmd->arity)) {
2403 addReplySds(c,
2404 sdscatprintf(sdsempty(),
2405 "-ERR wrong number of arguments for '%s' command\r\n",
2406 cmd->name));
2407 resetClient(c);
2408 return 1;
2409 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
2410 /* This is a bulk command, we have to read the last argument yet. */
2411 int bulklen = atoi(c->argv[c->argc-1]->ptr);
2412
2413 decrRefCount(c->argv[c->argc-1]);
2414 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2415 c->argc--;
2416 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2417 resetClient(c);
2418 return 1;
2419 }
2420 c->argc--;
2421 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2422 /* It is possible that the bulk read is already in the
2423 * buffer. Check this condition and handle it accordingly.
2424 * This is just a fast path, alternative to call processInputBuffer().
2425 * It's a good idea since the code is small and this condition
2426 * happens most of the times. */
2427 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
2428 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2429 c->argc++;
2430 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2431 } else {
2432 /* Otherwise return... there is to read the last argument
2433 * from the socket. */
2434 return 1;
2435 }
2436 }
2437 /* Let's try to encode the bulk object to save space. */
2438 if (cmd->flags & REDIS_CMD_BULK)
2439 c->argv[c->argc-1] = tryObjectEncoding(c->argv[c->argc-1]);
2440
2441 /* Check if the user is authenticated */
2442 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
2443 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
2444 resetClient(c);
2445 return 1;
2446 }
2447
2448 /* Handle the maxmemory directive */
2449 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
2450 zmalloc_used_memory() > server.maxmemory)
2451 {
2452 addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2453 resetClient(c);
2454 return 1;
2455 }
2456
2457 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
2458 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
2459 &&
2460 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
2461 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
2462 addReplySds(c,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
2463 resetClient(c);
2464 return 1;
2465 }
2466
2467 /* Exec the command */
2468 if (c->flags & REDIS_MULTI &&
2469 cmd->proc != execCommand && cmd->proc != discardCommand &&
2470 cmd->proc != multiCommand && cmd->proc != watchCommand)
2471 {
2472 queueMultiCommand(c,cmd);
2473 addReply(c,shared.queued);
2474 } else {
2475 if (server.vm_enabled && server.vm_max_threads > 0 &&
2476 blockClientOnSwappedKeys(c,cmd)) return 1;
2477 call(c,cmd);
2478 }
2479
2480 /* Prepare the client for the next command */
2481 resetClient(c);
2482 return 1;
2483 }
2484
2485 static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
2486 listNode *ln;
2487 listIter li;
2488 int outc = 0, j;
2489 robj **outv;
2490 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2491 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2492 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2493 robj *static_outv[REDIS_STATIC_ARGS*3+1];
2494 robj *lenobj;
2495
2496 if (argc <= REDIS_STATIC_ARGS) {
2497 outv = static_outv;
2498 } else {
2499 outv = zmalloc(sizeof(robj*)*(argc*3+1));
2500 }
2501
2502 lenobj = createObject(REDIS_STRING,
2503 sdscatprintf(sdsempty(), "*%d\r\n", argc));
2504 lenobj->refcount = 0;
2505 outv[outc++] = lenobj;
2506 for (j = 0; j < argc; j++) {
2507 lenobj = createObject(REDIS_STRING,
2508 sdscatprintf(sdsempty(),"$%lu\r\n",
2509 (unsigned long) stringObjectLen(argv[j])));
2510 lenobj->refcount = 0;
2511 outv[outc++] = lenobj;
2512 outv[outc++] = argv[j];
2513 outv[outc++] = shared.crlf;
2514 }
2515
2516 /* Increment all the refcounts at start and decrement at end in order to
2517 * be sure to free objects if there is no slave in a replication state
2518 * able to be feed with commands */
2519 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
2520 listRewind(slaves,&li);
2521 while((ln = listNext(&li))) {
2522 redisClient *slave = ln->value;
2523
2524 /* Don't feed slaves that are still waiting for BGSAVE to start */
2525 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
2526
2527 /* Feed all the other slaves, MONITORs and so on */
2528 if (slave->slaveseldb != dictid) {
2529 robj *selectcmd;
2530
2531 switch(dictid) {
2532 case 0: selectcmd = shared.select0; break;
2533 case 1: selectcmd = shared.select1; break;
2534 case 2: selectcmd = shared.select2; break;
2535 case 3: selectcmd = shared.select3; break;
2536 case 4: selectcmd = shared.select4; break;
2537 case 5: selectcmd = shared.select5; break;
2538 case 6: selectcmd = shared.select6; break;
2539 case 7: selectcmd = shared.select7; break;
2540 case 8: selectcmd = shared.select8; break;
2541 case 9: selectcmd = shared.select9; break;
2542 default:
2543 selectcmd = createObject(REDIS_STRING,
2544 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
2545 selectcmd->refcount = 0;
2546 break;
2547 }
2548 addReply(slave,selectcmd);
2549 slave->slaveseldb = dictid;
2550 }
2551 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
2552 }
2553 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
2554 if (outv != static_outv) zfree(outv);
2555 }
2556
2557 static sds sdscatrepr(sds s, char *p, size_t len) {
2558 s = sdscatlen(s,"\"",1);
2559 while(len--) {
2560 switch(*p) {
2561 case '\\':
2562 case '"':
2563 s = sdscatprintf(s,"\\%c",*p);
2564 break;
2565 case '\n': s = sdscatlen(s,"\\n",1); break;
2566 case '\r': s = sdscatlen(s,"\\r",1); break;
2567 case '\t': s = sdscatlen(s,"\\t",1); break;
2568 case '\a': s = sdscatlen(s,"\\a",1); break;
2569 case '\b': s = sdscatlen(s,"\\b",1); break;
2570 default:
2571 if (isprint(*p))
2572 s = sdscatprintf(s,"%c",*p);
2573 else
2574 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
2575 break;
2576 }
2577 p++;
2578 }
2579 return sdscatlen(s,"\"",1);
2580 }
2581
2582 static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc) {
2583 listNode *ln;
2584 listIter li;
2585 int j;
2586 sds cmdrepr = sdsnew("+");
2587 robj *cmdobj;
2588 struct timeval tv;
2589
2590 gettimeofday(&tv,NULL);
2591 cmdrepr = sdscatprintf(cmdrepr,"%ld.%ld ",(long)tv.tv_sec,(long)tv.tv_usec);
2592 if (dictid != 0) cmdrepr = sdscatprintf(cmdrepr,"(db %d) ", dictid);
2593
2594 for (j = 0; j < argc; j++) {
2595 if (argv[j]->encoding == REDIS_ENCODING_INT) {
2596 cmdrepr = sdscatprintf(cmdrepr, "%ld", (long)argv[j]->ptr);
2597 } else {
2598 cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
2599 sdslen(argv[j]->ptr));
2600 }
2601 if (j != argc-1)
2602 cmdrepr = sdscatlen(cmdrepr," ",1);
2603 }
2604 cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
2605 cmdobj = createObject(REDIS_STRING,cmdrepr);
2606
2607 listRewind(monitors,&li);
2608 while((ln = listNext(&li))) {
2609 redisClient *monitor = ln->value;
2610 addReply(monitor,cmdobj);
2611 }
2612 decrRefCount(cmdobj);
2613 }
2614
2615 static void processInputBuffer(redisClient *c) {
2616 again:
2617 /* Before to process the input buffer, make sure the client is not
2618 * waitig for a blocking operation such as BLPOP. Note that the first
2619 * iteration the client is never blocked, otherwise the processInputBuffer
2620 * would not be called at all, but after the execution of the first commands
2621 * in the input buffer the client may be blocked, and the "goto again"
2622 * will try to reiterate. The following line will make it return asap. */
2623 if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
2624 if (c->bulklen == -1) {
2625 /* Read the first line of the query */
2626 char *p = strchr(c->querybuf,'\n');
2627 size_t querylen;
2628
2629 if (p) {
2630 sds query, *argv;
2631 int argc, j;
2632
2633 query = c->querybuf;
2634 c->querybuf = sdsempty();
2635 querylen = 1+(p-(query));
2636 if (sdslen(query) > querylen) {
2637 /* leave data after the first line of the query in the buffer */
2638 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
2639 }
2640 *p = '\0'; /* remove "\n" */
2641 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
2642 sdsupdatelen(query);
2643
2644 /* Now we can split the query in arguments */
2645 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
2646 sdsfree(query);
2647
2648 if (c->argv) zfree(c->argv);
2649 c->argv = zmalloc(sizeof(robj*)*argc);
2650
2651 for (j = 0; j < argc; j++) {
2652 if (sdslen(argv[j])) {
2653 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
2654 c->argc++;
2655 } else {
2656 sdsfree(argv[j]);
2657 }
2658 }
2659 zfree(argv);
2660 if (c->argc) {
2661 /* Execute the command. If the client is still valid
2662 * after processCommand() return and there is something
2663 * on the query buffer try to process the next command. */
2664 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2665 } else {
2666 /* Nothing to process, argc == 0. Just process the query
2667 * buffer if it's not empty or return to the caller */
2668 if (sdslen(c->querybuf)) goto again;
2669 }
2670 return;
2671 } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
2672 redisLog(REDIS_VERBOSE, "Client protocol error");
2673 freeClient(c);
2674 return;
2675 }
2676 } else {
2677 /* Bulk read handling. Note that if we are at this point
2678 the client already sent a command terminated with a newline,
2679 we are reading the bulk data that is actually the last
2680 argument of the command. */
2681 int qbl = sdslen(c->querybuf);
2682
2683 if (c->bulklen <= qbl) {
2684 /* Copy everything but the final CRLF as final argument */
2685 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2686 c->argc++;
2687 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2688 /* Process the command. If the client is still valid after
2689 * the processing and there is more data in the buffer
2690 * try to parse it. */
2691 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2692 return;
2693 }
2694 }
2695 }
2696
2697 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2698 redisClient *c = (redisClient*) privdata;
2699 char buf[REDIS_IOBUF_LEN];
2700 int nread;
2701 REDIS_NOTUSED(el);
2702 REDIS_NOTUSED(mask);
2703
2704 nread = read(fd, buf, REDIS_IOBUF_LEN);
2705 if (nread == -1) {
2706 if (errno == EAGAIN) {
2707 nread = 0;
2708 } else {
2709 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
2710 freeClient(c);
2711 return;
2712 }
2713 } else if (nread == 0) {
2714 redisLog(REDIS_VERBOSE, "Client closed connection");
2715 freeClient(c);
2716 return;
2717 }
2718 if (nread) {
2719 c->querybuf = sdscatlen(c->querybuf, buf, nread);
2720 c->lastinteraction = time(NULL);
2721 } else {
2722 return;
2723 }
2724 processInputBuffer(c);
2725 }
2726
2727 static int selectDb(redisClient *c, int id) {
2728 if (id < 0 || id >= server.dbnum)
2729 return REDIS_ERR;
2730 c->db = &server.db[id];
2731 return REDIS_OK;
2732 }
2733
2734 static void *dupClientReplyValue(void *o) {
2735 incrRefCount((robj*)o);
2736 return o;
2737 }
2738
2739 static int listMatchObjects(void *a, void *b) {
2740 return equalStringObjects(a,b);
2741 }
2742
2743 static redisClient *createClient(int fd) {
2744 redisClient *c = zmalloc(sizeof(*c));
2745
2746 anetNonBlock(NULL,fd);
2747 anetTcpNoDelay(NULL,fd);
2748 if (!c) return NULL;
2749 selectDb(c,0);
2750 c->fd = fd;
2751 c->querybuf = sdsempty();
2752 c->argc = 0;
2753 c->argv = NULL;
2754 c->bulklen = -1;
2755 c->multibulk = 0;
2756 c->mbargc = 0;
2757 c->mbargv = NULL;
2758 c->sentlen = 0;
2759 c->flags = 0;
2760 c->lastinteraction = time(NULL);
2761 c->authenticated = 0;
2762 c->replstate = REDIS_REPL_NONE;
2763 c->reply = listCreate();
2764 listSetFreeMethod(c->reply,decrRefCount);
2765 listSetDupMethod(c->reply,dupClientReplyValue);
2766 c->blocking_keys = NULL;
2767 c->blocking_keys_num = 0;
2768 c->io_keys = listCreate();
2769 c->watched_keys = listCreate();
2770 listSetFreeMethod(c->io_keys,decrRefCount);
2771 c->pubsub_channels = dictCreate(&setDictType,NULL);
2772 c->pubsub_patterns = listCreate();
2773 listSetFreeMethod(c->pubsub_patterns,decrRefCount);
2774 listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
2775 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
2776 readQueryFromClient, c) == AE_ERR) {
2777 freeClient(c);
2778 return NULL;
2779 }
2780 listAddNodeTail(server.clients,c);
2781 initClientMultiState(c);
2782 return c;
2783 }
2784
2785 static void addReply(redisClient *c, robj *obj) {
2786 if (listLength(c->reply) == 0 &&
2787 (c->replstate == REDIS_REPL_NONE ||
2788 c->replstate == REDIS_REPL_ONLINE) &&
2789 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
2790 sendReplyToClient, c) == AE_ERR) return;
2791
2792 if (server.vm_enabled && obj->storage != REDIS_VM_MEMORY) {
2793 obj = dupStringObject(obj);
2794 obj->refcount = 0; /* getDecodedObject() will increment the refcount */
2795 }
2796 listAddNodeTail(c->reply,getDecodedObject(obj));
2797 }
2798
2799 static void addReplySds(redisClient *c, sds s) {
2800 robj *o = createObject(REDIS_STRING,s);
2801 addReply(c,o);
2802 decrRefCount(o);
2803 }
2804
2805 static void addReplyDouble(redisClient *c, double d) {
2806 char buf[128];
2807
2808 snprintf(buf,sizeof(buf),"%.17g",d);
2809 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2810 (unsigned long) strlen(buf),buf));
2811 }
2812
2813 static void addReplyLongLong(redisClient *c, long long ll) {
2814 char buf[128];
2815 size_t len;
2816
2817 if (ll == 0) {
2818 addReply(c,shared.czero);
2819 return;
2820 } else if (ll == 1) {
2821 addReply(c,shared.cone);
2822 return;
2823 }
2824 buf[0] = ':';
2825 len = ll2string(buf+1,sizeof(buf)-1,ll);
2826 buf[len+1] = '\r';
2827 buf[len+2] = '\n';
2828 addReplySds(c,sdsnewlen(buf,len+3));
2829 }
2830
2831 static void addReplyUlong(redisClient *c, unsigned long ul) {
2832 char buf[128];
2833 size_t len;
2834
2835 if (ul == 0) {
2836 addReply(c,shared.czero);
2837 return;
2838 } else if (ul == 1) {
2839 addReply(c,shared.cone);
2840 return;
2841 }
2842 len = snprintf(buf,sizeof(buf),":%lu\r\n",ul);
2843 addReplySds(c,sdsnewlen(buf,len));
2844 }
2845
2846 static void addReplyBulkLen(redisClient *c, robj *obj) {
2847 size_t len, intlen;
2848 char buf[128];
2849
2850 if (obj->encoding == REDIS_ENCODING_RAW) {
2851 len = sdslen(obj->ptr);
2852 } else {
2853 long n = (long)obj->ptr;
2854
2855 /* Compute how many bytes will take this integer as a radix 10 string */
2856 len = 1;
2857 if (n < 0) {
2858 len++;
2859 n = -n;
2860 }
2861 while((n = n/10) != 0) {
2862 len++;
2863 }
2864 }
2865 buf[0] = '$';
2866 intlen = ll2string(buf+1,sizeof(buf)-1,(long long)len);
2867 buf[intlen+1] = '\r';
2868 buf[intlen+2] = '\n';
2869 addReplySds(c,sdsnewlen(buf,intlen+3));
2870 }
2871
2872 static void addReplyBulk(redisClient *c, robj *obj) {
2873 addReplyBulkLen(c,obj);
2874 addReply(c,obj);
2875 addReply(c,shared.crlf);
2876 }
2877
2878 /* In the CONFIG command we need to add vanilla C string as bulk replies */
2879 static void addReplyBulkCString(redisClient *c, char *s) {
2880 if (s == NULL) {
2881 addReply(c,shared.nullbulk);
2882 } else {
2883 robj *o = createStringObject(s,strlen(s));
2884 addReplyBulk(c,o);
2885 decrRefCount(o);
2886 }
2887 }
2888
2889 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2890 int cport, cfd;
2891 char cip[128];
2892 redisClient *c;
2893 REDIS_NOTUSED(el);
2894 REDIS_NOTUSED(mask);
2895 REDIS_NOTUSED(privdata);
2896
2897 cfd = anetAccept(server.neterr, fd, cip, &cport);
2898 if (cfd == AE_ERR) {
2899 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
2900 return;
2901 }
2902 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
2903 if ((c = createClient(cfd)) == NULL) {
2904 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2905 close(cfd); /* May be already closed, just ingore errors */
2906 return;
2907 }
2908 /* If maxclient directive is set and this is one client more... close the
2909 * connection. Note that we create the client instead to check before
2910 * for this condition, since now the socket is already set in nonblocking
2911 * mode and we can send an error for free using the Kernel I/O */
2912 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2913 char *err = "-ERR max number of clients reached\r\n";
2914
2915 /* That's a best effort error message, don't check write errors */
2916 if (write(c->fd,err,strlen(err)) == -1) {
2917 /* Nothing to do, Just to avoid the warning... */
2918 }
2919 freeClient(c);
2920 return;
2921 }
2922 server.stat_numconnections++;
2923 }
2924
2925 /* ======================= Redis objects implementation ===================== */
2926
2927 static robj *createObject(int type, void *ptr) {
2928 robj *o;
2929
2930 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
2931 if (listLength(server.objfreelist)) {
2932 listNode *head = listFirst(server.objfreelist);
2933 o = listNodeValue(head);
2934 listDelNode(server.objfreelist,head);
2935 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
2936 } else {
2937 if (server.vm_enabled) {
2938 pthread_mutex_unlock(&server.obj_freelist_mutex);
2939 o = zmalloc(sizeof(*o));
2940 } else {
2941 o = zmalloc(sizeof(*o)-sizeof(struct redisObjectVM));
2942 }
2943 }
2944 o->type = type;
2945 o->encoding = REDIS_ENCODING_RAW;
2946 o->ptr = ptr;
2947 o->refcount = 1;
2948 if (server.vm_enabled) {
2949 /* Note that this code may run in the context of an I/O thread
2950 * and accessing to server.unixtime in theory is an error
2951 * (no locks). But in practice this is safe, and even if we read
2952 * garbage Redis will not fail, as it's just a statistical info */
2953 o->vm.atime = server.unixtime;
2954 o->storage = REDIS_VM_MEMORY;
2955 }
2956 return o;
2957 }
2958
2959 static robj *createStringObject(char *ptr, size_t len) {
2960 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
2961 }
2962
2963 static robj *createStringObjectFromLongLong(long long value) {
2964 robj *o;
2965 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
2966 incrRefCount(shared.integers[value]);
2967 o = shared.integers[value];
2968 } else {
2969 if (value >= LONG_MIN && value <= LONG_MAX) {
2970 o = createObject(REDIS_STRING, NULL);
2971 o->encoding = REDIS_ENCODING_INT;
2972 o->ptr = (void*)((long)value);
2973 } else {
2974 o = createObject(REDIS_STRING,sdsfromlonglong(value));
2975 }
2976 }
2977 return o;
2978 }
2979
2980 static robj *dupStringObject(robj *o) {
2981 assert(o->encoding == REDIS_ENCODING_RAW);
2982 return createStringObject(o->ptr,sdslen(o->ptr));
2983 }
2984
2985 static robj *createListObject(void) {
2986 list *l = listCreate();
2987
2988 listSetFreeMethod(l,decrRefCount);
2989 return createObject(REDIS_LIST,l);
2990 }
2991
2992 static robj *createSetObject(void) {
2993 dict *d = dictCreate(&setDictType,NULL);
2994 return createObject(REDIS_SET,d);
2995 }
2996
2997 static robj *createHashObject(void) {
2998 /* All the Hashes start as zipmaps. Will be automatically converted
2999 * into hash tables if there are enough elements or big elements
3000 * inside. */
3001 unsigned char *zm = zipmapNew();
3002 robj *o = createObject(REDIS_HASH,zm);
3003 o->encoding = REDIS_ENCODING_ZIPMAP;
3004 return o;
3005 }
3006
3007 static robj *createZsetObject(void) {
3008 zset *zs = zmalloc(sizeof(*zs));
3009
3010 zs->dict = dictCreate(&zsetDictType,NULL);
3011 zs->zsl = zslCreate();
3012 return createObject(REDIS_ZSET,zs);
3013 }
3014
3015 static void freeStringObject(robj *o) {
3016 if (o->encoding == REDIS_ENCODING_RAW) {
3017 sdsfree(o->ptr);
3018 }
3019 }
3020
3021 static void freeListObject(robj *o) {
3022 switch (o->encoding) {
3023 case REDIS_ENCODING_LIST:
3024 listRelease((list*) o->ptr);
3025 break;
3026 case REDIS_ENCODING_ZIPLIST:
3027 zfree(o->ptr);
3028 break;
3029 default:
3030 redisPanic("Unknown list encoding type");
3031 }
3032 }
3033
3034 static void freeSetObject(robj *o) {
3035 dictRelease((dict*) o->ptr);
3036 }
3037
3038 static void freeZsetObject(robj *o) {
3039 zset *zs = o->ptr;
3040
3041 dictRelease(zs->dict);
3042 zslFree(zs->zsl);
3043 zfree(zs);
3044 }
3045
3046 static void freeHashObject(robj *o) {
3047 switch (o->encoding) {
3048 case REDIS_ENCODING_HT:
3049 dictRelease((dict*) o->ptr);
3050 break;
3051 case REDIS_ENCODING_ZIPMAP:
3052 zfree(o->ptr);
3053 break;
3054 default:
3055 redisPanic("Unknown hash encoding type");
3056 break;
3057 }
3058 }
3059
3060 static void incrRefCount(robj *o) {
3061 o->refcount++;
3062 }
3063
3064 static void decrRefCount(void *obj) {
3065 robj *o = obj;
3066
3067 if (o->refcount <= 0) redisPanic("decrRefCount against refcount <= 0");
3068 /* Object is a key of a swapped out value, or in the process of being
3069 * loaded. */
3070 if (server.vm_enabled &&
3071 (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
3072 {
3073 if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(obj);
3074 redisAssert(o->type == REDIS_STRING);
3075 freeStringObject(o);
3076 vmMarkPagesFree(o->vm.page,o->vm.usedpages);
3077 pthread_mutex_lock(&server.obj_freelist_mutex);
3078 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3079 !listAddNodeHead(server.objfreelist,o))
3080 zfree(o);
3081 pthread_mutex_unlock(&server.obj_freelist_mutex);
3082 server.vm_stats_swapped_objects--;
3083 return;
3084 }
3085 /* Object is in memory, or in the process of being swapped out. */
3086 if (--(o->refcount) == 0) {
3087 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
3088 vmCancelThreadedIOJob(obj);
3089 switch(o->type) {
3090 case REDIS_STRING: freeStringObject(o); break;
3091 case REDIS_LIST: freeListObject(o); break;
3092 case REDIS_SET: freeSetObject(o); break;
3093 case REDIS_ZSET: freeZsetObject(o); break;
3094 case REDIS_HASH: freeHashObject(o); break;
3095 default: redisPanic("Unknown object type"); break;
3096 }
3097 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
3098 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3099 !listAddNodeHead(server.objfreelist,o))
3100 zfree(o);
3101 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
3102 }
3103 }
3104
3105 static robj *lookupKey(redisDb *db, robj *key) {
3106 dictEntry *de = dictFind(db->dict,key);
3107 if (de) {
3108 robj *key = dictGetEntryKey(de);
3109 robj *val = dictGetEntryVal(de);
3110
3111 if (server.vm_enabled) {
3112 if (key->storage == REDIS_VM_MEMORY ||
3113 key->storage == REDIS_VM_SWAPPING)
3114 {
3115 /* If we were swapping the object out, stop it, this key
3116 * was requested. */
3117 if (key->storage == REDIS_VM_SWAPPING)
3118 vmCancelThreadedIOJob(key);
3119 /* Update the access time of the key for the aging algorithm. */
3120 key->vm.atime = server.unixtime;
3121 } else {
3122 int notify = (key->storage == REDIS_VM_LOADING);
3123
3124 /* Our value was swapped on disk. Bring it at home. */
3125 redisAssert(val == NULL);
3126 val = vmLoadObject(key);
3127 dictGetEntryVal(de) = val;
3128
3129 /* Clients blocked by the VM subsystem may be waiting for
3130 * this key... */
3131 if (notify) handleClientsBlockedOnSwappedKey(db,key);
3132 }
3133 }
3134 return val;
3135 } else {
3136 return NULL;
3137 }
3138 }
3139
3140 static robj *lookupKeyRead(redisDb *db, robj *key) {
3141 expireIfNeeded(db,key);
3142 return lookupKey(db,key);
3143 }
3144
3145 static robj *lookupKeyWrite(redisDb *db, robj *key) {
3146 deleteIfVolatile(db,key);
3147 touchWatchedKey(db,key);
3148 return lookupKey(db,key);
3149 }
3150
3151 static robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
3152 robj *o = lookupKeyRead(c->db, key);
3153 if (!o) addReply(c,reply);
3154 return o;
3155 }
3156
3157 static robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
3158 robj *o = lookupKeyWrite(c->db, key);
3159 if (!o) addReply(c,reply);
3160 return o;
3161 }
3162
3163 static int checkType(redisClient *c, robj *o, int type) {
3164 if (o->type != type) {
3165 addReply(c,shared.wrongtypeerr);
3166 return 1;
3167 }
3168 return 0;
3169 }
3170
3171 static int deleteKey(redisDb *db, robj *key) {
3172 int retval;
3173
3174 /* We need to protect key from destruction: after the first dictDelete()
3175 * it may happen that 'key' is no longer valid if we don't increment
3176 * it's count. This may happen when we get the object reference directly
3177 * from the hash table with dictRandomKey() or dict iterators */
3178 incrRefCount(key);
3179 if (dictSize(db->expires)) dictDelete(db->expires,key);
3180 retval = dictDelete(db->dict,key);
3181 decrRefCount(key);
3182
3183 return retval == DICT_OK;
3184 }
3185
3186 /* Check if the nul-terminated string 's' can be represented by a long
3187 * (that is, is a number that fits into long without any other space or
3188 * character before or after the digits).
3189 *
3190 * If so, the function returns REDIS_OK and *longval is set to the value
3191 * of the number. Otherwise REDIS_ERR is returned */
3192 static int isStringRepresentableAsLong(sds s, long *longval) {
3193 char buf[32], *endptr;
3194 long value;
3195 int slen;
3196
3197 value = strtol(s, &endptr, 10);
3198 if (endptr[0] != '\0') return REDIS_ERR;
3199 slen = ll2string(buf,32,value);
3200
3201 /* If the number converted back into a string is not identical
3202 * then it's not possible to encode the string as integer */
3203 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
3204 if (longval) *longval = value;
3205 return REDIS_OK;
3206 }
3207
3208 /* Try to encode a string object in order to save space */
3209 static robj *tryObjectEncoding(robj *o) {
3210 long value;
3211 sds s = o->ptr;
3212
3213 if (o->encoding != REDIS_ENCODING_RAW)
3214 return o; /* Already encoded */
3215
3216 /* It's not safe to encode shared objects: shared objects can be shared
3217 * everywhere in the "object space" of Redis. Encoded objects can only
3218 * appear as "values" (and not, for instance, as keys) */
3219 if (o->refcount > 1) return o;
3220
3221 /* Currently we try to encode only strings */
3222 redisAssert(o->type == REDIS_STRING);
3223
3224 /* Check if we can represent this string as a long integer */
3225 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return o;
3226
3227 /* Ok, this object can be encoded */
3228 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3229 decrRefCount(o);
3230 incrRefCount(shared.integers[value]);
3231 return shared.integers[value];
3232 } else {
3233 o->encoding = REDIS_ENCODING_INT;
3234 sdsfree(o->ptr);
3235 o->ptr = (void*) value;
3236 return o;
3237 }
3238 }
3239
3240 /* Get a decoded version of an encoded object (returned as a new object).
3241 * If the object is already raw-encoded just increment the ref count. */
3242 static robj *getDecodedObject(robj *o) {
3243 robj *dec;
3244
3245 if (o->encoding == REDIS_ENCODING_RAW) {
3246 incrRefCount(o);
3247 return o;
3248 }
3249 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
3250 char buf[32];
3251
3252 ll2string(buf,32,(long)o->ptr);
3253 dec = createStringObject(buf,strlen(buf));
3254 return dec;
3255 } else {
3256 redisPanic("Unknown encoding type");
3257 }
3258 }
3259
3260 /* Compare two string objects via strcmp() or alike.
3261 * Note that the objects may be integer-encoded. In such a case we
3262 * use ll2string() to get a string representation of the numbers on the stack
3263 * and compare the strings, it's much faster than calling getDecodedObject().
3264 *
3265 * Important note: if objects are not integer encoded, but binary-safe strings,
3266 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3267 * binary safe. */
3268 static int compareStringObjects(robj *a, robj *b) {
3269 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
3270 char bufa[128], bufb[128], *astr, *bstr;
3271 int bothsds = 1;
3272
3273 if (a == b) return 0;
3274 if (a->encoding != REDIS_ENCODING_RAW) {
3275 ll2string(bufa,sizeof(bufa),(long) a->ptr);
3276 astr = bufa;
3277 bothsds = 0;
3278 } else {
3279 astr = a->ptr;
3280 }
3281 if (b->encoding != REDIS_ENCODING_RAW) {
3282 ll2string(bufb,sizeof(bufb),(long) b->ptr);
3283 bstr = bufb;
3284 bothsds = 0;
3285 } else {
3286 bstr = b->ptr;
3287 }
3288 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
3289 }
3290
3291 /* Equal string objects return 1 if the two objects are the same from the
3292 * point of view of a string comparison, otherwise 0 is returned. Note that
3293 * this function is faster then checking for (compareStringObject(a,b) == 0)
3294 * because it can perform some more optimization. */
3295 static int equalStringObjects(robj *a, robj *b) {
3296 if (a->encoding != REDIS_ENCODING_RAW && b->encoding != REDIS_ENCODING_RAW){
3297 return a->ptr == b->ptr;
3298 } else {
3299 return compareStringObjects(a,b) == 0;
3300 }
3301 }
3302
3303 static size_t stringObjectLen(robj *o) {
3304 redisAssert(o->type == REDIS_STRING);
3305 if (o->encoding == REDIS_ENCODING_RAW) {
3306 return sdslen(o->ptr);
3307 } else {
3308 char buf[32];
3309
3310 return ll2string(buf,32,(long)o->ptr);
3311 }
3312 }
3313
3314 static int getDoubleFromObject(robj *o, double *target) {
3315 double value;
3316 char *eptr;
3317
3318 if (o == NULL) {
3319 value = 0;
3320 } else {
3321 redisAssert(o->type == REDIS_STRING);
3322 if (o->encoding == REDIS_ENCODING_RAW) {
3323 value = strtod(o->ptr, &eptr);
3324 if (eptr[0] != '\0') return REDIS_ERR;
3325 } else if (o->encoding == REDIS_ENCODING_INT) {
3326 value = (long)o->ptr;
3327 } else {
3328 redisPanic("Unknown string encoding");
3329 }
3330 }
3331
3332 *target = value;
3333 return REDIS_OK;
3334 }
3335
3336 static int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg) {
3337 double value;
3338 if (getDoubleFromObject(o, &value) != REDIS_OK) {
3339 if (msg != NULL) {
3340 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3341 } else {
3342 addReplySds(c, sdsnew("-ERR value is not a double\r\n"));
3343 }
3344 return REDIS_ERR;
3345 }
3346
3347 *target = value;
3348 return REDIS_OK;
3349 }
3350
3351 static int getLongLongFromObject(robj *o, long long *target) {
3352 long long value;
3353 char *eptr;
3354
3355 if (o == NULL) {
3356 value = 0;
3357 } else {
3358 redisAssert(o->type == REDIS_STRING);
3359 if (o->encoding == REDIS_ENCODING_RAW) {
3360 value = strtoll(o->ptr, &eptr, 10);
3361 if (eptr[0] != '\0') return REDIS_ERR;
3362 } else if (o->encoding == REDIS_ENCODING_INT) {
3363 value = (long)o->ptr;
3364 } else {
3365 redisPanic("Unknown string encoding");
3366 }
3367 }
3368
3369 *target = value;
3370 return REDIS_OK;
3371 }
3372
3373 static int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg) {
3374 long long value;
3375 if (getLongLongFromObject(o, &value) != REDIS_OK) {
3376 if (msg != NULL) {
3377 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3378 } else {
3379 addReplySds(c, sdsnew("-ERR value is not an integer\r\n"));
3380 }
3381 return REDIS_ERR;
3382 }
3383
3384 *target = value;
3385 return REDIS_OK;
3386 }
3387
3388 static int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg) {
3389 long long value;
3390
3391 if (getLongLongFromObjectOrReply(c, o, &value, msg) != REDIS_OK) return REDIS_ERR;
3392 if (value < LONG_MIN || value > LONG_MAX) {
3393 if (msg != NULL) {
3394 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3395 } else {
3396 addReplySds(c, sdsnew("-ERR value is out of range\r\n"));
3397 }
3398 return REDIS_ERR;
3399 }
3400
3401 *target = value;
3402 return REDIS_OK;
3403 }
3404
3405 /*============================ RDB saving/loading =========================== */
3406
3407 static int rdbSaveType(FILE *fp, unsigned char type) {
3408 if (fwrite(&type,1,1,fp) == 0) return -1;
3409 return 0;
3410 }
3411
3412 static int rdbSaveTime(FILE *fp, time_t t) {
3413 int32_t t32 = (int32_t) t;
3414 if (fwrite(&t32,4,1,fp) == 0) return -1;
3415 return 0;
3416 }
3417
3418 /* check rdbLoadLen() comments for more info */
3419 static int rdbSaveLen(FILE *fp, uint32_t len) {
3420 unsigned char buf[2];
3421
3422 if (len < (1<<6)) {
3423 /* Save a 6 bit len */
3424 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
3425 if (fwrite(buf,1,1,fp) == 0) return -1;
3426 } else if (len < (1<<14)) {
3427 /* Save a 14 bit len */
3428 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
3429 buf[1] = len&0xFF;
3430 if (fwrite(buf,2,1,fp) == 0) return -1;
3431 } else {
3432 /* Save a 32 bit len */
3433 buf[0] = (REDIS_RDB_32BITLEN<<6);
3434 if (fwrite(buf,1,1,fp) == 0) return -1;
3435 len = htonl(len);
3436 if (fwrite(&len,4,1,fp) == 0) return -1;
3437 }
3438 return 0;
3439 }
3440
3441 /* Encode 'value' as an integer if possible (if integer will fit the
3442 * supported range). If the function sucessful encoded the integer
3443 * then the (up to 5 bytes) encoded representation is written in the
3444 * string pointed by 'enc' and the length is returned. Otherwise
3445 * 0 is returned. */
3446 static int rdbEncodeInteger(long long value, unsigned char *enc) {
3447 /* Finally check if it fits in our ranges */
3448 if (value >= -(1<<7) && value <= (1<<7)-1) {
3449 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
3450 enc[1] = value&0xFF;
3451 return 2;
3452 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
3453 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
3454 enc[1] = value&0xFF;
3455 enc[2] = (value>>8)&0xFF;
3456 return 3;
3457 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
3458 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
3459 enc[1] = value&0xFF;
3460 enc[2] = (value>>8)&0xFF;
3461 enc[3] = (value>>16)&0xFF;
3462 enc[4] = (value>>24)&0xFF;
3463 return 5;
3464 } else {
3465 return 0;
3466 }
3467 }
3468
3469 /* String objects in the form "2391" "-100" without any space and with a
3470 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3471 * encoded as integers to save space */
3472 static int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
3473 long long value;
3474 char *endptr, buf[32];
3475
3476 /* Check if it's possible to encode this value as a number */
3477 value = strtoll(s, &endptr, 10);
3478 if (endptr[0] != '\0') return 0;
3479 ll2string(buf,32,value);
3480
3481 /* If the number converted back into a string is not identical
3482 * then it's not possible to encode the string as integer */
3483 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
3484
3485 return rdbEncodeInteger(value,enc);
3486 }
3487
3488 static int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
3489 size_t comprlen, outlen;
3490 unsigned char byte;
3491 void *out;
3492
3493 /* We require at least four bytes compression for this to be worth it */
3494 if (len <= 4) return 0;
3495 outlen = len-4;
3496 if ((out = zmalloc(outlen+1)) == NULL) return 0;
3497 comprlen = lzf_compress(s, len, out, outlen);
3498 if (comprlen == 0) {
3499 zfree(out);
3500 return 0;
3501 }
3502 /* Data compressed! Let's save it on disk */
3503 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
3504 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
3505 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
3506 if (rdbSaveLen(fp,len) == -1) goto writeerr;
3507 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
3508 zfree(out);
3509 return comprlen;
3510
3511 writeerr:
3512 zfree(out);
3513 return -1;
3514 }
3515
3516 /* Save a string objet as [len][data] on disk. If the object is a string
3517 * representation of an integer value we try to safe it in a special form */
3518 static int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
3519 int enclen;
3520
3521 /* Try integer encoding */
3522 if (len <= 11) {
3523 unsigned char buf[5];
3524 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
3525 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3526 return 0;
3527 }
3528 }
3529
3530 /* Try LZF compression - under 20 bytes it's unable to compress even
3531 * aaaaaaaaaaaaaaaaaa so skip it */
3532 if (server.rdbcompression && len > 20) {
3533 int retval;
3534
3535 retval = rdbSaveLzfStringObject(fp,s,len);
3536 if (retval == -1) return -1;
3537 if (retval > 0) return 0;
3538 /* retval == 0 means data can't be compressed, save the old way */
3539 }
3540
3541 /* Store verbatim */
3542 if (rdbSaveLen(fp,len) == -1) return -1;
3543 if (len && fwrite(s,len,1,fp) == 0) return -1;
3544 return 0;
3545 }
3546
3547 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3548 static int rdbSaveStringObject(FILE *fp, robj *obj) {
3549 int retval;
3550
3551 /* Avoid to decode the object, then encode it again, if the
3552 * object is alrady integer encoded. */
3553 if (obj->encoding == REDIS_ENCODING_INT) {
3554 long val = (long) obj->ptr;
3555 unsigned char buf[5];
3556 int enclen;
3557
3558 if ((enclen = rdbEncodeInteger(val,buf)) > 0) {
3559 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3560 return 0;
3561 }
3562 /* otherwise... fall throught and continue with the usual
3563 * code path. */
3564 }
3565
3566 /* Avoid incr/decr ref count business when possible.
3567 * This plays well with copy-on-write given that we are probably
3568 * in a child process (BGSAVE). Also this makes sure key objects
3569 * of swapped objects are not incRefCount-ed (an assert does not allow
3570 * this in order to avoid bugs) */
3571 if (obj->encoding != REDIS_ENCODING_RAW) {
3572 obj = getDecodedObject(obj);
3573 retval = rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
3574 decrRefCount(obj);
3575 } else {
3576 retval = rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
3577 }
3578 return retval;
3579 }
3580
3581 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3582 * 8 bit integer specifing the length of the representation.
3583 * This 8 bit integer has special values in order to specify the following
3584 * conditions:
3585 * 253: not a number
3586 * 254: + inf
3587 * 255: - inf
3588 */
3589 static int rdbSaveDoubleValue(FILE *fp, double val) {
3590 unsigned char buf[128];
3591 int len;
3592
3593 if (isnan(val)) {
3594 buf[0] = 253;
3595 len = 1;
3596 } else if (!isfinite(val)) {
3597 len = 1;
3598 buf[0] = (val < 0) ? 255 : 254;
3599 } else {
3600 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
3601 /* Check if the float is in a safe range to be casted into a
3602 * long long. We are assuming that long long is 64 bit here.
3603 * Also we are assuming that there are no implementations around where
3604 * double has precision < 52 bit.
3605 *
3606 * Under this assumptions we test if a double is inside an interval
3607 * where casting to long long is safe. Then using two castings we
3608 * make sure the decimal part is zero. If all this is true we use
3609 * integer printing function that is much faster. */
3610 double min = -4503599627370495; /* (2^52)-1 */
3611 double max = 4503599627370496; /* -(2^52) */
3612 if (val > min && val < max && val == ((double)((long long)val)))
3613 ll2string((char*)buf+1,sizeof(buf),(long long)val);
3614 else
3615 #endif
3616 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
3617 buf[0] = strlen((char*)buf+1);
3618 len = buf[0]+1;
3619 }
3620 if (fwrite(buf,len,1,fp) == 0) return -1;
3621 return 0;
3622 }
3623
3624 /* Save a Redis object. */
3625 static int rdbSaveObject(FILE *fp, robj *o) {
3626 if (o->type == REDIS_STRING) {
3627 /* Save a string value */
3628 if (rdbSaveStringObject(fp,o) == -1) return -1;
3629 } else if (o->type == REDIS_LIST) {
3630 /* Save a list value */
3631 list *list = o->ptr;
3632 listIter li;
3633 listNode *ln;
3634
3635 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
3636 listRewind(list,&li);
3637 while((ln = listNext(&li))) {
3638 robj *eleobj = listNodeValue(ln);
3639
3640 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3641 }
3642 } else if (o->type == REDIS_SET) {
3643 /* Save a set value */
3644 dict *set = o->ptr;
3645 dictIterator *di = dictGetIterator(set);
3646 dictEntry *de;
3647
3648 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
3649 while((de = dictNext(di)) != NULL) {
3650 robj *eleobj = dictGetEntryKey(de);
3651
3652 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3653 }
3654 dictReleaseIterator(di);
3655 } else if (o->type == REDIS_ZSET) {
3656 /* Save a set value */
3657 zset *zs = o->ptr;
3658 dictIterator *di = dictGetIterator(zs->dict);
3659 dictEntry *de;
3660
3661 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
3662 while((de = dictNext(di)) != NULL) {
3663 robj *eleobj = dictGetEntryKey(de);
3664 double *score = dictGetEntryVal(de);
3665
3666 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3667 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
3668 }
3669 dictReleaseIterator(di);
3670 } else if (o->type == REDIS_HASH) {
3671 /* Save a hash value */
3672 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3673 unsigned char *p = zipmapRewind(o->ptr);
3674 unsigned int count = zipmapLen(o->ptr);
3675 unsigned char *key, *val;
3676 unsigned int klen, vlen;
3677
3678 if (rdbSaveLen(fp,count) == -1) return -1;
3679 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
3680 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
3681 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
3682 }
3683 } else {
3684 dictIterator *di = dictGetIterator(o->ptr);
3685 dictEntry *de;
3686
3687 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
3688 while((de = dictNext(di)) != NULL) {
3689 robj *key = dictGetEntryKey(de);
3690 robj *val = dictGetEntryVal(de);
3691
3692 if (rdbSaveStringObject(fp,key) == -1) return -1;
3693 if (rdbSaveStringObject(fp,val) == -1) return -1;
3694 }
3695 dictReleaseIterator(di);
3696 }
3697 } else {
3698 redisPanic("Unknown object type");
3699 }
3700 return 0;
3701 }
3702
3703 /* Return the length the object will have on disk if saved with
3704 * the rdbSaveObject() function. Currently we use a trick to get
3705 * this length with very little changes to the code. In the future
3706 * we could switch to a faster solution. */
3707 static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
3708 if (fp == NULL) fp = server.devnull;
3709 rewind(fp);
3710 assert(rdbSaveObject(fp,o) != 1);
3711 return ftello(fp);
3712 }
3713
3714 /* Return the number of pages required to save this object in the swap file */
3715 static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
3716 off_t bytes = rdbSavedObjectLen(o,fp);
3717
3718 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
3719 }
3720
3721 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3722 static int rdbSave(char *filename) {
3723 dictIterator *di = NULL;
3724 dictEntry *de;
3725 FILE *fp;
3726 char tmpfile[256];
3727 int j;
3728 time_t now = time(NULL);
3729
3730 /* Wait for I/O therads to terminate, just in case this is a
3731 * foreground-saving, to avoid seeking the swap file descriptor at the
3732 * same time. */
3733 if (server.vm_enabled)
3734 waitEmptyIOJobsQueue();
3735
3736 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
3737 fp = fopen(tmpfile,"w");
3738 if (!fp) {
3739 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
3740 return REDIS_ERR;
3741 }
3742 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
3743 for (j = 0; j < server.dbnum; j++) {
3744 redisDb *db = server.db+j;
3745 dict *d = db->dict;
3746 if (dictSize(d) == 0) continue;
3747 di = dictGetIterator(d);
3748 if (!di) {
3749 fclose(fp);
3750 return REDIS_ERR;
3751 }
3752
3753 /* Write the SELECT DB opcode */
3754 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
3755 if (rdbSaveLen(fp,j) == -1) goto werr;
3756
3757 /* Iterate this DB writing every entry */
3758 while((de = dictNext(di)) != NULL) {
3759 robj *key = dictGetEntryKey(de);
3760 robj *o = dictGetEntryVal(de);
3761 time_t expiretime = getExpire(db,key);
3762
3763 /* Save the expire time */
3764 if (expiretime != -1) {
3765 /* If this key is already expired skip it */
3766 if (expiretime < now) continue;
3767 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
3768 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
3769 }
3770 /* Save the key and associated value. This requires special
3771 * handling if the value is swapped out. */
3772 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
3773 key->storage == REDIS_VM_SWAPPING) {
3774 /* Save type, key, value */
3775 if (rdbSaveType(fp,o->type) == -1) goto werr;
3776 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3777 if (rdbSaveObject(fp,o) == -1) goto werr;
3778 } else {
3779 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3780 robj *po;
3781 /* Get a preview of the object in memory */
3782 po = vmPreviewObject(key);
3783 /* Save type, key, value */
3784 if (rdbSaveType(fp,key->vtype) == -1) goto werr;
3785 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3786 if (rdbSaveObject(fp,po) == -1) goto werr;
3787 /* Remove the loaded object from memory */
3788 decrRefCount(po);
3789 }
3790 }
3791 dictReleaseIterator(di);
3792 }
3793 /* EOF opcode */
3794 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
3795
3796 /* Make sure data will not remain on the OS's output buffers */
3797 fflush(fp);
3798 fsync(fileno(fp));
3799 fclose(fp);
3800
3801 /* Use RENAME to make sure the DB file is changed atomically only
3802 * if the generate DB file is ok. */
3803 if (rename(tmpfile,filename) == -1) {
3804 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
3805 unlink(tmpfile);
3806 return REDIS_ERR;
3807 }
3808 redisLog(REDIS_NOTICE,"DB saved on disk");
3809 server.dirty = 0;
3810 server.lastsave = time(NULL);
3811 return REDIS_OK;
3812
3813 werr:
3814 fclose(fp);
3815 unlink(tmpfile);
3816 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
3817 if (di) dictReleaseIterator(di);
3818 return REDIS_ERR;
3819 }
3820
3821 static int rdbSaveBackground(char *filename) {
3822 pid_t childpid;
3823
3824 if (server.bgsavechildpid != -1) return REDIS_ERR;
3825 if (server.vm_enabled) waitEmptyIOJobsQueue();
3826 if ((childpid = fork()) == 0) {
3827 /* Child */
3828 if (server.vm_enabled) vmReopenSwapFile();
3829 close(server.fd);
3830 if (rdbSave(filename) == REDIS_OK) {
3831 _exit(0);
3832 } else {
3833 _exit(1);
3834 }
3835 } else {
3836 /* Parent */
3837 if (childpid == -1) {
3838 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
3839 strerror(errno));
3840 return REDIS_ERR;
3841 }
3842 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
3843 server.bgsavechildpid = childpid;
3844 updateDictResizePolicy();
3845 return REDIS_OK;
3846 }
3847 return REDIS_OK; /* unreached */
3848 }
3849
3850 static void rdbRemoveTempFile(pid_t childpid) {
3851 char tmpfile[256];
3852
3853 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
3854 unlink(tmpfile);
3855 }
3856
3857 static int rdbLoadType(FILE *fp) {
3858 unsigned char type;
3859 if (fread(&type,1,1,fp) == 0) return -1;
3860 return type;
3861 }
3862
3863 static time_t rdbLoadTime(FILE *fp) {
3864 int32_t t32;
3865 if (fread(&t32,4,1,fp) == 0) return -1;
3866 return (time_t) t32;
3867 }
3868
3869 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3870 * of this file for a description of how this are stored on disk.
3871 *
3872 * isencoded is set to 1 if the readed length is not actually a length but
3873 * an "encoding type", check the above comments for more info */
3874 static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
3875 unsigned char buf[2];
3876 uint32_t len;
3877 int type;
3878
3879 if (isencoded) *isencoded = 0;
3880 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
3881 type = (buf[0]&0xC0)>>6;
3882 if (type == REDIS_RDB_6BITLEN) {
3883 /* Read a 6 bit len */
3884 return buf[0]&0x3F;
3885 } else if (type == REDIS_RDB_ENCVAL) {
3886 /* Read a 6 bit len encoding type */
3887 if (isencoded) *isencoded = 1;
3888 return buf[0]&0x3F;
3889 } else if (type == REDIS_RDB_14BITLEN) {
3890 /* Read a 14 bit len */
3891 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
3892 return ((buf[0]&0x3F)<<8)|buf[1];
3893 } else {
3894 /* Read a 32 bit len */
3895 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
3896 return ntohl(len);
3897 }
3898 }
3899
3900 /* Load an integer-encoded object from file 'fp', with the specified
3901 * encoding type 'enctype'. If encode is true the function may return
3902 * an integer-encoded object as reply, otherwise the returned object
3903 * will always be encoded as a raw string. */
3904 static robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
3905 unsigned char enc[4];
3906 long long val;
3907
3908 if (enctype == REDIS_RDB_ENC_INT8) {
3909 if (fread(enc,1,1,fp) == 0) return NULL;
3910 val = (signed char)enc[0];
3911 } else if (enctype == REDIS_RDB_ENC_INT16) {
3912 uint16_t v;
3913 if (fread(enc,2,1,fp) == 0) return NULL;
3914 v = enc[0]|(enc[1]<<8);
3915 val = (int16_t)v;
3916 } else if (enctype == REDIS_RDB_ENC_INT32) {
3917 uint32_t v;
3918 if (fread(enc,4,1,fp) == 0) return NULL;
3919 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
3920 val = (int32_t)v;
3921 } else {
3922 val = 0; /* anti-warning */
3923 redisPanic("Unknown RDB integer encoding type");
3924 }
3925 if (encode)
3926 return createStringObjectFromLongLong(val);
3927 else
3928 return createObject(REDIS_STRING,sdsfromlonglong(val));
3929 }
3930
3931 static robj *rdbLoadLzfStringObject(FILE*fp) {
3932 unsigned int len, clen;
3933 unsigned char *c = NULL;
3934 sds val = NULL;
3935
3936 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3937 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3938 if ((c = zmalloc(clen)) == NULL) goto err;
3939 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
3940 if (fread(c,clen,1,fp) == 0) goto err;
3941 if (lzf_decompress(c,clen,val,len) == 0) goto err;
3942 zfree(c);
3943 return createObject(REDIS_STRING,val);
3944 err:
3945 zfree(c);
3946 sdsfree(val);
3947 return NULL;
3948 }
3949
3950 static robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
3951 int isencoded;
3952 uint32_t len;
3953 sds val;
3954
3955 len = rdbLoadLen(fp,&isencoded);
3956 if (isencoded) {
3957 switch(len) {
3958 case REDIS_RDB_ENC_INT8:
3959 case REDIS_RDB_ENC_INT16:
3960 case REDIS_RDB_ENC_INT32:
3961 return rdbLoadIntegerObject(fp,len,encode);
3962 case REDIS_RDB_ENC_LZF:
3963 return rdbLoadLzfStringObject(fp);
3964 default:
3965 redisPanic("Unknown RDB encoding type");
3966 }
3967 }
3968
3969 if (len == REDIS_RDB_LENERR) return NULL;
3970 val = sdsnewlen(NULL,len);
3971 if (len && fread(val,len,1,fp) == 0) {
3972 sdsfree(val);
3973 return NULL;
3974 }
3975 return createObject(REDIS_STRING,val);
3976 }
3977
3978 static robj *rdbLoadStringObject(FILE *fp) {
3979 return rdbGenericLoadStringObject(fp,0);
3980 }
3981
3982 static robj *rdbLoadEncodedStringObject(FILE *fp) {
3983 return rdbGenericLoadStringObject(fp,1);
3984 }
3985
3986 /* For information about double serialization check rdbSaveDoubleValue() */
3987 static int rdbLoadDoubleValue(FILE *fp, double *val) {
3988 char buf[128];
3989 unsigned char len;
3990
3991 if (fread(&len,1,1,fp) == 0) return -1;
3992 switch(len) {
3993 case 255: *val = R_NegInf; return 0;
3994 case 254: *val = R_PosInf; return 0;
3995 case 253: *val = R_Nan; return 0;
3996 default:
3997 if (fread(buf,len,1,fp) == 0) return -1;
3998 buf[len] = '\0';
3999 sscanf(buf, "%lg", val);
4000 return 0;
4001 }
4002 }
4003
4004 /* Load a Redis object of the specified type from the specified file.
4005 * On success a newly allocated object is returned, otherwise NULL. */
4006 static robj *rdbLoadObject(int type, FILE *fp) {
4007 robj *o;
4008
4009 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
4010 if (type == REDIS_STRING) {
4011 /* Read string value */
4012 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4013 o = tryObjectEncoding(o);
4014 } else if (type == REDIS_LIST || type == REDIS_SET) {
4015 /* Read list/set value */
4016 uint32_t listlen;
4017
4018 if ((listlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4019 o = (type == REDIS_LIST) ? createListObject() : createSetObject();
4020 /* It's faster to expand the dict to the right size asap in order
4021 * to avoid rehashing */
4022 if (type == REDIS_SET && listlen > DICT_HT_INITIAL_SIZE)
4023 dictExpand(o->ptr,listlen);
4024 /* Load every single element of the list/set */
4025 while(listlen--) {
4026 robj *ele;
4027
4028 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4029 ele = tryObjectEncoding(ele);
4030 if (type == REDIS_LIST) {
4031 listAddNodeTail((list*)o->ptr,ele);
4032 } else {
4033 dictAdd((dict*)o->ptr,ele,NULL);
4034 }
4035 }
4036 } else if (type == REDIS_ZSET) {
4037 /* Read list/set value */
4038 size_t zsetlen;
4039 zset *zs;
4040
4041 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4042 o = createZsetObject();
4043 zs = o->ptr;
4044 /* Load every single element of the list/set */
4045 while(zsetlen--) {
4046 robj *ele;
4047 double *score = zmalloc(sizeof(double));
4048
4049 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4050 ele = tryObjectEncoding(ele);
4051 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
4052 dictAdd(zs->dict,ele,score);
4053 zslInsert(zs->zsl,*score,ele);
4054 incrRefCount(ele); /* added to skiplist */
4055 }
4056 } else if (type == REDIS_HASH) {
4057 size_t hashlen;
4058
4059 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4060 o = createHashObject();
4061 /* Too many entries? Use an hash table. */
4062 if (hashlen > server.hash_max_zipmap_entries)
4063 convertToRealHash(o);
4064 /* Load every key/value, then set it into the zipmap or hash
4065 * table, as needed. */
4066 while(hashlen--) {
4067 robj *key, *val;
4068
4069 if ((key = rdbLoadStringObject(fp)) == NULL) return NULL;
4070 if ((val = rdbLoadStringObject(fp)) == NULL) return NULL;
4071 /* If we are using a zipmap and there are too big values
4072 * the object is converted to real hash table encoding. */
4073 if (o->encoding != REDIS_ENCODING_HT &&
4074 (sdslen(key->ptr) > server.hash_max_zipmap_value ||
4075 sdslen(val->ptr) > server.hash_max_zipmap_value))
4076 {
4077 convertToRealHash(o);
4078 }
4079
4080 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
4081 unsigned char *zm = o->ptr;
4082
4083 zm = zipmapSet(zm,key->ptr,sdslen(key->ptr),
4084 val->ptr,sdslen(val->ptr),NULL);
4085 o->ptr = zm;
4086 decrRefCount(key);
4087 decrRefCount(val);
4088 } else {
4089 key = tryObjectEncoding(key);
4090 val = tryObjectEncoding(val);
4091 dictAdd((dict*)o->ptr,key,val);
4092 }
4093 }
4094 } else {
4095 redisPanic("Unknown object type");
4096 }
4097 return o;
4098 }
4099
4100 static int rdbLoad(char *filename) {
4101 FILE *fp;
4102 uint32_t dbid;
4103 int type, retval, rdbver;
4104 int swap_all_values = 0;
4105 dict *d = server.db[0].dict;
4106 redisDb *db = server.db+0;
4107 char buf[1024];
4108 time_t expiretime, now = time(NULL);
4109 long long loadedkeys = 0;
4110
4111 fp = fopen(filename,"r");
4112 if (!fp) return REDIS_ERR;
4113 if (fread(buf,9,1,fp) == 0) goto eoferr;
4114 buf[9] = '\0';
4115 if (memcmp(buf,"REDIS",5) != 0) {
4116 fclose(fp);
4117 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
4118 return REDIS_ERR;
4119 }
4120 rdbver = atoi(buf+5);
4121 if (rdbver != 1) {
4122 fclose(fp);
4123 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
4124 return REDIS_ERR;
4125 }
4126 while(1) {
4127 robj *key, *val;
4128
4129 expiretime = -1;
4130 /* Read type. */
4131 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4132 if (type == REDIS_EXPIRETIME) {
4133 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
4134 /* We read the time so we need to read the object type again */
4135 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4136 }
4137 if (type == REDIS_EOF) break;
4138 /* Handle SELECT DB opcode as a special case */
4139 if (type == REDIS_SELECTDB) {
4140 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
4141 goto eoferr;
4142 if (dbid >= (unsigned)server.dbnum) {
4143 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
4144 exit(1);
4145 }
4146 db = server.db+dbid;
4147 d = db->dict;
4148 continue;
4149 }
4150 /* Read key */
4151 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
4152 /* Read value */
4153 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
4154 /* Check if the key already expired */
4155 if (expiretime != -1 && expiretime < now) {
4156 decrRefCount(key);
4157 decrRefCount(val);
4158 continue;
4159 }
4160 /* Add the new object in the hash table */
4161 retval = dictAdd(d,key,val);
4162 if (retval == DICT_ERR) {
4163 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
4164 exit(1);
4165 }
4166 loadedkeys++;
4167 /* Set the expire time if needed */
4168 if (expiretime != -1) setExpire(db,key,expiretime);
4169
4170 /* Handle swapping while loading big datasets when VM is on */
4171
4172 /* If we detecter we are hopeless about fitting something in memory
4173 * we just swap every new key on disk. Directly...
4174 * Note that's important to check for this condition before resorting
4175 * to random sampling, otherwise we may try to swap already
4176 * swapped keys. */
4177 if (swap_all_values) {
4178 dictEntry *de = dictFind(d,key);
4179
4180 /* de may be NULL since the key already expired */
4181 if (de) {
4182 key = dictGetEntryKey(de);
4183 val = dictGetEntryVal(de);
4184
4185 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
4186 dictGetEntryVal(de) = NULL;
4187 }
4188 }
4189 continue;
4190 }
4191
4192 /* If we have still some hope of having some value fitting memory
4193 * then we try random sampling. */
4194 if (!swap_all_values && server.vm_enabled && (loadedkeys % 5000) == 0) {
4195 while (zmalloc_used_memory() > server.vm_max_memory) {
4196 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
4197 }
4198 if (zmalloc_used_memory() > server.vm_max_memory)
4199 swap_all_values = 1; /* We are already using too much mem */
4200 }
4201 }
4202 fclose(fp);
4203 return REDIS_OK;
4204
4205 eoferr: /* unexpected end of file is handled here with a fatal exit */
4206 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
4207 exit(1);
4208 return REDIS_ERR; /* Just to avoid warning */
4209 }
4210
4211 /*================================== Shutdown =============================== */
4212 static int prepareForShutdown() {
4213 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
4214 /* Kill the saving child if there is a background saving in progress.
4215 We want to avoid race conditions, for instance our saving child may
4216 overwrite the synchronous saving did by SHUTDOWN. */
4217 if (server.bgsavechildpid != -1) {
4218 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
4219 kill(server.bgsavechildpid,SIGKILL);
4220 rdbRemoveTempFile(server.bgsavechildpid);
4221 }
4222 if (server.appendonly) {
4223 /* Append only file: fsync() the AOF and exit */
4224 fsync(server.appendfd);
4225 if (server.vm_enabled) unlink(server.vm_swap_file);
4226 } else {
4227 /* Snapshotting. Perform a SYNC SAVE and exit */
4228 if (rdbSave(server.dbfilename) == REDIS_OK) {
4229 if (server.daemonize)
4230 unlink(server.pidfile);
4231 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
4232 } else {
4233 /* Ooops.. error saving! The best we can do is to continue
4234 * operating. Note that if there was a background saving process,
4235 * in the next cron() Redis will be notified that the background
4236 * saving aborted, handling special stuff like slaves pending for
4237 * synchronization... */
4238 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
4239 return REDIS_ERR;
4240 }
4241 }
4242 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
4243 return REDIS_OK;
4244 }
4245
4246 /*================================== Commands =============================== */
4247
4248 static void authCommand(redisClient *c) {
4249 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
4250 c->authenticated = 1;
4251 addReply(c,shared.ok);
4252 } else {
4253 c->authenticated = 0;
4254 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
4255 }
4256 }
4257
4258 static void pingCommand(redisClient *c) {
4259 addReply(c,shared.pong);
4260 }
4261
4262 static void echoCommand(redisClient *c) {
4263 addReplyBulk(c,c->argv[1]);
4264 }
4265
4266 /*=================================== Strings =============================== */
4267
4268 static void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
4269 int retval;
4270 long seconds = 0; /* initialized to avoid an harmness warning */
4271
4272 if (expire) {
4273 if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
4274 return;
4275 if (seconds <= 0) {
4276 addReplySds(c,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4277 return;
4278 }
4279 }
4280
4281 touchWatchedKey(c->db,key);
4282 if (nx) deleteIfVolatile(c->db,key);
4283 retval = dictAdd(c->db->dict,key,val);
4284 if (retval == DICT_ERR) {
4285 if (!nx) {
4286 /* If the key is about a swapped value, we want a new key object
4287 * to overwrite the old. So we delete the old key in the database.
4288 * This will also make sure that swap pages about the old object
4289 * will be marked as free. */
4290 if (server.vm_enabled && deleteIfSwapped(c->db,key))
4291 incrRefCount(key);
4292 dictReplace(c->db->dict,key,val);
4293 incrRefCount(val);
4294 } else {
4295 addReply(c,shared.czero);
4296 return;
4297 }
4298 } else {
4299 incrRefCount(key);
4300 incrRefCount(val);
4301 }
4302 server.dirty++;
4303 removeExpire(c->db,key);
4304 if (expire) setExpire(c->db,key,time(NULL)+seconds);
4305 addReply(c, nx ? shared.cone : shared.ok);
4306 }
4307
4308 static void setCommand(redisClient *c) {
4309 setGenericCommand(c,0,c->argv[1],c->argv[2],NULL);
4310 }
4311
4312 static void setnxCommand(redisClient *c) {
4313 setGenericCommand(c,1,c->argv[1],c->argv[2],NULL);
4314 }
4315
4316 static void setexCommand(redisClient *c) {
4317 setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
4318 }
4319
4320 static int getGenericCommand(redisClient *c) {
4321 robj *o;
4322
4323 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
4324 return REDIS_OK;
4325
4326 if (o->type != REDIS_STRING) {
4327 addReply(c,shared.wrongtypeerr);
4328 return REDIS_ERR;
4329 } else {
4330 addReplyBulk(c,o);
4331 return REDIS_OK;
4332 }
4333 }
4334
4335 static void getCommand(redisClient *c) {
4336 getGenericCommand(c);
4337 }
4338
4339 static void getsetCommand(redisClient *c) {
4340 if (getGenericCommand(c) == REDIS_ERR) return;
4341 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
4342 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
4343 } else {
4344 incrRefCount(c->argv[1]);
4345 }
4346 incrRefCount(c->argv[2]);
4347 server.dirty++;
4348 removeExpire(c->db,c->argv[1]);
4349 }
4350
4351 static void mgetCommand(redisClient *c) {
4352 int j;
4353
4354 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
4355 for (j = 1; j < c->argc; j++) {
4356 robj *o = lookupKeyRead(c->db,c->argv[j]);
4357 if (o == NULL) {
4358 addReply(c,shared.nullbulk);
4359 } else {
4360 if (o->type != REDIS_STRING) {
4361 addReply(c,shared.nullbulk);
4362 } else {
4363 addReplyBulk(c,o);
4364 }
4365 }
4366 }
4367 }
4368
4369 static void msetGenericCommand(redisClient *c, int nx) {
4370 int j, busykeys = 0;
4371
4372 if ((c->argc % 2) == 0) {
4373 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
4374 return;
4375 }
4376 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4377 * set nothing at all if at least one already key exists. */
4378 if (nx) {
4379 for (j = 1; j < c->argc; j += 2) {
4380 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
4381 busykeys++;
4382 }
4383 }
4384 }
4385 if (busykeys) {
4386 addReply(c, shared.czero);
4387 return;
4388 }
4389
4390 for (j = 1; j < c->argc; j += 2) {
4391 int retval;
4392
4393 c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
4394 retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
4395 if (retval == DICT_ERR) {
4396 dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
4397 incrRefCount(c->argv[j+1]);
4398 } else {
4399 incrRefCount(c->argv[j]);
4400 incrRefCount(c->argv[j+1]);
4401 }
4402 removeExpire(c->db,c->argv[j]);
4403 }
4404 server.dirty += (c->argc-1)/2;
4405 addReply(c, nx ? shared.cone : shared.ok);
4406 }
4407
4408 static void msetCommand(redisClient *c) {
4409 msetGenericCommand(c,0);
4410 }
4411
4412 static void msetnxCommand(redisClient *c) {
4413 msetGenericCommand(c,1);
4414 }
4415
4416 static void incrDecrCommand(redisClient *c, long long incr) {
4417 long long value;
4418 int retval;
4419 robj *o;
4420
4421 o = lookupKeyWrite(c->db,c->argv[1]);
4422 if (o != NULL && checkType(c,o,REDIS_STRING)) return;
4423 if (getLongLongFromObjectOrReply(c,o,&value,NULL) != REDIS_OK) return;
4424
4425 value += incr;
4426 o = createStringObjectFromLongLong(value);
4427 retval = dictAdd(c->db->dict,c->argv[1],o);
4428 if (retval == DICT_ERR) {
4429 dictReplace(c->db->dict,c->argv[1],o);
4430 removeExpire(c->db,c->argv[1]);
4431 } else {
4432 incrRefCount(c->argv[1]);
4433 }
4434 server.dirty++;
4435 addReply(c,shared.colon);
4436 addReply(c,o);
4437 addReply(c,shared.crlf);
4438 }
4439
4440 static void incrCommand(redisClient *c) {
4441 incrDecrCommand(c,1);
4442 }
4443
4444 static void decrCommand(redisClient *c) {
4445 incrDecrCommand(c,-1);
4446 }
4447
4448 static void incrbyCommand(redisClient *c) {
4449 long long incr;
4450
4451 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
4452 incrDecrCommand(c,incr);
4453 }
4454
4455 static void decrbyCommand(redisClient *c) {
4456 long long incr;
4457
4458 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
4459 incrDecrCommand(c,-incr);
4460 }
4461
4462 static void appendCommand(redisClient *c) {
4463 int retval;
4464 size_t totlen;
4465 robj *o;
4466
4467 o = lookupKeyWrite(c->db,c->argv[1]);
4468 if (o == NULL) {
4469 /* Create the key */
4470 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
4471 incrRefCount(c->argv[1]);
4472 incrRefCount(c->argv[2]);
4473 totlen = stringObjectLen(c->argv[2]);
4474 } else {
4475 dictEntry *de;
4476
4477 de = dictFind(c->db->dict,c->argv[1]);
4478 assert(de != NULL);
4479
4480 o = dictGetEntryVal(de);
4481 if (o->type != REDIS_STRING) {
4482 addReply(c,shared.wrongtypeerr);
4483 return;
4484 }
4485 /* If the object is specially encoded or shared we have to make
4486 * a copy */
4487 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
4488 robj *decoded = getDecodedObject(o);
4489
4490 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
4491 decrRefCount(decoded);
4492 dictReplace(c->db->dict,c->argv[1],o);
4493 }
4494 /* APPEND! */
4495 if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
4496 o->ptr = sdscatlen(o->ptr,
4497 c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
4498 } else {
4499 o->ptr = sdscatprintf(o->ptr, "%ld",
4500 (unsigned long) c->argv[2]->ptr);
4501 }
4502 totlen = sdslen(o->ptr);
4503 }
4504 server.dirty++;
4505 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
4506 }
4507
4508 static void substrCommand(redisClient *c) {
4509 robj *o;
4510 long start = atoi(c->argv[2]->ptr);
4511 long end = atoi(c->argv[3]->ptr);
4512 size_t rangelen, strlen;
4513 sds range;
4514
4515 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4516 checkType(c,o,REDIS_STRING)) return;
4517
4518 o = getDecodedObject(o);
4519 strlen = sdslen(o->ptr);
4520
4521 /* convert negative indexes */
4522 if (start < 0) start = strlen+start;
4523 if (end < 0) end = strlen+end;
4524 if (start < 0) start = 0;
4525 if (end < 0) end = 0;
4526
4527 /* indexes sanity checks */
4528 if (start > end || (size_t)start >= strlen) {
4529 /* Out of range start or start > end result in null reply */
4530 addReply(c,shared.nullbulk);
4531 decrRefCount(o);
4532 return;
4533 }
4534 if ((size_t)end >= strlen) end = strlen-1;
4535 rangelen = (end-start)+1;
4536
4537 /* Return the result */
4538 addReplySds(c,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen));
4539 range = sdsnewlen((char*)o->ptr+start,rangelen);
4540 addReplySds(c,range);
4541 addReply(c,shared.crlf);
4542 decrRefCount(o);
4543 }
4544
4545 /* ========================= Type agnostic commands ========================= */
4546
4547 static void delCommand(redisClient *c) {
4548 int deleted = 0, j;
4549
4550 for (j = 1; j < c->argc; j++) {
4551 if (deleteKey(c->db,c->argv[j])) {
4552 touchWatchedKey(c->db,c->argv[j]);
4553 server.dirty++;
4554 deleted++;
4555 }
4556 }
4557 addReplyLongLong(c,deleted);
4558 }
4559
4560 static void existsCommand(redisClient *c) {
4561 expireIfNeeded(c->db,c->argv[1]);
4562 if (dictFind(c->db->dict,c->argv[1])) {
4563 addReply(c, shared.cone);
4564 } else {
4565 addReply(c, shared.czero);
4566 }
4567 }
4568
4569 static void selectCommand(redisClient *c) {
4570 int id = atoi(c->argv[1]->ptr);
4571
4572 if (selectDb(c,id) == REDIS_ERR) {
4573 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
4574 } else {
4575 addReply(c,shared.ok);
4576 }
4577 }
4578
4579 static void randomkeyCommand(redisClient *c) {
4580 dictEntry *de;
4581 robj *key;
4582
4583 while(1) {
4584 de = dictGetRandomKey(c->db->dict);
4585 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
4586 }
4587
4588 if (de == NULL) {
4589 addReply(c,shared.nullbulk);
4590 return;
4591 }
4592
4593 key = dictGetEntryKey(de);
4594 if (server.vm_enabled) {
4595 key = dupStringObject(key);
4596 addReplyBulk(c,key);
4597 decrRefCount(key);
4598 } else {
4599 addReplyBulk(c,key);
4600 }
4601 }
4602
4603 static void keysCommand(redisClient *c) {
4604 dictIterator *di;
4605 dictEntry *de;
4606 sds pattern = c->argv[1]->ptr;
4607 int plen = sdslen(pattern);
4608 unsigned long numkeys = 0;
4609 robj *lenobj = createObject(REDIS_STRING,NULL);
4610
4611 di = dictGetIterator(c->db->dict);
4612 addReply(c,lenobj);
4613 decrRefCount(lenobj);
4614 while((de = dictNext(di)) != NULL) {
4615 robj *keyobj = dictGetEntryKey(de);
4616
4617 sds key = keyobj->ptr;
4618 if ((pattern[0] == '*' && pattern[1] == '\0') ||
4619 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
4620 if (expireIfNeeded(c->db,keyobj) == 0) {
4621 addReplyBulk(c,keyobj);
4622 numkeys++;
4623 }
4624 }
4625 }
4626 dictReleaseIterator(di);
4627 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
4628 }
4629
4630 static void dbsizeCommand(redisClient *c) {
4631 addReplySds(c,
4632 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
4633 }
4634
4635 static void lastsaveCommand(redisClient *c) {
4636 addReplySds(c,
4637 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
4638 }
4639
4640 static void typeCommand(redisClient *c) {
4641 robj *o;
4642 char *type;
4643
4644 o = lookupKeyRead(c->db,c->argv[1]);
4645 if (o == NULL) {
4646 type = "+none";
4647 } else {
4648 switch(o->type) {
4649 case REDIS_STRING: type = "+string"; break;
4650 case REDIS_LIST: type = "+list"; break;
4651 case REDIS_SET: type = "+set"; break;
4652 case REDIS_ZSET: type = "+zset"; break;
4653 case REDIS_HASH: type = "+hash"; break;
4654 default: type = "+unknown"; break;
4655 }
4656 }
4657 addReplySds(c,sdsnew(type));
4658 addReply(c,shared.crlf);
4659 }
4660
4661 static void saveCommand(redisClient *c) {
4662 if (server.bgsavechildpid != -1) {
4663 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
4664 return;
4665 }
4666 if (rdbSave(server.dbfilename) == REDIS_OK) {
4667 addReply(c,shared.ok);
4668 } else {
4669 addReply(c,shared.err);
4670 }
4671 }
4672
4673 static void bgsaveCommand(redisClient *c) {
4674 if (server.bgsavechildpid != -1) {
4675 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
4676 return;
4677 }
4678 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
4679 char *status = "+Background saving started\r\n";
4680 addReplySds(c,sdsnew(status));
4681 } else {
4682 addReply(c,shared.err);
4683 }
4684 }
4685
4686 static void shutdownCommand(redisClient *c) {
4687 if (prepareForShutdown() == REDIS_OK)
4688 exit(0);
4689 addReplySds(c, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
4690 }
4691
4692 static void renameGenericCommand(redisClient *c, int nx) {
4693 robj *o;
4694
4695 /* To use the same key as src and dst is probably an error */
4696 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
4697 addReply(c,shared.sameobjecterr);
4698 return;
4699 }
4700
4701 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
4702 return;
4703
4704 incrRefCount(o);
4705 deleteIfVolatile(c->db,c->argv[2]);
4706 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
4707 if (nx) {
4708 decrRefCount(o);
4709 addReply(c,shared.czero);
4710 return;
4711 }
4712 dictReplace(c->db->dict,c->argv[2],o);
4713 } else {
4714 incrRefCount(c->argv[2]);
4715 }
4716 deleteKey(c->db,c->argv[1]);
4717 touchWatchedKey(c->db,c->argv[2]);
4718 server.dirty++;
4719 addReply(c,nx ? shared.cone : shared.ok);
4720 }
4721
4722 static void renameCommand(redisClient *c) {
4723 renameGenericCommand(c,0);
4724 }
4725
4726 static void renamenxCommand(redisClient *c) {
4727 renameGenericCommand(c,1);
4728 }
4729
4730 static void moveCommand(redisClient *c) {
4731 robj *o;
4732 redisDb *src, *dst;
4733 int srcid;
4734
4735 /* Obtain source and target DB pointers */
4736 src = c->db;
4737 srcid = c->db->id;
4738 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
4739 addReply(c,shared.outofrangeerr);
4740 return;
4741 }
4742 dst = c->db;
4743 selectDb(c,srcid); /* Back to the source DB */
4744
4745 /* If the user is moving using as target the same
4746 * DB as the source DB it is probably an error. */
4747 if (src == dst) {
4748 addReply(c,shared.sameobjecterr);
4749 return;
4750 }
4751
4752 /* Check if the element exists and get a reference */
4753 o = lookupKeyWrite(c->db,c->argv[1]);
4754 if (!o) {
4755 addReply(c,shared.czero);
4756 return;
4757 }
4758
4759 /* Try to add the element to the target DB */
4760 deleteIfVolatile(dst,c->argv[1]);
4761 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
4762 addReply(c,shared.czero);
4763 return;
4764 }
4765 incrRefCount(c->argv[1]);
4766 incrRefCount(o);
4767
4768 /* OK! key moved, free the entry in the source DB */
4769 deleteKey(src,c->argv[1]);
4770 server.dirty++;
4771 addReply(c,shared.cone);
4772 }
4773
4774 /* =================================== Lists ================================ */
4775 static void lPush(robj *subject, robj *value, int where) {
4776 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4777 int pos = (where == REDIS_HEAD) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
4778 value = getDecodedObject(value);
4779 subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),pos);
4780 decrRefCount(value);
4781 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4782 if (where == REDIS_HEAD) {
4783 listAddNodeHead(subject->ptr,value);
4784 } else {
4785 listAddNodeTail(subject->ptr,value);
4786 }
4787 incrRefCount(value);
4788 } else {
4789 redisPanic("Unknown list encoding");
4790 }
4791 }
4792
4793
4794 static void pushGenericCommand(redisClient *c, int where) {
4795 robj *lobj = lookupKeyWrite(c->db,c->argv[1]);
4796 if (lobj == NULL) {
4797 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
4798 addReply(c,shared.cone);
4799 return;
4800 }
4801 lobj = createObject(REDIS_LIST,ziplistNew());
4802 lobj->encoding = REDIS_ENCODING_ZIPLIST;
4803 dictAdd(c->db->dict,c->argv[1],lobj);
4804 incrRefCount(c->argv[1]);
4805 } else {
4806 if (lobj->type != REDIS_LIST) {
4807 addReply(c,shared.wrongtypeerr);
4808 return;
4809 }
4810 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
4811 addReply(c,shared.cone);
4812 return;
4813 }
4814 }
4815 lPush(lobj,c->argv[2],where);
4816 addReplyLongLong(c,lLength(lobj));
4817 server.dirty++;
4818 }
4819
4820 static void lpushCommand(redisClient *c) {
4821 pushGenericCommand(c,REDIS_HEAD);
4822 }
4823
4824 static void rpushCommand(redisClient *c) {
4825 pushGenericCommand(c,REDIS_TAIL);
4826 }
4827
4828 static void llenCommand(redisClient *c) {
4829 robj *o;
4830 list *l;
4831
4832 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
4833 checkType(c,o,REDIS_LIST)) return;
4834
4835 l = o->ptr;
4836 addReplyUlong(c,listLength(l));
4837 }
4838
4839 static void lindexCommand(redisClient *c) {
4840 robj *o;
4841 int index = atoi(c->argv[2]->ptr);
4842 list *list;
4843 listNode *ln;
4844
4845 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4846 checkType(c,o,REDIS_LIST)) return;
4847 list = o->ptr;
4848
4849 ln = listIndex(list, index);
4850 if (ln == NULL) {
4851 addReply(c,shared.nullbulk);
4852 } else {
4853 robj *ele = listNodeValue(ln);
4854 addReplyBulk(c,ele);
4855 }
4856 }
4857
4858 static void lsetCommand(redisClient *c) {
4859 robj *o;
4860 int index = atoi(c->argv[2]->ptr);
4861 list *list;
4862 listNode *ln;
4863
4864 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL ||
4865 checkType(c,o,REDIS_LIST)) return;
4866 list = o->ptr;
4867
4868 ln = listIndex(list, index);
4869 if (ln == NULL) {
4870 addReply(c,shared.outofrangeerr);
4871 } else {
4872 robj *ele = listNodeValue(ln);
4873
4874 decrRefCount(ele);
4875 listNodeValue(ln) = c->argv[3];
4876 incrRefCount(c->argv[3]);
4877 addReply(c,shared.ok);
4878 server.dirty++;
4879 }
4880 }
4881
4882 static void popGenericCommand(redisClient *c, int where) {
4883 robj *o;
4884 list *list;
4885 listNode *ln;
4886
4887 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4888 checkType(c,o,REDIS_LIST)) return;
4889 list = o->ptr;
4890
4891 if (where == REDIS_HEAD)
4892 ln = listFirst(list);
4893 else
4894 ln = listLast(list);
4895
4896 if (ln == NULL) {
4897 addReply(c,shared.nullbulk);
4898 } else {
4899 robj *ele = listNodeValue(ln);
4900 addReplyBulk(c,ele);
4901 listDelNode(list,ln);
4902 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
4903 server.dirty++;
4904 }
4905 }
4906
4907 static void lpopCommand(redisClient *c) {
4908 popGenericCommand(c,REDIS_HEAD);
4909 }
4910
4911 static void rpopCommand(redisClient *c) {
4912 popGenericCommand(c,REDIS_TAIL);
4913 }
4914
4915 static void lrangeCommand(redisClient *c) {
4916 robj *o;
4917 int start = atoi(c->argv[2]->ptr);
4918 int end = atoi(c->argv[3]->ptr);
4919 int llen;
4920 int rangelen, j;
4921 list *list;
4922 listNode *ln;
4923 robj *ele;
4924
4925 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
4926 || checkType(c,o,REDIS_LIST)) return;
4927 list = o->ptr;
4928 llen = listLength(list);
4929
4930 /* convert negative indexes */
4931 if (start < 0) start = llen+start;
4932 if (end < 0) end = llen+end;
4933 if (start < 0) start = 0;
4934 if (end < 0) end = 0;
4935
4936 /* indexes sanity checks */
4937 if (start > end || start >= llen) {
4938 /* Out of range start or start > end result in empty list */
4939 addReply(c,shared.emptymultibulk);
4940 return;
4941 }
4942 if (end >= llen) end = llen-1;
4943 rangelen = (end-start)+1;
4944
4945 /* Return the result in form of a multi-bulk reply */
4946 ln = listIndex(list, start);
4947 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
4948 for (j = 0; j < rangelen; j++) {
4949 ele = listNodeValue(ln);
4950 addReplyBulk(c,ele);
4951 ln = ln->next;
4952 }
4953 }
4954
4955 static void ltrimCommand(redisClient *c) {
4956 robj *o;
4957 int start = atoi(c->argv[2]->ptr);
4958 int end = atoi(c->argv[3]->ptr);
4959 int llen;
4960 int j, ltrim, rtrim;
4961 list *list;
4962 listNode *ln;
4963
4964 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
4965 checkType(c,o,REDIS_LIST)) return;
4966 list = o->ptr;
4967 llen = listLength(list);
4968
4969 /* convert negative indexes */
4970 if (start < 0) start = llen+start;
4971 if (end < 0) end = llen+end;
4972 if (start < 0) start = 0;
4973 if (end < 0) end = 0;
4974
4975 /* indexes sanity checks */
4976 if (start > end || start >= llen) {
4977 /* Out of range start or start > end result in empty list */
4978 ltrim = llen;
4979 rtrim = 0;
4980 } else {
4981 if (end >= llen) end = llen-1;
4982 ltrim = start;
4983 rtrim = llen-end-1;
4984 }
4985
4986 /* Remove list elements to perform the trim */
4987 for (j = 0; j < ltrim; j++) {
4988 ln = listFirst(list);
4989 listDelNode(list,ln);
4990 }
4991 for (j = 0; j < rtrim; j++) {
4992 ln = listLast(list);
4993 listDelNode(list,ln);
4994 }
4995 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
4996 server.dirty++;
4997 addReply(c,shared.ok);
4998 }
4999
5000 static void lremCommand(redisClient *c) {
5001 robj *o;
5002 list *list;
5003 listNode *ln, *next;
5004 int toremove = atoi(c->argv[2]->ptr);
5005 int removed = 0;
5006 int fromtail = 0;
5007
5008 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5009 checkType(c,o,REDIS_LIST)) return;
5010 list = o->ptr;
5011
5012 if (toremove < 0) {
5013 toremove = -toremove;
5014 fromtail = 1;
5015 }
5016 ln = fromtail ? list->tail : list->head;
5017 while (ln) {
5018 robj *ele = listNodeValue(ln);
5019
5020 next = fromtail ? ln->prev : ln->next;
5021 if (equalStringObjects(ele,c->argv[3])) {
5022 listDelNode(list,ln);
5023 server.dirty++;
5024 removed++;
5025 if (toremove && removed == toremove) break;
5026 }
5027 ln = next;
5028 }
5029 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
5030 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
5031 }
5032
5033 /* This is the semantic of this command:
5034 * RPOPLPUSH srclist dstlist:
5035 * IF LLEN(srclist) > 0
5036 * element = RPOP srclist
5037 * LPUSH dstlist element
5038 * RETURN element
5039 * ELSE
5040 * RETURN nil
5041 * END
5042 * END
5043 *
5044 * The idea is to be able to get an element from a list in a reliable way
5045 * since the element is not just returned but pushed against another list
5046 * as well. This command was originally proposed by Ezra Zygmuntowicz.
5047 */
5048 static void rpoplpushcommand(redisClient *c) {
5049 robj *sobj;
5050 list *srclist;
5051 listNode *ln;
5052
5053 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5054 checkType(c,sobj,REDIS_LIST)) return;
5055 srclist = sobj->ptr;
5056 ln = listLast(srclist);
5057
5058 if (ln == NULL) {
5059 addReply(c,shared.nullbulk);
5060 } else {
5061 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
5062 robj *ele = listNodeValue(ln);
5063 list *dstlist;
5064
5065 if (dobj && dobj->type != REDIS_LIST) {
5066 addReply(c,shared.wrongtypeerr);
5067 return;
5068 }
5069
5070 /* Add the element to the target list (unless it's directly
5071 * passed to some BLPOP-ing client */
5072 if (!handleClientsWaitingListPush(c,c->argv[2],ele)) {
5073 if (dobj == NULL) {
5074 /* Create the list if the key does not exist */
5075 dobj = createListObject();
5076 dictAdd(c->db->dict,c->argv[2],dobj);
5077 incrRefCount(c->argv[2]);
5078 }
5079 dstlist = dobj->ptr;
5080 listAddNodeHead(dstlist,ele);
5081 incrRefCount(ele);
5082 }
5083
5084 /* Send the element to the client as reply as well */
5085 addReplyBulk(c,ele);
5086
5087 /* Finally remove the element from the source list */
5088 listDelNode(srclist,ln);
5089 if (listLength(srclist) == 0) deleteKey(c->db,c->argv[1]);
5090 server.dirty++;
5091 }
5092 }
5093
5094 /* ==================================== Sets ================================ */
5095
5096 static void saddCommand(redisClient *c) {
5097 robj *set;
5098
5099 set = lookupKeyWrite(c->db,c->argv[1]);
5100 if (set == NULL) {
5101 set = createSetObject();
5102 dictAdd(c->db->dict,c->argv[1],set);
5103 incrRefCount(c->argv[1]);
5104 } else {
5105 if (set->type != REDIS_SET) {
5106 addReply(c,shared.wrongtypeerr);
5107 return;
5108 }
5109 }
5110 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
5111 incrRefCount(c->argv[2]);
5112 server.dirty++;
5113 addReply(c,shared.cone);
5114 } else {
5115 addReply(c,shared.czero);
5116 }
5117 }
5118
5119 static void sremCommand(redisClient *c) {
5120 robj *set;
5121
5122 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5123 checkType(c,set,REDIS_SET)) return;
5124
5125 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
5126 server.dirty++;
5127 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
5128 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
5129 addReply(c,shared.cone);
5130 } else {
5131 addReply(c,shared.czero);
5132 }
5133 }
5134
5135 static void smoveCommand(redisClient *c) {
5136 robj *srcset, *dstset;
5137
5138 srcset = lookupKeyWrite(c->db,c->argv[1]);
5139 dstset = lookupKeyWrite(c->db,c->argv[2]);
5140
5141 /* If the source key does not exist return 0, if it's of the wrong type
5142 * raise an error */
5143 if (srcset == NULL || srcset->type != REDIS_SET) {
5144 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
5145 return;
5146 }
5147 /* Error if the destination key is not a set as well */
5148 if (dstset && dstset->type != REDIS_SET) {
5149 addReply(c,shared.wrongtypeerr);
5150 return;
5151 }
5152 /* Remove the element from the source set */
5153 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
5154 /* Key not found in the src set! return zero */
5155 addReply(c,shared.czero);
5156 return;
5157 }
5158 if (dictSize((dict*)srcset->ptr) == 0 && srcset != dstset)
5159 deleteKey(c->db,c->argv[1]);
5160 server.dirty++;
5161 /* Add the element to the destination set */
5162 if (!dstset) {
5163 dstset = createSetObject();
5164 dictAdd(c->db->dict,c->argv[2],dstset);
5165 incrRefCount(c->argv[2]);
5166 }
5167 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
5168 incrRefCount(c->argv[3]);
5169 addReply(c,shared.cone);
5170 }
5171
5172 static void sismemberCommand(redisClient *c) {
5173 robj *set;
5174
5175 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5176 checkType(c,set,REDIS_SET)) return;
5177
5178 if (dictFind(set->ptr,c->argv[2]))
5179 addReply(c,shared.cone);
5180 else
5181 addReply(c,shared.czero);
5182 }
5183
5184 static void scardCommand(redisClient *c) {
5185 robj *o;
5186 dict *s;
5187
5188 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5189 checkType(c,o,REDIS_SET)) return;
5190
5191 s = o->ptr;
5192 addReplyUlong(c,dictSize(s));
5193 }
5194
5195 static void spopCommand(redisClient *c) {
5196 robj *set;
5197 dictEntry *de;
5198
5199 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5200 checkType(c,set,REDIS_SET)) return;
5201
5202 de = dictGetRandomKey(set->ptr);
5203 if (de == NULL) {
5204 addReply(c,shared.nullbulk);
5205 } else {
5206 robj *ele = dictGetEntryKey(de);
5207
5208 addReplyBulk(c,ele);
5209 dictDelete(set->ptr,ele);
5210 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
5211 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
5212 server.dirty++;
5213 }
5214 }
5215
5216 static void srandmemberCommand(redisClient *c) {
5217 robj *set;
5218 dictEntry *de;
5219
5220 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5221 checkType(c,set,REDIS_SET)) return;
5222
5223 de = dictGetRandomKey(set->ptr);
5224 if (de == NULL) {
5225 addReply(c,shared.nullbulk);
5226 } else {
5227 robj *ele = dictGetEntryKey(de);
5228
5229 addReplyBulk(c,ele);
5230 }
5231 }
5232
5233 static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
5234 dict **d1 = (void*) s1, **d2 = (void*) s2;
5235
5236 return dictSize(*d1)-dictSize(*d2);
5237 }
5238
5239 static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
5240 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5241 dictIterator *di;
5242 dictEntry *de;
5243 robj *lenobj = NULL, *dstset = NULL;
5244 unsigned long j, cardinality = 0;
5245
5246 for (j = 0; j < setsnum; j++) {
5247 robj *setobj;
5248
5249 setobj = dstkey ?
5250 lookupKeyWrite(c->db,setskeys[j]) :
5251 lookupKeyRead(c->db,setskeys[j]);
5252 if (!setobj) {
5253 zfree(dv);
5254 if (dstkey) {
5255 if (deleteKey(c->db,dstkey))
5256 server.dirty++;
5257 addReply(c,shared.czero);
5258 } else {
5259 addReply(c,shared.emptymultibulk);
5260 }
5261 return;
5262 }
5263 if (setobj->type != REDIS_SET) {
5264 zfree(dv);
5265 addReply(c,shared.wrongtypeerr);
5266 return;
5267 }
5268 dv[j] = setobj->ptr;
5269 }
5270 /* Sort sets from the smallest to largest, this will improve our
5271 * algorithm's performace */
5272 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
5273
5274 /* The first thing we should output is the total number of elements...
5275 * since this is a multi-bulk write, but at this stage we don't know
5276 * the intersection set size, so we use a trick, append an empty object
5277 * to the output list and save the pointer to later modify it with the
5278 * right length */
5279 if (!dstkey) {
5280 lenobj = createObject(REDIS_STRING,NULL);
5281 addReply(c,lenobj);
5282 decrRefCount(lenobj);
5283 } else {
5284 /* If we have a target key where to store the resulting set
5285 * create this key with an empty set inside */
5286 dstset = createSetObject();
5287 }
5288
5289 /* Iterate all the elements of the first (smallest) set, and test
5290 * the element against all the other sets, if at least one set does
5291 * not include the element it is discarded */
5292 di = dictGetIterator(dv[0]);
5293
5294 while((de = dictNext(di)) != NULL) {
5295 robj *ele;
5296
5297 for (j = 1; j < setsnum; j++)
5298 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
5299 if (j != setsnum)
5300 continue; /* at least one set does not contain the member */
5301 ele = dictGetEntryKey(de);
5302 if (!dstkey) {
5303 addReplyBulk(c,ele);
5304 cardinality++;
5305 } else {
5306 dictAdd(dstset->ptr,ele,NULL);
5307 incrRefCount(ele);
5308 }
5309 }
5310 dictReleaseIterator(di);
5311
5312 if (dstkey) {
5313 /* Store the resulting set into the target, if the intersection
5314 * is not an empty set. */
5315 deleteKey(c->db,dstkey);
5316 if (dictSize((dict*)dstset->ptr) > 0) {
5317 dictAdd(c->db->dict,dstkey,dstset);
5318 incrRefCount(dstkey);
5319 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
5320 } else {
5321 decrRefCount(dstset);
5322 addReply(c,shared.czero);
5323 }
5324 server.dirty++;
5325 } else {
5326 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
5327 }
5328 zfree(dv);
5329 }
5330
5331 static void sinterCommand(redisClient *c) {
5332 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
5333 }
5334
5335 static void sinterstoreCommand(redisClient *c) {
5336 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
5337 }
5338
5339 #define REDIS_OP_UNION 0
5340 #define REDIS_OP_DIFF 1
5341 #define REDIS_OP_INTER 2
5342
5343 static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
5344 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5345 dictIterator *di;
5346 dictEntry *de;
5347 robj *dstset = NULL;
5348 int j, cardinality = 0;
5349
5350 for (j = 0; j < setsnum; j++) {
5351 robj *setobj;
5352
5353 setobj = dstkey ?
5354 lookupKeyWrite(c->db,setskeys[j]) :
5355 lookupKeyRead(c->db,setskeys[j]);
5356 if (!setobj) {
5357 dv[j] = NULL;
5358 continue;
5359 }
5360 if (setobj->type != REDIS_SET) {
5361 zfree(dv);
5362 addReply(c,shared.wrongtypeerr);
5363 return;
5364 }
5365 dv[j] = setobj->ptr;
5366 }
5367
5368 /* We need a temp set object to store our union. If the dstkey
5369 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5370 * this set object will be the resulting object to set into the target key*/
5371 dstset = createSetObject();
5372
5373 /* Iterate all the elements of all the sets, add every element a single
5374 * time to the result set */
5375 for (j = 0; j < setsnum; j++) {
5376 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
5377 if (!dv[j]) continue; /* non existing keys are like empty sets */
5378
5379 di = dictGetIterator(dv[j]);
5380
5381 while((de = dictNext(di)) != NULL) {
5382 robj *ele;
5383
5384 /* dictAdd will not add the same element multiple times */
5385 ele = dictGetEntryKey(de);
5386 if (op == REDIS_OP_UNION || j == 0) {
5387 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
5388 incrRefCount(ele);
5389 cardinality++;
5390 }
5391 } else if (op == REDIS_OP_DIFF) {
5392 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
5393 cardinality--;
5394 }
5395 }
5396 }
5397 dictReleaseIterator(di);
5398
5399 /* result set is empty? Exit asap. */
5400 if (op == REDIS_OP_DIFF && cardinality == 0) break;
5401 }
5402
5403 /* Output the content of the resulting set, if not in STORE mode */
5404 if (!dstkey) {
5405 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
5406 di = dictGetIterator(dstset->ptr);
5407 while((de = dictNext(di)) != NULL) {
5408 robj *ele;
5409
5410 ele = dictGetEntryKey(de);
5411 addReplyBulk(c,ele);
5412 }
5413 dictReleaseIterator(di);
5414 decrRefCount(dstset);
5415 } else {
5416 /* If we have a target key where to store the resulting set
5417 * create this key with the result set inside */
5418 deleteKey(c->db,dstkey);
5419 if (dictSize((dict*)dstset->ptr) > 0) {
5420 dictAdd(c->db->dict,dstkey,dstset);
5421 incrRefCount(dstkey);
5422 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
5423 } else {
5424 decrRefCount(dstset);
5425 addReply(c,shared.czero);
5426 }
5427 server.dirty++;
5428 }
5429 zfree(dv);
5430 }
5431
5432 static void sunionCommand(redisClient *c) {
5433 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
5434 }
5435
5436 static void sunionstoreCommand(redisClient *c) {
5437 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
5438 }
5439
5440 static void sdiffCommand(redisClient *c) {
5441 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
5442 }
5443
5444 static void sdiffstoreCommand(redisClient *c) {
5445 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
5446 }
5447
5448 /* ==================================== ZSets =============================== */
5449
5450 /* ZSETs are ordered sets using two data structures to hold the same elements
5451 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5452 * data structure.
5453 *
5454 * The elements are added to an hash table mapping Redis objects to scores.
5455 * At the same time the elements are added to a skip list mapping scores
5456 * to Redis objects (so objects are sorted by scores in this "view"). */
5457
5458 /* This skiplist implementation is almost a C translation of the original
5459 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5460 * Alternative to Balanced Trees", modified in three ways:
5461 * a) this implementation allows for repeated values.
5462 * b) the comparison is not just by key (our 'score') but by satellite data.
5463 * c) there is a back pointer, so it's a doubly linked list with the back
5464 * pointers being only at "level 1". This allows to traverse the list
5465 * from tail to head, useful for ZREVRANGE. */
5466
5467 static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
5468 zskiplistNode *zn = zmalloc(sizeof(*zn));
5469
5470 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
5471 if (level > 1)
5472 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
5473 else
5474 zn->span = NULL;
5475 zn->score = score;
5476 zn->obj = obj;
5477 return zn;
5478 }
5479
5480 static zskiplist *zslCreate(void) {
5481 int j;
5482 zskiplist *zsl;
5483
5484 zsl = zmalloc(sizeof(*zsl));
5485 zsl->level = 1;
5486 zsl->length = 0;
5487 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
5488 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
5489 zsl->header->forward[j] = NULL;
5490
5491 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5492 if (j < ZSKIPLIST_MAXLEVEL-1)
5493 zsl->header->span[j] = 0;
5494 }
5495 zsl->header->backward = NULL;
5496 zsl->tail = NULL;
5497 return zsl;
5498 }
5499
5500 static void zslFreeNode(zskiplistNode *node) {
5501 decrRefCount(node->obj);
5502 zfree(node->forward);
5503 zfree(node->span);
5504 zfree(node);
5505 }
5506
5507 static void zslFree(zskiplist *zsl) {
5508 zskiplistNode *node = zsl->header->forward[0], *next;
5509
5510 zfree(zsl->header->forward);
5511 zfree(zsl->header->span);
5512 zfree(zsl->header);
5513 while(node) {
5514 next = node->forward[0];
5515 zslFreeNode(node);
5516 node = next;
5517 }
5518 zfree(zsl);
5519 }
5520
5521 static int zslRandomLevel(void) {
5522 int level = 1;
5523 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
5524 level += 1;
5525 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
5526 }
5527
5528 static void zslInsert(zskiplist *zsl, double score, robj *obj) {
5529 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5530 unsigned int rank[ZSKIPLIST_MAXLEVEL];
5531 int i, level;
5532
5533 x = zsl->header;
5534 for (i = zsl->level-1; i >= 0; i--) {
5535 /* store rank that is crossed to reach the insert position */
5536 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
5537
5538 while (x->forward[i] &&
5539 (x->forward[i]->score < score ||
5540 (x->forward[i]->score == score &&
5541 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
5542 rank[i] += i > 0 ? x->span[i-1] : 1;
5543 x = x->forward[i];
5544 }
5545 update[i] = x;
5546 }
5547 /* we assume the key is not already inside, since we allow duplicated
5548 * scores, and the re-insertion of score and redis object should never
5549 * happpen since the caller of zslInsert() should test in the hash table
5550 * if the element is already inside or not. */
5551 level = zslRandomLevel();
5552 if (level > zsl->level) {
5553 for (i = zsl->level; i < level; i++) {
5554 rank[i] = 0;
5555 update[i] = zsl->header;
5556 update[i]->span[i-1] = zsl->length;
5557 }
5558 zsl->level = level;
5559 }
5560 x = zslCreateNode(level,score,obj);
5561 for (i = 0; i < level; i++) {
5562 x->forward[i] = update[i]->forward[i];
5563 update[i]->forward[i] = x;
5564
5565 /* update span covered by update[i] as x is inserted here */
5566 if (i > 0) {
5567 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
5568 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
5569 }
5570 }
5571
5572 /* increment span for untouched levels */
5573 for (i = level; i < zsl->level; i++) {
5574 update[i]->span[i-1]++;
5575 }
5576
5577 x->backward = (update[0] == zsl->header) ? NULL : update[0];
5578 if (x->forward[0])
5579 x->forward[0]->backward = x;
5580 else
5581 zsl->tail = x;
5582 zsl->length++;
5583 }
5584
5585 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5586 void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
5587 int i;
5588 for (i = 0; i < zsl->level; i++) {
5589 if (update[i]->forward[i] == x) {
5590 if (i > 0) {
5591 update[i]->span[i-1] += x->span[i-1] - 1;
5592 }
5593 update[i]->forward[i] = x->forward[i];
5594 } else {
5595 /* invariant: i > 0, because update[0]->forward[0]
5596 * is always equal to x */
5597 update[i]->span[i-1] -= 1;
5598 }
5599 }
5600 if (x->forward[0]) {
5601 x->forward[0]->backward = x->backward;
5602 } else {
5603 zsl->tail = x->backward;
5604 }
5605 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
5606 zsl->level--;
5607 zsl->length--;
5608 }
5609
5610 /* Delete an element with matching score/object from the skiplist. */
5611 static int zslDelete(zskiplist *zsl, double score, robj *obj) {
5612 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5613 int i;
5614
5615 x = zsl->header;
5616 for (i = zsl->level-1; i >= 0; i--) {
5617 while (x->forward[i] &&
5618 (x->forward[i]->score < score ||
5619 (x->forward[i]->score == score &&
5620 compareStringObjects(x->forward[i]->obj,obj) < 0)))
5621 x = x->forward[i];
5622 update[i] = x;
5623 }
5624 /* We may have multiple elements with the same score, what we need
5625 * is to find the element with both the right score and object. */
5626 x = x->forward[0];
5627 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
5628 zslDeleteNode(zsl, x, update);
5629 zslFreeNode(x);
5630 return 1;
5631 } else {
5632 return 0; /* not found */
5633 }
5634 return 0; /* not found */
5635 }
5636
5637 /* Delete all the elements with score between min and max from the skiplist.
5638 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5639 * Note that this function takes the reference to the hash table view of the
5640 * sorted set, in order to remove the elements from the hash table too. */
5641 static unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
5642 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5643 unsigned long removed = 0;
5644 int i;
5645
5646 x = zsl->header;
5647 for (i = zsl->level-1; i >= 0; i--) {
5648 while (x->forward[i] && x->forward[i]->score < min)
5649 x = x->forward[i];
5650 update[i] = x;
5651 }
5652 /* We may have multiple elements with the same score, what we need
5653 * is to find the element with both the right score and object. */
5654 x = x->forward[0];
5655 while (x && x->score <= max) {
5656 zskiplistNode *next = x->forward[0];
5657 zslDeleteNode(zsl, x, update);
5658 dictDelete(dict,x->obj);
5659 zslFreeNode(x);
5660 removed++;
5661 x = next;
5662 }
5663 return removed; /* not found */
5664 }
5665
5666 /* Delete all the elements with rank between start and end from the skiplist.
5667 * Start and end are inclusive. Note that start and end need to be 1-based */
5668 static unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
5669 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5670 unsigned long traversed = 0, removed = 0;
5671 int i;
5672
5673 x = zsl->header;
5674 for (i = zsl->level-1; i >= 0; i--) {
5675 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
5676 traversed += i > 0 ? x->span[i-1] : 1;
5677 x = x->forward[i];
5678 }
5679 update[i] = x;
5680 }
5681
5682 traversed++;
5683 x = x->forward[0];
5684 while (x && traversed <= end) {
5685 zskiplistNode *next = x->forward[0];
5686 zslDeleteNode(zsl, x, update);
5687 dictDelete(dict,x->obj);
5688 zslFreeNode(x);
5689 removed++;
5690 traversed++;
5691 x = next;
5692 }
5693 return removed;
5694 }
5695
5696 /* Find the first node having a score equal or greater than the specified one.
5697 * Returns NULL if there is no match. */
5698 static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
5699 zskiplistNode *x;
5700 int i;
5701
5702 x = zsl->header;
5703 for (i = zsl->level-1; i >= 0; i--) {
5704 while (x->forward[i] && x->forward[i]->score < score)
5705 x = x->forward[i];
5706 }
5707 /* We may have multiple elements with the same score, what we need
5708 * is to find the element with both the right score and object. */
5709 return x->forward[0];
5710 }
5711
5712 /* Find the rank for an element by both score and key.
5713 * Returns 0 when the element cannot be found, rank otherwise.
5714 * Note that the rank is 1-based due to the span of zsl->header to the
5715 * first element. */
5716 static unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
5717 zskiplistNode *x;
5718 unsigned long rank = 0;
5719 int i;
5720
5721 x = zsl->header;
5722 for (i = zsl->level-1; i >= 0; i--) {
5723 while (x->forward[i] &&
5724 (x->forward[i]->score < score ||
5725 (x->forward[i]->score == score &&
5726 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
5727 rank += i > 0 ? x->span[i-1] : 1;
5728 x = x->forward[i];
5729 }
5730
5731 /* x might be equal to zsl->header, so test if obj is non-NULL */
5732 if (x->obj && equalStringObjects(x->obj,o)) {
5733 return rank;
5734 }
5735 }
5736 return 0;
5737 }
5738
5739 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5740 zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
5741 zskiplistNode *x;
5742 unsigned long traversed = 0;
5743 int i;
5744
5745 x = zsl->header;
5746 for (i = zsl->level-1; i >= 0; i--) {
5747 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
5748 {
5749 traversed += i > 0 ? x->span[i-1] : 1;
5750 x = x->forward[i];
5751 }
5752 if (traversed == rank) {
5753 return x;
5754 }
5755 }
5756 return NULL;
5757 }
5758
5759 /* The actual Z-commands implementations */
5760
5761 /* This generic command implements both ZADD and ZINCRBY.
5762 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5763 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5764 static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
5765 robj *zsetobj;
5766 zset *zs;
5767 double *score;
5768
5769 if (isnan(scoreval)) {
5770 addReplySds(c,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
5771 return;
5772 }
5773
5774 zsetobj = lookupKeyWrite(c->db,key);
5775 if (zsetobj == NULL) {
5776 zsetobj = createZsetObject();
5777 dictAdd(c->db->dict,key,zsetobj);
5778 incrRefCount(key);
5779 } else {
5780 if (zsetobj->type != REDIS_ZSET) {
5781 addReply(c,shared.wrongtypeerr);
5782 return;
5783 }
5784 }
5785 zs = zsetobj->ptr;
5786
5787 /* Ok now since we implement both ZADD and ZINCRBY here the code
5788 * needs to handle the two different conditions. It's all about setting
5789 * '*score', that is, the new score to set, to the right value. */
5790 score = zmalloc(sizeof(double));
5791 if (doincrement) {
5792 dictEntry *de;
5793
5794 /* Read the old score. If the element was not present starts from 0 */
5795 de = dictFind(zs->dict,ele);
5796 if (de) {
5797 double *oldscore = dictGetEntryVal(de);
5798 *score = *oldscore + scoreval;
5799 } else {
5800 *score = scoreval;
5801 }
5802 if (isnan(*score)) {
5803 addReplySds(c,
5804 sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
5805 zfree(score);
5806 /* Note that we don't need to check if the zset may be empty and
5807 * should be removed here, as we can only obtain Nan as score if
5808 * there was already an element in the sorted set. */
5809 return;
5810 }
5811 } else {
5812 *score = scoreval;
5813 }
5814
5815 /* What follows is a simple remove and re-insert operation that is common
5816 * to both ZADD and ZINCRBY... */
5817 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
5818 /* case 1: New element */
5819 incrRefCount(ele); /* added to hash */
5820 zslInsert(zs->zsl,*score,ele);
5821 incrRefCount(ele); /* added to skiplist */
5822 server.dirty++;
5823 if (doincrement)
5824 addReplyDouble(c,*score);
5825 else
5826 addReply(c,shared.cone);
5827 } else {
5828 dictEntry *de;
5829 double *oldscore;
5830
5831 /* case 2: Score update operation */
5832 de = dictFind(zs->dict,ele);
5833 redisAssert(de != NULL);
5834 oldscore = dictGetEntryVal(de);
5835 if (*score != *oldscore) {
5836 int deleted;
5837
5838 /* Remove and insert the element in the skip list with new score */
5839 deleted = zslDelete(zs->zsl,*oldscore,ele);
5840 redisAssert(deleted != 0);
5841 zslInsert(zs->zsl,*score,ele);
5842 incrRefCount(ele);
5843 /* Update the score in the hash table */
5844 dictReplace(zs->dict,ele,score);
5845 server.dirty++;
5846 } else {
5847 zfree(score);
5848 }
5849 if (doincrement)
5850 addReplyDouble(c,*score);
5851 else
5852 addReply(c,shared.czero);
5853 }
5854 }
5855
5856 static void zaddCommand(redisClient *c) {
5857 double scoreval;
5858
5859 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
5860 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
5861 }
5862
5863 static void zincrbyCommand(redisClient *c) {
5864 double scoreval;
5865
5866 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
5867 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
5868 }
5869
5870 static void zremCommand(redisClient *c) {
5871 robj *zsetobj;
5872 zset *zs;
5873 dictEntry *de;
5874 double *oldscore;
5875 int deleted;
5876
5877 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5878 checkType(c,zsetobj,REDIS_ZSET)) return;
5879
5880 zs = zsetobj->ptr;
5881 de = dictFind(zs->dict,c->argv[2]);
5882 if (de == NULL) {
5883 addReply(c,shared.czero);
5884 return;
5885 }
5886 /* Delete from the skiplist */
5887 oldscore = dictGetEntryVal(de);
5888 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
5889 redisAssert(deleted != 0);
5890
5891 /* Delete from the hash table */
5892 dictDelete(zs->dict,c->argv[2]);
5893 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
5894 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
5895 server.dirty++;
5896 addReply(c,shared.cone);
5897 }
5898
5899 static void zremrangebyscoreCommand(redisClient *c) {
5900 double min;
5901 double max;
5902 long deleted;
5903 robj *zsetobj;
5904 zset *zs;
5905
5906 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
5907 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
5908
5909 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5910 checkType(c,zsetobj,REDIS_ZSET)) return;
5911
5912 zs = zsetobj->ptr;
5913 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
5914 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
5915 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
5916 server.dirty += deleted;
5917 addReplyLongLong(c,deleted);
5918 }
5919
5920 static void zremrangebyrankCommand(redisClient *c) {
5921 long start;
5922 long end;
5923 int llen;
5924 long deleted;
5925 robj *zsetobj;
5926 zset *zs;
5927
5928 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
5929 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
5930
5931 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5932 checkType(c,zsetobj,REDIS_ZSET)) return;
5933 zs = zsetobj->ptr;
5934 llen = zs->zsl->length;
5935
5936 /* convert negative indexes */
5937 if (start < 0) start = llen+start;
5938 if (end < 0) end = llen+end;
5939 if (start < 0) start = 0;
5940 if (end < 0) end = 0;
5941
5942 /* indexes sanity checks */
5943 if (start > end || start >= llen) {
5944 addReply(c,shared.czero);
5945 return;
5946 }
5947 if (end >= llen) end = llen-1;
5948
5949 /* increment start and end because zsl*Rank functions
5950 * use 1-based rank */
5951 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
5952 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
5953 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
5954 server.dirty += deleted;
5955 addReplyLongLong(c, deleted);
5956 }
5957
5958 typedef struct {
5959 dict *dict;
5960 double weight;
5961 } zsetopsrc;
5962
5963 static int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
5964 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
5965 unsigned long size1, size2;
5966 size1 = d1->dict ? dictSize(d1->dict) : 0;
5967 size2 = d2->dict ? dictSize(d2->dict) : 0;
5968 return size1 - size2;
5969 }
5970
5971 #define REDIS_AGGR_SUM 1
5972 #define REDIS_AGGR_MIN 2
5973 #define REDIS_AGGR_MAX 3
5974 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
5975
5976 inline static void zunionInterAggregate(double *target, double val, int aggregate) {
5977 if (aggregate == REDIS_AGGR_SUM) {
5978 *target = *target + val;
5979 } else if (aggregate == REDIS_AGGR_MIN) {
5980 *target = val < *target ? val : *target;
5981 } else if (aggregate == REDIS_AGGR_MAX) {
5982 *target = val > *target ? val : *target;
5983 } else {
5984 /* safety net */
5985 redisPanic("Unknown ZUNION/INTER aggregate type");
5986 }
5987 }
5988
5989 static void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
5990 int i, j, setnum;
5991 int aggregate = REDIS_AGGR_SUM;
5992 zsetopsrc *src;
5993 robj *dstobj;
5994 zset *dstzset;
5995 dictIterator *di;
5996 dictEntry *de;
5997
5998 /* expect setnum input keys to be given */
5999 setnum = atoi(c->argv[2]->ptr);
6000 if (setnum < 1) {
6001 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
6002 return;
6003 }
6004
6005 /* test if the expected number of keys would overflow */
6006 if (3+setnum > c->argc) {
6007 addReply(c,shared.syntaxerr);
6008 return;
6009 }
6010
6011 /* read keys to be used for input */
6012 src = zmalloc(sizeof(zsetopsrc) * setnum);
6013 for (i = 0, j = 3; i < setnum; i++, j++) {
6014 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
6015 if (!obj) {
6016 src[i].dict = NULL;
6017 } else {
6018 if (obj->type == REDIS_ZSET) {
6019 src[i].dict = ((zset*)obj->ptr)->dict;
6020 } else if (obj->type == REDIS_SET) {
6021 src[i].dict = (obj->ptr);
6022 } else {
6023 zfree(src);
6024 addReply(c,shared.wrongtypeerr);
6025 return;
6026 }
6027 }
6028
6029 /* default all weights to 1 */
6030 src[i].weight = 1.0;
6031 }
6032
6033 /* parse optional extra arguments */
6034 if (j < c->argc) {
6035 int remaining = c->argc - j;
6036
6037 while (remaining) {
6038 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
6039 j++; remaining--;
6040 for (i = 0; i < setnum; i++, j++, remaining--) {
6041 if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK)
6042 return;
6043 }
6044 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
6045 j++; remaining--;
6046 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
6047 aggregate = REDIS_AGGR_SUM;
6048 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
6049 aggregate = REDIS_AGGR_MIN;
6050 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
6051 aggregate = REDIS_AGGR_MAX;
6052 } else {
6053 zfree(src);
6054 addReply(c,shared.syntaxerr);
6055 return;
6056 }
6057 j++; remaining--;
6058 } else {
6059 zfree(src);
6060 addReply(c,shared.syntaxerr);
6061 return;
6062 }
6063 }
6064 }
6065
6066 /* sort sets from the smallest to largest, this will improve our
6067 * algorithm's performance */
6068 qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);
6069
6070 dstobj = createZsetObject();
6071 dstzset = dstobj->ptr;
6072
6073 if (op == REDIS_OP_INTER) {
6074 /* skip going over all entries if the smallest zset is NULL or empty */
6075 if (src[0].dict && dictSize(src[0].dict) > 0) {
6076 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6077 * from small to large, all src[i > 0].dict are non-empty too */
6078 di = dictGetIterator(src[0].dict);
6079 while((de = dictNext(di)) != NULL) {
6080 double *score = zmalloc(sizeof(double)), value;
6081 *score = src[0].weight * zunionInterDictValue(de);
6082
6083 for (j = 1; j < setnum; j++) {
6084 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
6085 if (other) {
6086 value = src[j].weight * zunionInterDictValue(other);
6087 zunionInterAggregate(score, value, aggregate);
6088 } else {
6089 break;
6090 }
6091 }
6092
6093 /* skip entry when not present in every source dict */
6094 if (j != setnum) {
6095 zfree(score);
6096 } else {
6097 robj *o = dictGetEntryKey(de);
6098 dictAdd(dstzset->dict,o,score);
6099 incrRefCount(o); /* added to dictionary */
6100 zslInsert(dstzset->zsl,*score,o);
6101 incrRefCount(o); /* added to skiplist */
6102 }
6103 }
6104 dictReleaseIterator(di);
6105 }
6106 } else if (op == REDIS_OP_UNION) {
6107 for (i = 0; i < setnum; i++) {
6108 if (!src[i].dict) continue;
6109
6110 di = dictGetIterator(src[i].dict);
6111 while((de = dictNext(di)) != NULL) {
6112 /* skip key when already processed */
6113 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
6114
6115 double *score = zmalloc(sizeof(double)), value;
6116 *score = src[i].weight * zunionInterDictValue(de);
6117
6118 /* because the zsets are sorted by size, its only possible
6119 * for sets at larger indices to hold this entry */
6120 for (j = (i+1); j < setnum; j++) {
6121 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
6122 if (other) {
6123 value = src[j].weight * zunionInterDictValue(other);
6124 zunionInterAggregate(score, value, aggregate);
6125 }
6126 }
6127
6128 robj *o = dictGetEntryKey(de);
6129 dictAdd(dstzset->dict,o,score);
6130 incrRefCount(o); /* added to dictionary */
6131 zslInsert(dstzset->zsl,*score,o);
6132 incrRefCount(o); /* added to skiplist */
6133 }
6134 dictReleaseIterator(di);
6135 }
6136 } else {
6137 /* unknown operator */
6138 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
6139 }
6140
6141 deleteKey(c->db,dstkey);
6142 if (dstzset->zsl->length) {
6143 dictAdd(c->db->dict,dstkey,dstobj);
6144 incrRefCount(dstkey);
6145 addReplyLongLong(c, dstzset->zsl->length);
6146 server.dirty++;
6147 } else {
6148 decrRefCount(dstobj);
6149 addReply(c, shared.czero);
6150 }
6151 zfree(src);
6152 }
6153
6154 static void zunionstoreCommand(redisClient *c) {
6155 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
6156 }
6157
6158 static void zinterstoreCommand(redisClient *c) {
6159 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
6160 }
6161
6162 static void zrangeGenericCommand(redisClient *c, int reverse) {
6163 robj *o;
6164 long start;
6165 long end;
6166 int withscores = 0;
6167 int llen;
6168 int rangelen, j;
6169 zset *zsetobj;
6170 zskiplist *zsl;
6171 zskiplistNode *ln;
6172 robj *ele;
6173
6174 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6175 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
6176
6177 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
6178 withscores = 1;
6179 } else if (c->argc >= 5) {
6180 addReply(c,shared.syntaxerr);
6181 return;
6182 }
6183
6184 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6185 || checkType(c,o,REDIS_ZSET)) return;
6186 zsetobj = o->ptr;
6187 zsl = zsetobj->zsl;
6188 llen = zsl->length;
6189
6190 /* convert negative indexes */
6191 if (start < 0) start = llen+start;
6192 if (end < 0) end = llen+end;
6193 if (start < 0) start = 0;
6194 if (end < 0) end = 0;
6195
6196 /* indexes sanity checks */
6197 if (start > end || start >= llen) {
6198 /* Out of range start or start > end result in empty list */
6199 addReply(c,shared.emptymultibulk);
6200 return;
6201 }
6202 if (end >= llen) end = llen-1;
6203 rangelen = (end-start)+1;
6204
6205 /* check if starting point is trivial, before searching
6206 * the element in log(N) time */
6207 if (reverse) {
6208 ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start);
6209 } else {
6210 ln = start == 0 ?
6211 zsl->header->forward[0] : zslGetElementByRank(zsl, start+1);
6212 }
6213
6214 /* Return the result in form of a multi-bulk reply */
6215 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
6216 withscores ? (rangelen*2) : rangelen));
6217 for (j = 0; j < rangelen; j++) {
6218 ele = ln->obj;
6219 addReplyBulk(c,ele);
6220 if (withscores)
6221 addReplyDouble(c,ln->score);
6222 ln = reverse ? ln->backward : ln->forward[0];
6223 }
6224 }
6225
6226 static void zrangeCommand(redisClient *c) {
6227 zrangeGenericCommand(c,0);
6228 }
6229
6230 static void zrevrangeCommand(redisClient *c) {
6231 zrangeGenericCommand(c,1);
6232 }
6233
6234 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
6235 * If justcount is non-zero, just the count is returned. */
6236 static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
6237 robj *o;
6238 double min, max;
6239 int minex = 0, maxex = 0; /* are min or max exclusive? */
6240 int offset = 0, limit = -1;
6241 int withscores = 0;
6242 int badsyntax = 0;
6243
6244 /* Parse the min-max interval. If one of the values is prefixed
6245 * by the "(" character, it's considered "open". For instance
6246 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6247 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6248 if (((char*)c->argv[2]->ptr)[0] == '(') {
6249 min = strtod((char*)c->argv[2]->ptr+1,NULL);
6250 minex = 1;
6251 } else {
6252 min = strtod(c->argv[2]->ptr,NULL);
6253 }
6254 if (((char*)c->argv[3]->ptr)[0] == '(') {
6255 max = strtod((char*)c->argv[3]->ptr+1,NULL);
6256 maxex = 1;
6257 } else {
6258 max = strtod(c->argv[3]->ptr,NULL);
6259 }
6260
6261 /* Parse "WITHSCORES": note that if the command was called with
6262 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6263 * enter the following paths to parse WITHSCORES and LIMIT. */
6264 if (c->argc == 5 || c->argc == 8) {
6265 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
6266 withscores = 1;
6267 else
6268 badsyntax = 1;
6269 }
6270 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
6271 badsyntax = 1;
6272 if (badsyntax) {
6273 addReplySds(c,
6274 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
6275 return;
6276 }
6277
6278 /* Parse "LIMIT" */
6279 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
6280 addReply(c,shared.syntaxerr);
6281 return;
6282 } else if (c->argc == (7 + withscores)) {
6283 offset = atoi(c->argv[5]->ptr);
6284 limit = atoi(c->argv[6]->ptr);
6285 if (offset < 0) offset = 0;
6286 }
6287
6288 /* Ok, lookup the key and get the range */
6289 o = lookupKeyRead(c->db,c->argv[1]);
6290 if (o == NULL) {
6291 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
6292 } else {
6293 if (o->type != REDIS_ZSET) {
6294 addReply(c,shared.wrongtypeerr);
6295 } else {
6296 zset *zsetobj = o->ptr;
6297 zskiplist *zsl = zsetobj->zsl;
6298 zskiplistNode *ln;
6299 robj *ele, *lenobj = NULL;
6300 unsigned long rangelen = 0;
6301
6302 /* Get the first node with the score >= min, or with
6303 * score > min if 'minex' is true. */
6304 ln = zslFirstWithScore(zsl,min);
6305 while (minex && ln && ln->score == min) ln = ln->forward[0];
6306
6307 if (ln == NULL) {
6308 /* No element matching the speciifed interval */
6309 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
6310 return;
6311 }
6312
6313 /* We don't know in advance how many matching elements there
6314 * are in the list, so we push this object that will represent
6315 * the multi-bulk length in the output buffer, and will "fix"
6316 * it later */
6317 if (!justcount) {
6318 lenobj = createObject(REDIS_STRING,NULL);
6319 addReply(c,lenobj);
6320 decrRefCount(lenobj);
6321 }
6322
6323 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
6324 if (offset) {
6325 offset--;
6326 ln = ln->forward[0];
6327 continue;
6328 }
6329 if (limit == 0) break;
6330 if (!justcount) {
6331 ele = ln->obj;
6332 addReplyBulk(c,ele);
6333 if (withscores)
6334 addReplyDouble(c,ln->score);
6335 }
6336 ln = ln->forward[0];
6337 rangelen++;
6338 if (limit > 0) limit--;
6339 }
6340 if (justcount) {
6341 addReplyLongLong(c,(long)rangelen);
6342 } else {
6343 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
6344 withscores ? (rangelen*2) : rangelen);
6345 }
6346 }
6347 }
6348 }
6349
6350 static void zrangebyscoreCommand(redisClient *c) {
6351 genericZrangebyscoreCommand(c,0);
6352 }
6353
6354 static void zcountCommand(redisClient *c) {
6355 genericZrangebyscoreCommand(c,1);
6356 }
6357
6358 static void zcardCommand(redisClient *c) {
6359 robj *o;
6360 zset *zs;
6361
6362 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6363 checkType(c,o,REDIS_ZSET)) return;
6364
6365 zs = o->ptr;
6366 addReplyUlong(c,zs->zsl->length);
6367 }
6368
6369 static void zscoreCommand(redisClient *c) {
6370 robj *o;
6371 zset *zs;
6372 dictEntry *de;
6373
6374 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6375 checkType(c,o,REDIS_ZSET)) return;
6376
6377 zs = o->ptr;
6378 de = dictFind(zs->dict,c->argv[2]);
6379 if (!de) {
6380 addReply(c,shared.nullbulk);
6381 } else {
6382 double *score = dictGetEntryVal(de);
6383
6384 addReplyDouble(c,*score);
6385 }
6386 }
6387
6388 static void zrankGenericCommand(redisClient *c, int reverse) {
6389 robj *o;
6390 zset *zs;
6391 zskiplist *zsl;
6392 dictEntry *de;
6393 unsigned long rank;
6394 double *score;
6395
6396 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6397 checkType(c,o,REDIS_ZSET)) return;
6398
6399 zs = o->ptr;
6400 zsl = zs->zsl;
6401 de = dictFind(zs->dict,c->argv[2]);
6402 if (!de) {
6403 addReply(c,shared.nullbulk);
6404 return;
6405 }
6406
6407 score = dictGetEntryVal(de);
6408 rank = zslGetRank(zsl, *score, c->argv[2]);
6409 if (rank) {
6410 if (reverse) {
6411 addReplyLongLong(c, zsl->length - rank);
6412 } else {
6413 addReplyLongLong(c, rank-1);
6414 }
6415 } else {
6416 addReply(c,shared.nullbulk);
6417 }
6418 }
6419
6420 static void zrankCommand(redisClient *c) {
6421 zrankGenericCommand(c, 0);
6422 }
6423
6424 static void zrevrankCommand(redisClient *c) {
6425 zrankGenericCommand(c, 1);
6426 }
6427
6428 /* ========================= Hashes utility functions ======================= */
6429 #define REDIS_HASH_KEY 1
6430 #define REDIS_HASH_VALUE 2
6431
6432 /* Check the length of a number of objects to see if we need to convert a
6433 * zipmap to a real hash. Note that we only check string encoded objects
6434 * as their string length can be queried in constant time. */
6435 static void hashTryConversion(robj *subject, robj **argv, int start, int end) {
6436 int i;
6437 if (subject->encoding != REDIS_ENCODING_ZIPMAP) return;
6438
6439 for (i = start; i <= end; i++) {
6440 if (argv[i]->encoding == REDIS_ENCODING_RAW &&
6441 sdslen(argv[i]->ptr) > server.hash_max_zipmap_value)
6442 {
6443 convertToRealHash(subject);
6444 return;
6445 }
6446 }
6447 }
6448
6449 /* Encode given objects in-place when the hash uses a dict. */
6450 static void hashTryObjectEncoding(robj *subject, robj **o1, robj **o2) {
6451 if (subject->encoding == REDIS_ENCODING_HT) {
6452 if (o1) *o1 = tryObjectEncoding(*o1);
6453 if (o2) *o2 = tryObjectEncoding(*o2);
6454 }
6455 }
6456
6457 /* Get the value from a hash identified by key. Returns either a string
6458 * object or NULL if the value cannot be found. The refcount of the object
6459 * is always increased by 1 when the value was found. */
6460 static robj *hashGet(robj *o, robj *key) {
6461 robj *value = NULL;
6462 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6463 unsigned char *v;
6464 unsigned int vlen;
6465 key = getDecodedObject(key);
6466 if (zipmapGet(o->ptr,key->ptr,sdslen(key->ptr),&v,&vlen)) {
6467 value = createStringObject((char*)v,vlen);
6468 }
6469 decrRefCount(key);
6470 } else {
6471 dictEntry *de = dictFind(o->ptr,key);
6472 if (de != NULL) {
6473 value = dictGetEntryVal(de);
6474 incrRefCount(value);
6475 }
6476 }
6477 return value;
6478 }
6479
6480 /* Test if the key exists in the given hash. Returns 1 if the key
6481 * exists and 0 when it doesn't. */
6482 static int hashExists(robj *o, robj *key) {
6483 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6484 key = getDecodedObject(key);
6485 if (zipmapExists(o->ptr,key->ptr,sdslen(key->ptr))) {
6486 decrRefCount(key);
6487 return 1;
6488 }
6489 decrRefCount(key);
6490 } else {
6491 if (dictFind(o->ptr,key) != NULL) {
6492 return 1;
6493 }
6494 }
6495 return 0;
6496 }
6497
6498 /* Add an element, discard the old if the key already exists.
6499 * Return 0 on insert and 1 on update. */
6500 static int hashSet(robj *o, robj *key, robj *value) {
6501 int update = 0;
6502 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6503 key = getDecodedObject(key);
6504 value = getDecodedObject(value);
6505 o->ptr = zipmapSet(o->ptr,
6506 key->ptr,sdslen(key->ptr),
6507 value->ptr,sdslen(value->ptr), &update);
6508 decrRefCount(key);
6509 decrRefCount(value);
6510
6511 /* Check if the zipmap needs to be upgraded to a real hash table */
6512 if (zipmapLen(o->ptr) > server.hash_max_zipmap_entries)
6513 convertToRealHash(o);
6514 } else {
6515 if (dictReplace(o->ptr,key,value)) {
6516 /* Insert */
6517 incrRefCount(key);
6518 } else {
6519 /* Update */
6520 update = 1;
6521 }
6522 incrRefCount(value);
6523 }
6524 return update;
6525 }
6526
6527 /* Delete an element from a hash.
6528 * Return 1 on deleted and 0 on not found. */
6529 static int hashDelete(robj *o, robj *key) {
6530 int deleted = 0;
6531 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6532 key = getDecodedObject(key);
6533 o->ptr = zipmapDel(o->ptr,key->ptr,sdslen(key->ptr), &deleted);
6534 decrRefCount(key);
6535 } else {
6536 deleted = dictDelete((dict*)o->ptr,key) == DICT_OK;
6537 /* Always check if the dictionary needs a resize after a delete. */
6538 if (deleted && htNeedsResize(o->ptr)) dictResize(o->ptr);
6539 }
6540 return deleted;
6541 }
6542
6543 /* Return the number of elements in a hash. */
6544 static unsigned long hashLength(robj *o) {
6545 return (o->encoding == REDIS_ENCODING_ZIPMAP) ?
6546 zipmapLen((unsigned char*)o->ptr) : dictSize((dict*)o->ptr);
6547 }
6548
6549 /* Structure to hold hash iteration abstration. Note that iteration over
6550 * hashes involves both fields and values. Because it is possible that
6551 * not both are required, store pointers in the iterator to avoid
6552 * unnecessary memory allocation for fields/values. */
6553 typedef struct {
6554 int encoding;
6555 unsigned char *zi;
6556 unsigned char *zk, *zv;
6557 unsigned int zklen, zvlen;
6558
6559 dictIterator *di;
6560 dictEntry *de;
6561 } hashIterator;
6562
6563 static hashIterator *hashInitIterator(robj *subject) {
6564 hashIterator *hi = zmalloc(sizeof(hashIterator));
6565 hi->encoding = subject->encoding;
6566 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6567 hi->zi = zipmapRewind(subject->ptr);
6568 } else if (hi->encoding == REDIS_ENCODING_HT) {
6569 hi->di = dictGetIterator(subject->ptr);
6570 } else {
6571 redisAssert(NULL);
6572 }
6573 return hi;
6574 }
6575
6576 static void hashReleaseIterator(hashIterator *hi) {
6577 if (hi->encoding == REDIS_ENCODING_HT) {
6578 dictReleaseIterator(hi->di);
6579 }
6580 zfree(hi);
6581 }
6582
6583 /* Move to the next entry in the hash. Return REDIS_OK when the next entry
6584 * could be found and REDIS_ERR when the iterator reaches the end. */
6585 static int hashNext(hashIterator *hi) {
6586 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6587 if ((hi->zi = zipmapNext(hi->zi, &hi->zk, &hi->zklen,
6588 &hi->zv, &hi->zvlen)) == NULL) return REDIS_ERR;
6589 } else {
6590 if ((hi->de = dictNext(hi->di)) == NULL) return REDIS_ERR;
6591 }
6592 return REDIS_OK;
6593 }
6594
6595 /* Get key or value object at current iteration position.
6596 * This increases the refcount of the field object by 1. */
6597 static robj *hashCurrent(hashIterator *hi, int what) {
6598 robj *o;
6599 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6600 if (what & REDIS_HASH_KEY) {
6601 o = createStringObject((char*)hi->zk,hi->zklen);
6602 } else {
6603 o = createStringObject((char*)hi->zv,hi->zvlen);
6604 }
6605 } else {
6606 if (what & REDIS_HASH_KEY) {
6607 o = dictGetEntryKey(hi->de);
6608 } else {
6609 o = dictGetEntryVal(hi->de);
6610 }
6611 incrRefCount(o);
6612 }
6613 return o;
6614 }
6615
6616 static robj *hashLookupWriteOrCreate(redisClient *c, robj *key) {
6617 robj *o = lookupKeyWrite(c->db,key);
6618 if (o == NULL) {
6619 o = createHashObject();
6620 dictAdd(c->db->dict,key,o);
6621 incrRefCount(key);
6622 } else {
6623 if (o->type != REDIS_HASH) {
6624 addReply(c,shared.wrongtypeerr);
6625 return NULL;
6626 }
6627 }
6628 return o;
6629 }
6630
6631 /* ============================= Hash commands ============================== */
6632 static void hsetCommand(redisClient *c) {
6633 int update;
6634 robj *o;
6635
6636 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6637 hashTryConversion(o,c->argv,2,3);
6638 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
6639 update = hashSet(o,c->argv[2],c->argv[3]);
6640 addReply(c, update ? shared.czero : shared.cone);
6641 server.dirty++;
6642 }
6643
6644 static void hsetnxCommand(redisClient *c) {
6645 robj *o;
6646 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6647 hashTryConversion(o,c->argv,2,3);
6648
6649 if (hashExists(o, c->argv[2])) {
6650 addReply(c, shared.czero);
6651 } else {
6652 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
6653 hashSet(o,c->argv[2],c->argv[3]);
6654 addReply(c, shared.cone);
6655 server.dirty++;
6656 }
6657 }
6658
6659 static void hmsetCommand(redisClient *c) {
6660 int i;
6661 robj *o;
6662
6663 if ((c->argc % 2) == 1) {
6664 addReplySds(c,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6665 return;
6666 }
6667
6668 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6669 hashTryConversion(o,c->argv,2,c->argc-1);
6670 for (i = 2; i < c->argc; i += 2) {
6671 hashTryObjectEncoding(o,&c->argv[i], &c->argv[i+1]);
6672 hashSet(o,c->argv[i],c->argv[i+1]);
6673 }
6674 addReply(c, shared.ok);
6675 server.dirty++;
6676 }
6677
6678 static void hincrbyCommand(redisClient *c) {
6679 long long value, incr;
6680 robj *o, *current, *new;
6681
6682 if (getLongLongFromObjectOrReply(c,c->argv[3],&incr,NULL) != REDIS_OK) return;
6683 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6684 if ((current = hashGet(o,c->argv[2])) != NULL) {
6685 if (getLongLongFromObjectOrReply(c,current,&value,
6686 "hash value is not an integer") != REDIS_OK) {
6687 decrRefCount(current);
6688 return;
6689 }
6690 decrRefCount(current);
6691 } else {
6692 value = 0;
6693 }
6694
6695 value += incr;
6696 new = createStringObjectFromLongLong(value);
6697 hashTryObjectEncoding(o,&c->argv[2],NULL);
6698 hashSet(o,c->argv[2],new);
6699 decrRefCount(new);
6700 addReplyLongLong(c,value);
6701 server.dirty++;
6702 }
6703
6704 static void hgetCommand(redisClient *c) {
6705 robj *o, *value;
6706 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6707 checkType(c,o,REDIS_HASH)) return;
6708
6709 if ((value = hashGet(o,c->argv[2])) != NULL) {
6710 addReplyBulk(c,value);
6711 decrRefCount(value);
6712 } else {
6713 addReply(c,shared.nullbulk);
6714 }
6715 }
6716
6717 static void hmgetCommand(redisClient *c) {
6718 int i;
6719 robj *o, *value;
6720 o = lookupKeyRead(c->db,c->argv[1]);
6721 if (o != NULL && o->type != REDIS_HASH) {
6722 addReply(c,shared.wrongtypeerr);
6723 }
6724
6725 /* Note the check for o != NULL happens inside the loop. This is
6726 * done because objects that cannot be found are considered to be
6727 * an empty hash. The reply should then be a series of NULLs. */
6728 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-2));
6729 for (i = 2; i < c->argc; i++) {
6730 if (o != NULL && (value = hashGet(o,c->argv[i])) != NULL) {
6731 addReplyBulk(c,value);
6732 decrRefCount(value);
6733 } else {
6734 addReply(c,shared.nullbulk);
6735 }
6736 }
6737 }
6738
6739 static void hdelCommand(redisClient *c) {
6740 robj *o;
6741 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6742 checkType(c,o,REDIS_HASH)) return;
6743
6744 if (hashDelete(o,c->argv[2])) {
6745 if (hashLength(o) == 0) deleteKey(c->db,c->argv[1]);
6746 addReply(c,shared.cone);
6747 server.dirty++;
6748 } else {
6749 addReply(c,shared.czero);
6750 }
6751 }
6752
6753 static void hlenCommand(redisClient *c) {
6754 robj *o;
6755 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6756 checkType(c,o,REDIS_HASH)) return;
6757
6758 addReplyUlong(c,hashLength(o));
6759 }
6760
6761 static void genericHgetallCommand(redisClient *c, int flags) {
6762 robj *o, *lenobj, *obj;
6763 unsigned long count = 0;
6764 hashIterator *hi;
6765
6766 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6767 || checkType(c,o,REDIS_HASH)) return;
6768
6769 lenobj = createObject(REDIS_STRING,NULL);
6770 addReply(c,lenobj);
6771 decrRefCount(lenobj);
6772
6773 hi = hashInitIterator(o);
6774 while (hashNext(hi) != REDIS_ERR) {
6775 if (flags & REDIS_HASH_KEY) {
6776 obj = hashCurrent(hi,REDIS_HASH_KEY);
6777 addReplyBulk(c,obj);
6778 decrRefCount(obj);
6779 count++;
6780 }
6781 if (flags & REDIS_HASH_VALUE) {
6782 obj = hashCurrent(hi,REDIS_HASH_VALUE);
6783 addReplyBulk(c,obj);
6784 decrRefCount(obj);
6785 count++;
6786 }
6787 }
6788 hashReleaseIterator(hi);
6789
6790 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",count);
6791 }
6792
6793 static void hkeysCommand(redisClient *c) {
6794 genericHgetallCommand(c,REDIS_HASH_KEY);
6795 }
6796
6797 static void hvalsCommand(redisClient *c) {
6798 genericHgetallCommand(c,REDIS_HASH_VALUE);
6799 }
6800
6801 static void hgetallCommand(redisClient *c) {
6802 genericHgetallCommand(c,REDIS_HASH_KEY|REDIS_HASH_VALUE);
6803 }
6804
6805 static void hexistsCommand(redisClient *c) {
6806 robj *o;
6807 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6808 checkType(c,o,REDIS_HASH)) return;
6809
6810 addReply(c, hashExists(o,c->argv[2]) ? shared.cone : shared.czero);
6811 }
6812
6813 static void convertToRealHash(robj *o) {
6814 unsigned char *key, *val, *p, *zm = o->ptr;
6815 unsigned int klen, vlen;
6816 dict *dict = dictCreate(&hashDictType,NULL);
6817
6818 assert(o->type == REDIS_HASH && o->encoding != REDIS_ENCODING_HT);
6819 p = zipmapRewind(zm);
6820 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
6821 robj *keyobj, *valobj;
6822
6823 keyobj = createStringObject((char*)key,klen);
6824 valobj = createStringObject((char*)val,vlen);
6825 keyobj = tryObjectEncoding(keyobj);
6826 valobj = tryObjectEncoding(valobj);
6827 dictAdd(dict,keyobj,valobj);
6828 }
6829 o->encoding = REDIS_ENCODING_HT;
6830 o->ptr = dict;
6831 zfree(zm);
6832 }
6833
6834 /* ========================= Non type-specific commands ==================== */
6835
6836 static void flushdbCommand(redisClient *c) {
6837 server.dirty += dictSize(c->db->dict);
6838 touchWatchedKeysOnFlush(c->db->id);
6839 dictEmpty(c->db->dict);
6840 dictEmpty(c->db->expires);
6841 addReply(c,shared.ok);
6842 }
6843
6844 static void flushallCommand(redisClient *c) {
6845 touchWatchedKeysOnFlush(-1);
6846 server.dirty += emptyDb();
6847 addReply(c,shared.ok);
6848 if (server.bgsavechildpid != -1) {
6849 kill(server.bgsavechildpid,SIGKILL);
6850 rdbRemoveTempFile(server.bgsavechildpid);
6851 }
6852 rdbSave(server.dbfilename);
6853 server.dirty++;
6854 }
6855
6856 static redisSortOperation *createSortOperation(int type, robj *pattern) {
6857 redisSortOperation *so = zmalloc(sizeof(*so));
6858 so->type = type;
6859 so->pattern = pattern;
6860 return so;
6861 }
6862
6863 /* Return the value associated to the key with a name obtained
6864 * substituting the first occurence of '*' in 'pattern' with 'subst'.
6865 * The returned object will always have its refcount increased by 1
6866 * when it is non-NULL. */
6867 static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
6868 char *p, *f;
6869 sds spat, ssub;
6870 robj keyobj, fieldobj, *o;
6871 int prefixlen, sublen, postfixlen, fieldlen;
6872 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6873 struct {
6874 long len;
6875 long free;
6876 char buf[REDIS_SORTKEY_MAX+1];
6877 } keyname, fieldname;
6878
6879 /* If the pattern is "#" return the substitution object itself in order
6880 * to implement the "SORT ... GET #" feature. */
6881 spat = pattern->ptr;
6882 if (spat[0] == '#' && spat[1] == '\0') {
6883 incrRefCount(subst);
6884 return subst;
6885 }
6886
6887 /* The substitution object may be specially encoded. If so we create
6888 * a decoded object on the fly. Otherwise getDecodedObject will just
6889 * increment the ref count, that we'll decrement later. */
6890 subst = getDecodedObject(subst);
6891
6892 ssub = subst->ptr;
6893 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
6894 p = strchr(spat,'*');
6895 if (!p) {
6896 decrRefCount(subst);
6897 return NULL;
6898 }
6899
6900 /* Find out if we're dealing with a hash dereference. */
6901 if ((f = strstr(p+1, "->")) != NULL) {
6902 fieldlen = sdslen(spat)-(f-spat);
6903 /* this also copies \0 character */
6904 memcpy(fieldname.buf,f+2,fieldlen-1);
6905 fieldname.len = fieldlen-2;
6906 } else {
6907 fieldlen = 0;
6908 }
6909
6910 prefixlen = p-spat;
6911 sublen = sdslen(ssub);
6912 postfixlen = sdslen(spat)-(prefixlen+1)-fieldlen;
6913 memcpy(keyname.buf,spat,prefixlen);
6914 memcpy(keyname.buf+prefixlen,ssub,sublen);
6915 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
6916 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
6917 keyname.len = prefixlen+sublen+postfixlen;
6918 decrRefCount(subst);
6919
6920 /* Lookup substituted key */
6921 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2));
6922 o = lookupKeyRead(db,&keyobj);
6923 if (o == NULL) return NULL;
6924
6925 if (fieldlen > 0) {
6926 if (o->type != REDIS_HASH || fieldname.len < 1) return NULL;
6927
6928 /* Retrieve value from hash by the field name. This operation
6929 * already increases the refcount of the returned object. */
6930 initStaticStringObject(fieldobj,((char*)&fieldname)+(sizeof(long)*2));
6931 o = hashGet(o, &fieldobj);
6932 } else {
6933 if (o->type != REDIS_STRING) return NULL;
6934
6935 /* Every object that this function returns needs to have its refcount
6936 * increased. sortCommand decreases it again. */
6937 incrRefCount(o);
6938 }
6939
6940 return o;
6941 }
6942
6943 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6944 * the additional parameter is not standard but a BSD-specific we have to
6945 * pass sorting parameters via the global 'server' structure */
6946 static int sortCompare(const void *s1, const void *s2) {
6947 const redisSortObject *so1 = s1, *so2 = s2;
6948 int cmp;
6949
6950 if (!server.sort_alpha) {
6951 /* Numeric sorting. Here it's trivial as we precomputed scores */
6952 if (so1->u.score > so2->u.score) {
6953 cmp = 1;
6954 } else if (so1->u.score < so2->u.score) {
6955 cmp = -1;
6956 } else {
6957 cmp = 0;
6958 }
6959 } else {
6960 /* Alphanumeric sorting */
6961 if (server.sort_bypattern) {
6962 if (!so1->u.cmpobj || !so2->u.cmpobj) {
6963 /* At least one compare object is NULL */
6964 if (so1->u.cmpobj == so2->u.cmpobj)
6965 cmp = 0;
6966 else if (so1->u.cmpobj == NULL)
6967 cmp = -1;
6968 else
6969 cmp = 1;
6970 } else {
6971 /* We have both the objects, use strcoll */
6972 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
6973 }
6974 } else {
6975 /* Compare elements directly. */
6976 cmp = compareStringObjects(so1->obj,so2->obj);
6977 }
6978 }
6979 return server.sort_desc ? -cmp : cmp;
6980 }
6981
6982 /* The SORT command is the most complex command in Redis. Warning: this code
6983 * is optimized for speed and a bit less for readability */
6984 static void sortCommand(redisClient *c) {
6985 list *operations;
6986 int outputlen = 0;
6987 int desc = 0, alpha = 0;
6988 int limit_start = 0, limit_count = -1, start, end;
6989 int j, dontsort = 0, vectorlen;
6990 int getop = 0; /* GET operation counter */
6991 robj *sortval, *sortby = NULL, *storekey = NULL;
6992 redisSortObject *vector; /* Resulting vector to sort */
6993
6994 /* Lookup the key to sort. It must be of the right types */
6995 sortval = lookupKeyRead(c->db,c->argv[1]);
6996 if (sortval == NULL) {
6997 addReply(c,shared.emptymultibulk);
6998 return;
6999 }
7000 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
7001 sortval->type != REDIS_ZSET)
7002 {
7003 addReply(c,shared.wrongtypeerr);
7004 return;
7005 }
7006
7007 /* Create a list of operations to perform for every sorted element.
7008 * Operations can be GET/DEL/INCR/DECR */
7009 operations = listCreate();
7010 listSetFreeMethod(operations,zfree);
7011 j = 2;
7012
7013 /* Now we need to protect sortval incrementing its count, in the future
7014 * SORT may have options able to overwrite/delete keys during the sorting
7015 * and the sorted key itself may get destroied */
7016 incrRefCount(sortval);
7017
7018 /* The SORT command has an SQL-alike syntax, parse it */
7019 while(j < c->argc) {
7020 int leftargs = c->argc-j-1;
7021 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
7022 desc = 0;
7023 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
7024 desc = 1;
7025 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
7026 alpha = 1;
7027 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
7028 limit_start = atoi(c->argv[j+1]->ptr);
7029 limit_count = atoi(c->argv[j+2]->ptr);
7030 j+=2;
7031 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
7032 storekey = c->argv[j+1];
7033 j++;
7034 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
7035 sortby = c->argv[j+1];
7036 /* If the BY pattern does not contain '*', i.e. it is constant,
7037 * we don't need to sort nor to lookup the weight keys. */
7038 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
7039 j++;
7040 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
7041 listAddNodeTail(operations,createSortOperation(
7042 REDIS_SORT_GET,c->argv[j+1]));
7043 getop++;
7044 j++;
7045 } else {
7046 decrRefCount(sortval);
7047 listRelease(operations);
7048 addReply(c,shared.syntaxerr);
7049 return;
7050 }
7051 j++;
7052 }
7053
7054 /* Load the sorting vector with all the objects to sort */
7055 switch(sortval->type) {
7056 case REDIS_LIST: vectorlen = listLength((list*)sortval->ptr); break;
7057 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
7058 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
7059 default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
7060 }
7061 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
7062 j = 0;
7063
7064 if (sortval->type == REDIS_LIST) {
7065 list *list = sortval->ptr;
7066 listNode *ln;
7067 listIter li;
7068
7069 listRewind(list,&li);
7070 while((ln = listNext(&li))) {
7071 robj *ele = ln->value;
7072 vector[j].obj = ele;
7073 vector[j].u.score = 0;
7074 vector[j].u.cmpobj = NULL;
7075 j++;
7076 }
7077 } else {
7078 dict *set;
7079 dictIterator *di;
7080 dictEntry *setele;
7081
7082 if (sortval->type == REDIS_SET) {
7083 set = sortval->ptr;
7084 } else {
7085 zset *zs = sortval->ptr;
7086 set = zs->dict;
7087 }
7088
7089 di = dictGetIterator(set);
7090 while((setele = dictNext(di)) != NULL) {
7091 vector[j].obj = dictGetEntryKey(setele);
7092 vector[j].u.score = 0;
7093 vector[j].u.cmpobj = NULL;
7094 j++;
7095 }
7096 dictReleaseIterator(di);
7097 }
7098 redisAssert(j == vectorlen);
7099
7100 /* Now it's time to load the right scores in the sorting vector */
7101 if (dontsort == 0) {
7102 for (j = 0; j < vectorlen; j++) {
7103 robj *byval;
7104 if (sortby) {
7105 /* lookup value to sort by */
7106 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
7107 if (!byval) continue;
7108 } else {
7109 /* use object itself to sort by */
7110 byval = vector[j].obj;
7111 }
7112
7113 if (alpha) {
7114 if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
7115 } else {
7116 if (byval->encoding == REDIS_ENCODING_RAW) {
7117 vector[j].u.score = strtod(byval->ptr,NULL);
7118 } else if (byval->encoding == REDIS_ENCODING_INT) {
7119 /* Don't need to decode the object if it's
7120 * integer-encoded (the only encoding supported) so
7121 * far. We can just cast it */
7122 vector[j].u.score = (long)byval->ptr;
7123 } else {
7124 redisAssert(1 != 1);
7125 }
7126 }
7127
7128 /* when the object was retrieved using lookupKeyByPattern,
7129 * its refcount needs to be decreased. */
7130 if (sortby) {
7131 decrRefCount(byval);
7132 }
7133 }
7134 }
7135
7136 /* We are ready to sort the vector... perform a bit of sanity check
7137 * on the LIMIT option too. We'll use a partial version of quicksort. */
7138 start = (limit_start < 0) ? 0 : limit_start;
7139 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
7140 if (start >= vectorlen) {
7141 start = vectorlen-1;
7142 end = vectorlen-2;
7143 }
7144 if (end >= vectorlen) end = vectorlen-1;
7145
7146 if (dontsort == 0) {
7147 server.sort_desc = desc;
7148 server.sort_alpha = alpha;
7149 server.sort_bypattern = sortby ? 1 : 0;
7150 if (sortby && (start != 0 || end != vectorlen-1))
7151 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
7152 else
7153 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
7154 }
7155
7156 /* Send command output to the output buffer, performing the specified
7157 * GET/DEL/INCR/DECR operations if any. */
7158 outputlen = getop ? getop*(end-start+1) : end-start+1;
7159 if (storekey == NULL) {
7160 /* STORE option not specified, sent the sorting result to client */
7161 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
7162 for (j = start; j <= end; j++) {
7163 listNode *ln;
7164 listIter li;
7165
7166 if (!getop) addReplyBulk(c,vector[j].obj);
7167 listRewind(operations,&li);
7168 while((ln = listNext(&li))) {
7169 redisSortOperation *sop = ln->value;
7170 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7171 vector[j].obj);
7172
7173 if (sop->type == REDIS_SORT_GET) {
7174 if (!val) {
7175 addReply(c,shared.nullbulk);
7176 } else {
7177 addReplyBulk(c,val);
7178 decrRefCount(val);
7179 }
7180 } else {
7181 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
7182 }
7183 }
7184 }
7185 } else {
7186 robj *listObject = createListObject();
7187 list *listPtr = (list*) listObject->ptr;
7188
7189 /* STORE option specified, set the sorting result as a List object */
7190 for (j = start; j <= end; j++) {
7191 listNode *ln;
7192 listIter li;
7193
7194 if (!getop) {
7195 listAddNodeTail(listPtr,vector[j].obj);
7196 incrRefCount(vector[j].obj);
7197 }
7198 listRewind(operations,&li);
7199 while((ln = listNext(&li))) {
7200 redisSortOperation *sop = ln->value;
7201 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7202 vector[j].obj);
7203
7204 if (sop->type == REDIS_SORT_GET) {
7205 if (!val) {
7206 listAddNodeTail(listPtr,createStringObject("",0));
7207 } else {
7208 /* We should do a incrRefCount on val because it is
7209 * added to the list, but also a decrRefCount because
7210 * it is returned by lookupKeyByPattern. This results
7211 * in doing nothing at all. */
7212 listAddNodeTail(listPtr,val);
7213 }
7214 } else {
7215 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
7216 }
7217 }
7218 }
7219 if (dictReplace(c->db->dict,storekey,listObject)) {
7220 incrRefCount(storekey);
7221 }
7222 /* Note: we add 1 because the DB is dirty anyway since even if the
7223 * SORT result is empty a new key is set and maybe the old content
7224 * replaced. */
7225 server.dirty += 1+outputlen;
7226 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
7227 }
7228
7229 /* Cleanup */
7230 decrRefCount(sortval);
7231 listRelease(operations);
7232 for (j = 0; j < vectorlen; j++) {
7233 if (alpha && vector[j].u.cmpobj)
7234 decrRefCount(vector[j].u.cmpobj);
7235 }
7236 zfree(vector);
7237 }
7238
7239 /* Convert an amount of bytes into a human readable string in the form
7240 * of 100B, 2G, 100M, 4K, and so forth. */
7241 static void bytesToHuman(char *s, unsigned long long n) {
7242 double d;
7243
7244 if (n < 1024) {
7245 /* Bytes */
7246 sprintf(s,"%lluB",n);
7247 return;
7248 } else if (n < (1024*1024)) {
7249 d = (double)n/(1024);
7250 sprintf(s,"%.2fK",d);
7251 } else if (n < (1024LL*1024*1024)) {
7252 d = (double)n/(1024*1024);
7253 sprintf(s,"%.2fM",d);
7254 } else if (n < (1024LL*1024*1024*1024)) {
7255 d = (double)n/(1024LL*1024*1024);
7256 sprintf(s,"%.2fG",d);
7257 }
7258 }
7259
7260 /* Create the string returned by the INFO command. This is decoupled
7261 * by the INFO command itself as we need to report the same information
7262 * on memory corruption problems. */
7263 static sds genRedisInfoString(void) {
7264 sds info;
7265 time_t uptime = time(NULL)-server.stat_starttime;
7266 int j;
7267 char hmem[64];
7268
7269 bytesToHuman(hmem,zmalloc_used_memory());
7270 info = sdscatprintf(sdsempty(),
7271 "redis_version:%s\r\n"
7272 "redis_git_sha1:%s\r\n"
7273 "redis_git_dirty:%d\r\n"
7274 "arch_bits:%s\r\n"
7275 "multiplexing_api:%s\r\n"
7276 "process_id:%ld\r\n"
7277 "uptime_in_seconds:%ld\r\n"
7278 "uptime_in_days:%ld\r\n"
7279 "connected_clients:%d\r\n"
7280 "connected_slaves:%d\r\n"
7281 "blocked_clients:%d\r\n"
7282 "used_memory:%zu\r\n"
7283 "used_memory_human:%s\r\n"
7284 "changes_since_last_save:%lld\r\n"
7285 "bgsave_in_progress:%d\r\n"
7286 "last_save_time:%ld\r\n"
7287 "bgrewriteaof_in_progress:%d\r\n"
7288 "total_connections_received:%lld\r\n"
7289 "total_commands_processed:%lld\r\n"
7290 "expired_keys:%lld\r\n"
7291 "hash_max_zipmap_entries:%zu\r\n"
7292 "hash_max_zipmap_value:%zu\r\n"
7293 "pubsub_channels:%ld\r\n"
7294 "pubsub_patterns:%u\r\n"
7295 "vm_enabled:%d\r\n"
7296 "role:%s\r\n"
7297 ,REDIS_VERSION,
7298 REDIS_GIT_SHA1,
7299 strtol(REDIS_GIT_DIRTY,NULL,10) > 0,
7300 (sizeof(long) == 8) ? "64" : "32",
7301 aeGetApiName(),
7302 (long) getpid(),
7303 uptime,
7304 uptime/(3600*24),
7305 listLength(server.clients)-listLength(server.slaves),
7306 listLength(server.slaves),
7307 server.blpop_blocked_clients,
7308 zmalloc_used_memory(),
7309 hmem,
7310 server.dirty,
7311 server.bgsavechildpid != -1,
7312 server.lastsave,
7313 server.bgrewritechildpid != -1,
7314 server.stat_numconnections,
7315 server.stat_numcommands,
7316 server.stat_expiredkeys,
7317 server.hash_max_zipmap_entries,
7318 server.hash_max_zipmap_value,
7319 dictSize(server.pubsub_channels),
7320 listLength(server.pubsub_patterns),
7321 server.vm_enabled != 0,
7322 server.masterhost == NULL ? "master" : "slave"
7323 );
7324 if (server.masterhost) {
7325 info = sdscatprintf(info,
7326 "master_host:%s\r\n"
7327 "master_port:%d\r\n"
7328 "master_link_status:%s\r\n"
7329 "master_last_io_seconds_ago:%d\r\n"
7330 ,server.masterhost,
7331 server.masterport,
7332 (server.replstate == REDIS_REPL_CONNECTED) ?
7333 "up" : "down",
7334 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
7335 );
7336 }
7337 if (server.vm_enabled) {
7338 lockThreadedIO();
7339 info = sdscatprintf(info,
7340 "vm_conf_max_memory:%llu\r\n"
7341 "vm_conf_page_size:%llu\r\n"
7342 "vm_conf_pages:%llu\r\n"
7343 "vm_stats_used_pages:%llu\r\n"
7344 "vm_stats_swapped_objects:%llu\r\n"
7345 "vm_stats_swappin_count:%llu\r\n"
7346 "vm_stats_swappout_count:%llu\r\n"
7347 "vm_stats_io_newjobs_len:%lu\r\n"
7348 "vm_stats_io_processing_len:%lu\r\n"
7349 "vm_stats_io_processed_len:%lu\r\n"
7350 "vm_stats_io_active_threads:%lu\r\n"
7351 "vm_stats_blocked_clients:%lu\r\n"
7352 ,(unsigned long long) server.vm_max_memory,
7353 (unsigned long long) server.vm_page_size,
7354 (unsigned long long) server.vm_pages,
7355 (unsigned long long) server.vm_stats_used_pages,
7356 (unsigned long long) server.vm_stats_swapped_objects,
7357 (unsigned long long) server.vm_stats_swapins,
7358 (unsigned long long) server.vm_stats_swapouts,
7359 (unsigned long) listLength(server.io_newjobs),
7360 (unsigned long) listLength(server.io_processing),
7361 (unsigned long) listLength(server.io_processed),
7362 (unsigned long) server.io_active_threads,
7363 (unsigned long) server.vm_blocked_clients
7364 );
7365 unlockThreadedIO();
7366 }
7367 for (j = 0; j < server.dbnum; j++) {
7368 long long keys, vkeys;
7369
7370 keys = dictSize(server.db[j].dict);
7371 vkeys = dictSize(server.db[j].expires);
7372 if (keys || vkeys) {
7373 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
7374 j, keys, vkeys);
7375 }
7376 }
7377 return info;
7378 }
7379
7380 static void infoCommand(redisClient *c) {
7381 sds info = genRedisInfoString();
7382 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
7383 (unsigned long)sdslen(info)));
7384 addReplySds(c,info);
7385 addReply(c,shared.crlf);
7386 }
7387
7388 static void monitorCommand(redisClient *c) {
7389 /* ignore MONITOR if aleady slave or in monitor mode */
7390 if (c->flags & REDIS_SLAVE) return;
7391
7392 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
7393 c->slaveseldb = 0;
7394 listAddNodeTail(server.monitors,c);
7395 addReply(c,shared.ok);
7396 }
7397
7398 /* ================================= Expire ================================= */
7399 static int removeExpire(redisDb *db, robj *key) {
7400 if (dictDelete(db->expires,key) == DICT_OK) {
7401 return 1;
7402 } else {
7403 return 0;
7404 }
7405 }
7406
7407 static int setExpire(redisDb *db, robj *key, time_t when) {
7408 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
7409 return 0;
7410 } else {
7411 incrRefCount(key);
7412 return 1;
7413 }
7414 }
7415
7416 /* Return the expire time of the specified key, or -1 if no expire
7417 * is associated with this key (i.e. the key is non volatile) */
7418 static time_t getExpire(redisDb *db, robj *key) {
7419 dictEntry *de;
7420
7421 /* No expire? return ASAP */
7422 if (dictSize(db->expires) == 0 ||
7423 (de = dictFind(db->expires,key)) == NULL) return -1;
7424
7425 return (time_t) dictGetEntryVal(de);
7426 }
7427
7428 static int expireIfNeeded(redisDb *db, robj *key) {
7429 time_t when;
7430 dictEntry *de;
7431
7432 /* No expire? return ASAP */
7433 if (dictSize(db->expires) == 0 ||
7434 (de = dictFind(db->expires,key)) == NULL) return 0;
7435
7436 /* Lookup the expire */
7437 when = (time_t) dictGetEntryVal(de);
7438 if (time(NULL) <= when) return 0;
7439
7440 /* Delete the key */
7441 dictDelete(db->expires,key);
7442 server.stat_expiredkeys++;
7443 return dictDelete(db->dict,key) == DICT_OK;
7444 }
7445
7446 static int deleteIfVolatile(redisDb *db, robj *key) {
7447 dictEntry *de;
7448
7449 /* No expire? return ASAP */
7450 if (dictSize(db->expires) == 0 ||
7451 (de = dictFind(db->expires,key)) == NULL) return 0;
7452
7453 /* Delete the key */
7454 server.dirty++;
7455 server.stat_expiredkeys++;
7456 dictDelete(db->expires,key);
7457 return dictDelete(db->dict,key) == DICT_OK;
7458 }
7459
7460 static void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
7461 dictEntry *de;
7462 time_t seconds;
7463
7464 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
7465
7466 seconds -= offset;
7467
7468 de = dictFind(c->db->dict,key);
7469 if (de == NULL) {
7470 addReply(c,shared.czero);
7471 return;
7472 }
7473 if (seconds <= 0) {
7474 if (deleteKey(c->db,key)) server.dirty++;
7475 addReply(c, shared.cone);
7476 return;
7477 } else {
7478 time_t when = time(NULL)+seconds;
7479 if (setExpire(c->db,key,when)) {
7480 addReply(c,shared.cone);
7481 server.dirty++;
7482 } else {
7483 addReply(c,shared.czero);
7484 }
7485 return;
7486 }
7487 }
7488
7489 static void expireCommand(redisClient *c) {
7490 expireGenericCommand(c,c->argv[1],c->argv[2],0);
7491 }
7492
7493 static void expireatCommand(redisClient *c) {
7494 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
7495 }
7496
7497 static void ttlCommand(redisClient *c) {
7498 time_t expire;
7499 int ttl = -1;
7500
7501 expire = getExpire(c->db,c->argv[1]);
7502 if (expire != -1) {
7503 ttl = (int) (expire-time(NULL));
7504 if (ttl < 0) ttl = -1;
7505 }
7506 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
7507 }
7508
7509 /* ================================ MULTI/EXEC ============================== */
7510
7511 /* Client state initialization for MULTI/EXEC */
7512 static void initClientMultiState(redisClient *c) {
7513 c->mstate.commands = NULL;
7514 c->mstate.count = 0;
7515 }
7516
7517 /* Release all the resources associated with MULTI/EXEC state */
7518 static void freeClientMultiState(redisClient *c) {
7519 int j;
7520
7521 for (j = 0; j < c->mstate.count; j++) {
7522 int i;
7523 multiCmd *mc = c->mstate.commands+j;
7524
7525 for (i = 0; i < mc->argc; i++)
7526 decrRefCount(mc->argv[i]);
7527 zfree(mc->argv);
7528 }
7529 zfree(c->mstate.commands);
7530 }
7531
7532 /* Add a new command into the MULTI commands queue */
7533 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
7534 multiCmd *mc;
7535 int j;
7536
7537 c->mstate.commands = zrealloc(c->mstate.commands,
7538 sizeof(multiCmd)*(c->mstate.count+1));
7539 mc = c->mstate.commands+c->mstate.count;
7540 mc->cmd = cmd;
7541 mc->argc = c->argc;
7542 mc->argv = zmalloc(sizeof(robj*)*c->argc);
7543 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
7544 for (j = 0; j < c->argc; j++)
7545 incrRefCount(mc->argv[j]);
7546 c->mstate.count++;
7547 }
7548
7549 static void multiCommand(redisClient *c) {
7550 if (c->flags & REDIS_MULTI) {
7551 addReplySds(c,sdsnew("-ERR MULTI calls can not be nested\r\n"));
7552 return;
7553 }
7554 c->flags |= REDIS_MULTI;
7555 addReply(c,shared.ok);
7556 }
7557
7558 static void discardCommand(redisClient *c) {
7559 if (!(c->flags & REDIS_MULTI)) {
7560 addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
7561 return;
7562 }
7563
7564 freeClientMultiState(c);
7565 initClientMultiState(c);
7566 c->flags &= (~REDIS_MULTI);
7567 addReply(c,shared.ok);
7568 }
7569
7570 /* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7571 * implememntation for more information. */
7572 static void execCommandReplicateMulti(redisClient *c) {
7573 struct redisCommand *cmd;
7574 robj *multistring = createStringObject("MULTI",5);
7575
7576 cmd = lookupCommand("multi");
7577 if (server.appendonly)
7578 feedAppendOnlyFile(cmd,c->db->id,&multistring,1);
7579 if (listLength(server.slaves))
7580 replicationFeedSlaves(server.slaves,c->db->id,&multistring,1);
7581 decrRefCount(multistring);
7582 }
7583
7584 static void execCommand(redisClient *c) {
7585 int j;
7586 robj **orig_argv;
7587 int orig_argc;
7588
7589 if (!(c->flags & REDIS_MULTI)) {
7590 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
7591 return;
7592 }
7593
7594 /* Check if we need to abort the EXEC if some WATCHed key was touched.
7595 * A failed EXEC will return a multi bulk nil object. */
7596 if (c->flags & REDIS_DIRTY_CAS) {
7597 freeClientMultiState(c);
7598 initClientMultiState(c);
7599 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
7600 unwatchAllKeys(c);
7601 addReply(c,shared.nullmultibulk);
7602 return;
7603 }
7604
7605 /* Replicate a MULTI request now that we are sure the block is executed.
7606 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7607 * both the AOF and the replication link will have the same consistency
7608 * and atomicity guarantees. */
7609 execCommandReplicateMulti(c);
7610
7611 /* Exec all the queued commands */
7612 unwatchAllKeys(c); /* Unwatch ASAP otherwise we'll waste CPU cycles */
7613 orig_argv = c->argv;
7614 orig_argc = c->argc;
7615 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
7616 for (j = 0; j < c->mstate.count; j++) {
7617 c->argc = c->mstate.commands[j].argc;
7618 c->argv = c->mstate.commands[j].argv;
7619 call(c,c->mstate.commands[j].cmd);
7620 }
7621 c->argv = orig_argv;
7622 c->argc = orig_argc;
7623 freeClientMultiState(c);
7624 initClientMultiState(c);
7625 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
7626 /* Make sure the EXEC command is always replicated / AOF, since we
7627 * always send the MULTI command (we can't know beforehand if the
7628 * next operations will contain at least a modification to the DB). */
7629 server.dirty++;
7630 }
7631
7632 /* =========================== Blocking Operations ========================= */
7633
7634 /* Currently Redis blocking operations support is limited to list POP ops,
7635 * so the current implementation is not fully generic, but it is also not
7636 * completely specific so it will not require a rewrite to support new
7637 * kind of blocking operations in the future.
7638 *
7639 * Still it's important to note that list blocking operations can be already
7640 * used as a notification mechanism in order to implement other blocking
7641 * operations at application level, so there must be a very strong evidence
7642 * of usefulness and generality before new blocking operations are implemented.
7643 *
7644 * This is how the current blocking POP works, we use BLPOP as example:
7645 * - If the user calls BLPOP and the key exists and contains a non empty list
7646 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7647 * if there is not to block.
7648 * - If instead BLPOP is called and the key does not exists or the list is
7649 * empty we need to block. In order to do so we remove the notification for
7650 * new data to read in the client socket (so that we'll not serve new
7651 * requests if the blocking request is not served). Also we put the client
7652 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
7653 * blocking for this keys.
7654 * - If a PUSH operation against a key with blocked clients waiting is
7655 * performed, we serve the first in the list: basically instead to push
7656 * the new element inside the list we return it to the (first / oldest)
7657 * blocking client, unblock the client, and remove it form the list.
7658 *
7659 * The above comment and the source code should be enough in order to understand
7660 * the implementation and modify / fix it later.
7661 */
7662
7663 /* Set a client in blocking mode for the specified key, with the specified
7664 * timeout */
7665 static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
7666 dictEntry *de;
7667 list *l;
7668 int j;
7669
7670 c->blocking_keys = zmalloc(sizeof(robj*)*numkeys);
7671 c->blocking_keys_num = numkeys;
7672 c->blockingto = timeout;
7673 for (j = 0; j < numkeys; j++) {
7674 /* Add the key in the client structure, to map clients -> keys */
7675 c->blocking_keys[j] = keys[j];
7676 incrRefCount(keys[j]);
7677
7678 /* And in the other "side", to map keys -> clients */
7679 de = dictFind(c->db->blocking_keys,keys[j]);
7680 if (de == NULL) {
7681 int retval;
7682
7683 /* For every key we take a list of clients blocked for it */
7684 l = listCreate();
7685 retval = dictAdd(c->db->blocking_keys,keys[j],l);
7686 incrRefCount(keys[j]);
7687 assert(retval == DICT_OK);
7688 } else {
7689 l = dictGetEntryVal(de);
7690 }
7691 listAddNodeTail(l,c);
7692 }
7693 /* Mark the client as a blocked client */
7694 c->flags |= REDIS_BLOCKED;
7695 server.blpop_blocked_clients++;
7696 }
7697
7698 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
7699 static void unblockClientWaitingData(redisClient *c) {
7700 dictEntry *de;
7701 list *l;
7702 int j;
7703
7704 assert(c->blocking_keys != NULL);
7705 /* The client may wait for multiple keys, so unblock it for every key. */
7706 for (j = 0; j < c->blocking_keys_num; j++) {
7707 /* Remove this client from the list of clients waiting for this key. */
7708 de = dictFind(c->db->blocking_keys,c->blocking_keys[j]);
7709 assert(de != NULL);
7710 l = dictGetEntryVal(de);
7711 listDelNode(l,listSearchKey(l,c));
7712 /* If the list is empty we need to remove it to avoid wasting memory */
7713 if (listLength(l) == 0)
7714 dictDelete(c->db->blocking_keys,c->blocking_keys[j]);
7715 decrRefCount(c->blocking_keys[j]);
7716 }
7717 /* Cleanup the client structure */
7718 zfree(c->blocking_keys);
7719 c->blocking_keys = NULL;
7720 c->flags &= (~REDIS_BLOCKED);
7721 server.blpop_blocked_clients--;
7722 /* We want to process data if there is some command waiting
7723 * in the input buffer. Note that this is safe even if
7724 * unblockClientWaitingData() gets called from freeClient() because
7725 * freeClient() will be smart enough to call this function
7726 * *after* c->querybuf was set to NULL. */
7727 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
7728 }
7729
7730 /* This should be called from any function PUSHing into lists.
7731 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7732 * 'ele' is the element pushed.
7733 *
7734 * If the function returns 0 there was no client waiting for a list push
7735 * against this key.
7736 *
7737 * If the function returns 1 there was a client waiting for a list push
7738 * against this key, the element was passed to this client thus it's not
7739 * needed to actually add it to the list and the caller should return asap. */
7740 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
7741 struct dictEntry *de;
7742 redisClient *receiver;
7743 list *l;
7744 listNode *ln;
7745
7746 de = dictFind(c->db->blocking_keys,key);
7747 if (de == NULL) return 0;
7748 l = dictGetEntryVal(de);
7749 ln = listFirst(l);
7750 assert(ln != NULL);
7751 receiver = ln->value;
7752
7753 addReplySds(receiver,sdsnew("*2\r\n"));
7754 addReplyBulk(receiver,key);
7755 addReplyBulk(receiver,ele);
7756 unblockClientWaitingData(receiver);
7757 return 1;
7758 }
7759
7760 /* Blocking RPOP/LPOP */
7761 static void blockingPopGenericCommand(redisClient *c, int where) {
7762 robj *o;
7763 time_t timeout;
7764 int j;
7765
7766 for (j = 1; j < c->argc-1; j++) {
7767 o = lookupKeyWrite(c->db,c->argv[j]);
7768 if (o != NULL) {
7769 if (o->type != REDIS_LIST) {
7770 addReply(c,shared.wrongtypeerr);
7771 return;
7772 } else {
7773 list *list = o->ptr;
7774 if (listLength(list) != 0) {
7775 /* If the list contains elements fall back to the usual
7776 * non-blocking POP operation */
7777 robj *argv[2], **orig_argv;
7778 int orig_argc;
7779
7780 /* We need to alter the command arguments before to call
7781 * popGenericCommand() as the command takes a single key. */
7782 orig_argv = c->argv;
7783 orig_argc = c->argc;
7784 argv[1] = c->argv[j];
7785 c->argv = argv;
7786 c->argc = 2;
7787
7788 /* Also the return value is different, we need to output
7789 * the multi bulk reply header and the key name. The
7790 * "real" command will add the last element (the value)
7791 * for us. If this souds like an hack to you it's just
7792 * because it is... */
7793 addReplySds(c,sdsnew("*2\r\n"));
7794 addReplyBulk(c,argv[1]);
7795 popGenericCommand(c,where);
7796
7797 /* Fix the client structure with the original stuff */
7798 c->argv = orig_argv;
7799 c->argc = orig_argc;
7800 return;
7801 }
7802 }
7803 }
7804 }
7805 /* If the list is empty or the key does not exists we must block */
7806 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
7807 if (timeout > 0) timeout += time(NULL);
7808 blockForKeys(c,c->argv+1,c->argc-2,timeout);
7809 }
7810
7811 static void blpopCommand(redisClient *c) {
7812 blockingPopGenericCommand(c,REDIS_HEAD);
7813 }
7814
7815 static void brpopCommand(redisClient *c) {
7816 blockingPopGenericCommand(c,REDIS_TAIL);
7817 }
7818
7819 /* =============================== Replication ============================= */
7820
7821 static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
7822 ssize_t nwritten, ret = size;
7823 time_t start = time(NULL);
7824
7825 timeout++;
7826 while(size) {
7827 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
7828 nwritten = write(fd,ptr,size);
7829 if (nwritten == -1) return -1;
7830 ptr += nwritten;
7831 size -= nwritten;
7832 }
7833 if ((time(NULL)-start) > timeout) {
7834 errno = ETIMEDOUT;
7835 return -1;
7836 }
7837 }
7838 return ret;
7839 }
7840
7841 static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
7842 ssize_t nread, totread = 0;
7843 time_t start = time(NULL);
7844
7845 timeout++;
7846 while(size) {
7847 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
7848 nread = read(fd,ptr,size);
7849 if (nread == -1) return -1;
7850 ptr += nread;
7851 size -= nread;
7852 totread += nread;
7853 }
7854 if ((time(NULL)-start) > timeout) {
7855 errno = ETIMEDOUT;
7856 return -1;
7857 }
7858 }
7859 return totread;
7860 }
7861
7862 static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
7863 ssize_t nread = 0;
7864
7865 size--;
7866 while(size) {
7867 char c;
7868
7869 if (syncRead(fd,&c,1,timeout) == -1) return -1;
7870 if (c == '\n') {
7871 *ptr = '\0';
7872 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
7873 return nread;
7874 } else {
7875 *ptr++ = c;
7876 *ptr = '\0';
7877 nread++;
7878 }
7879 }
7880 return nread;
7881 }
7882
7883 static void syncCommand(redisClient *c) {
7884 /* ignore SYNC if aleady slave or in monitor mode */
7885 if (c->flags & REDIS_SLAVE) return;
7886
7887 /* SYNC can't be issued when the server has pending data to send to
7888 * the client about already issued commands. We need a fresh reply
7889 * buffer registering the differences between the BGSAVE and the current
7890 * dataset, so that we can copy to other slaves if needed. */
7891 if (listLength(c->reply) != 0) {
7892 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7893 return;
7894 }
7895
7896 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
7897 /* Here we need to check if there is a background saving operation
7898 * in progress, or if it is required to start one */
7899 if (server.bgsavechildpid != -1) {
7900 /* Ok a background save is in progress. Let's check if it is a good
7901 * one for replication, i.e. if there is another slave that is
7902 * registering differences since the server forked to save */
7903 redisClient *slave;
7904 listNode *ln;
7905 listIter li;
7906
7907 listRewind(server.slaves,&li);
7908 while((ln = listNext(&li))) {
7909 slave = ln->value;
7910 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
7911 }
7912 if (ln) {
7913 /* Perfect, the server is already registering differences for
7914 * another slave. Set the right state, and copy the buffer. */
7915 listRelease(c->reply);
7916 c->reply = listDup(slave->reply);
7917 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7918 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
7919 } else {
7920 /* No way, we need to wait for the next BGSAVE in order to
7921 * register differences */
7922 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
7923 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
7924 }
7925 } else {
7926 /* Ok we don't have a BGSAVE in progress, let's start one */
7927 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
7928 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
7929 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
7930 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
7931 return;
7932 }
7933 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7934 }
7935 c->repldbfd = -1;
7936 c->flags |= REDIS_SLAVE;
7937 c->slaveseldb = 0;
7938 listAddNodeTail(server.slaves,c);
7939 return;
7940 }
7941
7942 static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
7943 redisClient *slave = privdata;
7944 REDIS_NOTUSED(el);
7945 REDIS_NOTUSED(mask);
7946 char buf[REDIS_IOBUF_LEN];
7947 ssize_t nwritten, buflen;
7948
7949 if (slave->repldboff == 0) {
7950 /* Write the bulk write count before to transfer the DB. In theory here
7951 * we don't know how much room there is in the output buffer of the
7952 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7953 * operations) will never be smaller than the few bytes we need. */
7954 sds bulkcount;
7955
7956 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7957 slave->repldbsize);
7958 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
7959 {
7960 sdsfree(bulkcount);
7961 freeClient(slave);
7962 return;
7963 }
7964 sdsfree(bulkcount);
7965 }
7966 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
7967 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
7968 if (buflen <= 0) {
7969 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
7970 (buflen == 0) ? "premature EOF" : strerror(errno));
7971 freeClient(slave);
7972 return;
7973 }
7974 if ((nwritten = write(fd,buf,buflen)) == -1) {
7975 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
7976 strerror(errno));
7977 freeClient(slave);
7978 return;
7979 }
7980 slave->repldboff += nwritten;
7981 if (slave->repldboff == slave->repldbsize) {
7982 close(slave->repldbfd);
7983 slave->repldbfd = -1;
7984 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
7985 slave->replstate = REDIS_REPL_ONLINE;
7986 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
7987 sendReplyToClient, slave) == AE_ERR) {
7988 freeClient(slave);
7989 return;
7990 }
7991 addReplySds(slave,sdsempty());
7992 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
7993 }
7994 }
7995
7996 /* This function is called at the end of every backgrond saving.
7997 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
7998 * otherwise REDIS_ERR is passed to the function.
7999 *
8000 * The goal of this function is to handle slaves waiting for a successful
8001 * background saving in order to perform non-blocking synchronization. */
8002 static void updateSlavesWaitingBgsave(int bgsaveerr) {
8003 listNode *ln;
8004 int startbgsave = 0;
8005 listIter li;
8006
8007 listRewind(server.slaves,&li);
8008 while((ln = listNext(&li))) {
8009 redisClient *slave = ln->value;
8010
8011 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
8012 startbgsave = 1;
8013 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8014 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
8015 struct redis_stat buf;
8016
8017 if (bgsaveerr != REDIS_OK) {
8018 freeClient(slave);
8019 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
8020 continue;
8021 }
8022 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
8023 redis_fstat(slave->repldbfd,&buf) == -1) {
8024 freeClient(slave);
8025 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
8026 continue;
8027 }
8028 slave->repldboff = 0;
8029 slave->repldbsize = buf.st_size;
8030 slave->replstate = REDIS_REPL_SEND_BULK;
8031 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8032 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
8033 freeClient(slave);
8034 continue;
8035 }
8036 }
8037 }
8038 if (startbgsave) {
8039 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
8040 listIter li;
8041
8042 listRewind(server.slaves,&li);
8043 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
8044 while((ln = listNext(&li))) {
8045 redisClient *slave = ln->value;
8046
8047 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
8048 freeClient(slave);
8049 }
8050 }
8051 }
8052 }
8053
8054 static int syncWithMaster(void) {
8055 char buf[1024], tmpfile[256], authcmd[1024];
8056 long dumpsize;
8057 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
8058 int dfd, maxtries = 5;
8059
8060 if (fd == -1) {
8061 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
8062 strerror(errno));
8063 return REDIS_ERR;
8064 }
8065
8066 /* AUTH with the master if required. */
8067 if(server.masterauth) {
8068 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
8069 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
8070 close(fd);
8071 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
8072 strerror(errno));
8073 return REDIS_ERR;
8074 }
8075 /* Read the AUTH result. */
8076 if (syncReadLine(fd,buf,1024,3600) == -1) {
8077 close(fd);
8078 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
8079 strerror(errno));
8080 return REDIS_ERR;
8081 }
8082 if (buf[0] != '+') {
8083 close(fd);
8084 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
8085 return REDIS_ERR;
8086 }
8087 }
8088
8089 /* Issue the SYNC command */
8090 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
8091 close(fd);
8092 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
8093 strerror(errno));
8094 return REDIS_ERR;
8095 }
8096 /* Read the bulk write count */
8097 if (syncReadLine(fd,buf,1024,3600) == -1) {
8098 close(fd);
8099 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
8100 strerror(errno));
8101 return REDIS_ERR;
8102 }
8103 if (buf[0] != '$') {
8104 close(fd);
8105 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8106 return REDIS_ERR;
8107 }
8108 dumpsize = strtol(buf+1,NULL,10);
8109 redisLog(REDIS_NOTICE,"Receiving %ld bytes data dump from MASTER",dumpsize);
8110 /* Read the bulk write data on a temp file */
8111 while(maxtries--) {
8112 snprintf(tmpfile,256,
8113 "temp-%d.%ld.rdb",(int)time(NULL),(long int)getpid());
8114 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
8115 if (dfd != -1) break;
8116 sleep(1);
8117 }
8118 if (dfd == -1) {
8119 close(fd);
8120 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
8121 return REDIS_ERR;
8122 }
8123 while(dumpsize) {
8124 int nread, nwritten;
8125
8126 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
8127 if (nread == -1) {
8128 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
8129 strerror(errno));
8130 close(fd);
8131 close(dfd);
8132 return REDIS_ERR;
8133 }
8134 nwritten = write(dfd,buf,nread);
8135 if (nwritten == -1) {
8136 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
8137 close(fd);
8138 close(dfd);
8139 return REDIS_ERR;
8140 }
8141 dumpsize -= nread;
8142 }
8143 close(dfd);
8144 if (rename(tmpfile,server.dbfilename) == -1) {
8145 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
8146 unlink(tmpfile);
8147 close(fd);
8148 return REDIS_ERR;
8149 }
8150 emptyDb();
8151 if (rdbLoad(server.dbfilename) != REDIS_OK) {
8152 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
8153 close(fd);
8154 return REDIS_ERR;
8155 }
8156 server.master = createClient(fd);
8157 server.master->flags |= REDIS_MASTER;
8158 server.master->authenticated = 1;
8159 server.replstate = REDIS_REPL_CONNECTED;
8160 return REDIS_OK;
8161 }
8162
8163 static void slaveofCommand(redisClient *c) {
8164 if (!strcasecmp(c->argv[1]->ptr,"no") &&
8165 !strcasecmp(c->argv[2]->ptr,"one")) {
8166 if (server.masterhost) {
8167 sdsfree(server.masterhost);
8168 server.masterhost = NULL;
8169 if (server.master) freeClient(server.master);
8170 server.replstate = REDIS_REPL_NONE;
8171 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
8172 }
8173 } else {
8174 sdsfree(server.masterhost);
8175 server.masterhost = sdsdup(c->argv[1]->ptr);
8176 server.masterport = atoi(c->argv[2]->ptr);
8177 if (server.master) freeClient(server.master);
8178 server.replstate = REDIS_REPL_CONNECT;
8179 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
8180 server.masterhost, server.masterport);
8181 }
8182 addReply(c,shared.ok);
8183 }
8184
8185 /* ============================ Maxmemory directive ======================== */
8186
8187 /* Try to free one object form the pre-allocated objects free list.
8188 * This is useful under low mem conditions as by default we take 1 million
8189 * free objects allocated. On success REDIS_OK is returned, otherwise
8190 * REDIS_ERR. */
8191 static int tryFreeOneObjectFromFreelist(void) {
8192 robj *o;
8193
8194 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
8195 if (listLength(server.objfreelist)) {
8196 listNode *head = listFirst(server.objfreelist);
8197 o = listNodeValue(head);
8198 listDelNode(server.objfreelist,head);
8199 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8200 zfree(o);
8201 return REDIS_OK;
8202 } else {
8203 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8204 return REDIS_ERR;
8205 }
8206 }
8207
8208 /* This function gets called when 'maxmemory' is set on the config file to limit
8209 * the max memory used by the server, and we are out of memory.
8210 * This function will try to, in order:
8211 *
8212 * - Free objects from the free list
8213 * - Try to remove keys with an EXPIRE set
8214 *
8215 * It is not possible to free enough memory to reach used-memory < maxmemory
8216 * the server will start refusing commands that will enlarge even more the
8217 * memory usage.
8218 */
8219 static void freeMemoryIfNeeded(void) {
8220 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
8221 int j, k, freed = 0;
8222
8223 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
8224 for (j = 0; j < server.dbnum; j++) {
8225 int minttl = -1;
8226 robj *minkey = NULL;
8227 struct dictEntry *de;
8228
8229 if (dictSize(server.db[j].expires)) {
8230 freed = 1;
8231 /* From a sample of three keys drop the one nearest to
8232 * the natural expire */
8233 for (k = 0; k < 3; k++) {
8234 time_t t;
8235
8236 de = dictGetRandomKey(server.db[j].expires);
8237 t = (time_t) dictGetEntryVal(de);
8238 if (minttl == -1 || t < minttl) {
8239 minkey = dictGetEntryKey(de);
8240 minttl = t;
8241 }
8242 }
8243 deleteKey(server.db+j,minkey);
8244 }
8245 }
8246 if (!freed) return; /* nothing to free... */
8247 }
8248 }
8249
8250 /* ============================== Append Only file ========================== */
8251
8252 /* Write the append only file buffer on disk.
8253 *
8254 * Since we are required to write the AOF before replying to the client,
8255 * and the only way the client socket can get a write is entering when the
8256 * the event loop, we accumulate all the AOF writes in a memory
8257 * buffer and write it on disk using this function just before entering
8258 * the event loop again. */
8259 static void flushAppendOnlyFile(void) {
8260 time_t now;
8261 ssize_t nwritten;
8262
8263 if (sdslen(server.aofbuf) == 0) return;
8264
8265 /* We want to perform a single write. This should be guaranteed atomic
8266 * at least if the filesystem we are writing is a real physical one.
8267 * While this will save us against the server being killed I don't think
8268 * there is much to do about the whole server stopping for power problems
8269 * or alike */
8270 nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf));
8271 if (nwritten != (signed)sdslen(server.aofbuf)) {
8272 /* Ooops, we are in troubles. The best thing to do for now is
8273 * aborting instead of giving the illusion that everything is
8274 * working as expected. */
8275 if (nwritten == -1) {
8276 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
8277 } else {
8278 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
8279 }
8280 exit(1);
8281 }
8282 sdsfree(server.aofbuf);
8283 server.aofbuf = sdsempty();
8284
8285 /* Fsync if needed */
8286 now = time(NULL);
8287 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
8288 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
8289 now-server.lastfsync > 1))
8290 {
8291 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8292 * flushing metadata. */
8293 aof_fsync(server.appendfd); /* Let's try to get this data on the disk */
8294 server.lastfsync = now;
8295 }
8296 }
8297
8298 static sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) {
8299 int j;
8300 buf = sdscatprintf(buf,"*%d\r\n",argc);
8301 for (j = 0; j < argc; j++) {
8302 robj *o = getDecodedObject(argv[j]);
8303 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
8304 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
8305 buf = sdscatlen(buf,"\r\n",2);
8306 decrRefCount(o);
8307 }
8308 return buf;
8309 }
8310
8311 static sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) {
8312 int argc = 3;
8313 long when;
8314 robj *argv[3];
8315
8316 /* Make sure we can use strtol */
8317 seconds = getDecodedObject(seconds);
8318 when = time(NULL)+strtol(seconds->ptr,NULL,10);
8319 decrRefCount(seconds);
8320
8321 argv[0] = createStringObject("EXPIREAT",8);
8322 argv[1] = key;
8323 argv[2] = createObject(REDIS_STRING,
8324 sdscatprintf(sdsempty(),"%ld",when));
8325 buf = catAppendOnlyGenericCommand(buf, argc, argv);
8326 decrRefCount(argv[0]);
8327 decrRefCount(argv[2]);
8328 return buf;
8329 }
8330
8331 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
8332 sds buf = sdsempty();
8333 robj *tmpargv[3];
8334
8335 /* The DB this command was targetting is not the same as the last command
8336 * we appendend. To issue a SELECT command is needed. */
8337 if (dictid != server.appendseldb) {
8338 char seldb[64];
8339
8340 snprintf(seldb,sizeof(seldb),"%d",dictid);
8341 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
8342 (unsigned long)strlen(seldb),seldb);
8343 server.appendseldb = dictid;
8344 }
8345
8346 if (cmd->proc == expireCommand) {
8347 /* Translate EXPIRE into EXPIREAT */
8348 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8349 } else if (cmd->proc == setexCommand) {
8350 /* Translate SETEX to SET and EXPIREAT */
8351 tmpargv[0] = createStringObject("SET",3);
8352 tmpargv[1] = argv[1];
8353 tmpargv[2] = argv[3];
8354 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
8355 decrRefCount(tmpargv[0]);
8356 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8357 } else {
8358 buf = catAppendOnlyGenericCommand(buf,argc,argv);
8359 }
8360
8361 /* Append to the AOF buffer. This will be flushed on disk just before
8362 * of re-entering the event loop, so before the client will get a
8363 * positive reply about the operation performed. */
8364 server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf));
8365
8366 /* If a background append only file rewriting is in progress we want to
8367 * accumulate the differences between the child DB and the current one
8368 * in a buffer, so that when the child process will do its work we
8369 * can append the differences to the new append only file. */
8370 if (server.bgrewritechildpid != -1)
8371 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
8372
8373 sdsfree(buf);
8374 }
8375
8376 /* In Redis commands are always executed in the context of a client, so in
8377 * order to load the append only file we need to create a fake client. */
8378 static struct redisClient *createFakeClient(void) {
8379 struct redisClient *c = zmalloc(sizeof(*c));
8380
8381 selectDb(c,0);
8382 c->fd = -1;
8383 c->querybuf = sdsempty();
8384 c->argc = 0;
8385 c->argv = NULL;
8386 c->flags = 0;
8387 /* We set the fake client as a slave waiting for the synchronization
8388 * so that Redis will not try to send replies to this client. */
8389 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
8390 c->reply = listCreate();
8391 listSetFreeMethod(c->reply,decrRefCount);
8392 listSetDupMethod(c->reply,dupClientReplyValue);
8393 initClientMultiState(c);
8394 return c;
8395 }
8396
8397 static void freeFakeClient(struct redisClient *c) {
8398 sdsfree(c->querybuf);
8399 listRelease(c->reply);
8400 freeClientMultiState(c);
8401 zfree(c);
8402 }
8403
8404 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
8405 * error (the append only file is zero-length) REDIS_ERR is returned. On
8406 * fatal error an error message is logged and the program exists. */
8407 int loadAppendOnlyFile(char *filename) {
8408 struct redisClient *fakeClient;
8409 FILE *fp = fopen(filename,"r");
8410 struct redis_stat sb;
8411 unsigned long long loadedkeys = 0;
8412 int appendonly = server.appendonly;
8413
8414 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
8415 return REDIS_ERR;
8416
8417 if (fp == NULL) {
8418 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
8419 exit(1);
8420 }
8421
8422 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8423 * to the same file we're about to read. */
8424 server.appendonly = 0;
8425
8426 fakeClient = createFakeClient();
8427 while(1) {
8428 int argc, j;
8429 unsigned long len;
8430 robj **argv;
8431 char buf[128];
8432 sds argsds;
8433 struct redisCommand *cmd;
8434
8435 if (fgets(buf,sizeof(buf),fp) == NULL) {
8436 if (feof(fp))
8437 break;
8438 else
8439 goto readerr;
8440 }
8441 if (buf[0] != '*') goto fmterr;
8442 argc = atoi(buf+1);
8443 argv = zmalloc(sizeof(robj*)*argc);
8444 for (j = 0; j < argc; j++) {
8445 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
8446 if (buf[0] != '$') goto fmterr;
8447 len = strtol(buf+1,NULL,10);
8448 argsds = sdsnewlen(NULL,len);
8449 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
8450 argv[j] = createObject(REDIS_STRING,argsds);
8451 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
8452 }
8453
8454 /* Command lookup */
8455 cmd = lookupCommand(argv[0]->ptr);
8456 if (!cmd) {
8457 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
8458 exit(1);
8459 }
8460 /* Try object encoding */
8461 if (cmd->flags & REDIS_CMD_BULK)
8462 argv[argc-1] = tryObjectEncoding(argv[argc-1]);
8463 /* Run the command in the context of a fake client */
8464 fakeClient->argc = argc;
8465 fakeClient->argv = argv;
8466 cmd->proc(fakeClient);
8467 /* Discard the reply objects list from the fake client */
8468 while(listLength(fakeClient->reply))
8469 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
8470 /* Clean up, ready for the next command */
8471 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
8472 zfree(argv);
8473 /* Handle swapping while loading big datasets when VM is on */
8474 loadedkeys++;
8475 if (server.vm_enabled && (loadedkeys % 5000) == 0) {
8476 while (zmalloc_used_memory() > server.vm_max_memory) {
8477 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
8478 }
8479 }
8480 }
8481
8482 /* This point can only be reached when EOF is reached without errors.
8483 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8484 if (fakeClient->flags & REDIS_MULTI) goto readerr;
8485
8486 fclose(fp);
8487 freeFakeClient(fakeClient);
8488 server.appendonly = appendonly;
8489 return REDIS_OK;
8490
8491 readerr:
8492 if (feof(fp)) {
8493 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
8494 } else {
8495 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
8496 }
8497 exit(1);
8498 fmterr:
8499 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
8500 exit(1);
8501 }
8502
8503 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
8504 static int fwriteBulkObject(FILE *fp, robj *obj) {
8505 char buf[128];
8506 int decrrc = 0;
8507
8508 /* Avoid the incr/decr ref count business if possible to help
8509 * copy-on-write (we are often in a child process when this function
8510 * is called).
8511 * Also makes sure that key objects don't get incrRefCount-ed when VM
8512 * is enabled */
8513 if (obj->encoding != REDIS_ENCODING_RAW) {
8514 obj = getDecodedObject(obj);
8515 decrrc = 1;
8516 }
8517 snprintf(buf,sizeof(buf),"$%ld\r\n",(long)sdslen(obj->ptr));
8518 if (fwrite(buf,strlen(buf),1,fp) == 0) goto err;
8519 if (sdslen(obj->ptr) && fwrite(obj->ptr,sdslen(obj->ptr),1,fp) == 0)
8520 goto err;
8521 if (fwrite("\r\n",2,1,fp) == 0) goto err;
8522 if (decrrc) decrRefCount(obj);
8523 return 1;
8524 err:
8525 if (decrrc) decrRefCount(obj);
8526 return 0;
8527 }
8528
8529 /* Write binary-safe string into a file in the bulkformat
8530 * $<count>\r\n<payload>\r\n */
8531 static int fwriteBulkString(FILE *fp, char *s, unsigned long len) {
8532 char buf[128];
8533
8534 snprintf(buf,sizeof(buf),"$%ld\r\n",(unsigned long)len);
8535 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8536 if (len && fwrite(s,len,1,fp) == 0) return 0;
8537 if (fwrite("\r\n",2,1,fp) == 0) return 0;
8538 return 1;
8539 }
8540
8541 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8542 static int fwriteBulkDouble(FILE *fp, double d) {
8543 char buf[128], dbuf[128];
8544
8545 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
8546 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
8547 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8548 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
8549 return 1;
8550 }
8551
8552 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8553 static int fwriteBulkLong(FILE *fp, long l) {
8554 char buf[128], lbuf[128];
8555
8556 snprintf(lbuf,sizeof(lbuf),"%ld\r\n",l);
8557 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(lbuf)-2);
8558 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8559 if (fwrite(lbuf,strlen(lbuf),1,fp) == 0) return 0;
8560 return 1;
8561 }
8562
8563 /* Write a sequence of commands able to fully rebuild the dataset into
8564 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8565 static int rewriteAppendOnlyFile(char *filename) {
8566 dictIterator *di = NULL;
8567 dictEntry *de;
8568 FILE *fp;
8569 char tmpfile[256];
8570 int j;
8571 time_t now = time(NULL);
8572
8573 /* Note that we have to use a different temp name here compared to the
8574 * one used by rewriteAppendOnlyFileBackground() function. */
8575 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
8576 fp = fopen(tmpfile,"w");
8577 if (!fp) {
8578 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
8579 return REDIS_ERR;
8580 }
8581 for (j = 0; j < server.dbnum; j++) {
8582 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
8583 redisDb *db = server.db+j;
8584 dict *d = db->dict;
8585 if (dictSize(d) == 0) continue;
8586 di = dictGetIterator(d);
8587 if (!di) {
8588 fclose(fp);
8589 return REDIS_ERR;
8590 }
8591
8592 /* SELECT the new DB */
8593 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
8594 if (fwriteBulkLong(fp,j) == 0) goto werr;
8595
8596 /* Iterate this DB writing every entry */
8597 while((de = dictNext(di)) != NULL) {
8598 robj *key, *o;
8599 time_t expiretime;
8600 int swapped;
8601
8602 key = dictGetEntryKey(de);
8603 /* If the value for this key is swapped, load a preview in memory.
8604 * We use a "swapped" flag to remember if we need to free the
8605 * value object instead to just increment the ref count anyway
8606 * in order to avoid copy-on-write of pages if we are forked() */
8607 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
8608 key->storage == REDIS_VM_SWAPPING) {
8609 o = dictGetEntryVal(de);
8610 swapped = 0;
8611 } else {
8612 o = vmPreviewObject(key);
8613 swapped = 1;
8614 }
8615 expiretime = getExpire(db,key);
8616
8617 /* Save the key and associated value */
8618 if (o->type == REDIS_STRING) {
8619 /* Emit a SET command */
8620 char cmd[]="*3\r\n$3\r\nSET\r\n";
8621 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8622 /* Key and value */
8623 if (fwriteBulkObject(fp,key) == 0) goto werr;
8624 if (fwriteBulkObject(fp,o) == 0) goto werr;
8625 } else if (o->type == REDIS_LIST) {
8626 /* Emit the RPUSHes needed to rebuild the list */
8627 list *list = o->ptr;
8628 listNode *ln;
8629 listIter li;
8630
8631 listRewind(list,&li);
8632 while((ln = listNext(&li))) {
8633 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
8634 robj *eleobj = listNodeValue(ln);
8635
8636 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8637 if (fwriteBulkObject(fp,key) == 0) goto werr;
8638 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8639 }
8640 } else if (o->type == REDIS_SET) {
8641 /* Emit the SADDs needed to rebuild the set */
8642 dict *set = o->ptr;
8643 dictIterator *di = dictGetIterator(set);
8644 dictEntry *de;
8645
8646 while((de = dictNext(di)) != NULL) {
8647 char cmd[]="*3\r\n$4\r\nSADD\r\n";
8648 robj *eleobj = dictGetEntryKey(de);
8649
8650 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8651 if (fwriteBulkObject(fp,key) == 0) goto werr;
8652 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8653 }
8654 dictReleaseIterator(di);
8655 } else if (o->type == REDIS_ZSET) {
8656 /* Emit the ZADDs needed to rebuild the sorted set */
8657 zset *zs = o->ptr;
8658 dictIterator *di = dictGetIterator(zs->dict);
8659 dictEntry *de;
8660
8661 while((de = dictNext(di)) != NULL) {
8662 char cmd[]="*4\r\n$4\r\nZADD\r\n";
8663 robj *eleobj = dictGetEntryKey(de);
8664 double *score = dictGetEntryVal(de);
8665
8666 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8667 if (fwriteBulkObject(fp,key) == 0) goto werr;
8668 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
8669 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8670 }
8671 dictReleaseIterator(di);
8672 } else if (o->type == REDIS_HASH) {
8673 char cmd[]="*4\r\n$4\r\nHSET\r\n";
8674
8675 /* Emit the HSETs needed to rebuild the hash */
8676 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
8677 unsigned char *p = zipmapRewind(o->ptr);
8678 unsigned char *field, *val;
8679 unsigned int flen, vlen;
8680
8681 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
8682 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8683 if (fwriteBulkObject(fp,key) == 0) goto werr;
8684 if (fwriteBulkString(fp,(char*)field,flen) == -1)
8685 return -1;
8686 if (fwriteBulkString(fp,(char*)val,vlen) == -1)
8687 return -1;
8688 }
8689 } else {
8690 dictIterator *di = dictGetIterator(o->ptr);
8691 dictEntry *de;
8692
8693 while((de = dictNext(di)) != NULL) {
8694 robj *field = dictGetEntryKey(de);
8695 robj *val = dictGetEntryVal(de);
8696
8697 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8698 if (fwriteBulkObject(fp,key) == 0) goto werr;
8699 if (fwriteBulkObject(fp,field) == -1) return -1;
8700 if (fwriteBulkObject(fp,val) == -1) return -1;
8701 }
8702 dictReleaseIterator(di);
8703 }
8704 } else {
8705 redisPanic("Unknown object type");
8706 }
8707 /* Save the expire time */
8708 if (expiretime != -1) {
8709 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
8710 /* If this key is already expired skip it */
8711 if (expiretime < now) continue;
8712 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8713 if (fwriteBulkObject(fp,key) == 0) goto werr;
8714 if (fwriteBulkLong(fp,expiretime) == 0) goto werr;
8715 }
8716 if (swapped) decrRefCount(o);
8717 }
8718 dictReleaseIterator(di);
8719 }
8720
8721 /* Make sure data will not remain on the OS's output buffers */
8722 fflush(fp);
8723 fsync(fileno(fp));
8724 fclose(fp);
8725
8726 /* Use RENAME to make sure the DB file is changed atomically only
8727 * if the generate DB file is ok. */
8728 if (rename(tmpfile,filename) == -1) {
8729 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
8730 unlink(tmpfile);
8731 return REDIS_ERR;
8732 }
8733 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
8734 return REDIS_OK;
8735
8736 werr:
8737 fclose(fp);
8738 unlink(tmpfile);
8739 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
8740 if (di) dictReleaseIterator(di);
8741 return REDIS_ERR;
8742 }
8743
8744 /* This is how rewriting of the append only file in background works:
8745 *
8746 * 1) The user calls BGREWRITEAOF
8747 * 2) Redis calls this function, that forks():
8748 * 2a) the child rewrite the append only file in a temp file.
8749 * 2b) the parent accumulates differences in server.bgrewritebuf.
8750 * 3) When the child finished '2a' exists.
8751 * 4) The parent will trap the exit code, if it's OK, will append the
8752 * data accumulated into server.bgrewritebuf into the temp file, and
8753 * finally will rename(2) the temp file in the actual file name.
8754 * The the new file is reopened as the new append only file. Profit!
8755 */
8756 static int rewriteAppendOnlyFileBackground(void) {
8757 pid_t childpid;
8758
8759 if (server.bgrewritechildpid != -1) return REDIS_ERR;
8760 if (server.vm_enabled) waitEmptyIOJobsQueue();
8761 if ((childpid = fork()) == 0) {
8762 /* Child */
8763 char tmpfile[256];
8764
8765 if (server.vm_enabled) vmReopenSwapFile();
8766 close(server.fd);
8767 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
8768 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
8769 _exit(0);
8770 } else {
8771 _exit(1);
8772 }
8773 } else {
8774 /* Parent */
8775 if (childpid == -1) {
8776 redisLog(REDIS_WARNING,
8777 "Can't rewrite append only file in background: fork: %s",
8778 strerror(errno));
8779 return REDIS_ERR;
8780 }
8781 redisLog(REDIS_NOTICE,
8782 "Background append only file rewriting started by pid %d",childpid);
8783 server.bgrewritechildpid = childpid;
8784 updateDictResizePolicy();
8785 /* We set appendseldb to -1 in order to force the next call to the
8786 * feedAppendOnlyFile() to issue a SELECT command, so the differences
8787 * accumulated by the parent into server.bgrewritebuf will start
8788 * with a SELECT statement and it will be safe to merge. */
8789 server.appendseldb = -1;
8790 return REDIS_OK;
8791 }
8792 return REDIS_OK; /* unreached */
8793 }
8794
8795 static void bgrewriteaofCommand(redisClient *c) {
8796 if (server.bgrewritechildpid != -1) {
8797 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
8798 return;
8799 }
8800 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
8801 char *status = "+Background append only file rewriting started\r\n";
8802 addReplySds(c,sdsnew(status));
8803 } else {
8804 addReply(c,shared.err);
8805 }
8806 }
8807
8808 static void aofRemoveTempFile(pid_t childpid) {
8809 char tmpfile[256];
8810
8811 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
8812 unlink(tmpfile);
8813 }
8814
8815 /* Virtual Memory is composed mainly of two subsystems:
8816 * - Blocking Virutal Memory
8817 * - Threaded Virtual Memory I/O
8818 * The two parts are not fully decoupled, but functions are split among two
8819 * different sections of the source code (delimited by comments) in order to
8820 * make more clear what functionality is about the blocking VM and what about
8821 * the threaded (not blocking) VM.
8822 *
8823 * Redis VM design:
8824 *
8825 * Redis VM is a blocking VM (one that blocks reading swapped values from
8826 * disk into memory when a value swapped out is needed in memory) that is made
8827 * unblocking by trying to examine the command argument vector in order to
8828 * load in background values that will likely be needed in order to exec
8829 * the command. The command is executed only once all the relevant keys
8830 * are loaded into memory.
8831 *
8832 * This basically is almost as simple of a blocking VM, but almost as parallel
8833 * as a fully non-blocking VM.
8834 */
8835
8836 /* Called when the user switches from "appendonly yes" to "appendonly no"
8837 * at runtime using the CONFIG command. */
8838 static void stopAppendOnly(void) {
8839 flushAppendOnlyFile();
8840 fsync(server.appendfd);
8841 close(server.appendfd);
8842
8843 server.appendfd = -1;
8844 server.appendseldb = -1;
8845 server.appendonly = 0;
8846 /* rewrite operation in progress? kill it, wait child exit */
8847 if (server.bgsavechildpid != -1) {
8848 int statloc;
8849
8850 if (kill(server.bgsavechildpid,SIGKILL) != -1)
8851 wait3(&statloc,0,NULL);
8852 /* reset the buffer accumulating changes while the child saves */
8853 sdsfree(server.bgrewritebuf);
8854 server.bgrewritebuf = sdsempty();
8855 server.bgsavechildpid = -1;
8856 }
8857 }
8858
8859 /* Called when the user switches from "appendonly no" to "appendonly yes"
8860 * at runtime using the CONFIG command. */
8861 static int startAppendOnly(void) {
8862 server.appendonly = 1;
8863 server.lastfsync = time(NULL);
8864 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
8865 if (server.appendfd == -1) {
8866 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno));
8867 return REDIS_ERR;
8868 }
8869 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
8870 server.appendonly = 0;
8871 close(server.appendfd);
8872 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));
8873 return REDIS_ERR;
8874 }
8875 return REDIS_OK;
8876 }
8877
8878 /* =================== Virtual Memory - Blocking Side ====================== */
8879
8880 static void vmInit(void) {
8881 off_t totsize;
8882 int pipefds[2];
8883 size_t stacksize;
8884 struct flock fl;
8885
8886 if (server.vm_max_threads != 0)
8887 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
8888
8889 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
8890 /* Try to open the old swap file, otherwise create it */
8891 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
8892 server.vm_fp = fopen(server.vm_swap_file,"w+b");
8893 }
8894 if (server.vm_fp == NULL) {
8895 redisLog(REDIS_WARNING,
8896 "Can't open the swap file: %s. Exiting.",
8897 strerror(errno));
8898 exit(1);
8899 }
8900 server.vm_fd = fileno(server.vm_fp);
8901 /* Lock the swap file for writing, this is useful in order to avoid
8902 * another instance to use the same swap file for a config error. */
8903 fl.l_type = F_WRLCK;
8904 fl.l_whence = SEEK_SET;
8905 fl.l_start = fl.l_len = 0;
8906 if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
8907 redisLog(REDIS_WARNING,
8908 "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));
8909 exit(1);
8910 }
8911 /* Initialize */
8912 server.vm_next_page = 0;
8913 server.vm_near_pages = 0;
8914 server.vm_stats_used_pages = 0;
8915 server.vm_stats_swapped_objects = 0;
8916 server.vm_stats_swapouts = 0;
8917 server.vm_stats_swapins = 0;
8918 totsize = server.vm_pages*server.vm_page_size;
8919 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
8920 if (ftruncate(server.vm_fd,totsize) == -1) {
8921 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
8922 strerror(errno));
8923 exit(1);
8924 } else {
8925 redisLog(REDIS_NOTICE,"Swap file allocated with success");
8926 }
8927 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
8928 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
8929 (long long) (server.vm_pages+7)/8, server.vm_pages);
8930 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
8931
8932 /* Initialize threaded I/O (used by Virtual Memory) */
8933 server.io_newjobs = listCreate();
8934 server.io_processing = listCreate();
8935 server.io_processed = listCreate();
8936 server.io_ready_clients = listCreate();
8937 pthread_mutex_init(&server.io_mutex,NULL);
8938 pthread_mutex_init(&server.obj_freelist_mutex,NULL);
8939 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
8940 server.io_active_threads = 0;
8941 if (pipe(pipefds) == -1) {
8942 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
8943 ,strerror(errno));
8944 exit(1);
8945 }
8946 server.io_ready_pipe_read = pipefds[0];
8947 server.io_ready_pipe_write = pipefds[1];
8948 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
8949 /* LZF requires a lot of stack */
8950 pthread_attr_init(&server.io_threads_attr);
8951 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
8952 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
8953 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
8954 /* Listen for events in the threaded I/O pipe */
8955 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
8956 vmThreadedIOCompletedJob, NULL) == AE_ERR)
8957 oom("creating file event");
8958 }
8959
8960 /* Mark the page as used */
8961 static void vmMarkPageUsed(off_t page) {
8962 off_t byte = page/8;
8963 int bit = page&7;
8964 redisAssert(vmFreePage(page) == 1);
8965 server.vm_bitmap[byte] |= 1<<bit;
8966 }
8967
8968 /* Mark N contiguous pages as used, with 'page' being the first. */
8969 static void vmMarkPagesUsed(off_t page, off_t count) {
8970 off_t j;
8971
8972 for (j = 0; j < count; j++)
8973 vmMarkPageUsed(page+j);
8974 server.vm_stats_used_pages += count;
8975 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
8976 (long long)count, (long long)page);
8977 }
8978
8979 /* Mark the page as free */
8980 static void vmMarkPageFree(off_t page) {
8981 off_t byte = page/8;
8982 int bit = page&7;
8983 redisAssert(vmFreePage(page) == 0);
8984 server.vm_bitmap[byte] &= ~(1<<bit);
8985 }
8986
8987 /* Mark N contiguous pages as free, with 'page' being the first. */
8988 static void vmMarkPagesFree(off_t page, off_t count) {
8989 off_t j;
8990
8991 for (j = 0; j < count; j++)
8992 vmMarkPageFree(page+j);
8993 server.vm_stats_used_pages -= count;
8994 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
8995 (long long)count, (long long)page);
8996 }
8997
8998 /* Test if the page is free */
8999 static int vmFreePage(off_t page) {
9000 off_t byte = page/8;
9001 int bit = page&7;
9002 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
9003 }
9004
9005 /* Find N contiguous free pages storing the first page of the cluster in *first.
9006 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
9007 * REDIS_ERR is returned.
9008 *
9009 * This function uses a simple algorithm: we try to allocate
9010 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
9011 * again from the start of the swap file searching for free spaces.
9012 *
9013 * If it looks pretty clear that there are no free pages near our offset
9014 * we try to find less populated places doing a forward jump of
9015 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
9016 * without hurry, and then we jump again and so forth...
9017 *
9018 * This function can be improved using a free list to avoid to guess
9019 * too much, since we could collect data about freed pages.
9020 *
9021 * note: I implemented this function just after watching an episode of
9022 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
9023 */
9024 static int vmFindContiguousPages(off_t *first, off_t n) {
9025 off_t base, offset = 0, since_jump = 0, numfree = 0;
9026
9027 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
9028 server.vm_near_pages = 0;
9029 server.vm_next_page = 0;
9030 }
9031 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
9032 base = server.vm_next_page;
9033
9034 while(offset < server.vm_pages) {
9035 off_t this = base+offset;
9036
9037 /* If we overflow, restart from page zero */
9038 if (this >= server.vm_pages) {
9039 this -= server.vm_pages;
9040 if (this == 0) {
9041 /* Just overflowed, what we found on tail is no longer
9042 * interesting, as it's no longer contiguous. */
9043 numfree = 0;
9044 }
9045 }
9046 if (vmFreePage(this)) {
9047 /* This is a free page */
9048 numfree++;
9049 /* Already got N free pages? Return to the caller, with success */
9050 if (numfree == n) {
9051 *first = this-(n-1);
9052 server.vm_next_page = this+1;
9053 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
9054 return REDIS_OK;
9055 }
9056 } else {
9057 /* The current one is not a free page */
9058 numfree = 0;
9059 }
9060
9061 /* Fast-forward if the current page is not free and we already
9062 * searched enough near this place. */
9063 since_jump++;
9064 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
9065 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
9066 since_jump = 0;
9067 /* Note that even if we rewind after the jump, we are don't need
9068 * to make sure numfree is set to zero as we only jump *if* it
9069 * is set to zero. */
9070 } else {
9071 /* Otherwise just check the next page */
9072 offset++;
9073 }
9074 }
9075 return REDIS_ERR;
9076 }
9077
9078 /* Write the specified object at the specified page of the swap file */
9079 static int vmWriteObjectOnSwap(robj *o, off_t page) {
9080 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9081 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9082 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9083 redisLog(REDIS_WARNING,
9084 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
9085 strerror(errno));
9086 return REDIS_ERR;
9087 }
9088 rdbSaveObject(server.vm_fp,o);
9089 fflush(server.vm_fp);
9090 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9091 return REDIS_OK;
9092 }
9093
9094 /* Swap the 'val' object relative to 'key' into disk. Store all the information
9095 * needed to later retrieve the object into the key object.
9096 * If we can't find enough contiguous empty pages to swap the object on disk
9097 * REDIS_ERR is returned. */
9098 static int vmSwapObjectBlocking(robj *key, robj *val) {
9099 off_t pages = rdbSavedObjectPages(val,NULL);
9100 off_t page;
9101
9102 assert(key->storage == REDIS_VM_MEMORY);
9103 assert(key->refcount == 1);
9104 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return REDIS_ERR;
9105 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return REDIS_ERR;
9106 key->vm.page = page;
9107 key->vm.usedpages = pages;
9108 key->storage = REDIS_VM_SWAPPED;
9109 key->vtype = val->type;
9110 decrRefCount(val); /* Deallocate the object from memory. */
9111 vmMarkPagesUsed(page,pages);
9112 redisLog(REDIS_DEBUG,"VM: object %s swapped out at %lld (%lld pages)",
9113 (unsigned char*) key->ptr,
9114 (unsigned long long) page, (unsigned long long) pages);
9115 server.vm_stats_swapped_objects++;
9116 server.vm_stats_swapouts++;
9117 return REDIS_OK;
9118 }
9119
9120 static robj *vmReadObjectFromSwap(off_t page, int type) {
9121 robj *o;
9122
9123 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9124 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9125 redisLog(REDIS_WARNING,
9126 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
9127 strerror(errno));
9128 _exit(1);
9129 }
9130 o = rdbLoadObject(type,server.vm_fp);
9131 if (o == NULL) {
9132 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
9133 _exit(1);
9134 }
9135 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9136 return o;
9137 }
9138
9139 /* Load the value object relative to the 'key' object from swap to memory.
9140 * The newly allocated object is returned.
9141 *
9142 * If preview is true the unserialized object is returned to the caller but
9143 * no changes are made to the key object, nor the pages are marked as freed */
9144 static robj *vmGenericLoadObject(robj *key, int preview) {
9145 robj *val;
9146
9147 redisAssert(key->storage == REDIS_VM_SWAPPED || key->storage == REDIS_VM_LOADING);
9148 val = vmReadObjectFromSwap(key->vm.page,key->vtype);
9149 if (!preview) {
9150 key->storage = REDIS_VM_MEMORY;
9151 key->vm.atime = server.unixtime;
9152 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9153 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk",
9154 (unsigned char*) key->ptr);
9155 server.vm_stats_swapped_objects--;
9156 } else {
9157 redisLog(REDIS_DEBUG, "VM: object %s previewed from disk",
9158 (unsigned char*) key->ptr);
9159 }
9160 server.vm_stats_swapins++;
9161 return val;
9162 }
9163
9164 /* Plain object loading, from swap to memory */
9165 static robj *vmLoadObject(robj *key) {
9166 /* If we are loading the object in background, stop it, we
9167 * need to load this object synchronously ASAP. */
9168 if (key->storage == REDIS_VM_LOADING)
9169 vmCancelThreadedIOJob(key);
9170 return vmGenericLoadObject(key,0);
9171 }
9172
9173 /* Just load the value on disk, without to modify the key.
9174 * This is useful when we want to perform some operation on the value
9175 * without to really bring it from swap to memory, like while saving the
9176 * dataset or rewriting the append only log. */
9177 static robj *vmPreviewObject(robj *key) {
9178 return vmGenericLoadObject(key,1);
9179 }
9180
9181 /* How a good candidate is this object for swapping?
9182 * The better candidate it is, the greater the returned value.
9183 *
9184 * Currently we try to perform a fast estimation of the object size in
9185 * memory, and combine it with aging informations.
9186 *
9187 * Basically swappability = idle-time * log(estimated size)
9188 *
9189 * Bigger objects are preferred over smaller objects, but not
9190 * proportionally, this is why we use the logarithm. This algorithm is
9191 * just a first try and will probably be tuned later. */
9192 static double computeObjectSwappability(robj *o) {
9193 time_t age = server.unixtime - o->vm.atime;
9194 long asize = 0;
9195 list *l;
9196 dict *d;
9197 struct dictEntry *de;
9198 int z;
9199
9200 if (age <= 0) return 0;
9201 switch(o->type) {
9202 case REDIS_STRING:
9203 if (o->encoding != REDIS_ENCODING_RAW) {
9204 asize = sizeof(*o);
9205 } else {
9206 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
9207 }
9208 break;
9209 case REDIS_LIST:
9210 l = o->ptr;
9211 listNode *ln = listFirst(l);
9212
9213 asize = sizeof(list);
9214 if (ln) {
9215 robj *ele = ln->value;
9216 long elesize;
9217
9218 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9219 (sizeof(*o)+sdslen(ele->ptr)) :
9220 sizeof(*o);
9221 asize += (sizeof(listNode)+elesize)*listLength(l);
9222 }
9223 break;
9224 case REDIS_SET:
9225 case REDIS_ZSET:
9226 z = (o->type == REDIS_ZSET);
9227 d = z ? ((zset*)o->ptr)->dict : o->ptr;
9228
9229 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9230 if (z) asize += sizeof(zset)-sizeof(dict);
9231 if (dictSize(d)) {
9232 long elesize;
9233 robj *ele;
9234
9235 de = dictGetRandomKey(d);
9236 ele = dictGetEntryKey(de);
9237 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9238 (sizeof(*o)+sdslen(ele->ptr)) :
9239 sizeof(*o);
9240 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9241 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
9242 }
9243 break;
9244 case REDIS_HASH:
9245 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9246 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
9247 unsigned int len = zipmapLen((unsigned char*)o->ptr);
9248 unsigned int klen, vlen;
9249 unsigned char *key, *val;
9250
9251 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
9252 klen = 0;
9253 vlen = 0;
9254 }
9255 asize = len*(klen+vlen+3);
9256 } else if (o->encoding == REDIS_ENCODING_HT) {
9257 d = o->ptr;
9258 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9259 if (dictSize(d)) {
9260 long elesize;
9261 robj *ele;
9262
9263 de = dictGetRandomKey(d);
9264 ele = dictGetEntryKey(de);
9265 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9266 (sizeof(*o)+sdslen(ele->ptr)) :
9267 sizeof(*o);
9268 ele = dictGetEntryVal(de);
9269 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9270 (sizeof(*o)+sdslen(ele->ptr)) :
9271 sizeof(*o);
9272 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9273 }
9274 }
9275 break;
9276 }
9277 return (double)age*log(1+asize);
9278 }
9279
9280 /* Try to swap an object that's a good candidate for swapping.
9281 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
9282 * to swap any object at all.
9283 *
9284 * If 'usethreaded' is true, Redis will try to swap the object in background
9285 * using I/O threads. */
9286 static int vmSwapOneObject(int usethreads) {
9287 int j, i;
9288 struct dictEntry *best = NULL;
9289 double best_swappability = 0;
9290 redisDb *best_db = NULL;
9291 robj *key, *val;
9292
9293 for (j = 0; j < server.dbnum; j++) {
9294 redisDb *db = server.db+j;
9295 /* Why maxtries is set to 100?
9296 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9297 * are swappable objects */
9298 int maxtries = 100;
9299
9300 if (dictSize(db->dict) == 0) continue;
9301 for (i = 0; i < 5; i++) {
9302 dictEntry *de;
9303 double swappability;
9304
9305 if (maxtries) maxtries--;
9306 de = dictGetRandomKey(db->dict);
9307 key = dictGetEntryKey(de);
9308 val = dictGetEntryVal(de);
9309 /* Only swap objects that are currently in memory.
9310 *
9311 * Also don't swap shared objects if threaded VM is on, as we
9312 * try to ensure that the main thread does not touch the
9313 * object while the I/O thread is using it, but we can't
9314 * control other keys without adding additional mutex. */
9315 if (key->storage != REDIS_VM_MEMORY ||
9316 (server.vm_max_threads != 0 && val->refcount != 1)) {
9317 if (maxtries) i--; /* don't count this try */
9318 continue;
9319 }
9320 swappability = computeObjectSwappability(val);
9321 if (!best || swappability > best_swappability) {
9322 best = de;
9323 best_swappability = swappability;
9324 best_db = db;
9325 }
9326 }
9327 }
9328 if (best == NULL) return REDIS_ERR;
9329 key = dictGetEntryKey(best);
9330 val = dictGetEntryVal(best);
9331
9332 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
9333 key->ptr, best_swappability);
9334
9335 /* Unshare the key if needed */
9336 if (key->refcount > 1) {
9337 robj *newkey = dupStringObject(key);
9338 decrRefCount(key);
9339 key = dictGetEntryKey(best) = newkey;
9340 }
9341 /* Swap it */
9342 if (usethreads) {
9343 vmSwapObjectThreaded(key,val,best_db);
9344 return REDIS_OK;
9345 } else {
9346 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
9347 dictGetEntryVal(best) = NULL;
9348 return REDIS_OK;
9349 } else {
9350 return REDIS_ERR;
9351 }
9352 }
9353 }
9354
9355 static int vmSwapOneObjectBlocking() {
9356 return vmSwapOneObject(0);
9357 }
9358
9359 static int vmSwapOneObjectThreaded() {
9360 return vmSwapOneObject(1);
9361 }
9362
9363 /* Return true if it's safe to swap out objects in a given moment.
9364 * Basically we don't want to swap objects out while there is a BGSAVE
9365 * or a BGAEOREWRITE running in backgroud. */
9366 static int vmCanSwapOut(void) {
9367 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
9368 }
9369
9370 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
9371 * and was deleted. Otherwise 0 is returned. */
9372 static int deleteIfSwapped(redisDb *db, robj *key) {
9373 dictEntry *de;
9374 robj *foundkey;
9375
9376 if ((de = dictFind(db->dict,key)) == NULL) return 0;
9377 foundkey = dictGetEntryKey(de);
9378 if (foundkey->storage == REDIS_VM_MEMORY) return 0;
9379 deleteKey(db,key);
9380 return 1;
9381 }
9382
9383 /* =================== Virtual Memory - Threaded I/O ======================= */
9384
9385 static void freeIOJob(iojob *j) {
9386 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
9387 j->type == REDIS_IOJOB_DO_SWAP ||
9388 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
9389 decrRefCount(j->val);
9390 /* We don't decrRefCount the j->key field as we did't incremented
9391 * the count creating IO Jobs. This is because the key field here is
9392 * just used as an indentifier and if a key is removed the Job should
9393 * never be touched again. */
9394 zfree(j);
9395 }
9396
9397 /* Every time a thread finished a Job, it writes a byte into the write side
9398 * of an unix pipe in order to "awake" the main thread, and this function
9399 * is called. */
9400 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
9401 int mask)
9402 {
9403 char buf[1];
9404 int retval, processed = 0, toprocess = -1, trytoswap = 1;
9405 REDIS_NOTUSED(el);
9406 REDIS_NOTUSED(mask);
9407 REDIS_NOTUSED(privdata);
9408
9409 /* For every byte we read in the read side of the pipe, there is one
9410 * I/O job completed to process. */
9411 while((retval = read(fd,buf,1)) == 1) {
9412 iojob *j;
9413 listNode *ln;
9414 robj *key;
9415 struct dictEntry *de;
9416
9417 redisLog(REDIS_DEBUG,"Processing I/O completed job");
9418
9419 /* Get the processed element (the oldest one) */
9420 lockThreadedIO();
9421 assert(listLength(server.io_processed) != 0);
9422 if (toprocess == -1) {
9423 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
9424 if (toprocess <= 0) toprocess = 1;
9425 }
9426 ln = listFirst(server.io_processed);
9427 j = ln->value;
9428 listDelNode(server.io_processed,ln);
9429 unlockThreadedIO();
9430 /* If this job is marked as canceled, just ignore it */
9431 if (j->canceled) {
9432 freeIOJob(j);
9433 continue;
9434 }
9435 /* Post process it in the main thread, as there are things we
9436 * can do just here to avoid race conditions and/or invasive locks */
9437 redisLog(REDIS_DEBUG,"Job %p type: %d, key at %p (%s) refcount: %d\n", (void*) j, j->type, (void*)j->key, (char*)j->key->ptr, j->key->refcount);
9438 de = dictFind(j->db->dict,j->key);
9439 assert(de != NULL);
9440 key = dictGetEntryKey(de);
9441 if (j->type == REDIS_IOJOB_LOAD) {
9442 redisDb *db;
9443
9444 /* Key loaded, bring it at home */
9445 key->storage = REDIS_VM_MEMORY;
9446 key->vm.atime = server.unixtime;
9447 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9448 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
9449 (unsigned char*) key->ptr);
9450 server.vm_stats_swapped_objects--;
9451 server.vm_stats_swapins++;
9452 dictGetEntryVal(de) = j->val;
9453 incrRefCount(j->val);
9454 db = j->db;
9455 freeIOJob(j);
9456 /* Handle clients waiting for this key to be loaded. */
9457 handleClientsBlockedOnSwappedKey(db,key);
9458 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9459 /* Now we know the amount of pages required to swap this object.
9460 * Let's find some space for it, and queue this task again
9461 * rebranded as REDIS_IOJOB_DO_SWAP. */
9462 if (!vmCanSwapOut() ||
9463 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
9464 {
9465 /* Ooops... no space or we can't swap as there is
9466 * a fork()ed Redis trying to save stuff on disk. */
9467 freeIOJob(j);
9468 key->storage = REDIS_VM_MEMORY; /* undo operation */
9469 } else {
9470 /* Note that we need to mark this pages as used now,
9471 * if the job will be canceled, we'll mark them as freed
9472 * again. */
9473 vmMarkPagesUsed(j->page,j->pages);
9474 j->type = REDIS_IOJOB_DO_SWAP;
9475 lockThreadedIO();
9476 queueIOJob(j);
9477 unlockThreadedIO();
9478 }
9479 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9480 robj *val;
9481
9482 /* Key swapped. We can finally free some memory. */
9483 if (key->storage != REDIS_VM_SWAPPING) {
9484 printf("key->storage: %d\n",key->storage);
9485 printf("key->name: %s\n",(char*)key->ptr);
9486 printf("key->refcount: %d\n",key->refcount);
9487 printf("val: %p\n",(void*)j->val);
9488 printf("val->type: %d\n",j->val->type);
9489 printf("val->ptr: %s\n",(char*)j->val->ptr);
9490 }
9491 redisAssert(key->storage == REDIS_VM_SWAPPING);
9492 val = dictGetEntryVal(de);
9493 key->vm.page = j->page;
9494 key->vm.usedpages = j->pages;
9495 key->storage = REDIS_VM_SWAPPED;
9496 key->vtype = j->val->type;
9497 decrRefCount(val); /* Deallocate the object from memory. */
9498 dictGetEntryVal(de) = NULL;
9499 redisLog(REDIS_DEBUG,
9500 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9501 (unsigned char*) key->ptr,
9502 (unsigned long long) j->page, (unsigned long long) j->pages);
9503 server.vm_stats_swapped_objects++;
9504 server.vm_stats_swapouts++;
9505 freeIOJob(j);
9506 /* Put a few more swap requests in queue if we are still
9507 * out of memory */
9508 if (trytoswap && vmCanSwapOut() &&
9509 zmalloc_used_memory() > server.vm_max_memory)
9510 {
9511 int more = 1;
9512 while(more) {
9513 lockThreadedIO();
9514 more = listLength(server.io_newjobs) <
9515 (unsigned) server.vm_max_threads;
9516 unlockThreadedIO();
9517 /* Don't waste CPU time if swappable objects are rare. */
9518 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
9519 trytoswap = 0;
9520 break;
9521 }
9522 }
9523 }
9524 }
9525 processed++;
9526 if (processed == toprocess) return;
9527 }
9528 if (retval < 0 && errno != EAGAIN) {
9529 redisLog(REDIS_WARNING,
9530 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9531 strerror(errno));
9532 }
9533 }
9534
9535 static void lockThreadedIO(void) {
9536 pthread_mutex_lock(&server.io_mutex);
9537 }
9538
9539 static void unlockThreadedIO(void) {
9540 pthread_mutex_unlock(&server.io_mutex);
9541 }
9542
9543 /* Remove the specified object from the threaded I/O queue if still not
9544 * processed, otherwise make sure to flag it as canceled. */
9545 static void vmCancelThreadedIOJob(robj *o) {
9546 list *lists[3] = {
9547 server.io_newjobs, /* 0 */
9548 server.io_processing, /* 1 */
9549 server.io_processed /* 2 */
9550 };
9551 int i;
9552
9553 assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
9554 again:
9555 lockThreadedIO();
9556 /* Search for a matching key in one of the queues */
9557 for (i = 0; i < 3; i++) {
9558 listNode *ln;
9559 listIter li;
9560
9561 listRewind(lists[i],&li);
9562 while ((ln = listNext(&li)) != NULL) {
9563 iojob *job = ln->value;
9564
9565 if (job->canceled) continue; /* Skip this, already canceled. */
9566 if (job->key == o) {
9567 redisLog(REDIS_DEBUG,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
9568 (void*)job, (char*)o->ptr, job->type, i);
9569 /* Mark the pages as free since the swap didn't happened
9570 * or happened but is now discarded. */
9571 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
9572 vmMarkPagesFree(job->page,job->pages);
9573 /* Cancel the job. It depends on the list the job is
9574 * living in. */
9575 switch(i) {
9576 case 0: /* io_newjobs */
9577 /* If the job was yet not processed the best thing to do
9578 * is to remove it from the queue at all */
9579 freeIOJob(job);
9580 listDelNode(lists[i],ln);
9581 break;
9582 case 1: /* io_processing */
9583 /* Oh Shi- the thread is messing with the Job:
9584 *
9585 * Probably it's accessing the object if this is a
9586 * PREPARE_SWAP or DO_SWAP job.
9587 * If it's a LOAD job it may be reading from disk and
9588 * if we don't wait for the job to terminate before to
9589 * cancel it, maybe in a few microseconds data can be
9590 * corrupted in this pages. So the short story is:
9591 *
9592 * Better to wait for the job to move into the
9593 * next queue (processed)... */
9594
9595 /* We try again and again until the job is completed. */
9596 unlockThreadedIO();
9597 /* But let's wait some time for the I/O thread
9598 * to finish with this job. After all this condition
9599 * should be very rare. */
9600 usleep(1);
9601 goto again;
9602 case 2: /* io_processed */
9603 /* The job was already processed, that's easy...
9604 * just mark it as canceled so that we'll ignore it
9605 * when processing completed jobs. */
9606 job->canceled = 1;
9607 break;
9608 }
9609 /* Finally we have to adjust the storage type of the object
9610 * in order to "UNDO" the operaiton. */
9611 if (o->storage == REDIS_VM_LOADING)
9612 o->storage = REDIS_VM_SWAPPED;
9613 else if (o->storage == REDIS_VM_SWAPPING)
9614 o->storage = REDIS_VM_MEMORY;
9615 unlockThreadedIO();
9616 return;
9617 }
9618 }
9619 }
9620 unlockThreadedIO();
9621 assert(1 != 1); /* We should never reach this */
9622 }
9623
9624 static void *IOThreadEntryPoint(void *arg) {
9625 iojob *j;
9626 listNode *ln;
9627 REDIS_NOTUSED(arg);
9628
9629 pthread_detach(pthread_self());
9630 while(1) {
9631 /* Get a new job to process */
9632 lockThreadedIO();
9633 if (listLength(server.io_newjobs) == 0) {
9634 /* No new jobs in queue, exit. */
9635 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
9636 (long) pthread_self());
9637 server.io_active_threads--;
9638 unlockThreadedIO();
9639 return NULL;
9640 }
9641 ln = listFirst(server.io_newjobs);
9642 j = ln->value;
9643 listDelNode(server.io_newjobs,ln);
9644 /* Add the job in the processing queue */
9645 j->thread = pthread_self();
9646 listAddNodeTail(server.io_processing,j);
9647 ln = listLast(server.io_processing); /* We use ln later to remove it */
9648 unlockThreadedIO();
9649 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
9650 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
9651
9652 /* Process the Job */
9653 if (j->type == REDIS_IOJOB_LOAD) {
9654 j->val = vmReadObjectFromSwap(j->page,j->key->vtype);
9655 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9656 FILE *fp = fopen("/dev/null","w+");
9657 j->pages = rdbSavedObjectPages(j->val,fp);
9658 fclose(fp);
9659 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9660 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
9661 j->canceled = 1;
9662 }
9663
9664 /* Done: insert the job into the processed queue */
9665 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
9666 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
9667 lockThreadedIO();
9668 listDelNode(server.io_processing,ln);
9669 listAddNodeTail(server.io_processed,j);
9670 unlockThreadedIO();
9671
9672 /* Signal the main thread there is new stuff to process */
9673 assert(write(server.io_ready_pipe_write,"x",1) == 1);
9674 }
9675 return NULL; /* never reached */
9676 }
9677
9678 static void spawnIOThread(void) {
9679 pthread_t thread;
9680 sigset_t mask, omask;
9681 int err;
9682
9683 sigemptyset(&mask);
9684 sigaddset(&mask,SIGCHLD);
9685 sigaddset(&mask,SIGHUP);
9686 sigaddset(&mask,SIGPIPE);
9687 pthread_sigmask(SIG_SETMASK, &mask, &omask);
9688 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
9689 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
9690 strerror(err));
9691 usleep(1000000);
9692 }
9693 pthread_sigmask(SIG_SETMASK, &omask, NULL);
9694 server.io_active_threads++;
9695 }
9696
9697 /* We need to wait for the last thread to exit before we are able to
9698 * fork() in order to BGSAVE or BGREWRITEAOF. */
9699 static void waitEmptyIOJobsQueue(void) {
9700 while(1) {
9701 int io_processed_len;
9702
9703 lockThreadedIO();
9704 if (listLength(server.io_newjobs) == 0 &&
9705 listLength(server.io_processing) == 0 &&
9706 server.io_active_threads == 0)
9707 {
9708 unlockThreadedIO();
9709 return;
9710 }
9711 /* While waiting for empty jobs queue condition we post-process some
9712 * finshed job, as I/O threads may be hanging trying to write against
9713 * the io_ready_pipe_write FD but there are so much pending jobs that
9714 * it's blocking. */
9715 io_processed_len = listLength(server.io_processed);
9716 unlockThreadedIO();
9717 if (io_processed_len) {
9718 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
9719 usleep(1000); /* 1 millisecond */
9720 } else {
9721 usleep(10000); /* 10 milliseconds */
9722 }
9723 }
9724 }
9725
9726 static void vmReopenSwapFile(void) {
9727 /* Note: we don't close the old one as we are in the child process
9728 * and don't want to mess at all with the original file object. */
9729 server.vm_fp = fopen(server.vm_swap_file,"r+b");
9730 if (server.vm_fp == NULL) {
9731 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
9732 server.vm_swap_file);
9733 _exit(1);
9734 }
9735 server.vm_fd = fileno(server.vm_fp);
9736 }
9737
9738 /* This function must be called while with threaded IO locked */
9739 static void queueIOJob(iojob *j) {
9740 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
9741 (void*)j, j->type, (char*)j->key->ptr);
9742 listAddNodeTail(server.io_newjobs,j);
9743 if (server.io_active_threads < server.vm_max_threads)
9744 spawnIOThread();
9745 }
9746
9747 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
9748 iojob *j;
9749
9750 assert(key->storage == REDIS_VM_MEMORY);
9751 assert(key->refcount == 1);
9752
9753 j = zmalloc(sizeof(*j));
9754 j->type = REDIS_IOJOB_PREPARE_SWAP;
9755 j->db = db;
9756 j->key = key;
9757 j->val = val;
9758 incrRefCount(val);
9759 j->canceled = 0;
9760 j->thread = (pthread_t) -1;
9761 key->storage = REDIS_VM_SWAPPING;
9762
9763 lockThreadedIO();
9764 queueIOJob(j);
9765 unlockThreadedIO();
9766 return REDIS_OK;
9767 }
9768
9769 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
9770
9771 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
9772 * If there is not already a job loading the key, it is craeted.
9773 * The key is added to the io_keys list in the client structure, and also
9774 * in the hash table mapping swapped keys to waiting clients, that is,
9775 * server.io_waited_keys. */
9776 static int waitForSwappedKey(redisClient *c, robj *key) {
9777 struct dictEntry *de;
9778 robj *o;
9779 list *l;
9780
9781 /* If the key does not exist or is already in RAM we don't need to
9782 * block the client at all. */
9783 de = dictFind(c->db->dict,key);
9784 if (de == NULL) return 0;
9785 o = dictGetEntryKey(de);
9786 if (o->storage == REDIS_VM_MEMORY) {
9787 return 0;
9788 } else if (o->storage == REDIS_VM_SWAPPING) {
9789 /* We were swapping the key, undo it! */
9790 vmCancelThreadedIOJob(o);
9791 return 0;
9792 }
9793
9794 /* OK: the key is either swapped, or being loaded just now. */
9795
9796 /* Add the key to the list of keys this client is waiting for.
9797 * This maps clients to keys they are waiting for. */
9798 listAddNodeTail(c->io_keys,key);
9799 incrRefCount(key);
9800
9801 /* Add the client to the swapped keys => clients waiting map. */
9802 de = dictFind(c->db->io_keys,key);
9803 if (de == NULL) {
9804 int retval;
9805
9806 /* For every key we take a list of clients blocked for it */
9807 l = listCreate();
9808 retval = dictAdd(c->db->io_keys,key,l);
9809 incrRefCount(key);
9810 assert(retval == DICT_OK);
9811 } else {
9812 l = dictGetEntryVal(de);
9813 }
9814 listAddNodeTail(l,c);
9815
9816 /* Are we already loading the key from disk? If not create a job */
9817 if (o->storage == REDIS_VM_SWAPPED) {
9818 iojob *j;
9819
9820 o->storage = REDIS_VM_LOADING;
9821 j = zmalloc(sizeof(*j));
9822 j->type = REDIS_IOJOB_LOAD;
9823 j->db = c->db;
9824 j->key = o;
9825 j->key->vtype = o->vtype;
9826 j->page = o->vm.page;
9827 j->val = NULL;
9828 j->canceled = 0;
9829 j->thread = (pthread_t) -1;
9830 lockThreadedIO();
9831 queueIOJob(j);
9832 unlockThreadedIO();
9833 }
9834 return 1;
9835 }
9836
9837 /* Preload keys for any command with first, last and step values for
9838 * the command keys prototype, as defined in the command table. */
9839 static void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
9840 int j, last;
9841 if (cmd->vm_firstkey == 0) return;
9842 last = cmd->vm_lastkey;
9843 if (last < 0) last = argc+last;
9844 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
9845 redisAssert(j < argc);
9846 waitForSwappedKey(c,argv[j]);
9847 }
9848 }
9849
9850 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
9851 * Note that the number of keys to preload is user-defined, so we need to
9852 * apply a sanity check against argc. */
9853 static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
9854 int i, num;
9855 REDIS_NOTUSED(cmd);
9856
9857 num = atoi(argv[2]->ptr);
9858 if (num > (argc-3)) return;
9859 for (i = 0; i < num; i++) {
9860 waitForSwappedKey(c,argv[3+i]);
9861 }
9862 }
9863
9864 /* Preload keys needed to execute the entire MULTI/EXEC block.
9865 *
9866 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
9867 * and will block the client when any command requires a swapped out value. */
9868 static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
9869 int i, margc;
9870 struct redisCommand *mcmd;
9871 robj **margv;
9872 REDIS_NOTUSED(cmd);
9873 REDIS_NOTUSED(argc);
9874 REDIS_NOTUSED(argv);
9875
9876 if (!(c->flags & REDIS_MULTI)) return;
9877 for (i = 0; i < c->mstate.count; i++) {
9878 mcmd = c->mstate.commands[i].cmd;
9879 margc = c->mstate.commands[i].argc;
9880 margv = c->mstate.commands[i].argv;
9881
9882 if (mcmd->vm_preload_proc != NULL) {
9883 mcmd->vm_preload_proc(c,mcmd,margc,margv);
9884 } else {
9885 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
9886 }
9887 }
9888 }
9889
9890 /* Is this client attempting to run a command against swapped keys?
9891 * If so, block it ASAP, load the keys in background, then resume it.
9892 *
9893 * The important idea about this function is that it can fail! If keys will
9894 * still be swapped when the client is resumed, this key lookups will
9895 * just block loading keys from disk. In practical terms this should only
9896 * happen with SORT BY command or if there is a bug in this function.
9897 *
9898 * Return 1 if the client is marked as blocked, 0 if the client can
9899 * continue as the keys it is going to access appear to be in memory. */
9900 static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
9901 if (cmd->vm_preload_proc != NULL) {
9902 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
9903 } else {
9904 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
9905 }
9906
9907 /* If the client was blocked for at least one key, mark it as blocked. */
9908 if (listLength(c->io_keys)) {
9909 c->flags |= REDIS_IO_WAIT;
9910 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
9911 server.vm_blocked_clients++;
9912 return 1;
9913 } else {
9914 return 0;
9915 }
9916 }
9917
9918 /* Remove the 'key' from the list of blocked keys for a given client.
9919 *
9920 * The function returns 1 when there are no longer blocking keys after
9921 * the current one was removed (and the client can be unblocked). */
9922 static int dontWaitForSwappedKey(redisClient *c, robj *key) {
9923 list *l;
9924 listNode *ln;
9925 listIter li;
9926 struct dictEntry *de;
9927
9928 /* Remove the key from the list of keys this client is waiting for. */
9929 listRewind(c->io_keys,&li);
9930 while ((ln = listNext(&li)) != NULL) {
9931 if (equalStringObjects(ln->value,key)) {
9932 listDelNode(c->io_keys,ln);
9933 break;
9934 }
9935 }
9936 assert(ln != NULL);
9937
9938 /* Remove the client form the key => waiting clients map. */
9939 de = dictFind(c->db->io_keys,key);
9940 assert(de != NULL);
9941 l = dictGetEntryVal(de);
9942 ln = listSearchKey(l,c);
9943 assert(ln != NULL);
9944 listDelNode(l,ln);
9945 if (listLength(l) == 0)
9946 dictDelete(c->db->io_keys,key);
9947
9948 return listLength(c->io_keys) == 0;
9949 }
9950
9951 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
9952 struct dictEntry *de;
9953 list *l;
9954 listNode *ln;
9955 int len;
9956
9957 de = dictFind(db->io_keys,key);
9958 if (!de) return;
9959
9960 l = dictGetEntryVal(de);
9961 len = listLength(l);
9962 /* Note: we can't use something like while(listLength(l)) as the list
9963 * can be freed by the calling function when we remove the last element. */
9964 while (len--) {
9965 ln = listFirst(l);
9966 redisClient *c = ln->value;
9967
9968 if (dontWaitForSwappedKey(c,key)) {
9969 /* Put the client in the list of clients ready to go as we
9970 * loaded all the keys about it. */
9971 listAddNodeTail(server.io_ready_clients,c);
9972 }
9973 }
9974 }
9975
9976 /* =========================== Remote Configuration ========================= */
9977
9978 static void configSetCommand(redisClient *c) {
9979 robj *o = getDecodedObject(c->argv[3]);
9980 long long ll;
9981
9982 if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
9983 zfree(server.dbfilename);
9984 server.dbfilename = zstrdup(o->ptr);
9985 } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
9986 zfree(server.requirepass);
9987 server.requirepass = zstrdup(o->ptr);
9988 } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
9989 zfree(server.masterauth);
9990 server.masterauth = zstrdup(o->ptr);
9991 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
9992 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
9993 ll < 0) goto badfmt;
9994 server.maxmemory = ll;
9995 } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
9996 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
9997 ll < 0 || ll > LONG_MAX) goto badfmt;
9998 server.maxidletime = ll;
9999 } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
10000 if (!strcasecmp(o->ptr,"no")) {
10001 server.appendfsync = APPENDFSYNC_NO;
10002 } else if (!strcasecmp(o->ptr,"everysec")) {
10003 server.appendfsync = APPENDFSYNC_EVERYSEC;
10004 } else if (!strcasecmp(o->ptr,"always")) {
10005 server.appendfsync = APPENDFSYNC_ALWAYS;
10006 } else {
10007 goto badfmt;
10008 }
10009 } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
10010 int old = server.appendonly;
10011 int new = yesnotoi(o->ptr);
10012
10013 if (new == -1) goto badfmt;
10014 if (old != new) {
10015 if (new == 0) {
10016 stopAppendOnly();
10017 } else {
10018 if (startAppendOnly() == REDIS_ERR) {
10019 addReplySds(c,sdscatprintf(sdsempty(),
10020 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
10021 decrRefCount(o);
10022 return;
10023 }
10024 }
10025 }
10026 } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
10027 int vlen, j;
10028 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
10029
10030 /* Perform sanity check before setting the new config:
10031 * - Even number of args
10032 * - Seconds >= 1, changes >= 0 */
10033 if (vlen & 1) {
10034 sdsfreesplitres(v,vlen);
10035 goto badfmt;
10036 }
10037 for (j = 0; j < vlen; j++) {
10038 char *eptr;
10039 long val;
10040
10041 val = strtoll(v[j], &eptr, 10);
10042 if (eptr[0] != '\0' ||
10043 ((j & 1) == 0 && val < 1) ||
10044 ((j & 1) == 1 && val < 0)) {
10045 sdsfreesplitres(v,vlen);
10046 goto badfmt;
10047 }
10048 }
10049 /* Finally set the new config */
10050 resetServerSaveParams();
10051 for (j = 0; j < vlen; j += 2) {
10052 time_t seconds;
10053 int changes;
10054
10055 seconds = strtoll(v[j],NULL,10);
10056 changes = strtoll(v[j+1],NULL,10);
10057 appendServerSaveParams(seconds, changes);
10058 }
10059 sdsfreesplitres(v,vlen);
10060 } else {
10061 addReplySds(c,sdscatprintf(sdsempty(),
10062 "-ERR not supported CONFIG parameter %s\r\n",
10063 (char*)c->argv[2]->ptr));
10064 decrRefCount(o);
10065 return;
10066 }
10067 decrRefCount(o);
10068 addReply(c,shared.ok);
10069 return;
10070
10071 badfmt: /* Bad format errors */
10072 addReplySds(c,sdscatprintf(sdsempty(),
10073 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
10074 (char*)o->ptr,
10075 (char*)c->argv[2]->ptr));
10076 decrRefCount(o);
10077 }
10078
10079 static void configGetCommand(redisClient *c) {
10080 robj *o = getDecodedObject(c->argv[2]);
10081 robj *lenobj = createObject(REDIS_STRING,NULL);
10082 char *pattern = o->ptr;
10083 int matches = 0;
10084
10085 addReply(c,lenobj);
10086 decrRefCount(lenobj);
10087
10088 if (stringmatch(pattern,"dbfilename",0)) {
10089 addReplyBulkCString(c,"dbfilename");
10090 addReplyBulkCString(c,server.dbfilename);
10091 matches++;
10092 }
10093 if (stringmatch(pattern,"requirepass",0)) {
10094 addReplyBulkCString(c,"requirepass");
10095 addReplyBulkCString(c,server.requirepass);
10096 matches++;
10097 }
10098 if (stringmatch(pattern,"masterauth",0)) {
10099 addReplyBulkCString(c,"masterauth");
10100 addReplyBulkCString(c,server.masterauth);
10101 matches++;
10102 }
10103 if (stringmatch(pattern,"maxmemory",0)) {
10104 char buf[128];
10105
10106 ll2string(buf,128,server.maxmemory);
10107 addReplyBulkCString(c,"maxmemory");
10108 addReplyBulkCString(c,buf);
10109 matches++;
10110 }
10111 if (stringmatch(pattern,"timeout",0)) {
10112 char buf[128];
10113
10114 ll2string(buf,128,server.maxidletime);
10115 addReplyBulkCString(c,"timeout");
10116 addReplyBulkCString(c,buf);
10117 matches++;
10118 }
10119 if (stringmatch(pattern,"appendonly",0)) {
10120 addReplyBulkCString(c,"appendonly");
10121 addReplyBulkCString(c,server.appendonly ? "yes" : "no");
10122 matches++;
10123 }
10124 if (stringmatch(pattern,"appendfsync",0)) {
10125 char *policy;
10126
10127 switch(server.appendfsync) {
10128 case APPENDFSYNC_NO: policy = "no"; break;
10129 case APPENDFSYNC_EVERYSEC: policy = "everysec"; break;
10130 case APPENDFSYNC_ALWAYS: policy = "always"; break;
10131 default: policy = "unknown"; break; /* too harmless to panic */
10132 }
10133 addReplyBulkCString(c,"appendfsync");
10134 addReplyBulkCString(c,policy);
10135 matches++;
10136 }
10137 if (stringmatch(pattern,"save",0)) {
10138 sds buf = sdsempty();
10139 int j;
10140
10141 for (j = 0; j < server.saveparamslen; j++) {
10142 buf = sdscatprintf(buf,"%ld %d",
10143 server.saveparams[j].seconds,
10144 server.saveparams[j].changes);
10145 if (j != server.saveparamslen-1)
10146 buf = sdscatlen(buf," ",1);
10147 }
10148 addReplyBulkCString(c,"save");
10149 addReplyBulkCString(c,buf);
10150 sdsfree(buf);
10151 matches++;
10152 }
10153 decrRefCount(o);
10154 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",matches*2);
10155 }
10156
10157 static void configCommand(redisClient *c) {
10158 if (!strcasecmp(c->argv[1]->ptr,"set")) {
10159 if (c->argc != 4) goto badarity;
10160 configSetCommand(c);
10161 } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
10162 if (c->argc != 3) goto badarity;
10163 configGetCommand(c);
10164 } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
10165 if (c->argc != 2) goto badarity;
10166 server.stat_numcommands = 0;
10167 server.stat_numconnections = 0;
10168 server.stat_expiredkeys = 0;
10169 server.stat_starttime = time(NULL);
10170 addReply(c,shared.ok);
10171 } else {
10172 addReplySds(c,sdscatprintf(sdsempty(),
10173 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10174 }
10175 return;
10176
10177 badarity:
10178 addReplySds(c,sdscatprintf(sdsempty(),
10179 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10180 (char*) c->argv[1]->ptr));
10181 }
10182
10183 /* =========================== Pubsub implementation ======================== */
10184
10185 static void freePubsubPattern(void *p) {
10186 pubsubPattern *pat = p;
10187
10188 decrRefCount(pat->pattern);
10189 zfree(pat);
10190 }
10191
10192 static int listMatchPubsubPattern(void *a, void *b) {
10193 pubsubPattern *pa = a, *pb = b;
10194
10195 return (pa->client == pb->client) &&
10196 (equalStringObjects(pa->pattern,pb->pattern));
10197 }
10198
10199 /* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10200 * 0 if the client was already subscribed to that channel. */
10201 static int pubsubSubscribeChannel(redisClient *c, robj *channel) {
10202 struct dictEntry *de;
10203 list *clients = NULL;
10204 int retval = 0;
10205
10206 /* Add the channel to the client -> channels hash table */
10207 if (dictAdd(c->pubsub_channels,channel,NULL) == DICT_OK) {
10208 retval = 1;
10209 incrRefCount(channel);
10210 /* Add the client to the channel -> list of clients hash table */
10211 de = dictFind(server.pubsub_channels,channel);
10212 if (de == NULL) {
10213 clients = listCreate();
10214 dictAdd(server.pubsub_channels,channel,clients);
10215 incrRefCount(channel);
10216 } else {
10217 clients = dictGetEntryVal(de);
10218 }
10219 listAddNodeTail(clients,c);
10220 }
10221 /* Notify the client */
10222 addReply(c,shared.mbulk3);
10223 addReply(c,shared.subscribebulk);
10224 addReplyBulk(c,channel);
10225 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10226 return retval;
10227 }
10228
10229 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10230 * 0 if the client was not subscribed to the specified channel. */
10231 static int pubsubUnsubscribeChannel(redisClient *c, robj *channel, int notify) {
10232 struct dictEntry *de;
10233 list *clients;
10234 listNode *ln;
10235 int retval = 0;
10236
10237 /* Remove the channel from the client -> channels hash table */
10238 incrRefCount(channel); /* channel may be just a pointer to the same object
10239 we have in the hash tables. Protect it... */
10240 if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
10241 retval = 1;
10242 /* Remove the client from the channel -> clients list hash table */
10243 de = dictFind(server.pubsub_channels,channel);
10244 assert(de != NULL);
10245 clients = dictGetEntryVal(de);
10246 ln = listSearchKey(clients,c);
10247 assert(ln != NULL);
10248 listDelNode(clients,ln);
10249 if (listLength(clients) == 0) {
10250 /* Free the list and associated hash entry at all if this was
10251 * the latest client, so that it will be possible to abuse
10252 * Redis PUBSUB creating millions of channels. */
10253 dictDelete(server.pubsub_channels,channel);
10254 }
10255 }
10256 /* Notify the client */
10257 if (notify) {
10258 addReply(c,shared.mbulk3);
10259 addReply(c,shared.unsubscribebulk);
10260 addReplyBulk(c,channel);
10261 addReplyLongLong(c,dictSize(c->pubsub_channels)+
10262 listLength(c->pubsub_patterns));
10263
10264 }
10265 decrRefCount(channel); /* it is finally safe to release it */
10266 return retval;
10267 }
10268
10269 /* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10270 static int pubsubSubscribePattern(redisClient *c, robj *pattern) {
10271 int retval = 0;
10272
10273 if (listSearchKey(c->pubsub_patterns,pattern) == NULL) {
10274 retval = 1;
10275 pubsubPattern *pat;
10276 listAddNodeTail(c->pubsub_patterns,pattern);
10277 incrRefCount(pattern);
10278 pat = zmalloc(sizeof(*pat));
10279 pat->pattern = getDecodedObject(pattern);
10280 pat->client = c;
10281 listAddNodeTail(server.pubsub_patterns,pat);
10282 }
10283 /* Notify the client */
10284 addReply(c,shared.mbulk3);
10285 addReply(c,shared.psubscribebulk);
10286 addReplyBulk(c,pattern);
10287 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10288 return retval;
10289 }
10290
10291 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10292 * 0 if the client was not subscribed to the specified channel. */
10293 static int pubsubUnsubscribePattern(redisClient *c, robj *pattern, int notify) {
10294 listNode *ln;
10295 pubsubPattern pat;
10296 int retval = 0;
10297
10298 incrRefCount(pattern); /* Protect the object. May be the same we remove */
10299 if ((ln = listSearchKey(c->pubsub_patterns,pattern)) != NULL) {
10300 retval = 1;
10301 listDelNode(c->pubsub_patterns,ln);
10302 pat.client = c;
10303 pat.pattern = pattern;
10304 ln = listSearchKey(server.pubsub_patterns,&pat);
10305 listDelNode(server.pubsub_patterns,ln);
10306 }
10307 /* Notify the client */
10308 if (notify) {
10309 addReply(c,shared.mbulk3);
10310 addReply(c,shared.punsubscribebulk);
10311 addReplyBulk(c,pattern);
10312 addReplyLongLong(c,dictSize(c->pubsub_channels)+
10313 listLength(c->pubsub_patterns));
10314 }
10315 decrRefCount(pattern);
10316 return retval;
10317 }
10318
10319 /* Unsubscribe from all the channels. Return the number of channels the
10320 * client was subscribed from. */
10321 static int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
10322 dictIterator *di = dictGetIterator(c->pubsub_channels);
10323 dictEntry *de;
10324 int count = 0;
10325
10326 while((de = dictNext(di)) != NULL) {
10327 robj *channel = dictGetEntryKey(de);
10328
10329 count += pubsubUnsubscribeChannel(c,channel,notify);
10330 }
10331 dictReleaseIterator(di);
10332 return count;
10333 }
10334
10335 /* Unsubscribe from all the patterns. Return the number of patterns the
10336 * client was subscribed from. */
10337 static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify) {
10338 listNode *ln;
10339 listIter li;
10340 int count = 0;
10341
10342 listRewind(c->pubsub_patterns,&li);
10343 while ((ln = listNext(&li)) != NULL) {
10344 robj *pattern = ln->value;
10345
10346 count += pubsubUnsubscribePattern(c,pattern,notify);
10347 }
10348 return count;
10349 }
10350
10351 /* Publish a message */
10352 static int pubsubPublishMessage(robj *channel, robj *message) {
10353 int receivers = 0;
10354 struct dictEntry *de;
10355 listNode *ln;
10356 listIter li;
10357
10358 /* Send to clients listening for that channel */
10359 de = dictFind(server.pubsub_channels,channel);
10360 if (de) {
10361 list *list = dictGetEntryVal(de);
10362 listNode *ln;
10363 listIter li;
10364
10365 listRewind(list,&li);
10366 while ((ln = listNext(&li)) != NULL) {
10367 redisClient *c = ln->value;
10368
10369 addReply(c,shared.mbulk3);
10370 addReply(c,shared.messagebulk);
10371 addReplyBulk(c,channel);
10372 addReplyBulk(c,message);
10373 receivers++;
10374 }
10375 }
10376 /* Send to clients listening to matching channels */
10377 if (listLength(server.pubsub_patterns)) {
10378 listRewind(server.pubsub_patterns,&li);
10379 channel = getDecodedObject(channel);
10380 while ((ln = listNext(&li)) != NULL) {
10381 pubsubPattern *pat = ln->value;
10382
10383 if (stringmatchlen((char*)pat->pattern->ptr,
10384 sdslen(pat->pattern->ptr),
10385 (char*)channel->ptr,
10386 sdslen(channel->ptr),0)) {
10387 addReply(pat->client,shared.mbulk4);
10388 addReply(pat->client,shared.pmessagebulk);
10389 addReplyBulk(pat->client,pat->pattern);
10390 addReplyBulk(pat->client,channel);
10391 addReplyBulk(pat->client,message);
10392 receivers++;
10393 }
10394 }
10395 decrRefCount(channel);
10396 }
10397 return receivers;
10398 }
10399
10400 static void subscribeCommand(redisClient *c) {
10401 int j;
10402
10403 for (j = 1; j < c->argc; j++)
10404 pubsubSubscribeChannel(c,c->argv[j]);
10405 }
10406
10407 static void unsubscribeCommand(redisClient *c) {
10408 if (c->argc == 1) {
10409 pubsubUnsubscribeAllChannels(c,1);
10410 return;
10411 } else {
10412 int j;
10413
10414 for (j = 1; j < c->argc; j++)
10415 pubsubUnsubscribeChannel(c,c->argv[j],1);
10416 }
10417 }
10418
10419 static void psubscribeCommand(redisClient *c) {
10420 int j;
10421
10422 for (j = 1; j < c->argc; j++)
10423 pubsubSubscribePattern(c,c->argv[j]);
10424 }
10425
10426 static void punsubscribeCommand(redisClient *c) {
10427 if (c->argc == 1) {
10428 pubsubUnsubscribeAllPatterns(c,1);
10429 return;
10430 } else {
10431 int j;
10432
10433 for (j = 1; j < c->argc; j++)
10434 pubsubUnsubscribePattern(c,c->argv[j],1);
10435 }
10436 }
10437
10438 static void publishCommand(redisClient *c) {
10439 int receivers = pubsubPublishMessage(c->argv[1],c->argv[2]);
10440 addReplyLongLong(c,receivers);
10441 }
10442
10443 /* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
10444 *
10445 * The implementation uses a per-DB hash table mapping keys to list of clients
10446 * WATCHing those keys, so that given a key that is going to be modified
10447 * we can mark all the associated clients as dirty.
10448 *
10449 * Also every client contains a list of WATCHed keys so that's possible to
10450 * un-watch such keys when the client is freed or when UNWATCH is called. */
10451
10452 /* In the client->watched_keys list we need to use watchedKey structures
10453 * as in order to identify a key in Redis we need both the key name and the
10454 * DB */
10455 typedef struct watchedKey {
10456 robj *key;
10457 redisDb *db;
10458 } watchedKey;
10459
10460 /* Watch for the specified key */
10461 static void watchForKey(redisClient *c, robj *key) {
10462 list *clients = NULL;
10463 listIter li;
10464 listNode *ln;
10465 watchedKey *wk;
10466
10467 /* Check if we are already watching for this key */
10468 listRewind(c->watched_keys,&li);
10469 while((ln = listNext(&li))) {
10470 wk = listNodeValue(ln);
10471 if (wk->db == c->db && equalStringObjects(key,wk->key))
10472 return; /* Key already watched */
10473 }
10474 /* This key is not already watched in this DB. Let's add it */
10475 clients = dictFetchValue(c->db->watched_keys,key);
10476 if (!clients) {
10477 clients = listCreate();
10478 dictAdd(c->db->watched_keys,key,clients);
10479 incrRefCount(key);
10480 }
10481 listAddNodeTail(clients,c);
10482 /* Add the new key to the lits of keys watched by this client */
10483 wk = zmalloc(sizeof(*wk));
10484 wk->key = key;
10485 wk->db = c->db;
10486 incrRefCount(key);
10487 listAddNodeTail(c->watched_keys,wk);
10488 }
10489
10490 /* Unwatch all the keys watched by this client. To clean the EXEC dirty
10491 * flag is up to the caller. */
10492 static void unwatchAllKeys(redisClient *c) {
10493 listIter li;
10494 listNode *ln;
10495
10496 if (listLength(c->watched_keys) == 0) return;
10497 listRewind(c->watched_keys,&li);
10498 while((ln = listNext(&li))) {
10499 list *clients;
10500 watchedKey *wk;
10501
10502 /* Lookup the watched key -> clients list and remove the client
10503 * from the list */
10504 wk = listNodeValue(ln);
10505 clients = dictFetchValue(wk->db->watched_keys, wk->key);
10506 assert(clients != NULL);
10507 listDelNode(clients,listSearchKey(clients,c));
10508 /* Kill the entry at all if this was the only client */
10509 if (listLength(clients) == 0)
10510 dictDelete(wk->db->watched_keys, wk->key);
10511 /* Remove this watched key from the client->watched list */
10512 listDelNode(c->watched_keys,ln);
10513 decrRefCount(wk->key);
10514 zfree(wk);
10515 }
10516 }
10517
10518 /* "Touch" a key, so that if this key is being WATCHed by some client the
10519 * next EXEC will fail. */
10520 static void touchWatchedKey(redisDb *db, robj *key) {
10521 list *clients;
10522 listIter li;
10523 listNode *ln;
10524
10525 if (dictSize(db->watched_keys) == 0) return;
10526 clients = dictFetchValue(db->watched_keys, key);
10527 if (!clients) return;
10528
10529 /* Mark all the clients watching this key as REDIS_DIRTY_CAS */
10530 /* Check if we are already watching for this key */
10531 listRewind(clients,&li);
10532 while((ln = listNext(&li))) {
10533 redisClient *c = listNodeValue(ln);
10534
10535 c->flags |= REDIS_DIRTY_CAS;
10536 }
10537 }
10538
10539 /* On FLUSHDB or FLUSHALL all the watched keys that are present before the
10540 * flush but will be deleted as effect of the flushing operation should
10541 * be touched. "dbid" is the DB that's getting the flush. -1 if it is
10542 * a FLUSHALL operation (all the DBs flushed). */
10543 static void touchWatchedKeysOnFlush(int dbid) {
10544 listIter li1, li2;
10545 listNode *ln;
10546
10547 /* For every client, check all the waited keys */
10548 listRewind(server.clients,&li1);
10549 while((ln = listNext(&li1))) {
10550 redisClient *c = listNodeValue(ln);
10551 listRewind(c->watched_keys,&li2);
10552 while((ln = listNext(&li2))) {
10553 watchedKey *wk = listNodeValue(ln);
10554
10555 /* For every watched key matching the specified DB, if the
10556 * key exists, mark the client as dirty, as the key will be
10557 * removed. */
10558 if (dbid == -1 || wk->db->id == dbid) {
10559 if (dictFind(wk->db->dict, wk->key) != NULL)
10560 c->flags |= REDIS_DIRTY_CAS;
10561 }
10562 }
10563 }
10564 }
10565
10566 static void watchCommand(redisClient *c) {
10567 int j;
10568
10569 if (c->flags & REDIS_MULTI) {
10570 addReplySds(c,sdsnew("-ERR WATCH inside MULTI is not allowed\r\n"));
10571 return;
10572 }
10573 for (j = 1; j < c->argc; j++)
10574 watchForKey(c,c->argv[j]);
10575 addReply(c,shared.ok);
10576 }
10577
10578 static void unwatchCommand(redisClient *c) {
10579 unwatchAllKeys(c);
10580 c->flags &= (~REDIS_DIRTY_CAS);
10581 addReply(c,shared.ok);
10582 }
10583
10584 /* ================================= Debugging ============================== */
10585
10586 /* Compute the sha1 of string at 's' with 'len' bytes long.
10587 * The SHA1 is then xored againt the string pointed by digest.
10588 * Since xor is commutative, this operation is used in order to
10589 * "add" digests relative to unordered elements.
10590 *
10591 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10592 static void xorDigest(unsigned char *digest, void *ptr, size_t len) {
10593 SHA1_CTX ctx;
10594 unsigned char hash[20], *s = ptr;
10595 int j;
10596
10597 SHA1Init(&ctx);
10598 SHA1Update(&ctx,s,len);
10599 SHA1Final(hash,&ctx);
10600
10601 for (j = 0; j < 20; j++)
10602 digest[j] ^= hash[j];
10603 }
10604
10605 static void xorObjectDigest(unsigned char *digest, robj *o) {
10606 o = getDecodedObject(o);
10607 xorDigest(digest,o->ptr,sdslen(o->ptr));
10608 decrRefCount(o);
10609 }
10610
10611 /* This function instead of just computing the SHA1 and xoring it
10612 * against diget, also perform the digest of "digest" itself and
10613 * replace the old value with the new one.
10614 *
10615 * So the final digest will be:
10616 *
10617 * digest = SHA1(digest xor SHA1(data))
10618 *
10619 * This function is used every time we want to preserve the order so
10620 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
10621 *
10622 * Also note that mixdigest("foo") followed by mixdigest("bar")
10623 * will lead to a different digest compared to "fo", "obar".
10624 */
10625 static void mixDigest(unsigned char *digest, void *ptr, size_t len) {
10626 SHA1_CTX ctx;
10627 char *s = ptr;
10628
10629 xorDigest(digest,s,len);
10630 SHA1Init(&ctx);
10631 SHA1Update(&ctx,digest,20);
10632 SHA1Final(digest,&ctx);
10633 }
10634
10635 static void mixObjectDigest(unsigned char *digest, robj *o) {
10636 o = getDecodedObject(o);
10637 mixDigest(digest,o->ptr,sdslen(o->ptr));
10638 decrRefCount(o);
10639 }
10640
10641 /* Compute the dataset digest. Since keys, sets elements, hashes elements
10642 * are not ordered, we use a trick: every aggregate digest is the xor
10643 * of the digests of their elements. This way the order will not change
10644 * the result. For list instead we use a feedback entering the output digest
10645 * as input in order to ensure that a different ordered list will result in
10646 * a different digest. */
10647 static void computeDatasetDigest(unsigned char *final) {
10648 unsigned char digest[20];
10649 char buf[128];
10650 dictIterator *di = NULL;
10651 dictEntry *de;
10652 int j;
10653 uint32_t aux;
10654
10655 memset(final,0,20); /* Start with a clean result */
10656
10657 for (j = 0; j < server.dbnum; j++) {
10658 redisDb *db = server.db+j;
10659
10660 if (dictSize(db->dict) == 0) continue;
10661 di = dictGetIterator(db->dict);
10662
10663 /* hash the DB id, so the same dataset moved in a different
10664 * DB will lead to a different digest */
10665 aux = htonl(j);
10666 mixDigest(final,&aux,sizeof(aux));
10667
10668 /* Iterate this DB writing every entry */
10669 while((de = dictNext(di)) != NULL) {
10670 robj *key, *o, *kcopy;
10671 time_t expiretime;
10672
10673 memset(digest,0,20); /* This key-val digest */
10674 key = dictGetEntryKey(de);
10675
10676 if (!server.vm_enabled) {
10677 mixObjectDigest(digest,key);
10678 o = dictGetEntryVal(de);
10679 } else {
10680 /* Don't work with the key directly as when VM is active
10681 * this is unsafe: TODO: fix decrRefCount to check if the
10682 * count really reached 0 to avoid this mess */
10683 kcopy = dupStringObject(key);
10684 mixObjectDigest(digest,kcopy);
10685 o = lookupKeyRead(db,kcopy);
10686 decrRefCount(kcopy);
10687 }
10688 aux = htonl(o->type);
10689 mixDigest(digest,&aux,sizeof(aux));
10690 expiretime = getExpire(db,key);
10691
10692 /* Save the key and associated value */
10693 if (o->type == REDIS_STRING) {
10694 mixObjectDigest(digest,o);
10695 } else if (o->type == REDIS_LIST) {
10696 list *list = o->ptr;
10697 listNode *ln;
10698 listIter li;
10699
10700 listRewind(list,&li);
10701 while((ln = listNext(&li))) {
10702 robj *eleobj = listNodeValue(ln);
10703
10704 mixObjectDigest(digest,eleobj);
10705 }
10706 } else if (o->type == REDIS_SET) {
10707 dict *set = o->ptr;
10708 dictIterator *di = dictGetIterator(set);
10709 dictEntry *de;
10710
10711 while((de = dictNext(di)) != NULL) {
10712 robj *eleobj = dictGetEntryKey(de);
10713
10714 xorObjectDigest(digest,eleobj);
10715 }
10716 dictReleaseIterator(di);
10717 } else if (o->type == REDIS_ZSET) {
10718 zset *zs = o->ptr;
10719 dictIterator *di = dictGetIterator(zs->dict);
10720 dictEntry *de;
10721
10722 while((de = dictNext(di)) != NULL) {
10723 robj *eleobj = dictGetEntryKey(de);
10724 double *score = dictGetEntryVal(de);
10725 unsigned char eledigest[20];
10726
10727 snprintf(buf,sizeof(buf),"%.17g",*score);
10728 memset(eledigest,0,20);
10729 mixObjectDigest(eledigest,eleobj);
10730 mixDigest(eledigest,buf,strlen(buf));
10731 xorDigest(digest,eledigest,20);
10732 }
10733 dictReleaseIterator(di);
10734 } else if (o->type == REDIS_HASH) {
10735 hashIterator *hi;
10736 robj *obj;
10737
10738 hi = hashInitIterator(o);
10739 while (hashNext(hi) != REDIS_ERR) {
10740 unsigned char eledigest[20];
10741
10742 memset(eledigest,0,20);
10743 obj = hashCurrent(hi,REDIS_HASH_KEY);
10744 mixObjectDigest(eledigest,obj);
10745 decrRefCount(obj);
10746 obj = hashCurrent(hi,REDIS_HASH_VALUE);
10747 mixObjectDigest(eledigest,obj);
10748 decrRefCount(obj);
10749 xorDigest(digest,eledigest,20);
10750 }
10751 hashReleaseIterator(hi);
10752 } else {
10753 redisPanic("Unknown object type");
10754 }
10755 /* If the key has an expire, add it to the mix */
10756 if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
10757 /* We can finally xor the key-val digest to the final digest */
10758 xorDigest(final,digest,20);
10759 }
10760 dictReleaseIterator(di);
10761 }
10762 }
10763
10764 static void debugCommand(redisClient *c) {
10765 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
10766 *((char*)-1) = 'x';
10767 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
10768 if (rdbSave(server.dbfilename) != REDIS_OK) {
10769 addReply(c,shared.err);
10770 return;
10771 }
10772 emptyDb();
10773 if (rdbLoad(server.dbfilename) != REDIS_OK) {
10774 addReply(c,shared.err);
10775 return;
10776 }
10777 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
10778 addReply(c,shared.ok);
10779 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
10780 emptyDb();
10781 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
10782 addReply(c,shared.err);
10783 return;
10784 }
10785 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
10786 addReply(c,shared.ok);
10787 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
10788 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
10789 robj *key, *val;
10790
10791 if (!de) {
10792 addReply(c,shared.nokeyerr);
10793 return;
10794 }
10795 key = dictGetEntryKey(de);
10796 val = dictGetEntryVal(de);
10797 if (!server.vm_enabled || (key->storage == REDIS_VM_MEMORY ||
10798 key->storage == REDIS_VM_SWAPPING)) {
10799 char *strenc;
10800 char buf[128];
10801
10802 if (val->encoding < (sizeof(strencoding)/sizeof(char*))) {
10803 strenc = strencoding[val->encoding];
10804 } else {
10805 snprintf(buf,64,"unknown encoding %d\n", val->encoding);
10806 strenc = buf;
10807 }
10808 addReplySds(c,sdscatprintf(sdsempty(),
10809 "+Key at:%p refcount:%d, value at:%p refcount:%d "
10810 "encoding:%s serializedlength:%lld\r\n",
10811 (void*)key, key->refcount, (void*)val, val->refcount,
10812 strenc, (long long) rdbSavedObjectLen(val,NULL)));
10813 } else {
10814 addReplySds(c,sdscatprintf(sdsempty(),
10815 "+Key at:%p refcount:%d, value swapped at: page %llu "
10816 "using %llu pages\r\n",
10817 (void*)key, key->refcount, (unsigned long long) key->vm.page,
10818 (unsigned long long) key->vm.usedpages));
10819 }
10820 } else if (!strcasecmp(c->argv[1]->ptr,"swapin") && c->argc == 3) {
10821 lookupKeyRead(c->db,c->argv[2]);
10822 addReply(c,shared.ok);
10823 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
10824 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
10825 robj *key, *val;
10826
10827 if (!server.vm_enabled) {
10828 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
10829 return;
10830 }
10831 if (!de) {
10832 addReply(c,shared.nokeyerr);
10833 return;
10834 }
10835 key = dictGetEntryKey(de);
10836 val = dictGetEntryVal(de);
10837 /* If the key is shared we want to create a copy */
10838 if (key->refcount > 1) {
10839 robj *newkey = dupStringObject(key);
10840 decrRefCount(key);
10841 key = dictGetEntryKey(de) = newkey;
10842 }
10843 /* Swap it */
10844 if (key->storage != REDIS_VM_MEMORY) {
10845 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
10846 } else if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
10847 dictGetEntryVal(de) = NULL;
10848 addReply(c,shared.ok);
10849 } else {
10850 addReply(c,shared.err);
10851 }
10852 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
10853 long keys, j;
10854 robj *key, *val;
10855 char buf[128];
10856
10857 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
10858 return;
10859 for (j = 0; j < keys; j++) {
10860 snprintf(buf,sizeof(buf),"key:%lu",j);
10861 key = createStringObject(buf,strlen(buf));
10862 if (lookupKeyRead(c->db,key) != NULL) {
10863 decrRefCount(key);
10864 continue;
10865 }
10866 snprintf(buf,sizeof(buf),"value:%lu",j);
10867 val = createStringObject(buf,strlen(buf));
10868 dictAdd(c->db->dict,key,val);
10869 }
10870 addReply(c,shared.ok);
10871 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
10872 unsigned char digest[20];
10873 sds d = sdsnew("+");
10874 int j;
10875
10876 computeDatasetDigest(digest);
10877 for (j = 0; j < 20; j++)
10878 d = sdscatprintf(d, "%02x",digest[j]);
10879
10880 d = sdscatlen(d,"\r\n",2);
10881 addReplySds(c,d);
10882 } else {
10883 addReplySds(c,sdsnew(
10884 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
10885 }
10886 }
10887
10888 static void _redisAssert(char *estr, char *file, int line) {
10889 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
10890 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
10891 #ifdef HAVE_BACKTRACE
10892 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
10893 *((char*)-1) = 'x';
10894 #endif
10895 }
10896
10897 static void _redisPanic(char *msg, char *file, int line) {
10898 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
10899 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
10900 #ifdef HAVE_BACKTRACE
10901 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
10902 *((char*)-1) = 'x';
10903 #endif
10904 }
10905
10906 /* =================================== Main! ================================ */
10907
10908 #ifdef __linux__
10909 int linuxOvercommitMemoryValue(void) {
10910 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
10911 char buf[64];
10912
10913 if (!fp) return -1;
10914 if (fgets(buf,64,fp) == NULL) {
10915 fclose(fp);
10916 return -1;
10917 }
10918 fclose(fp);
10919
10920 return atoi(buf);
10921 }
10922
10923 void linuxOvercommitMemoryWarning(void) {
10924 if (linuxOvercommitMemoryValue() == 0) {
10925 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.");
10926 }
10927 }
10928 #endif /* __linux__ */
10929
10930 static void daemonize(void) {
10931 int fd;
10932 FILE *fp;
10933
10934 if (fork() != 0) exit(0); /* parent exits */
10935 setsid(); /* create a new session */
10936
10937 /* Every output goes to /dev/null. If Redis is daemonized but
10938 * the 'logfile' is set to 'stdout' in the configuration file
10939 * it will not log at all. */
10940 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
10941 dup2(fd, STDIN_FILENO);
10942 dup2(fd, STDOUT_FILENO);
10943 dup2(fd, STDERR_FILENO);
10944 if (fd > STDERR_FILENO) close(fd);
10945 }
10946 /* Try to write the pid file */
10947 fp = fopen(server.pidfile,"w");
10948 if (fp) {
10949 fprintf(fp,"%d\n",getpid());
10950 fclose(fp);
10951 }
10952 }
10953
10954 static void version() {
10955 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
10956 REDIS_GIT_SHA1, atoi(REDIS_GIT_DIRTY) > 0);
10957 exit(0);
10958 }
10959
10960 static void usage() {
10961 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
10962 fprintf(stderr," ./redis-server - (read config from stdin)\n");
10963 exit(1);
10964 }
10965
10966 int main(int argc, char **argv) {
10967 time_t start;
10968
10969 initServerConfig();
10970 sortCommandTable();
10971 if (argc == 2) {
10972 if (strcmp(argv[1], "-v") == 0 ||
10973 strcmp(argv[1], "--version") == 0) version();
10974 if (strcmp(argv[1], "--help") == 0) usage();
10975 resetServerSaveParams();
10976 loadServerConfig(argv[1]);
10977 } else if ((argc > 2)) {
10978 usage();
10979 } else {
10980 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'");
10981 }
10982 if (server.daemonize) daemonize();
10983 initServer();
10984 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
10985 #ifdef __linux__
10986 linuxOvercommitMemoryWarning();
10987 #endif
10988 start = time(NULL);
10989 if (server.appendonly) {
10990 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
10991 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
10992 } else {
10993 if (rdbLoad(server.dbfilename) == REDIS_OK)
10994 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
10995 }
10996 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
10997 aeSetBeforeSleepProc(server.el,beforeSleep);
10998 aeMain(server.el);
10999 aeDeleteEventLoop(server.el);
11000 return 0;
11001 }
11002
11003 /* ============================= Backtrace support ========================= */
11004
11005 #ifdef HAVE_BACKTRACE
11006 static char *findFuncName(void *pointer, unsigned long *offset);
11007
11008 static void *getMcontextEip(ucontext_t *uc) {
11009 #if defined(__FreeBSD__)
11010 return (void*) uc->uc_mcontext.mc_eip;
11011 #elif defined(__dietlibc__)
11012 return (void*) uc->uc_mcontext.eip;
11013 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
11014 #if __x86_64__
11015 return (void*) uc->uc_mcontext->__ss.__rip;
11016 #else
11017 return (void*) uc->uc_mcontext->__ss.__eip;
11018 #endif
11019 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
11020 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
11021 return (void*) uc->uc_mcontext->__ss.__rip;
11022 #else
11023 return (void*) uc->uc_mcontext->__ss.__eip;
11024 #endif
11025 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
11026 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
11027 #elif defined(__ia64__) /* Linux IA64 */
11028 return (void*) uc->uc_mcontext.sc_ip;
11029 #else
11030 return NULL;
11031 #endif
11032 }
11033
11034 static void segvHandler(int sig, siginfo_t *info, void *secret) {
11035 void *trace[100];
11036 char **messages = NULL;
11037 int i, trace_size = 0;
11038 unsigned long offset=0;
11039 ucontext_t *uc = (ucontext_t*) secret;
11040 sds infostring;
11041 REDIS_NOTUSED(info);
11042
11043 redisLog(REDIS_WARNING,
11044 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
11045 infostring = genRedisInfoString();
11046 redisLog(REDIS_WARNING, "%s",infostring);
11047 /* It's not safe to sdsfree() the returned string under memory
11048 * corruption conditions. Let it leak as we are going to abort */
11049
11050 trace_size = backtrace(trace, 100);
11051 /* overwrite sigaction with caller's address */
11052 if (getMcontextEip(uc) != NULL) {
11053 trace[1] = getMcontextEip(uc);
11054 }
11055 messages = backtrace_symbols(trace, trace_size);
11056
11057 for (i=1; i<trace_size; ++i) {
11058 char *fn = findFuncName(trace[i], &offset), *p;
11059
11060 p = strchr(messages[i],'+');
11061 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
11062 redisLog(REDIS_WARNING,"%s", messages[i]);
11063 } else {
11064 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
11065 }
11066 }
11067 /* free(messages); Don't call free() with possibly corrupted memory. */
11068 _exit(0);
11069 }
11070
11071 static void sigtermHandler(int sig) {
11072 REDIS_NOTUSED(sig);
11073
11074 redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
11075 server.shutdown_asap = 1;
11076 }
11077
11078 static void setupSigSegvAction(void) {
11079 struct sigaction act;
11080
11081 sigemptyset (&act.sa_mask);
11082 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
11083 * is used. Otherwise, sa_handler is used */
11084 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
11085 act.sa_sigaction = segvHandler;
11086 sigaction (SIGSEGV, &act, NULL);
11087 sigaction (SIGBUS, &act, NULL);
11088 sigaction (SIGFPE, &act, NULL);
11089 sigaction (SIGILL, &act, NULL);
11090 sigaction (SIGBUS, &act, NULL);
11091
11092 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
11093 act.sa_handler = sigtermHandler;
11094 sigaction (SIGTERM, &act, NULL);
11095 return;
11096 }
11097
11098 #include "staticsymbols.h"
11099 /* This function try to convert a pointer into a function name. It's used in
11100 * oreder to provide a backtrace under segmentation fault that's able to
11101 * display functions declared as static (otherwise the backtrace is useless). */
11102 static char *findFuncName(void *pointer, unsigned long *offset){
11103 int i, ret = -1;
11104 unsigned long off, minoff = 0;
11105
11106 /* Try to match against the Symbol with the smallest offset */
11107 for (i=0; symsTable[i].pointer; i++) {
11108 unsigned long lp = (unsigned long) pointer;
11109
11110 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
11111 off=lp-symsTable[i].pointer;
11112 if (ret < 0 || off < minoff) {
11113 minoff=off;
11114 ret=i;
11115 }
11116 }
11117 }
11118 if (ret == -1) return NULL;
11119 *offset = minoff;
11120 return symsTable[ret].name;
11121 }
11122 #else /* HAVE_BACKTRACE */
11123 static void setupSigSegvAction(void) {
11124 }
11125 #endif /* HAVE_BACKTRACE */
11126
11127
11128
11129 /* The End */
11130
11131
11132