]> git.saurik.com Git - redis.git/blob - redis.c
support rewriting the AOF with dual list encoding
[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 robj *o = createObject(REDIS_LIST,l);
2988 listSetFreeMethod(l,decrRefCount);
2989 o->encoding = REDIS_ENCODING_LIST;
2990 return o;
2991 }
2992
2993 static robj *createZiplistObject(void) {
2994 unsigned char *zl = ziplistNew();
2995 robj *o = createObject(REDIS_LIST,zl);
2996 o->encoding = REDIS_ENCODING_ZIPLIST;
2997 return o;
2998 }
2999
3000 static robj *createSetObject(void) {
3001 dict *d = dictCreate(&setDictType,NULL);
3002 return createObject(REDIS_SET,d);
3003 }
3004
3005 static robj *createHashObject(void) {
3006 /* All the Hashes start as zipmaps. Will be automatically converted
3007 * into hash tables if there are enough elements or big elements
3008 * inside. */
3009 unsigned char *zm = zipmapNew();
3010 robj *o = createObject(REDIS_HASH,zm);
3011 o->encoding = REDIS_ENCODING_ZIPMAP;
3012 return o;
3013 }
3014
3015 static robj *createZsetObject(void) {
3016 zset *zs = zmalloc(sizeof(*zs));
3017
3018 zs->dict = dictCreate(&zsetDictType,NULL);
3019 zs->zsl = zslCreate();
3020 return createObject(REDIS_ZSET,zs);
3021 }
3022
3023 static void freeStringObject(robj *o) {
3024 if (o->encoding == REDIS_ENCODING_RAW) {
3025 sdsfree(o->ptr);
3026 }
3027 }
3028
3029 static void freeListObject(robj *o) {
3030 switch (o->encoding) {
3031 case REDIS_ENCODING_LIST:
3032 listRelease((list*) o->ptr);
3033 break;
3034 case REDIS_ENCODING_ZIPLIST:
3035 zfree(o->ptr);
3036 break;
3037 default:
3038 redisPanic("Unknown list encoding type");
3039 }
3040 }
3041
3042 static void freeSetObject(robj *o) {
3043 dictRelease((dict*) o->ptr);
3044 }
3045
3046 static void freeZsetObject(robj *o) {
3047 zset *zs = o->ptr;
3048
3049 dictRelease(zs->dict);
3050 zslFree(zs->zsl);
3051 zfree(zs);
3052 }
3053
3054 static void freeHashObject(robj *o) {
3055 switch (o->encoding) {
3056 case REDIS_ENCODING_HT:
3057 dictRelease((dict*) o->ptr);
3058 break;
3059 case REDIS_ENCODING_ZIPMAP:
3060 zfree(o->ptr);
3061 break;
3062 default:
3063 redisPanic("Unknown hash encoding type");
3064 break;
3065 }
3066 }
3067
3068 static void incrRefCount(robj *o) {
3069 o->refcount++;
3070 }
3071
3072 static void decrRefCount(void *obj) {
3073 robj *o = obj;
3074
3075 if (o->refcount <= 0) redisPanic("decrRefCount against refcount <= 0");
3076 /* Object is a key of a swapped out value, or in the process of being
3077 * loaded. */
3078 if (server.vm_enabled &&
3079 (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
3080 {
3081 if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(obj);
3082 redisAssert(o->type == REDIS_STRING);
3083 freeStringObject(o);
3084 vmMarkPagesFree(o->vm.page,o->vm.usedpages);
3085 pthread_mutex_lock(&server.obj_freelist_mutex);
3086 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3087 !listAddNodeHead(server.objfreelist,o))
3088 zfree(o);
3089 pthread_mutex_unlock(&server.obj_freelist_mutex);
3090 server.vm_stats_swapped_objects--;
3091 return;
3092 }
3093 /* Object is in memory, or in the process of being swapped out. */
3094 if (--(o->refcount) == 0) {
3095 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
3096 vmCancelThreadedIOJob(obj);
3097 switch(o->type) {
3098 case REDIS_STRING: freeStringObject(o); break;
3099 case REDIS_LIST: freeListObject(o); break;
3100 case REDIS_SET: freeSetObject(o); break;
3101 case REDIS_ZSET: freeZsetObject(o); break;
3102 case REDIS_HASH: freeHashObject(o); break;
3103 default: redisPanic("Unknown object type"); break;
3104 }
3105 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
3106 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3107 !listAddNodeHead(server.objfreelist,o))
3108 zfree(o);
3109 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
3110 }
3111 }
3112
3113 static robj *lookupKey(redisDb *db, robj *key) {
3114 dictEntry *de = dictFind(db->dict,key);
3115 if (de) {
3116 robj *key = dictGetEntryKey(de);
3117 robj *val = dictGetEntryVal(de);
3118
3119 if (server.vm_enabled) {
3120 if (key->storage == REDIS_VM_MEMORY ||
3121 key->storage == REDIS_VM_SWAPPING)
3122 {
3123 /* If we were swapping the object out, stop it, this key
3124 * was requested. */
3125 if (key->storage == REDIS_VM_SWAPPING)
3126 vmCancelThreadedIOJob(key);
3127 /* Update the access time of the key for the aging algorithm. */
3128 key->vm.atime = server.unixtime;
3129 } else {
3130 int notify = (key->storage == REDIS_VM_LOADING);
3131
3132 /* Our value was swapped on disk. Bring it at home. */
3133 redisAssert(val == NULL);
3134 val = vmLoadObject(key);
3135 dictGetEntryVal(de) = val;
3136
3137 /* Clients blocked by the VM subsystem may be waiting for
3138 * this key... */
3139 if (notify) handleClientsBlockedOnSwappedKey(db,key);
3140 }
3141 }
3142 return val;
3143 } else {
3144 return NULL;
3145 }
3146 }
3147
3148 static robj *lookupKeyRead(redisDb *db, robj *key) {
3149 expireIfNeeded(db,key);
3150 return lookupKey(db,key);
3151 }
3152
3153 static robj *lookupKeyWrite(redisDb *db, robj *key) {
3154 deleteIfVolatile(db,key);
3155 touchWatchedKey(db,key);
3156 return lookupKey(db,key);
3157 }
3158
3159 static robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
3160 robj *o = lookupKeyRead(c->db, key);
3161 if (!o) addReply(c,reply);
3162 return o;
3163 }
3164
3165 static robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
3166 robj *o = lookupKeyWrite(c->db, key);
3167 if (!o) addReply(c,reply);
3168 return o;
3169 }
3170
3171 static int checkType(redisClient *c, robj *o, int type) {
3172 if (o->type != type) {
3173 addReply(c,shared.wrongtypeerr);
3174 return 1;
3175 }
3176 return 0;
3177 }
3178
3179 static int deleteKey(redisDb *db, robj *key) {
3180 int retval;
3181
3182 /* We need to protect key from destruction: after the first dictDelete()
3183 * it may happen that 'key' is no longer valid if we don't increment
3184 * it's count. This may happen when we get the object reference directly
3185 * from the hash table with dictRandomKey() or dict iterators */
3186 incrRefCount(key);
3187 if (dictSize(db->expires)) dictDelete(db->expires,key);
3188 retval = dictDelete(db->dict,key);
3189 decrRefCount(key);
3190
3191 return retval == DICT_OK;
3192 }
3193
3194 /* Check if the nul-terminated string 's' can be represented by a long
3195 * (that is, is a number that fits into long without any other space or
3196 * character before or after the digits).
3197 *
3198 * If so, the function returns REDIS_OK and *longval is set to the value
3199 * of the number. Otherwise REDIS_ERR is returned */
3200 static int isStringRepresentableAsLong(sds s, long *longval) {
3201 char buf[32], *endptr;
3202 long value;
3203 int slen;
3204
3205 value = strtol(s, &endptr, 10);
3206 if (endptr[0] != '\0') return REDIS_ERR;
3207 slen = ll2string(buf,32,value);
3208
3209 /* If the number converted back into a string is not identical
3210 * then it's not possible to encode the string as integer */
3211 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
3212 if (longval) *longval = value;
3213 return REDIS_OK;
3214 }
3215
3216 /* Try to encode a string object in order to save space */
3217 static robj *tryObjectEncoding(robj *o) {
3218 long value;
3219 sds s = o->ptr;
3220
3221 if (o->encoding != REDIS_ENCODING_RAW)
3222 return o; /* Already encoded */
3223
3224 /* It's not safe to encode shared objects: shared objects can be shared
3225 * everywhere in the "object space" of Redis. Encoded objects can only
3226 * appear as "values" (and not, for instance, as keys) */
3227 if (o->refcount > 1) return o;
3228
3229 /* Currently we try to encode only strings */
3230 redisAssert(o->type == REDIS_STRING);
3231
3232 /* Check if we can represent this string as a long integer */
3233 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return o;
3234
3235 /* Ok, this object can be encoded */
3236 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3237 decrRefCount(o);
3238 incrRefCount(shared.integers[value]);
3239 return shared.integers[value];
3240 } else {
3241 o->encoding = REDIS_ENCODING_INT;
3242 sdsfree(o->ptr);
3243 o->ptr = (void*) value;
3244 return o;
3245 }
3246 }
3247
3248 /* Get a decoded version of an encoded object (returned as a new object).
3249 * If the object is already raw-encoded just increment the ref count. */
3250 static robj *getDecodedObject(robj *o) {
3251 robj *dec;
3252
3253 if (o->encoding == REDIS_ENCODING_RAW) {
3254 incrRefCount(o);
3255 return o;
3256 }
3257 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
3258 char buf[32];
3259
3260 ll2string(buf,32,(long)o->ptr);
3261 dec = createStringObject(buf,strlen(buf));
3262 return dec;
3263 } else {
3264 redisPanic("Unknown encoding type");
3265 }
3266 }
3267
3268 /* Compare two string objects via strcmp() or alike.
3269 * Note that the objects may be integer-encoded. In such a case we
3270 * use ll2string() to get a string representation of the numbers on the stack
3271 * and compare the strings, it's much faster than calling getDecodedObject().
3272 *
3273 * Important note: if objects are not integer encoded, but binary-safe strings,
3274 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3275 * binary safe. */
3276 static int compareStringObjects(robj *a, robj *b) {
3277 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
3278 char bufa[128], bufb[128], *astr, *bstr;
3279 int bothsds = 1;
3280
3281 if (a == b) return 0;
3282 if (a->encoding != REDIS_ENCODING_RAW) {
3283 ll2string(bufa,sizeof(bufa),(long) a->ptr);
3284 astr = bufa;
3285 bothsds = 0;
3286 } else {
3287 astr = a->ptr;
3288 }
3289 if (b->encoding != REDIS_ENCODING_RAW) {
3290 ll2string(bufb,sizeof(bufb),(long) b->ptr);
3291 bstr = bufb;
3292 bothsds = 0;
3293 } else {
3294 bstr = b->ptr;
3295 }
3296 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
3297 }
3298
3299 /* Equal string objects return 1 if the two objects are the same from the
3300 * point of view of a string comparison, otherwise 0 is returned. Note that
3301 * this function is faster then checking for (compareStringObject(a,b) == 0)
3302 * because it can perform some more optimization. */
3303 static int equalStringObjects(robj *a, robj *b) {
3304 if (a->encoding != REDIS_ENCODING_RAW && b->encoding != REDIS_ENCODING_RAW){
3305 return a->ptr == b->ptr;
3306 } else {
3307 return compareStringObjects(a,b) == 0;
3308 }
3309 }
3310
3311 static size_t stringObjectLen(robj *o) {
3312 redisAssert(o->type == REDIS_STRING);
3313 if (o->encoding == REDIS_ENCODING_RAW) {
3314 return sdslen(o->ptr);
3315 } else {
3316 char buf[32];
3317
3318 return ll2string(buf,32,(long)o->ptr);
3319 }
3320 }
3321
3322 static int getDoubleFromObject(robj *o, double *target) {
3323 double value;
3324 char *eptr;
3325
3326 if (o == NULL) {
3327 value = 0;
3328 } else {
3329 redisAssert(o->type == REDIS_STRING);
3330 if (o->encoding == REDIS_ENCODING_RAW) {
3331 value = strtod(o->ptr, &eptr);
3332 if (eptr[0] != '\0') return REDIS_ERR;
3333 } else if (o->encoding == REDIS_ENCODING_INT) {
3334 value = (long)o->ptr;
3335 } else {
3336 redisPanic("Unknown string encoding");
3337 }
3338 }
3339
3340 *target = value;
3341 return REDIS_OK;
3342 }
3343
3344 static int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg) {
3345 double value;
3346 if (getDoubleFromObject(o, &value) != REDIS_OK) {
3347 if (msg != NULL) {
3348 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3349 } else {
3350 addReplySds(c, sdsnew("-ERR value is not a double\r\n"));
3351 }
3352 return REDIS_ERR;
3353 }
3354
3355 *target = value;
3356 return REDIS_OK;
3357 }
3358
3359 static int getLongLongFromObject(robj *o, long long *target) {
3360 long long value;
3361 char *eptr;
3362
3363 if (o == NULL) {
3364 value = 0;
3365 } else {
3366 redisAssert(o->type == REDIS_STRING);
3367 if (o->encoding == REDIS_ENCODING_RAW) {
3368 value = strtoll(o->ptr, &eptr, 10);
3369 if (eptr[0] != '\0') return REDIS_ERR;
3370 } else if (o->encoding == REDIS_ENCODING_INT) {
3371 value = (long)o->ptr;
3372 } else {
3373 redisPanic("Unknown string encoding");
3374 }
3375 }
3376
3377 *target = value;
3378 return REDIS_OK;
3379 }
3380
3381 static int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg) {
3382 long long value;
3383 if (getLongLongFromObject(o, &value) != REDIS_OK) {
3384 if (msg != NULL) {
3385 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3386 } else {
3387 addReplySds(c, sdsnew("-ERR value is not an integer\r\n"));
3388 }
3389 return REDIS_ERR;
3390 }
3391
3392 *target = value;
3393 return REDIS_OK;
3394 }
3395
3396 static int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg) {
3397 long long value;
3398
3399 if (getLongLongFromObjectOrReply(c, o, &value, msg) != REDIS_OK) return REDIS_ERR;
3400 if (value < LONG_MIN || value > LONG_MAX) {
3401 if (msg != NULL) {
3402 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3403 } else {
3404 addReplySds(c, sdsnew("-ERR value is out of range\r\n"));
3405 }
3406 return REDIS_ERR;
3407 }
3408
3409 *target = value;
3410 return REDIS_OK;
3411 }
3412
3413 /*============================ RDB saving/loading =========================== */
3414
3415 static int rdbSaveType(FILE *fp, unsigned char type) {
3416 if (fwrite(&type,1,1,fp) == 0) return -1;
3417 return 0;
3418 }
3419
3420 static int rdbSaveTime(FILE *fp, time_t t) {
3421 int32_t t32 = (int32_t) t;
3422 if (fwrite(&t32,4,1,fp) == 0) return -1;
3423 return 0;
3424 }
3425
3426 /* check rdbLoadLen() comments for more info */
3427 static int rdbSaveLen(FILE *fp, uint32_t len) {
3428 unsigned char buf[2];
3429
3430 if (len < (1<<6)) {
3431 /* Save a 6 bit len */
3432 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
3433 if (fwrite(buf,1,1,fp) == 0) return -1;
3434 } else if (len < (1<<14)) {
3435 /* Save a 14 bit len */
3436 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
3437 buf[1] = len&0xFF;
3438 if (fwrite(buf,2,1,fp) == 0) return -1;
3439 } else {
3440 /* Save a 32 bit len */
3441 buf[0] = (REDIS_RDB_32BITLEN<<6);
3442 if (fwrite(buf,1,1,fp) == 0) return -1;
3443 len = htonl(len);
3444 if (fwrite(&len,4,1,fp) == 0) return -1;
3445 }
3446 return 0;
3447 }
3448
3449 /* Encode 'value' as an integer if possible (if integer will fit the
3450 * supported range). If the function sucessful encoded the integer
3451 * then the (up to 5 bytes) encoded representation is written in the
3452 * string pointed by 'enc' and the length is returned. Otherwise
3453 * 0 is returned. */
3454 static int rdbEncodeInteger(long long value, unsigned char *enc) {
3455 /* Finally check if it fits in our ranges */
3456 if (value >= -(1<<7) && value <= (1<<7)-1) {
3457 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
3458 enc[1] = value&0xFF;
3459 return 2;
3460 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
3461 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
3462 enc[1] = value&0xFF;
3463 enc[2] = (value>>8)&0xFF;
3464 return 3;
3465 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
3466 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
3467 enc[1] = value&0xFF;
3468 enc[2] = (value>>8)&0xFF;
3469 enc[3] = (value>>16)&0xFF;
3470 enc[4] = (value>>24)&0xFF;
3471 return 5;
3472 } else {
3473 return 0;
3474 }
3475 }
3476
3477 /* String objects in the form "2391" "-100" without any space and with a
3478 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3479 * encoded as integers to save space */
3480 static int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
3481 long long value;
3482 char *endptr, buf[32];
3483
3484 /* Check if it's possible to encode this value as a number */
3485 value = strtoll(s, &endptr, 10);
3486 if (endptr[0] != '\0') return 0;
3487 ll2string(buf,32,value);
3488
3489 /* If the number converted back into a string is not identical
3490 * then it's not possible to encode the string as integer */
3491 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
3492
3493 return rdbEncodeInteger(value,enc);
3494 }
3495
3496 static int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
3497 size_t comprlen, outlen;
3498 unsigned char byte;
3499 void *out;
3500
3501 /* We require at least four bytes compression for this to be worth it */
3502 if (len <= 4) return 0;
3503 outlen = len-4;
3504 if ((out = zmalloc(outlen+1)) == NULL) return 0;
3505 comprlen = lzf_compress(s, len, out, outlen);
3506 if (comprlen == 0) {
3507 zfree(out);
3508 return 0;
3509 }
3510 /* Data compressed! Let's save it on disk */
3511 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
3512 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
3513 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
3514 if (rdbSaveLen(fp,len) == -1) goto writeerr;
3515 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
3516 zfree(out);
3517 return comprlen;
3518
3519 writeerr:
3520 zfree(out);
3521 return -1;
3522 }
3523
3524 /* Save a string objet as [len][data] on disk. If the object is a string
3525 * representation of an integer value we try to safe it in a special form */
3526 static int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
3527 int enclen;
3528
3529 /* Try integer encoding */
3530 if (len <= 11) {
3531 unsigned char buf[5];
3532 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
3533 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3534 return 0;
3535 }
3536 }
3537
3538 /* Try LZF compression - under 20 bytes it's unable to compress even
3539 * aaaaaaaaaaaaaaaaaa so skip it */
3540 if (server.rdbcompression && len > 20) {
3541 int retval;
3542
3543 retval = rdbSaveLzfStringObject(fp,s,len);
3544 if (retval == -1) return -1;
3545 if (retval > 0) return 0;
3546 /* retval == 0 means data can't be compressed, save the old way */
3547 }
3548
3549 /* Store verbatim */
3550 if (rdbSaveLen(fp,len) == -1) return -1;
3551 if (len && fwrite(s,len,1,fp) == 0) return -1;
3552 return 0;
3553 }
3554
3555 /* Save a long long value as either an encoded string or a string. */
3556 static int rdbSaveLongLongAsStringObject(FILE *fp, long long value) {
3557 unsigned char buf[32];
3558 int enclen = rdbEncodeInteger(value,buf);
3559 if (enclen > 0) {
3560 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3561 } else {
3562 /* Encode as string */
3563 enclen = ll2string((char*)buf,32,value);
3564 redisAssert(enclen < 32);
3565 if (rdbSaveLen(fp,enclen) == -1) return -1;
3566 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3567 }
3568 return 0;
3569 }
3570
3571 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3572 static int rdbSaveStringObject(FILE *fp, robj *obj) {
3573 /* Avoid to decode the object, then encode it again, if the
3574 * object is alrady integer encoded. */
3575 if (obj->encoding == REDIS_ENCODING_INT) {
3576 return rdbSaveLongLongAsStringObject(fp,(long)obj->ptr);
3577 } else {
3578 redisAssert(obj->encoding == REDIS_ENCODING_RAW);
3579 return rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
3580 }
3581 }
3582
3583 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3584 * 8 bit integer specifing the length of the representation.
3585 * This 8 bit integer has special values in order to specify the following
3586 * conditions:
3587 * 253: not a number
3588 * 254: + inf
3589 * 255: - inf
3590 */
3591 static int rdbSaveDoubleValue(FILE *fp, double val) {
3592 unsigned char buf[128];
3593 int len;
3594
3595 if (isnan(val)) {
3596 buf[0] = 253;
3597 len = 1;
3598 } else if (!isfinite(val)) {
3599 len = 1;
3600 buf[0] = (val < 0) ? 255 : 254;
3601 } else {
3602 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
3603 /* Check if the float is in a safe range to be casted into a
3604 * long long. We are assuming that long long is 64 bit here.
3605 * Also we are assuming that there are no implementations around where
3606 * double has precision < 52 bit.
3607 *
3608 * Under this assumptions we test if a double is inside an interval
3609 * where casting to long long is safe. Then using two castings we
3610 * make sure the decimal part is zero. If all this is true we use
3611 * integer printing function that is much faster. */
3612 double min = -4503599627370495; /* (2^52)-1 */
3613 double max = 4503599627370496; /* -(2^52) */
3614 if (val > min && val < max && val == ((double)((long long)val)))
3615 ll2string((char*)buf+1,sizeof(buf),(long long)val);
3616 else
3617 #endif
3618 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
3619 buf[0] = strlen((char*)buf+1);
3620 len = buf[0]+1;
3621 }
3622 if (fwrite(buf,len,1,fp) == 0) return -1;
3623 return 0;
3624 }
3625
3626 /* Save a Redis object. */
3627 static int rdbSaveObject(FILE *fp, robj *o) {
3628 if (o->type == REDIS_STRING) {
3629 /* Save a string value */
3630 if (rdbSaveStringObject(fp,o) == -1) return -1;
3631 } else if (o->type == REDIS_LIST) {
3632 /* Save a list value */
3633 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
3634 unsigned char *p;
3635 unsigned char *vstr;
3636 unsigned int vlen;
3637 long long vlong;
3638
3639 if (rdbSaveLen(fp,ziplistLen(o->ptr)) == -1) return -1;
3640 p = ziplistIndex(o->ptr,0);
3641 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
3642 if (vstr) {
3643 if (rdbSaveRawString(fp,vstr,vlen) == -1)
3644 return -1;
3645 } else {
3646 if (rdbSaveLongLongAsStringObject(fp,vlong) == -1)
3647 return -1;
3648 }
3649 p = ziplistNext(o->ptr,p);
3650 }
3651 } else if (o->encoding == REDIS_ENCODING_LIST) {
3652 list *list = o->ptr;
3653 listIter li;
3654 listNode *ln;
3655
3656 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
3657 listRewind(list,&li);
3658 while((ln = listNext(&li))) {
3659 robj *eleobj = listNodeValue(ln);
3660 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3661 }
3662 } else {
3663 redisPanic("Unknown list encoding");
3664 }
3665 } else if (o->type == REDIS_SET) {
3666 /* Save a set value */
3667 dict *set = o->ptr;
3668 dictIterator *di = dictGetIterator(set);
3669 dictEntry *de;
3670
3671 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
3672 while((de = dictNext(di)) != NULL) {
3673 robj *eleobj = dictGetEntryKey(de);
3674
3675 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3676 }
3677 dictReleaseIterator(di);
3678 } else if (o->type == REDIS_ZSET) {
3679 /* Save a set value */
3680 zset *zs = o->ptr;
3681 dictIterator *di = dictGetIterator(zs->dict);
3682 dictEntry *de;
3683
3684 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
3685 while((de = dictNext(di)) != NULL) {
3686 robj *eleobj = dictGetEntryKey(de);
3687 double *score = dictGetEntryVal(de);
3688
3689 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3690 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
3691 }
3692 dictReleaseIterator(di);
3693 } else if (o->type == REDIS_HASH) {
3694 /* Save a hash value */
3695 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3696 unsigned char *p = zipmapRewind(o->ptr);
3697 unsigned int count = zipmapLen(o->ptr);
3698 unsigned char *key, *val;
3699 unsigned int klen, vlen;
3700
3701 if (rdbSaveLen(fp,count) == -1) return -1;
3702 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
3703 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
3704 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
3705 }
3706 } else {
3707 dictIterator *di = dictGetIterator(o->ptr);
3708 dictEntry *de;
3709
3710 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
3711 while((de = dictNext(di)) != NULL) {
3712 robj *key = dictGetEntryKey(de);
3713 robj *val = dictGetEntryVal(de);
3714
3715 if (rdbSaveStringObject(fp,key) == -1) return -1;
3716 if (rdbSaveStringObject(fp,val) == -1) return -1;
3717 }
3718 dictReleaseIterator(di);
3719 }
3720 } else {
3721 redisPanic("Unknown object type");
3722 }
3723 return 0;
3724 }
3725
3726 /* Return the length the object will have on disk if saved with
3727 * the rdbSaveObject() function. Currently we use a trick to get
3728 * this length with very little changes to the code. In the future
3729 * we could switch to a faster solution. */
3730 static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
3731 if (fp == NULL) fp = server.devnull;
3732 rewind(fp);
3733 assert(rdbSaveObject(fp,o) != 1);
3734 return ftello(fp);
3735 }
3736
3737 /* Return the number of pages required to save this object in the swap file */
3738 static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
3739 off_t bytes = rdbSavedObjectLen(o,fp);
3740
3741 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
3742 }
3743
3744 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3745 static int rdbSave(char *filename) {
3746 dictIterator *di = NULL;
3747 dictEntry *de;
3748 FILE *fp;
3749 char tmpfile[256];
3750 int j;
3751 time_t now = time(NULL);
3752
3753 /* Wait for I/O therads to terminate, just in case this is a
3754 * foreground-saving, to avoid seeking the swap file descriptor at the
3755 * same time. */
3756 if (server.vm_enabled)
3757 waitEmptyIOJobsQueue();
3758
3759 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
3760 fp = fopen(tmpfile,"w");
3761 if (!fp) {
3762 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
3763 return REDIS_ERR;
3764 }
3765 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
3766 for (j = 0; j < server.dbnum; j++) {
3767 redisDb *db = server.db+j;
3768 dict *d = db->dict;
3769 if (dictSize(d) == 0) continue;
3770 di = dictGetIterator(d);
3771 if (!di) {
3772 fclose(fp);
3773 return REDIS_ERR;
3774 }
3775
3776 /* Write the SELECT DB opcode */
3777 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
3778 if (rdbSaveLen(fp,j) == -1) goto werr;
3779
3780 /* Iterate this DB writing every entry */
3781 while((de = dictNext(di)) != NULL) {
3782 robj *key = dictGetEntryKey(de);
3783 robj *o = dictGetEntryVal(de);
3784 time_t expiretime = getExpire(db,key);
3785
3786 /* Save the expire time */
3787 if (expiretime != -1) {
3788 /* If this key is already expired skip it */
3789 if (expiretime < now) continue;
3790 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
3791 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
3792 }
3793 /* Save the key and associated value. This requires special
3794 * handling if the value is swapped out. */
3795 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
3796 key->storage == REDIS_VM_SWAPPING) {
3797 /* Save type, key, value */
3798 if (rdbSaveType(fp,o->type) == -1) goto werr;
3799 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3800 if (rdbSaveObject(fp,o) == -1) goto werr;
3801 } else {
3802 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3803 robj *po;
3804 /* Get a preview of the object in memory */
3805 po = vmPreviewObject(key);
3806 /* Save type, key, value */
3807 if (rdbSaveType(fp,key->vtype) == -1) goto werr;
3808 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3809 if (rdbSaveObject(fp,po) == -1) goto werr;
3810 /* Remove the loaded object from memory */
3811 decrRefCount(po);
3812 }
3813 }
3814 dictReleaseIterator(di);
3815 }
3816 /* EOF opcode */
3817 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
3818
3819 /* Make sure data will not remain on the OS's output buffers */
3820 fflush(fp);
3821 fsync(fileno(fp));
3822 fclose(fp);
3823
3824 /* Use RENAME to make sure the DB file is changed atomically only
3825 * if the generate DB file is ok. */
3826 if (rename(tmpfile,filename) == -1) {
3827 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
3828 unlink(tmpfile);
3829 return REDIS_ERR;
3830 }
3831 redisLog(REDIS_NOTICE,"DB saved on disk");
3832 server.dirty = 0;
3833 server.lastsave = time(NULL);
3834 return REDIS_OK;
3835
3836 werr:
3837 fclose(fp);
3838 unlink(tmpfile);
3839 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
3840 if (di) dictReleaseIterator(di);
3841 return REDIS_ERR;
3842 }
3843
3844 static int rdbSaveBackground(char *filename) {
3845 pid_t childpid;
3846
3847 if (server.bgsavechildpid != -1) return REDIS_ERR;
3848 if (server.vm_enabled) waitEmptyIOJobsQueue();
3849 if ((childpid = fork()) == 0) {
3850 /* Child */
3851 if (server.vm_enabled) vmReopenSwapFile();
3852 close(server.fd);
3853 if (rdbSave(filename) == REDIS_OK) {
3854 _exit(0);
3855 } else {
3856 _exit(1);
3857 }
3858 } else {
3859 /* Parent */
3860 if (childpid == -1) {
3861 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
3862 strerror(errno));
3863 return REDIS_ERR;
3864 }
3865 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
3866 server.bgsavechildpid = childpid;
3867 updateDictResizePolicy();
3868 return REDIS_OK;
3869 }
3870 return REDIS_OK; /* unreached */
3871 }
3872
3873 static void rdbRemoveTempFile(pid_t childpid) {
3874 char tmpfile[256];
3875
3876 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
3877 unlink(tmpfile);
3878 }
3879
3880 static int rdbLoadType(FILE *fp) {
3881 unsigned char type;
3882 if (fread(&type,1,1,fp) == 0) return -1;
3883 return type;
3884 }
3885
3886 static time_t rdbLoadTime(FILE *fp) {
3887 int32_t t32;
3888 if (fread(&t32,4,1,fp) == 0) return -1;
3889 return (time_t) t32;
3890 }
3891
3892 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3893 * of this file for a description of how this are stored on disk.
3894 *
3895 * isencoded is set to 1 if the readed length is not actually a length but
3896 * an "encoding type", check the above comments for more info */
3897 static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
3898 unsigned char buf[2];
3899 uint32_t len;
3900 int type;
3901
3902 if (isencoded) *isencoded = 0;
3903 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
3904 type = (buf[0]&0xC0)>>6;
3905 if (type == REDIS_RDB_6BITLEN) {
3906 /* Read a 6 bit len */
3907 return buf[0]&0x3F;
3908 } else if (type == REDIS_RDB_ENCVAL) {
3909 /* Read a 6 bit len encoding type */
3910 if (isencoded) *isencoded = 1;
3911 return buf[0]&0x3F;
3912 } else if (type == REDIS_RDB_14BITLEN) {
3913 /* Read a 14 bit len */
3914 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
3915 return ((buf[0]&0x3F)<<8)|buf[1];
3916 } else {
3917 /* Read a 32 bit len */
3918 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
3919 return ntohl(len);
3920 }
3921 }
3922
3923 /* Load an integer-encoded object from file 'fp', with the specified
3924 * encoding type 'enctype'. If encode is true the function may return
3925 * an integer-encoded object as reply, otherwise the returned object
3926 * will always be encoded as a raw string. */
3927 static robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
3928 unsigned char enc[4];
3929 long long val;
3930
3931 if (enctype == REDIS_RDB_ENC_INT8) {
3932 if (fread(enc,1,1,fp) == 0) return NULL;
3933 val = (signed char)enc[0];
3934 } else if (enctype == REDIS_RDB_ENC_INT16) {
3935 uint16_t v;
3936 if (fread(enc,2,1,fp) == 0) return NULL;
3937 v = enc[0]|(enc[1]<<8);
3938 val = (int16_t)v;
3939 } else if (enctype == REDIS_RDB_ENC_INT32) {
3940 uint32_t v;
3941 if (fread(enc,4,1,fp) == 0) return NULL;
3942 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
3943 val = (int32_t)v;
3944 } else {
3945 val = 0; /* anti-warning */
3946 redisPanic("Unknown RDB integer encoding type");
3947 }
3948 if (encode)
3949 return createStringObjectFromLongLong(val);
3950 else
3951 return createObject(REDIS_STRING,sdsfromlonglong(val));
3952 }
3953
3954 static robj *rdbLoadLzfStringObject(FILE*fp) {
3955 unsigned int len, clen;
3956 unsigned char *c = NULL;
3957 sds val = NULL;
3958
3959 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3960 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3961 if ((c = zmalloc(clen)) == NULL) goto err;
3962 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
3963 if (fread(c,clen,1,fp) == 0) goto err;
3964 if (lzf_decompress(c,clen,val,len) == 0) goto err;
3965 zfree(c);
3966 return createObject(REDIS_STRING,val);
3967 err:
3968 zfree(c);
3969 sdsfree(val);
3970 return NULL;
3971 }
3972
3973 static robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
3974 int isencoded;
3975 uint32_t len;
3976 sds val;
3977
3978 len = rdbLoadLen(fp,&isencoded);
3979 if (isencoded) {
3980 switch(len) {
3981 case REDIS_RDB_ENC_INT8:
3982 case REDIS_RDB_ENC_INT16:
3983 case REDIS_RDB_ENC_INT32:
3984 return rdbLoadIntegerObject(fp,len,encode);
3985 case REDIS_RDB_ENC_LZF:
3986 return rdbLoadLzfStringObject(fp);
3987 default:
3988 redisPanic("Unknown RDB encoding type");
3989 }
3990 }
3991
3992 if (len == REDIS_RDB_LENERR) return NULL;
3993 val = sdsnewlen(NULL,len);
3994 if (len && fread(val,len,1,fp) == 0) {
3995 sdsfree(val);
3996 return NULL;
3997 }
3998 return createObject(REDIS_STRING,val);
3999 }
4000
4001 static robj *rdbLoadStringObject(FILE *fp) {
4002 return rdbGenericLoadStringObject(fp,0);
4003 }
4004
4005 static robj *rdbLoadEncodedStringObject(FILE *fp) {
4006 return rdbGenericLoadStringObject(fp,1);
4007 }
4008
4009 /* For information about double serialization check rdbSaveDoubleValue() */
4010 static int rdbLoadDoubleValue(FILE *fp, double *val) {
4011 char buf[128];
4012 unsigned char len;
4013
4014 if (fread(&len,1,1,fp) == 0) return -1;
4015 switch(len) {
4016 case 255: *val = R_NegInf; return 0;
4017 case 254: *val = R_PosInf; return 0;
4018 case 253: *val = R_Nan; return 0;
4019 default:
4020 if (fread(buf,len,1,fp) == 0) return -1;
4021 buf[len] = '\0';
4022 sscanf(buf, "%lg", val);
4023 return 0;
4024 }
4025 }
4026
4027 /* Load a Redis object of the specified type from the specified file.
4028 * On success a newly allocated object is returned, otherwise NULL. */
4029 static robj *rdbLoadObject(int type, FILE *fp) {
4030 robj *o, *ele, *dec;
4031 size_t len;
4032
4033 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
4034 if (type == REDIS_STRING) {
4035 /* Read string value */
4036 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4037 o = tryObjectEncoding(o);
4038 } else if (type == REDIS_LIST) {
4039 /* Read list value */
4040 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4041
4042 o = createZiplistObject();
4043
4044 /* Load every single element of the list */
4045 while(len--) {
4046 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4047
4048 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
4049 dec = getDecodedObject(ele);
4050 o->ptr = ziplistPush(o->ptr,dec->ptr,sdslen(dec->ptr),REDIS_TAIL);
4051 decrRefCount(dec);
4052 decrRefCount(ele);
4053 } else {
4054 ele = tryObjectEncoding(ele);
4055 listAddNodeTail(o->ptr,ele);
4056 incrRefCount(ele);
4057 }
4058 }
4059 } else if (type == REDIS_SET) {
4060 /* Read list/set value */
4061 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4062 o = createSetObject();
4063 /* It's faster to expand the dict to the right size asap in order
4064 * to avoid rehashing */
4065 if (len > DICT_HT_INITIAL_SIZE)
4066 dictExpand(o->ptr,len);
4067 /* Load every single element of the list/set */
4068 while(len--) {
4069 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4070 ele = tryObjectEncoding(ele);
4071 dictAdd((dict*)o->ptr,ele,NULL);
4072 }
4073 } else if (type == REDIS_ZSET) {
4074 /* Read list/set value */
4075 size_t zsetlen;
4076 zset *zs;
4077
4078 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4079 o = createZsetObject();
4080 zs = o->ptr;
4081 /* Load every single element of the list/set */
4082 while(zsetlen--) {
4083 robj *ele;
4084 double *score = zmalloc(sizeof(double));
4085
4086 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4087 ele = tryObjectEncoding(ele);
4088 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
4089 dictAdd(zs->dict,ele,score);
4090 zslInsert(zs->zsl,*score,ele);
4091 incrRefCount(ele); /* added to skiplist */
4092 }
4093 } else if (type == REDIS_HASH) {
4094 size_t hashlen;
4095
4096 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4097 o = createHashObject();
4098 /* Too many entries? Use an hash table. */
4099 if (hashlen > server.hash_max_zipmap_entries)
4100 convertToRealHash(o);
4101 /* Load every key/value, then set it into the zipmap or hash
4102 * table, as needed. */
4103 while(hashlen--) {
4104 robj *key, *val;
4105
4106 if ((key = rdbLoadStringObject(fp)) == NULL) return NULL;
4107 if ((val = rdbLoadStringObject(fp)) == NULL) return NULL;
4108 /* If we are using a zipmap and there are too big values
4109 * the object is converted to real hash table encoding. */
4110 if (o->encoding != REDIS_ENCODING_HT &&
4111 (sdslen(key->ptr) > server.hash_max_zipmap_value ||
4112 sdslen(val->ptr) > server.hash_max_zipmap_value))
4113 {
4114 convertToRealHash(o);
4115 }
4116
4117 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
4118 unsigned char *zm = o->ptr;
4119
4120 zm = zipmapSet(zm,key->ptr,sdslen(key->ptr),
4121 val->ptr,sdslen(val->ptr),NULL);
4122 o->ptr = zm;
4123 decrRefCount(key);
4124 decrRefCount(val);
4125 } else {
4126 key = tryObjectEncoding(key);
4127 val = tryObjectEncoding(val);
4128 dictAdd((dict*)o->ptr,key,val);
4129 }
4130 }
4131 } else {
4132 redisPanic("Unknown object type");
4133 }
4134 return o;
4135 }
4136
4137 static int rdbLoad(char *filename) {
4138 FILE *fp;
4139 uint32_t dbid;
4140 int type, retval, rdbver;
4141 int swap_all_values = 0;
4142 dict *d = server.db[0].dict;
4143 redisDb *db = server.db+0;
4144 char buf[1024];
4145 time_t expiretime, now = time(NULL);
4146 long long loadedkeys = 0;
4147
4148 fp = fopen(filename,"r");
4149 if (!fp) return REDIS_ERR;
4150 if (fread(buf,9,1,fp) == 0) goto eoferr;
4151 buf[9] = '\0';
4152 if (memcmp(buf,"REDIS",5) != 0) {
4153 fclose(fp);
4154 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
4155 return REDIS_ERR;
4156 }
4157 rdbver = atoi(buf+5);
4158 if (rdbver != 1) {
4159 fclose(fp);
4160 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
4161 return REDIS_ERR;
4162 }
4163 while(1) {
4164 robj *key, *val;
4165
4166 expiretime = -1;
4167 /* Read type. */
4168 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4169 if (type == REDIS_EXPIRETIME) {
4170 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
4171 /* We read the time so we need to read the object type again */
4172 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4173 }
4174 if (type == REDIS_EOF) break;
4175 /* Handle SELECT DB opcode as a special case */
4176 if (type == REDIS_SELECTDB) {
4177 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
4178 goto eoferr;
4179 if (dbid >= (unsigned)server.dbnum) {
4180 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
4181 exit(1);
4182 }
4183 db = server.db+dbid;
4184 d = db->dict;
4185 continue;
4186 }
4187 /* Read key */
4188 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
4189 /* Read value */
4190 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
4191 /* Check if the key already expired */
4192 if (expiretime != -1 && expiretime < now) {
4193 decrRefCount(key);
4194 decrRefCount(val);
4195 continue;
4196 }
4197 /* Add the new object in the hash table */
4198 retval = dictAdd(d,key,val);
4199 if (retval == DICT_ERR) {
4200 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
4201 exit(1);
4202 }
4203 loadedkeys++;
4204 /* Set the expire time if needed */
4205 if (expiretime != -1) setExpire(db,key,expiretime);
4206
4207 /* Handle swapping while loading big datasets when VM is on */
4208
4209 /* If we detecter we are hopeless about fitting something in memory
4210 * we just swap every new key on disk. Directly...
4211 * Note that's important to check for this condition before resorting
4212 * to random sampling, otherwise we may try to swap already
4213 * swapped keys. */
4214 if (swap_all_values) {
4215 dictEntry *de = dictFind(d,key);
4216
4217 /* de may be NULL since the key already expired */
4218 if (de) {
4219 key = dictGetEntryKey(de);
4220 val = dictGetEntryVal(de);
4221
4222 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
4223 dictGetEntryVal(de) = NULL;
4224 }
4225 }
4226 continue;
4227 }
4228
4229 /* If we have still some hope of having some value fitting memory
4230 * then we try random sampling. */
4231 if (!swap_all_values && server.vm_enabled && (loadedkeys % 5000) == 0) {
4232 while (zmalloc_used_memory() > server.vm_max_memory) {
4233 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
4234 }
4235 if (zmalloc_used_memory() > server.vm_max_memory)
4236 swap_all_values = 1; /* We are already using too much mem */
4237 }
4238 }
4239 fclose(fp);
4240 return REDIS_OK;
4241
4242 eoferr: /* unexpected end of file is handled here with a fatal exit */
4243 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
4244 exit(1);
4245 return REDIS_ERR; /* Just to avoid warning */
4246 }
4247
4248 /*================================== Shutdown =============================== */
4249 static int prepareForShutdown() {
4250 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
4251 /* Kill the saving child if there is a background saving in progress.
4252 We want to avoid race conditions, for instance our saving child may
4253 overwrite the synchronous saving did by SHUTDOWN. */
4254 if (server.bgsavechildpid != -1) {
4255 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
4256 kill(server.bgsavechildpid,SIGKILL);
4257 rdbRemoveTempFile(server.bgsavechildpid);
4258 }
4259 if (server.appendonly) {
4260 /* Append only file: fsync() the AOF and exit */
4261 fsync(server.appendfd);
4262 if (server.vm_enabled) unlink(server.vm_swap_file);
4263 } else {
4264 /* Snapshotting. Perform a SYNC SAVE and exit */
4265 if (rdbSave(server.dbfilename) == REDIS_OK) {
4266 if (server.daemonize)
4267 unlink(server.pidfile);
4268 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
4269 } else {
4270 /* Ooops.. error saving! The best we can do is to continue
4271 * operating. Note that if there was a background saving process,
4272 * in the next cron() Redis will be notified that the background
4273 * saving aborted, handling special stuff like slaves pending for
4274 * synchronization... */
4275 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
4276 return REDIS_ERR;
4277 }
4278 }
4279 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
4280 return REDIS_OK;
4281 }
4282
4283 /*================================== Commands =============================== */
4284
4285 static void authCommand(redisClient *c) {
4286 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
4287 c->authenticated = 1;
4288 addReply(c,shared.ok);
4289 } else {
4290 c->authenticated = 0;
4291 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
4292 }
4293 }
4294
4295 static void pingCommand(redisClient *c) {
4296 addReply(c,shared.pong);
4297 }
4298
4299 static void echoCommand(redisClient *c) {
4300 addReplyBulk(c,c->argv[1]);
4301 }
4302
4303 /*=================================== Strings =============================== */
4304
4305 static void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
4306 int retval;
4307 long seconds = 0; /* initialized to avoid an harmness warning */
4308
4309 if (expire) {
4310 if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
4311 return;
4312 if (seconds <= 0) {
4313 addReplySds(c,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4314 return;
4315 }
4316 }
4317
4318 touchWatchedKey(c->db,key);
4319 if (nx) deleteIfVolatile(c->db,key);
4320 retval = dictAdd(c->db->dict,key,val);
4321 if (retval == DICT_ERR) {
4322 if (!nx) {
4323 /* If the key is about a swapped value, we want a new key object
4324 * to overwrite the old. So we delete the old key in the database.
4325 * This will also make sure that swap pages about the old object
4326 * will be marked as free. */
4327 if (server.vm_enabled && deleteIfSwapped(c->db,key))
4328 incrRefCount(key);
4329 dictReplace(c->db->dict,key,val);
4330 incrRefCount(val);
4331 } else {
4332 addReply(c,shared.czero);
4333 return;
4334 }
4335 } else {
4336 incrRefCount(key);
4337 incrRefCount(val);
4338 }
4339 server.dirty++;
4340 removeExpire(c->db,key);
4341 if (expire) setExpire(c->db,key,time(NULL)+seconds);
4342 addReply(c, nx ? shared.cone : shared.ok);
4343 }
4344
4345 static void setCommand(redisClient *c) {
4346 setGenericCommand(c,0,c->argv[1],c->argv[2],NULL);
4347 }
4348
4349 static void setnxCommand(redisClient *c) {
4350 setGenericCommand(c,1,c->argv[1],c->argv[2],NULL);
4351 }
4352
4353 static void setexCommand(redisClient *c) {
4354 setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
4355 }
4356
4357 static int getGenericCommand(redisClient *c) {
4358 robj *o;
4359
4360 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
4361 return REDIS_OK;
4362
4363 if (o->type != REDIS_STRING) {
4364 addReply(c,shared.wrongtypeerr);
4365 return REDIS_ERR;
4366 } else {
4367 addReplyBulk(c,o);
4368 return REDIS_OK;
4369 }
4370 }
4371
4372 static void getCommand(redisClient *c) {
4373 getGenericCommand(c);
4374 }
4375
4376 static void getsetCommand(redisClient *c) {
4377 if (getGenericCommand(c) == REDIS_ERR) return;
4378 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
4379 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
4380 } else {
4381 incrRefCount(c->argv[1]);
4382 }
4383 incrRefCount(c->argv[2]);
4384 server.dirty++;
4385 removeExpire(c->db,c->argv[1]);
4386 }
4387
4388 static void mgetCommand(redisClient *c) {
4389 int j;
4390
4391 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
4392 for (j = 1; j < c->argc; j++) {
4393 robj *o = lookupKeyRead(c->db,c->argv[j]);
4394 if (o == NULL) {
4395 addReply(c,shared.nullbulk);
4396 } else {
4397 if (o->type != REDIS_STRING) {
4398 addReply(c,shared.nullbulk);
4399 } else {
4400 addReplyBulk(c,o);
4401 }
4402 }
4403 }
4404 }
4405
4406 static void msetGenericCommand(redisClient *c, int nx) {
4407 int j, busykeys = 0;
4408
4409 if ((c->argc % 2) == 0) {
4410 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
4411 return;
4412 }
4413 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4414 * set nothing at all if at least one already key exists. */
4415 if (nx) {
4416 for (j = 1; j < c->argc; j += 2) {
4417 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
4418 busykeys++;
4419 }
4420 }
4421 }
4422 if (busykeys) {
4423 addReply(c, shared.czero);
4424 return;
4425 }
4426
4427 for (j = 1; j < c->argc; j += 2) {
4428 int retval;
4429
4430 c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
4431 retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
4432 if (retval == DICT_ERR) {
4433 dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
4434 incrRefCount(c->argv[j+1]);
4435 } else {
4436 incrRefCount(c->argv[j]);
4437 incrRefCount(c->argv[j+1]);
4438 }
4439 removeExpire(c->db,c->argv[j]);
4440 }
4441 server.dirty += (c->argc-1)/2;
4442 addReply(c, nx ? shared.cone : shared.ok);
4443 }
4444
4445 static void msetCommand(redisClient *c) {
4446 msetGenericCommand(c,0);
4447 }
4448
4449 static void msetnxCommand(redisClient *c) {
4450 msetGenericCommand(c,1);
4451 }
4452
4453 static void incrDecrCommand(redisClient *c, long long incr) {
4454 long long value;
4455 int retval;
4456 robj *o;
4457
4458 o = lookupKeyWrite(c->db,c->argv[1]);
4459 if (o != NULL && checkType(c,o,REDIS_STRING)) return;
4460 if (getLongLongFromObjectOrReply(c,o,&value,NULL) != REDIS_OK) return;
4461
4462 value += incr;
4463 o = createStringObjectFromLongLong(value);
4464 retval = dictAdd(c->db->dict,c->argv[1],o);
4465 if (retval == DICT_ERR) {
4466 dictReplace(c->db->dict,c->argv[1],o);
4467 removeExpire(c->db,c->argv[1]);
4468 } else {
4469 incrRefCount(c->argv[1]);
4470 }
4471 server.dirty++;
4472 addReply(c,shared.colon);
4473 addReply(c,o);
4474 addReply(c,shared.crlf);
4475 }
4476
4477 static void incrCommand(redisClient *c) {
4478 incrDecrCommand(c,1);
4479 }
4480
4481 static void decrCommand(redisClient *c) {
4482 incrDecrCommand(c,-1);
4483 }
4484
4485 static void incrbyCommand(redisClient *c) {
4486 long long incr;
4487
4488 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
4489 incrDecrCommand(c,incr);
4490 }
4491
4492 static void decrbyCommand(redisClient *c) {
4493 long long incr;
4494
4495 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
4496 incrDecrCommand(c,-incr);
4497 }
4498
4499 static void appendCommand(redisClient *c) {
4500 int retval;
4501 size_t totlen;
4502 robj *o;
4503
4504 o = lookupKeyWrite(c->db,c->argv[1]);
4505 if (o == NULL) {
4506 /* Create the key */
4507 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
4508 incrRefCount(c->argv[1]);
4509 incrRefCount(c->argv[2]);
4510 totlen = stringObjectLen(c->argv[2]);
4511 } else {
4512 dictEntry *de;
4513
4514 de = dictFind(c->db->dict,c->argv[1]);
4515 assert(de != NULL);
4516
4517 o = dictGetEntryVal(de);
4518 if (o->type != REDIS_STRING) {
4519 addReply(c,shared.wrongtypeerr);
4520 return;
4521 }
4522 /* If the object is specially encoded or shared we have to make
4523 * a copy */
4524 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
4525 robj *decoded = getDecodedObject(o);
4526
4527 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
4528 decrRefCount(decoded);
4529 dictReplace(c->db->dict,c->argv[1],o);
4530 }
4531 /* APPEND! */
4532 if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
4533 o->ptr = sdscatlen(o->ptr,
4534 c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
4535 } else {
4536 o->ptr = sdscatprintf(o->ptr, "%ld",
4537 (unsigned long) c->argv[2]->ptr);
4538 }
4539 totlen = sdslen(o->ptr);
4540 }
4541 server.dirty++;
4542 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
4543 }
4544
4545 static void substrCommand(redisClient *c) {
4546 robj *o;
4547 long start = atoi(c->argv[2]->ptr);
4548 long end = atoi(c->argv[3]->ptr);
4549 size_t rangelen, strlen;
4550 sds range;
4551
4552 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4553 checkType(c,o,REDIS_STRING)) return;
4554
4555 o = getDecodedObject(o);
4556 strlen = sdslen(o->ptr);
4557
4558 /* convert negative indexes */
4559 if (start < 0) start = strlen+start;
4560 if (end < 0) end = strlen+end;
4561 if (start < 0) start = 0;
4562 if (end < 0) end = 0;
4563
4564 /* indexes sanity checks */
4565 if (start > end || (size_t)start >= strlen) {
4566 /* Out of range start or start > end result in null reply */
4567 addReply(c,shared.nullbulk);
4568 decrRefCount(o);
4569 return;
4570 }
4571 if ((size_t)end >= strlen) end = strlen-1;
4572 rangelen = (end-start)+1;
4573
4574 /* Return the result */
4575 addReplySds(c,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen));
4576 range = sdsnewlen((char*)o->ptr+start,rangelen);
4577 addReplySds(c,range);
4578 addReply(c,shared.crlf);
4579 decrRefCount(o);
4580 }
4581
4582 /* ========================= Type agnostic commands ========================= */
4583
4584 static void delCommand(redisClient *c) {
4585 int deleted = 0, j;
4586
4587 for (j = 1; j < c->argc; j++) {
4588 if (deleteKey(c->db,c->argv[j])) {
4589 touchWatchedKey(c->db,c->argv[j]);
4590 server.dirty++;
4591 deleted++;
4592 }
4593 }
4594 addReplyLongLong(c,deleted);
4595 }
4596
4597 static void existsCommand(redisClient *c) {
4598 expireIfNeeded(c->db,c->argv[1]);
4599 if (dictFind(c->db->dict,c->argv[1])) {
4600 addReply(c, shared.cone);
4601 } else {
4602 addReply(c, shared.czero);
4603 }
4604 }
4605
4606 static void selectCommand(redisClient *c) {
4607 int id = atoi(c->argv[1]->ptr);
4608
4609 if (selectDb(c,id) == REDIS_ERR) {
4610 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
4611 } else {
4612 addReply(c,shared.ok);
4613 }
4614 }
4615
4616 static void randomkeyCommand(redisClient *c) {
4617 dictEntry *de;
4618 robj *key;
4619
4620 while(1) {
4621 de = dictGetRandomKey(c->db->dict);
4622 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
4623 }
4624
4625 if (de == NULL) {
4626 addReply(c,shared.nullbulk);
4627 return;
4628 }
4629
4630 key = dictGetEntryKey(de);
4631 if (server.vm_enabled) {
4632 key = dupStringObject(key);
4633 addReplyBulk(c,key);
4634 decrRefCount(key);
4635 } else {
4636 addReplyBulk(c,key);
4637 }
4638 }
4639
4640 static void keysCommand(redisClient *c) {
4641 dictIterator *di;
4642 dictEntry *de;
4643 sds pattern = c->argv[1]->ptr;
4644 int plen = sdslen(pattern);
4645 unsigned long numkeys = 0;
4646 robj *lenobj = createObject(REDIS_STRING,NULL);
4647
4648 di = dictGetIterator(c->db->dict);
4649 addReply(c,lenobj);
4650 decrRefCount(lenobj);
4651 while((de = dictNext(di)) != NULL) {
4652 robj *keyobj = dictGetEntryKey(de);
4653
4654 sds key = keyobj->ptr;
4655 if ((pattern[0] == '*' && pattern[1] == '\0') ||
4656 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
4657 if (expireIfNeeded(c->db,keyobj) == 0) {
4658 addReplyBulk(c,keyobj);
4659 numkeys++;
4660 }
4661 }
4662 }
4663 dictReleaseIterator(di);
4664 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
4665 }
4666
4667 static void dbsizeCommand(redisClient *c) {
4668 addReplySds(c,
4669 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
4670 }
4671
4672 static void lastsaveCommand(redisClient *c) {
4673 addReplySds(c,
4674 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
4675 }
4676
4677 static void typeCommand(redisClient *c) {
4678 robj *o;
4679 char *type;
4680
4681 o = lookupKeyRead(c->db,c->argv[1]);
4682 if (o == NULL) {
4683 type = "+none";
4684 } else {
4685 switch(o->type) {
4686 case REDIS_STRING: type = "+string"; break;
4687 case REDIS_LIST: type = "+list"; break;
4688 case REDIS_SET: type = "+set"; break;
4689 case REDIS_ZSET: type = "+zset"; break;
4690 case REDIS_HASH: type = "+hash"; break;
4691 default: type = "+unknown"; break;
4692 }
4693 }
4694 addReplySds(c,sdsnew(type));
4695 addReply(c,shared.crlf);
4696 }
4697
4698 static void saveCommand(redisClient *c) {
4699 if (server.bgsavechildpid != -1) {
4700 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
4701 return;
4702 }
4703 if (rdbSave(server.dbfilename) == REDIS_OK) {
4704 addReply(c,shared.ok);
4705 } else {
4706 addReply(c,shared.err);
4707 }
4708 }
4709
4710 static void bgsaveCommand(redisClient *c) {
4711 if (server.bgsavechildpid != -1) {
4712 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
4713 return;
4714 }
4715 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
4716 char *status = "+Background saving started\r\n";
4717 addReplySds(c,sdsnew(status));
4718 } else {
4719 addReply(c,shared.err);
4720 }
4721 }
4722
4723 static void shutdownCommand(redisClient *c) {
4724 if (prepareForShutdown() == REDIS_OK)
4725 exit(0);
4726 addReplySds(c, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
4727 }
4728
4729 static void renameGenericCommand(redisClient *c, int nx) {
4730 robj *o;
4731
4732 /* To use the same key as src and dst is probably an error */
4733 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
4734 addReply(c,shared.sameobjecterr);
4735 return;
4736 }
4737
4738 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
4739 return;
4740
4741 incrRefCount(o);
4742 deleteIfVolatile(c->db,c->argv[2]);
4743 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
4744 if (nx) {
4745 decrRefCount(o);
4746 addReply(c,shared.czero);
4747 return;
4748 }
4749 dictReplace(c->db->dict,c->argv[2],o);
4750 } else {
4751 incrRefCount(c->argv[2]);
4752 }
4753 deleteKey(c->db,c->argv[1]);
4754 touchWatchedKey(c->db,c->argv[2]);
4755 server.dirty++;
4756 addReply(c,nx ? shared.cone : shared.ok);
4757 }
4758
4759 static void renameCommand(redisClient *c) {
4760 renameGenericCommand(c,0);
4761 }
4762
4763 static void renamenxCommand(redisClient *c) {
4764 renameGenericCommand(c,1);
4765 }
4766
4767 static void moveCommand(redisClient *c) {
4768 robj *o;
4769 redisDb *src, *dst;
4770 int srcid;
4771
4772 /* Obtain source and target DB pointers */
4773 src = c->db;
4774 srcid = c->db->id;
4775 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
4776 addReply(c,shared.outofrangeerr);
4777 return;
4778 }
4779 dst = c->db;
4780 selectDb(c,srcid); /* Back to the source DB */
4781
4782 /* If the user is moving using as target the same
4783 * DB as the source DB it is probably an error. */
4784 if (src == dst) {
4785 addReply(c,shared.sameobjecterr);
4786 return;
4787 }
4788
4789 /* Check if the element exists and get a reference */
4790 o = lookupKeyWrite(c->db,c->argv[1]);
4791 if (!o) {
4792 addReply(c,shared.czero);
4793 return;
4794 }
4795
4796 /* Try to add the element to the target DB */
4797 deleteIfVolatile(dst,c->argv[1]);
4798 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
4799 addReply(c,shared.czero);
4800 return;
4801 }
4802 incrRefCount(c->argv[1]);
4803 incrRefCount(o);
4804
4805 /* OK! key moved, free the entry in the source DB */
4806 deleteKey(src,c->argv[1]);
4807 server.dirty++;
4808 addReply(c,shared.cone);
4809 }
4810
4811 /* =================================== Lists ================================ */
4812 static void lPush(robj *subject, robj *value, int where) {
4813 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4814 int pos = (where == REDIS_HEAD) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
4815 value = getDecodedObject(value);
4816 subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),pos);
4817 decrRefCount(value);
4818 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4819 if (where == REDIS_HEAD) {
4820 listAddNodeHead(subject->ptr,value);
4821 } else {
4822 listAddNodeTail(subject->ptr,value);
4823 }
4824 incrRefCount(value);
4825 } else {
4826 redisPanic("Unknown list encoding");
4827 }
4828 }
4829
4830 static robj *lPop(robj *subject, int where) {
4831 robj *value = NULL;
4832 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4833 unsigned char *p;
4834 unsigned char *vstr;
4835 unsigned int vlen;
4836 long long vlong;
4837 int pos = (where == REDIS_HEAD) ? 0 : -1;
4838 p = ziplistIndex(subject->ptr,pos);
4839 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
4840 if (vstr) {
4841 value = createStringObject((char*)vstr,vlen);
4842 } else {
4843 value = createStringObjectFromLongLong(vlong);
4844 }
4845 /* We only need to delete an element when it exists */
4846 subject->ptr = ziplistDelete(subject->ptr,&p);
4847 }
4848 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4849 list *list = subject->ptr;
4850 listNode *ln;
4851 if (where == REDIS_HEAD) {
4852 ln = listFirst(list);
4853 } else {
4854 ln = listLast(list);
4855 }
4856 if (ln != NULL) {
4857 value = listNodeValue(ln);
4858 incrRefCount(value);
4859 listDelNode(list,ln);
4860 }
4861 } else {
4862 redisPanic("Unknown list encoding");
4863 }
4864 return value;
4865 }
4866
4867 static unsigned long lLength(robj *subject) {
4868 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4869 return ziplistLen(subject->ptr);
4870 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4871 return listLength((list*)subject->ptr);
4872 } else {
4873 redisPanic("Unknown list encoding");
4874 }
4875 }
4876
4877 /* Structure to hold set iteration abstraction. */
4878 typedef struct {
4879 robj *subject;
4880 unsigned char encoding;
4881 unsigned char direction; /* Iteration direction */
4882 unsigned char *zi;
4883 listNode *ln;
4884 } lIterator;
4885
4886 /* Structure for an entry while iterating over a list. */
4887 typedef struct {
4888 lIterator *li;
4889 unsigned char *zi; /* Entry in ziplist */
4890 listNode *ln; /* Entry in linked list */
4891 } lEntry;
4892
4893 /* Initialize an iterator at the specified index. */
4894 static lIterator *lInitIterator(robj *subject, int index, unsigned char direction) {
4895 lIterator *li = zmalloc(sizeof(lIterator));
4896 li->subject = subject;
4897 li->encoding = subject->encoding;
4898 li->direction = direction;
4899 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4900 li->zi = ziplistIndex(subject->ptr,index);
4901 } else if (li->encoding == REDIS_ENCODING_LIST) {
4902 li->ln = listIndex(subject->ptr,index);
4903 } else {
4904 redisPanic("Unknown list encoding");
4905 }
4906 return li;
4907 }
4908
4909 /* Clean up the iterator. */
4910 static void lReleaseIterator(lIterator *li) {
4911 zfree(li);
4912 }
4913
4914 /* Stores pointer to current the entry in the provided entry structure
4915 * and advances the position of the iterator. Returns 1 when the current
4916 * entry is in fact an entry, 0 otherwise. */
4917 static int lNext(lIterator *li, lEntry *entry) {
4918 entry->li = li;
4919 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4920 entry->zi = li->zi;
4921 if (entry->zi != NULL) {
4922 if (li->direction == REDIS_TAIL)
4923 li->zi = ziplistNext(li->subject->ptr,li->zi);
4924 else
4925 li->zi = ziplistPrev(li->subject->ptr,li->zi);
4926 return 1;
4927 }
4928 } else if (li->encoding == REDIS_ENCODING_LIST) {
4929 entry->ln = li->ln;
4930 if (entry->ln != NULL) {
4931 if (li->direction == REDIS_TAIL)
4932 li->ln = li->ln->next;
4933 else
4934 li->ln = li->ln->prev;
4935 return 1;
4936 }
4937 } else {
4938 redisPanic("Unknown list encoding");
4939 }
4940 return 0;
4941 }
4942
4943 /* Return entry or NULL at the current position of the iterator. */
4944 static robj *lGet(lEntry *entry) {
4945 lIterator *li = entry->li;
4946 robj *value = NULL;
4947 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4948 unsigned char *vstr;
4949 unsigned int vlen;
4950 long long vlong;
4951 redisAssert(entry->zi != NULL);
4952 if (ziplistGet(entry->zi,&vstr,&vlen,&vlong)) {
4953 if (vstr) {
4954 value = createStringObject((char*)vstr,vlen);
4955 } else {
4956 value = createStringObjectFromLongLong(vlong);
4957 }
4958 }
4959 } else if (li->encoding == REDIS_ENCODING_LIST) {
4960 redisAssert(entry->ln != NULL);
4961 value = listNodeValue(entry->ln);
4962 incrRefCount(value);
4963 } else {
4964 redisPanic("Unknown list encoding");
4965 }
4966 return value;
4967 }
4968
4969 /* Compare the given object with the entry at the current position. */
4970 static int lEqual(lEntry *entry, robj *o) {
4971 lIterator *li = entry->li;
4972 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4973 redisAssert(o->encoding == REDIS_ENCODING_RAW);
4974 return ziplistCompare(entry->zi,o->ptr,sdslen(o->ptr));
4975 } else if (li->encoding == REDIS_ENCODING_LIST) {
4976 return equalStringObjects(o,listNodeValue(entry->ln));
4977 } else {
4978 redisPanic("Unknown list encoding");
4979 }
4980 }
4981
4982 /* Delete the element pointed to. */
4983 static void lDelete(lEntry *entry) {
4984 lIterator *li = entry->li;
4985 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4986 unsigned char *p = entry->zi;
4987 li->subject->ptr = ziplistDelete(li->subject->ptr,&p);
4988
4989 /* Update position of the iterator depending on the direction */
4990 if (li->direction == REDIS_TAIL)
4991 li->zi = p;
4992 else
4993 li->zi = ziplistPrev(li->subject->ptr,p);
4994 } else if (entry->li->encoding == REDIS_ENCODING_LIST) {
4995 listNode *next;
4996 if (li->direction == REDIS_TAIL)
4997 next = entry->ln->next;
4998 else
4999 next = entry->ln->prev;
5000 listDelNode(li->subject->ptr,entry->ln);
5001 li->ln = next;
5002 } else {
5003 redisPanic("Unknown list encoding");
5004 }
5005 }
5006
5007 static void pushGenericCommand(redisClient *c, int where) {
5008 robj *lobj = lookupKeyWrite(c->db,c->argv[1]);
5009 if (lobj == NULL) {
5010 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
5011 addReply(c,shared.cone);
5012 return;
5013 }
5014 lobj = createZiplistObject();
5015 dictAdd(c->db->dict,c->argv[1],lobj);
5016 incrRefCount(c->argv[1]);
5017 } else {
5018 if (lobj->type != REDIS_LIST) {
5019 addReply(c,shared.wrongtypeerr);
5020 return;
5021 }
5022 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
5023 addReply(c,shared.cone);
5024 return;
5025 }
5026 }
5027 lPush(lobj,c->argv[2],where);
5028 addReplyLongLong(c,lLength(lobj));
5029 server.dirty++;
5030 }
5031
5032 static void lpushCommand(redisClient *c) {
5033 pushGenericCommand(c,REDIS_HEAD);
5034 }
5035
5036 static void rpushCommand(redisClient *c) {
5037 pushGenericCommand(c,REDIS_TAIL);
5038 }
5039
5040 static void llenCommand(redisClient *c) {
5041 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.czero);
5042 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5043 addReplyUlong(c,lLength(o));
5044 }
5045
5046 static void lindexCommand(redisClient *c) {
5047 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk);
5048 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5049 int index = atoi(c->argv[2]->ptr);
5050 robj *value = NULL;
5051
5052 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5053 unsigned char *p;
5054 unsigned char *vstr;
5055 unsigned int vlen;
5056 long long vlong;
5057 p = ziplistIndex(o->ptr,index);
5058 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
5059 if (vstr) {
5060 value = createStringObject((char*)vstr,vlen);
5061 } else {
5062 value = createStringObjectFromLongLong(vlong);
5063 }
5064 addReplyBulk(c,value);
5065 decrRefCount(value);
5066 } else {
5067 addReply(c,shared.nullbulk);
5068 }
5069 } else if (o->encoding == REDIS_ENCODING_LIST) {
5070 listNode *ln = listIndex(o->ptr,index);
5071 if (ln != NULL) {
5072 value = listNodeValue(ln);
5073 addReplyBulk(c,value);
5074 } else {
5075 addReply(c,shared.nullbulk);
5076 }
5077 } else {
5078 redisPanic("Unknown list encoding");
5079 }
5080 }
5081
5082 static void lsetCommand(redisClient *c) {
5083 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr);
5084 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5085 int index = atoi(c->argv[2]->ptr);
5086 robj *value = c->argv[3];
5087
5088 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5089 unsigned char *p, *zl = o->ptr;
5090 p = ziplistIndex(zl,index);
5091 if (p == NULL) {
5092 addReply(c,shared.outofrangeerr);
5093 } else {
5094 o->ptr = ziplistDelete(o->ptr,&p);
5095 value = getDecodedObject(value);
5096 o->ptr = ziplistInsert(o->ptr,p,value->ptr,sdslen(value->ptr));
5097 decrRefCount(value);
5098 addReply(c,shared.ok);
5099 server.dirty++;
5100 }
5101 } else if (o->encoding == REDIS_ENCODING_LIST) {
5102 listNode *ln = listIndex(o->ptr,index);
5103 if (ln == NULL) {
5104 addReply(c,shared.outofrangeerr);
5105 } else {
5106 decrRefCount((robj*)listNodeValue(ln));
5107 listNodeValue(ln) = value;
5108 incrRefCount(value);
5109 addReply(c,shared.ok);
5110 server.dirty++;
5111 }
5112 } else {
5113 redisPanic("Unknown list encoding");
5114 }
5115 }
5116
5117 static void popGenericCommand(redisClient *c, int where) {
5118 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk);
5119 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5120
5121 robj *value = lPop(o,where);
5122 if (value == NULL) {
5123 addReply(c,shared.nullbulk);
5124 } else {
5125 addReplyBulk(c,value);
5126 decrRefCount(value);
5127 if (lLength(o) == 0) deleteKey(c->db,c->argv[1]);
5128 server.dirty++;
5129 }
5130 }
5131
5132 static void lpopCommand(redisClient *c) {
5133 popGenericCommand(c,REDIS_HEAD);
5134 }
5135
5136 static void rpopCommand(redisClient *c) {
5137 popGenericCommand(c,REDIS_TAIL);
5138 }
5139
5140 static void lrangeCommand(redisClient *c) {
5141 robj *o, *value;
5142 int start = atoi(c->argv[2]->ptr);
5143 int end = atoi(c->argv[3]->ptr);
5144 int llen;
5145 int rangelen, j;
5146 lEntry entry;
5147
5148 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
5149 || checkType(c,o,REDIS_LIST)) return;
5150 llen = lLength(o);
5151
5152 /* convert negative indexes */
5153 if (start < 0) start = llen+start;
5154 if (end < 0) end = llen+end;
5155 if (start < 0) start = 0;
5156 if (end < 0) end = 0;
5157
5158 /* indexes sanity checks */
5159 if (start > end || start >= llen) {
5160 /* Out of range start or start > end result in empty list */
5161 addReply(c,shared.emptymultibulk);
5162 return;
5163 }
5164 if (end >= llen) end = llen-1;
5165 rangelen = (end-start)+1;
5166
5167 /* Return the result in form of a multi-bulk reply */
5168 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
5169 lIterator *li = lInitIterator(o,start,REDIS_TAIL);
5170 for (j = 0; j < rangelen; j++) {
5171 redisAssert(lNext(li,&entry));
5172 value = lGet(&entry);
5173 addReplyBulk(c,value);
5174 decrRefCount(value);
5175 }
5176 lReleaseIterator(li);
5177 }
5178
5179 static void ltrimCommand(redisClient *c) {
5180 robj *o;
5181 int start = atoi(c->argv[2]->ptr);
5182 int end = atoi(c->argv[3]->ptr);
5183 int llen;
5184 int j, ltrim, rtrim;
5185 list *list;
5186 listNode *ln;
5187
5188 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
5189 checkType(c,o,REDIS_LIST)) return;
5190 llen = lLength(o);
5191
5192 /* convert negative indexes */
5193 if (start < 0) start = llen+start;
5194 if (end < 0) end = llen+end;
5195 if (start < 0) start = 0;
5196 if (end < 0) end = 0;
5197
5198 /* indexes sanity checks */
5199 if (start > end || start >= llen) {
5200 /* Out of range start or start > end result in empty list */
5201 ltrim = llen;
5202 rtrim = 0;
5203 } else {
5204 if (end >= llen) end = llen-1;
5205 ltrim = start;
5206 rtrim = llen-end-1;
5207 }
5208
5209 /* Remove list elements to perform the trim */
5210 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5211 o->ptr = ziplistDeleteRange(o->ptr,0,ltrim);
5212 o->ptr = ziplistDeleteRange(o->ptr,-rtrim,rtrim);
5213 } else if (o->encoding == REDIS_ENCODING_LIST) {
5214 list = o->ptr;
5215 for (j = 0; j < ltrim; j++) {
5216 ln = listFirst(list);
5217 listDelNode(list,ln);
5218 }
5219 for (j = 0; j < rtrim; j++) {
5220 ln = listLast(list);
5221 listDelNode(list,ln);
5222 }
5223 } else {
5224 redisPanic("Unknown list encoding");
5225 }
5226 if (lLength(o) == 0) deleteKey(c->db,c->argv[1]);
5227 server.dirty++;
5228 addReply(c,shared.ok);
5229 }
5230
5231 static void lremCommand(redisClient *c) {
5232 robj *subject, *obj = c->argv[3];
5233 int toremove = atoi(c->argv[2]->ptr);
5234 int removed = 0;
5235 lEntry entry;
5236
5237 subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero);
5238 if (subject == NULL || checkType(c,subject,REDIS_LIST)) return;
5239
5240 /* Make sure obj is raw when we're dealing with a ziplist */
5241 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
5242 obj = getDecodedObject(obj);
5243
5244 lIterator *li;
5245 if (toremove < 0) {
5246 toremove = -toremove;
5247 li = lInitIterator(subject,-1,REDIS_HEAD);
5248 } else {
5249 li = lInitIterator(subject,0,REDIS_TAIL);
5250 }
5251
5252 while (lNext(li,&entry)) {
5253 if (lEqual(&entry,obj)) {
5254 lDelete(&entry);
5255 server.dirty++;
5256 removed++;
5257 if (toremove && removed == toremove) break;
5258 }
5259 }
5260 lReleaseIterator(li);
5261
5262 /* Clean up raw encoded object */
5263 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
5264 decrRefCount(obj);
5265
5266 if (lLength(subject) == 0) deleteKey(c->db,c->argv[1]);
5267 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
5268 }
5269
5270 /* This is the semantic of this command:
5271 * RPOPLPUSH srclist dstlist:
5272 * IF LLEN(srclist) > 0
5273 * element = RPOP srclist
5274 * LPUSH dstlist element
5275 * RETURN element
5276 * ELSE
5277 * RETURN nil
5278 * END
5279 * END
5280 *
5281 * The idea is to be able to get an element from a list in a reliable way
5282 * since the element is not just returned but pushed against another list
5283 * as well. This command was originally proposed by Ezra Zygmuntowicz.
5284 */
5285 static void rpoplpushcommand(redisClient *c) {
5286 robj *sobj, *value;
5287 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5288 checkType(c,sobj,REDIS_LIST)) return;
5289
5290 if (lLength(sobj) == 0) {
5291 addReply(c,shared.nullbulk);
5292 } else {
5293 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
5294 if (dobj && checkType(c,dobj,REDIS_LIST)) return;
5295 value = lPop(sobj,REDIS_TAIL);
5296
5297 /* Add the element to the target list (unless it's directly
5298 * passed to some BLPOP-ing client */
5299 if (!handleClientsWaitingListPush(c,c->argv[2],value)) {
5300 /* Create the list if the key does not exist */
5301 if (!dobj) {
5302 dobj = createZiplistObject();
5303 dictAdd(c->db->dict,c->argv[2],dobj);
5304 incrRefCount(c->argv[2]);
5305 }
5306 lPush(dobj,value,REDIS_HEAD);
5307 }
5308
5309 /* Send the element to the client as reply as well */
5310 addReplyBulk(c,value);
5311
5312 /* lPop returns an object with its refcount incremented */
5313 decrRefCount(value);
5314
5315 /* Delete the source list when it is empty */
5316 if (lLength(sobj) == 0) deleteKey(c->db,c->argv[1]);
5317 server.dirty++;
5318 }
5319 }
5320
5321 /* ==================================== Sets ================================ */
5322
5323 static void saddCommand(redisClient *c) {
5324 robj *set;
5325
5326 set = lookupKeyWrite(c->db,c->argv[1]);
5327 if (set == NULL) {
5328 set = createSetObject();
5329 dictAdd(c->db->dict,c->argv[1],set);
5330 incrRefCount(c->argv[1]);
5331 } else {
5332 if (set->type != REDIS_SET) {
5333 addReply(c,shared.wrongtypeerr);
5334 return;
5335 }
5336 }
5337 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
5338 incrRefCount(c->argv[2]);
5339 server.dirty++;
5340 addReply(c,shared.cone);
5341 } else {
5342 addReply(c,shared.czero);
5343 }
5344 }
5345
5346 static void sremCommand(redisClient *c) {
5347 robj *set;
5348
5349 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5350 checkType(c,set,REDIS_SET)) return;
5351
5352 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
5353 server.dirty++;
5354 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
5355 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
5356 addReply(c,shared.cone);
5357 } else {
5358 addReply(c,shared.czero);
5359 }
5360 }
5361
5362 static void smoveCommand(redisClient *c) {
5363 robj *srcset, *dstset;
5364
5365 srcset = lookupKeyWrite(c->db,c->argv[1]);
5366 dstset = lookupKeyWrite(c->db,c->argv[2]);
5367
5368 /* If the source key does not exist return 0, if it's of the wrong type
5369 * raise an error */
5370 if (srcset == NULL || srcset->type != REDIS_SET) {
5371 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
5372 return;
5373 }
5374 /* Error if the destination key is not a set as well */
5375 if (dstset && dstset->type != REDIS_SET) {
5376 addReply(c,shared.wrongtypeerr);
5377 return;
5378 }
5379 /* Remove the element from the source set */
5380 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
5381 /* Key not found in the src set! return zero */
5382 addReply(c,shared.czero);
5383 return;
5384 }
5385 if (dictSize((dict*)srcset->ptr) == 0 && srcset != dstset)
5386 deleteKey(c->db,c->argv[1]);
5387 server.dirty++;
5388 /* Add the element to the destination set */
5389 if (!dstset) {
5390 dstset = createSetObject();
5391 dictAdd(c->db->dict,c->argv[2],dstset);
5392 incrRefCount(c->argv[2]);
5393 }
5394 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
5395 incrRefCount(c->argv[3]);
5396 addReply(c,shared.cone);
5397 }
5398
5399 static void sismemberCommand(redisClient *c) {
5400 robj *set;
5401
5402 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5403 checkType(c,set,REDIS_SET)) return;
5404
5405 if (dictFind(set->ptr,c->argv[2]))
5406 addReply(c,shared.cone);
5407 else
5408 addReply(c,shared.czero);
5409 }
5410
5411 static void scardCommand(redisClient *c) {
5412 robj *o;
5413 dict *s;
5414
5415 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5416 checkType(c,o,REDIS_SET)) return;
5417
5418 s = o->ptr;
5419 addReplyUlong(c,dictSize(s));
5420 }
5421
5422 static void spopCommand(redisClient *c) {
5423 robj *set;
5424 dictEntry *de;
5425
5426 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5427 checkType(c,set,REDIS_SET)) return;
5428
5429 de = dictGetRandomKey(set->ptr);
5430 if (de == NULL) {
5431 addReply(c,shared.nullbulk);
5432 } else {
5433 robj *ele = dictGetEntryKey(de);
5434
5435 addReplyBulk(c,ele);
5436 dictDelete(set->ptr,ele);
5437 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
5438 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
5439 server.dirty++;
5440 }
5441 }
5442
5443 static void srandmemberCommand(redisClient *c) {
5444 robj *set;
5445 dictEntry *de;
5446
5447 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5448 checkType(c,set,REDIS_SET)) return;
5449
5450 de = dictGetRandomKey(set->ptr);
5451 if (de == NULL) {
5452 addReply(c,shared.nullbulk);
5453 } else {
5454 robj *ele = dictGetEntryKey(de);
5455
5456 addReplyBulk(c,ele);
5457 }
5458 }
5459
5460 static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
5461 dict **d1 = (void*) s1, **d2 = (void*) s2;
5462
5463 return dictSize(*d1)-dictSize(*d2);
5464 }
5465
5466 static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
5467 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5468 dictIterator *di;
5469 dictEntry *de;
5470 robj *lenobj = NULL, *dstset = NULL;
5471 unsigned long j, cardinality = 0;
5472
5473 for (j = 0; j < setsnum; j++) {
5474 robj *setobj;
5475
5476 setobj = dstkey ?
5477 lookupKeyWrite(c->db,setskeys[j]) :
5478 lookupKeyRead(c->db,setskeys[j]);
5479 if (!setobj) {
5480 zfree(dv);
5481 if (dstkey) {
5482 if (deleteKey(c->db,dstkey))
5483 server.dirty++;
5484 addReply(c,shared.czero);
5485 } else {
5486 addReply(c,shared.emptymultibulk);
5487 }
5488 return;
5489 }
5490 if (setobj->type != REDIS_SET) {
5491 zfree(dv);
5492 addReply(c,shared.wrongtypeerr);
5493 return;
5494 }
5495 dv[j] = setobj->ptr;
5496 }
5497 /* Sort sets from the smallest to largest, this will improve our
5498 * algorithm's performace */
5499 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
5500
5501 /* The first thing we should output is the total number of elements...
5502 * since this is a multi-bulk write, but at this stage we don't know
5503 * the intersection set size, so we use a trick, append an empty object
5504 * to the output list and save the pointer to later modify it with the
5505 * right length */
5506 if (!dstkey) {
5507 lenobj = createObject(REDIS_STRING,NULL);
5508 addReply(c,lenobj);
5509 decrRefCount(lenobj);
5510 } else {
5511 /* If we have a target key where to store the resulting set
5512 * create this key with an empty set inside */
5513 dstset = createSetObject();
5514 }
5515
5516 /* Iterate all the elements of the first (smallest) set, and test
5517 * the element against all the other sets, if at least one set does
5518 * not include the element it is discarded */
5519 di = dictGetIterator(dv[0]);
5520
5521 while((de = dictNext(di)) != NULL) {
5522 robj *ele;
5523
5524 for (j = 1; j < setsnum; j++)
5525 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
5526 if (j != setsnum)
5527 continue; /* at least one set does not contain the member */
5528 ele = dictGetEntryKey(de);
5529 if (!dstkey) {
5530 addReplyBulk(c,ele);
5531 cardinality++;
5532 } else {
5533 dictAdd(dstset->ptr,ele,NULL);
5534 incrRefCount(ele);
5535 }
5536 }
5537 dictReleaseIterator(di);
5538
5539 if (dstkey) {
5540 /* Store the resulting set into the target, if the intersection
5541 * is not an empty set. */
5542 deleteKey(c->db,dstkey);
5543 if (dictSize((dict*)dstset->ptr) > 0) {
5544 dictAdd(c->db->dict,dstkey,dstset);
5545 incrRefCount(dstkey);
5546 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
5547 } else {
5548 decrRefCount(dstset);
5549 addReply(c,shared.czero);
5550 }
5551 server.dirty++;
5552 } else {
5553 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
5554 }
5555 zfree(dv);
5556 }
5557
5558 static void sinterCommand(redisClient *c) {
5559 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
5560 }
5561
5562 static void sinterstoreCommand(redisClient *c) {
5563 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
5564 }
5565
5566 #define REDIS_OP_UNION 0
5567 #define REDIS_OP_DIFF 1
5568 #define REDIS_OP_INTER 2
5569
5570 static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
5571 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5572 dictIterator *di;
5573 dictEntry *de;
5574 robj *dstset = NULL;
5575 int j, cardinality = 0;
5576
5577 for (j = 0; j < setsnum; j++) {
5578 robj *setobj;
5579
5580 setobj = dstkey ?
5581 lookupKeyWrite(c->db,setskeys[j]) :
5582 lookupKeyRead(c->db,setskeys[j]);
5583 if (!setobj) {
5584 dv[j] = NULL;
5585 continue;
5586 }
5587 if (setobj->type != REDIS_SET) {
5588 zfree(dv);
5589 addReply(c,shared.wrongtypeerr);
5590 return;
5591 }
5592 dv[j] = setobj->ptr;
5593 }
5594
5595 /* We need a temp set object to store our union. If the dstkey
5596 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5597 * this set object will be the resulting object to set into the target key*/
5598 dstset = createSetObject();
5599
5600 /* Iterate all the elements of all the sets, add every element a single
5601 * time to the result set */
5602 for (j = 0; j < setsnum; j++) {
5603 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
5604 if (!dv[j]) continue; /* non existing keys are like empty sets */
5605
5606 di = dictGetIterator(dv[j]);
5607
5608 while((de = dictNext(di)) != NULL) {
5609 robj *ele;
5610
5611 /* dictAdd will not add the same element multiple times */
5612 ele = dictGetEntryKey(de);
5613 if (op == REDIS_OP_UNION || j == 0) {
5614 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
5615 incrRefCount(ele);
5616 cardinality++;
5617 }
5618 } else if (op == REDIS_OP_DIFF) {
5619 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
5620 cardinality--;
5621 }
5622 }
5623 }
5624 dictReleaseIterator(di);
5625
5626 /* result set is empty? Exit asap. */
5627 if (op == REDIS_OP_DIFF && cardinality == 0) break;
5628 }
5629
5630 /* Output the content of the resulting set, if not in STORE mode */
5631 if (!dstkey) {
5632 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
5633 di = dictGetIterator(dstset->ptr);
5634 while((de = dictNext(di)) != NULL) {
5635 robj *ele;
5636
5637 ele = dictGetEntryKey(de);
5638 addReplyBulk(c,ele);
5639 }
5640 dictReleaseIterator(di);
5641 decrRefCount(dstset);
5642 } else {
5643 /* If we have a target key where to store the resulting set
5644 * create this key with the result set inside */
5645 deleteKey(c->db,dstkey);
5646 if (dictSize((dict*)dstset->ptr) > 0) {
5647 dictAdd(c->db->dict,dstkey,dstset);
5648 incrRefCount(dstkey);
5649 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
5650 } else {
5651 decrRefCount(dstset);
5652 addReply(c,shared.czero);
5653 }
5654 server.dirty++;
5655 }
5656 zfree(dv);
5657 }
5658
5659 static void sunionCommand(redisClient *c) {
5660 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
5661 }
5662
5663 static void sunionstoreCommand(redisClient *c) {
5664 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
5665 }
5666
5667 static void sdiffCommand(redisClient *c) {
5668 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
5669 }
5670
5671 static void sdiffstoreCommand(redisClient *c) {
5672 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
5673 }
5674
5675 /* ==================================== ZSets =============================== */
5676
5677 /* ZSETs are ordered sets using two data structures to hold the same elements
5678 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5679 * data structure.
5680 *
5681 * The elements are added to an hash table mapping Redis objects to scores.
5682 * At the same time the elements are added to a skip list mapping scores
5683 * to Redis objects (so objects are sorted by scores in this "view"). */
5684
5685 /* This skiplist implementation is almost a C translation of the original
5686 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5687 * Alternative to Balanced Trees", modified in three ways:
5688 * a) this implementation allows for repeated values.
5689 * b) the comparison is not just by key (our 'score') but by satellite data.
5690 * c) there is a back pointer, so it's a doubly linked list with the back
5691 * pointers being only at "level 1". This allows to traverse the list
5692 * from tail to head, useful for ZREVRANGE. */
5693
5694 static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
5695 zskiplistNode *zn = zmalloc(sizeof(*zn));
5696
5697 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
5698 if (level > 1)
5699 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
5700 else
5701 zn->span = NULL;
5702 zn->score = score;
5703 zn->obj = obj;
5704 return zn;
5705 }
5706
5707 static zskiplist *zslCreate(void) {
5708 int j;
5709 zskiplist *zsl;
5710
5711 zsl = zmalloc(sizeof(*zsl));
5712 zsl->level = 1;
5713 zsl->length = 0;
5714 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
5715 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
5716 zsl->header->forward[j] = NULL;
5717
5718 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5719 if (j < ZSKIPLIST_MAXLEVEL-1)
5720 zsl->header->span[j] = 0;
5721 }
5722 zsl->header->backward = NULL;
5723 zsl->tail = NULL;
5724 return zsl;
5725 }
5726
5727 static void zslFreeNode(zskiplistNode *node) {
5728 decrRefCount(node->obj);
5729 zfree(node->forward);
5730 zfree(node->span);
5731 zfree(node);
5732 }
5733
5734 static void zslFree(zskiplist *zsl) {
5735 zskiplistNode *node = zsl->header->forward[0], *next;
5736
5737 zfree(zsl->header->forward);
5738 zfree(zsl->header->span);
5739 zfree(zsl->header);
5740 while(node) {
5741 next = node->forward[0];
5742 zslFreeNode(node);
5743 node = next;
5744 }
5745 zfree(zsl);
5746 }
5747
5748 static int zslRandomLevel(void) {
5749 int level = 1;
5750 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
5751 level += 1;
5752 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
5753 }
5754
5755 static void zslInsert(zskiplist *zsl, double score, robj *obj) {
5756 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5757 unsigned int rank[ZSKIPLIST_MAXLEVEL];
5758 int i, level;
5759
5760 x = zsl->header;
5761 for (i = zsl->level-1; i >= 0; i--) {
5762 /* store rank that is crossed to reach the insert position */
5763 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
5764
5765 while (x->forward[i] &&
5766 (x->forward[i]->score < score ||
5767 (x->forward[i]->score == score &&
5768 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
5769 rank[i] += i > 0 ? x->span[i-1] : 1;
5770 x = x->forward[i];
5771 }
5772 update[i] = x;
5773 }
5774 /* we assume the key is not already inside, since we allow duplicated
5775 * scores, and the re-insertion of score and redis object should never
5776 * happpen since the caller of zslInsert() should test in the hash table
5777 * if the element is already inside or not. */
5778 level = zslRandomLevel();
5779 if (level > zsl->level) {
5780 for (i = zsl->level; i < level; i++) {
5781 rank[i] = 0;
5782 update[i] = zsl->header;
5783 update[i]->span[i-1] = zsl->length;
5784 }
5785 zsl->level = level;
5786 }
5787 x = zslCreateNode(level,score,obj);
5788 for (i = 0; i < level; i++) {
5789 x->forward[i] = update[i]->forward[i];
5790 update[i]->forward[i] = x;
5791
5792 /* update span covered by update[i] as x is inserted here */
5793 if (i > 0) {
5794 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
5795 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
5796 }
5797 }
5798
5799 /* increment span for untouched levels */
5800 for (i = level; i < zsl->level; i++) {
5801 update[i]->span[i-1]++;
5802 }
5803
5804 x->backward = (update[0] == zsl->header) ? NULL : update[0];
5805 if (x->forward[0])
5806 x->forward[0]->backward = x;
5807 else
5808 zsl->tail = x;
5809 zsl->length++;
5810 }
5811
5812 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5813 void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
5814 int i;
5815 for (i = 0; i < zsl->level; i++) {
5816 if (update[i]->forward[i] == x) {
5817 if (i > 0) {
5818 update[i]->span[i-1] += x->span[i-1] - 1;
5819 }
5820 update[i]->forward[i] = x->forward[i];
5821 } else {
5822 /* invariant: i > 0, because update[0]->forward[0]
5823 * is always equal to x */
5824 update[i]->span[i-1] -= 1;
5825 }
5826 }
5827 if (x->forward[0]) {
5828 x->forward[0]->backward = x->backward;
5829 } else {
5830 zsl->tail = x->backward;
5831 }
5832 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
5833 zsl->level--;
5834 zsl->length--;
5835 }
5836
5837 /* Delete an element with matching score/object from the skiplist. */
5838 static int zslDelete(zskiplist *zsl, double score, robj *obj) {
5839 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5840 int i;
5841
5842 x = zsl->header;
5843 for (i = zsl->level-1; i >= 0; i--) {
5844 while (x->forward[i] &&
5845 (x->forward[i]->score < score ||
5846 (x->forward[i]->score == score &&
5847 compareStringObjects(x->forward[i]->obj,obj) < 0)))
5848 x = x->forward[i];
5849 update[i] = x;
5850 }
5851 /* We may have multiple elements with the same score, what we need
5852 * is to find the element with both the right score and object. */
5853 x = x->forward[0];
5854 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
5855 zslDeleteNode(zsl, x, update);
5856 zslFreeNode(x);
5857 return 1;
5858 } else {
5859 return 0; /* not found */
5860 }
5861 return 0; /* not found */
5862 }
5863
5864 /* Delete all the elements with score between min and max from the skiplist.
5865 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5866 * Note that this function takes the reference to the hash table view of the
5867 * sorted set, in order to remove the elements from the hash table too. */
5868 static unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
5869 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5870 unsigned long removed = 0;
5871 int i;
5872
5873 x = zsl->header;
5874 for (i = zsl->level-1; i >= 0; i--) {
5875 while (x->forward[i] && x->forward[i]->score < min)
5876 x = x->forward[i];
5877 update[i] = x;
5878 }
5879 /* We may have multiple elements with the same score, what we need
5880 * is to find the element with both the right score and object. */
5881 x = x->forward[0];
5882 while (x && x->score <= max) {
5883 zskiplistNode *next = x->forward[0];
5884 zslDeleteNode(zsl, x, update);
5885 dictDelete(dict,x->obj);
5886 zslFreeNode(x);
5887 removed++;
5888 x = next;
5889 }
5890 return removed; /* not found */
5891 }
5892
5893 /* Delete all the elements with rank between start and end from the skiplist.
5894 * Start and end are inclusive. Note that start and end need to be 1-based */
5895 static unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
5896 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5897 unsigned long traversed = 0, removed = 0;
5898 int i;
5899
5900 x = zsl->header;
5901 for (i = zsl->level-1; i >= 0; i--) {
5902 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
5903 traversed += i > 0 ? x->span[i-1] : 1;
5904 x = x->forward[i];
5905 }
5906 update[i] = x;
5907 }
5908
5909 traversed++;
5910 x = x->forward[0];
5911 while (x && traversed <= end) {
5912 zskiplistNode *next = x->forward[0];
5913 zslDeleteNode(zsl, x, update);
5914 dictDelete(dict,x->obj);
5915 zslFreeNode(x);
5916 removed++;
5917 traversed++;
5918 x = next;
5919 }
5920 return removed;
5921 }
5922
5923 /* Find the first node having a score equal or greater than the specified one.
5924 * Returns NULL if there is no match. */
5925 static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
5926 zskiplistNode *x;
5927 int i;
5928
5929 x = zsl->header;
5930 for (i = zsl->level-1; i >= 0; i--) {
5931 while (x->forward[i] && x->forward[i]->score < score)
5932 x = x->forward[i];
5933 }
5934 /* We may have multiple elements with the same score, what we need
5935 * is to find the element with both the right score and object. */
5936 return x->forward[0];
5937 }
5938
5939 /* Find the rank for an element by both score and key.
5940 * Returns 0 when the element cannot be found, rank otherwise.
5941 * Note that the rank is 1-based due to the span of zsl->header to the
5942 * first element. */
5943 static unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
5944 zskiplistNode *x;
5945 unsigned long rank = 0;
5946 int i;
5947
5948 x = zsl->header;
5949 for (i = zsl->level-1; i >= 0; i--) {
5950 while (x->forward[i] &&
5951 (x->forward[i]->score < score ||
5952 (x->forward[i]->score == score &&
5953 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
5954 rank += i > 0 ? x->span[i-1] : 1;
5955 x = x->forward[i];
5956 }
5957
5958 /* x might be equal to zsl->header, so test if obj is non-NULL */
5959 if (x->obj && equalStringObjects(x->obj,o)) {
5960 return rank;
5961 }
5962 }
5963 return 0;
5964 }
5965
5966 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5967 zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
5968 zskiplistNode *x;
5969 unsigned long traversed = 0;
5970 int i;
5971
5972 x = zsl->header;
5973 for (i = zsl->level-1; i >= 0; i--) {
5974 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
5975 {
5976 traversed += i > 0 ? x->span[i-1] : 1;
5977 x = x->forward[i];
5978 }
5979 if (traversed == rank) {
5980 return x;
5981 }
5982 }
5983 return NULL;
5984 }
5985
5986 /* The actual Z-commands implementations */
5987
5988 /* This generic command implements both ZADD and ZINCRBY.
5989 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5990 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5991 static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
5992 robj *zsetobj;
5993 zset *zs;
5994 double *score;
5995
5996 if (isnan(scoreval)) {
5997 addReplySds(c,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
5998 return;
5999 }
6000
6001 zsetobj = lookupKeyWrite(c->db,key);
6002 if (zsetobj == NULL) {
6003 zsetobj = createZsetObject();
6004 dictAdd(c->db->dict,key,zsetobj);
6005 incrRefCount(key);
6006 } else {
6007 if (zsetobj->type != REDIS_ZSET) {
6008 addReply(c,shared.wrongtypeerr);
6009 return;
6010 }
6011 }
6012 zs = zsetobj->ptr;
6013
6014 /* Ok now since we implement both ZADD and ZINCRBY here the code
6015 * needs to handle the two different conditions. It's all about setting
6016 * '*score', that is, the new score to set, to the right value. */
6017 score = zmalloc(sizeof(double));
6018 if (doincrement) {
6019 dictEntry *de;
6020
6021 /* Read the old score. If the element was not present starts from 0 */
6022 de = dictFind(zs->dict,ele);
6023 if (de) {
6024 double *oldscore = dictGetEntryVal(de);
6025 *score = *oldscore + scoreval;
6026 } else {
6027 *score = scoreval;
6028 }
6029 if (isnan(*score)) {
6030 addReplySds(c,
6031 sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
6032 zfree(score);
6033 /* Note that we don't need to check if the zset may be empty and
6034 * should be removed here, as we can only obtain Nan as score if
6035 * there was already an element in the sorted set. */
6036 return;
6037 }
6038 } else {
6039 *score = scoreval;
6040 }
6041
6042 /* What follows is a simple remove and re-insert operation that is common
6043 * to both ZADD and ZINCRBY... */
6044 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
6045 /* case 1: New element */
6046 incrRefCount(ele); /* added to hash */
6047 zslInsert(zs->zsl,*score,ele);
6048 incrRefCount(ele); /* added to skiplist */
6049 server.dirty++;
6050 if (doincrement)
6051 addReplyDouble(c,*score);
6052 else
6053 addReply(c,shared.cone);
6054 } else {
6055 dictEntry *de;
6056 double *oldscore;
6057
6058 /* case 2: Score update operation */
6059 de = dictFind(zs->dict,ele);
6060 redisAssert(de != NULL);
6061 oldscore = dictGetEntryVal(de);
6062 if (*score != *oldscore) {
6063 int deleted;
6064
6065 /* Remove and insert the element in the skip list with new score */
6066 deleted = zslDelete(zs->zsl,*oldscore,ele);
6067 redisAssert(deleted != 0);
6068 zslInsert(zs->zsl,*score,ele);
6069 incrRefCount(ele);
6070 /* Update the score in the hash table */
6071 dictReplace(zs->dict,ele,score);
6072 server.dirty++;
6073 } else {
6074 zfree(score);
6075 }
6076 if (doincrement)
6077 addReplyDouble(c,*score);
6078 else
6079 addReply(c,shared.czero);
6080 }
6081 }
6082
6083 static void zaddCommand(redisClient *c) {
6084 double scoreval;
6085
6086 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
6087 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
6088 }
6089
6090 static void zincrbyCommand(redisClient *c) {
6091 double scoreval;
6092
6093 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
6094 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
6095 }
6096
6097 static void zremCommand(redisClient *c) {
6098 robj *zsetobj;
6099 zset *zs;
6100 dictEntry *de;
6101 double *oldscore;
6102 int deleted;
6103
6104 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6105 checkType(c,zsetobj,REDIS_ZSET)) return;
6106
6107 zs = zsetobj->ptr;
6108 de = dictFind(zs->dict,c->argv[2]);
6109 if (de == NULL) {
6110 addReply(c,shared.czero);
6111 return;
6112 }
6113 /* Delete from the skiplist */
6114 oldscore = dictGetEntryVal(de);
6115 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
6116 redisAssert(deleted != 0);
6117
6118 /* Delete from the hash table */
6119 dictDelete(zs->dict,c->argv[2]);
6120 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
6121 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
6122 server.dirty++;
6123 addReply(c,shared.cone);
6124 }
6125
6126 static void zremrangebyscoreCommand(redisClient *c) {
6127 double min;
6128 double max;
6129 long deleted;
6130 robj *zsetobj;
6131 zset *zs;
6132
6133 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
6134 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
6135
6136 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6137 checkType(c,zsetobj,REDIS_ZSET)) return;
6138
6139 zs = zsetobj->ptr;
6140 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
6141 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
6142 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
6143 server.dirty += deleted;
6144 addReplyLongLong(c,deleted);
6145 }
6146
6147 static void zremrangebyrankCommand(redisClient *c) {
6148 long start;
6149 long end;
6150 int llen;
6151 long deleted;
6152 robj *zsetobj;
6153 zset *zs;
6154
6155 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6156 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
6157
6158 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6159 checkType(c,zsetobj,REDIS_ZSET)) return;
6160 zs = zsetobj->ptr;
6161 llen = zs->zsl->length;
6162
6163 /* convert negative indexes */
6164 if (start < 0) start = llen+start;
6165 if (end < 0) end = llen+end;
6166 if (start < 0) start = 0;
6167 if (end < 0) end = 0;
6168
6169 /* indexes sanity checks */
6170 if (start > end || start >= llen) {
6171 addReply(c,shared.czero);
6172 return;
6173 }
6174 if (end >= llen) end = llen-1;
6175
6176 /* increment start and end because zsl*Rank functions
6177 * use 1-based rank */
6178 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
6179 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
6180 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
6181 server.dirty += deleted;
6182 addReplyLongLong(c, deleted);
6183 }
6184
6185 typedef struct {
6186 dict *dict;
6187 double weight;
6188 } zsetopsrc;
6189
6190 static int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
6191 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
6192 unsigned long size1, size2;
6193 size1 = d1->dict ? dictSize(d1->dict) : 0;
6194 size2 = d2->dict ? dictSize(d2->dict) : 0;
6195 return size1 - size2;
6196 }
6197
6198 #define REDIS_AGGR_SUM 1
6199 #define REDIS_AGGR_MIN 2
6200 #define REDIS_AGGR_MAX 3
6201 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
6202
6203 inline static void zunionInterAggregate(double *target, double val, int aggregate) {
6204 if (aggregate == REDIS_AGGR_SUM) {
6205 *target = *target + val;
6206 } else if (aggregate == REDIS_AGGR_MIN) {
6207 *target = val < *target ? val : *target;
6208 } else if (aggregate == REDIS_AGGR_MAX) {
6209 *target = val > *target ? val : *target;
6210 } else {
6211 /* safety net */
6212 redisPanic("Unknown ZUNION/INTER aggregate type");
6213 }
6214 }
6215
6216 static void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
6217 int i, j, setnum;
6218 int aggregate = REDIS_AGGR_SUM;
6219 zsetopsrc *src;
6220 robj *dstobj;
6221 zset *dstzset;
6222 dictIterator *di;
6223 dictEntry *de;
6224
6225 /* expect setnum input keys to be given */
6226 setnum = atoi(c->argv[2]->ptr);
6227 if (setnum < 1) {
6228 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
6229 return;
6230 }
6231
6232 /* test if the expected number of keys would overflow */
6233 if (3+setnum > c->argc) {
6234 addReply(c,shared.syntaxerr);
6235 return;
6236 }
6237
6238 /* read keys to be used for input */
6239 src = zmalloc(sizeof(zsetopsrc) * setnum);
6240 for (i = 0, j = 3; i < setnum; i++, j++) {
6241 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
6242 if (!obj) {
6243 src[i].dict = NULL;
6244 } else {
6245 if (obj->type == REDIS_ZSET) {
6246 src[i].dict = ((zset*)obj->ptr)->dict;
6247 } else if (obj->type == REDIS_SET) {
6248 src[i].dict = (obj->ptr);
6249 } else {
6250 zfree(src);
6251 addReply(c,shared.wrongtypeerr);
6252 return;
6253 }
6254 }
6255
6256 /* default all weights to 1 */
6257 src[i].weight = 1.0;
6258 }
6259
6260 /* parse optional extra arguments */
6261 if (j < c->argc) {
6262 int remaining = c->argc - j;
6263
6264 while (remaining) {
6265 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
6266 j++; remaining--;
6267 for (i = 0; i < setnum; i++, j++, remaining--) {
6268 if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK)
6269 return;
6270 }
6271 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
6272 j++; remaining--;
6273 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
6274 aggregate = REDIS_AGGR_SUM;
6275 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
6276 aggregate = REDIS_AGGR_MIN;
6277 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
6278 aggregate = REDIS_AGGR_MAX;
6279 } else {
6280 zfree(src);
6281 addReply(c,shared.syntaxerr);
6282 return;
6283 }
6284 j++; remaining--;
6285 } else {
6286 zfree(src);
6287 addReply(c,shared.syntaxerr);
6288 return;
6289 }
6290 }
6291 }
6292
6293 /* sort sets from the smallest to largest, this will improve our
6294 * algorithm's performance */
6295 qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);
6296
6297 dstobj = createZsetObject();
6298 dstzset = dstobj->ptr;
6299
6300 if (op == REDIS_OP_INTER) {
6301 /* skip going over all entries if the smallest zset is NULL or empty */
6302 if (src[0].dict && dictSize(src[0].dict) > 0) {
6303 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6304 * from small to large, all src[i > 0].dict are non-empty too */
6305 di = dictGetIterator(src[0].dict);
6306 while((de = dictNext(di)) != NULL) {
6307 double *score = zmalloc(sizeof(double)), value;
6308 *score = src[0].weight * zunionInterDictValue(de);
6309
6310 for (j = 1; j < setnum; j++) {
6311 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
6312 if (other) {
6313 value = src[j].weight * zunionInterDictValue(other);
6314 zunionInterAggregate(score, value, aggregate);
6315 } else {
6316 break;
6317 }
6318 }
6319
6320 /* skip entry when not present in every source dict */
6321 if (j != setnum) {
6322 zfree(score);
6323 } else {
6324 robj *o = dictGetEntryKey(de);
6325 dictAdd(dstzset->dict,o,score);
6326 incrRefCount(o); /* added to dictionary */
6327 zslInsert(dstzset->zsl,*score,o);
6328 incrRefCount(o); /* added to skiplist */
6329 }
6330 }
6331 dictReleaseIterator(di);
6332 }
6333 } else if (op == REDIS_OP_UNION) {
6334 for (i = 0; i < setnum; i++) {
6335 if (!src[i].dict) continue;
6336
6337 di = dictGetIterator(src[i].dict);
6338 while((de = dictNext(di)) != NULL) {
6339 /* skip key when already processed */
6340 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
6341
6342 double *score = zmalloc(sizeof(double)), value;
6343 *score = src[i].weight * zunionInterDictValue(de);
6344
6345 /* because the zsets are sorted by size, its only possible
6346 * for sets at larger indices to hold this entry */
6347 for (j = (i+1); j < setnum; j++) {
6348 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
6349 if (other) {
6350 value = src[j].weight * zunionInterDictValue(other);
6351 zunionInterAggregate(score, value, aggregate);
6352 }
6353 }
6354
6355 robj *o = dictGetEntryKey(de);
6356 dictAdd(dstzset->dict,o,score);
6357 incrRefCount(o); /* added to dictionary */
6358 zslInsert(dstzset->zsl,*score,o);
6359 incrRefCount(o); /* added to skiplist */
6360 }
6361 dictReleaseIterator(di);
6362 }
6363 } else {
6364 /* unknown operator */
6365 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
6366 }
6367
6368 deleteKey(c->db,dstkey);
6369 if (dstzset->zsl->length) {
6370 dictAdd(c->db->dict,dstkey,dstobj);
6371 incrRefCount(dstkey);
6372 addReplyLongLong(c, dstzset->zsl->length);
6373 server.dirty++;
6374 } else {
6375 decrRefCount(dstobj);
6376 addReply(c, shared.czero);
6377 }
6378 zfree(src);
6379 }
6380
6381 static void zunionstoreCommand(redisClient *c) {
6382 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
6383 }
6384
6385 static void zinterstoreCommand(redisClient *c) {
6386 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
6387 }
6388
6389 static void zrangeGenericCommand(redisClient *c, int reverse) {
6390 robj *o;
6391 long start;
6392 long end;
6393 int withscores = 0;
6394 int llen;
6395 int rangelen, j;
6396 zset *zsetobj;
6397 zskiplist *zsl;
6398 zskiplistNode *ln;
6399 robj *ele;
6400
6401 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6402 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
6403
6404 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
6405 withscores = 1;
6406 } else if (c->argc >= 5) {
6407 addReply(c,shared.syntaxerr);
6408 return;
6409 }
6410
6411 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6412 || checkType(c,o,REDIS_ZSET)) return;
6413 zsetobj = o->ptr;
6414 zsl = zsetobj->zsl;
6415 llen = zsl->length;
6416
6417 /* convert negative indexes */
6418 if (start < 0) start = llen+start;
6419 if (end < 0) end = llen+end;
6420 if (start < 0) start = 0;
6421 if (end < 0) end = 0;
6422
6423 /* indexes sanity checks */
6424 if (start > end || start >= llen) {
6425 /* Out of range start or start > end result in empty list */
6426 addReply(c,shared.emptymultibulk);
6427 return;
6428 }
6429 if (end >= llen) end = llen-1;
6430 rangelen = (end-start)+1;
6431
6432 /* check if starting point is trivial, before searching
6433 * the element in log(N) time */
6434 if (reverse) {
6435 ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start);
6436 } else {
6437 ln = start == 0 ?
6438 zsl->header->forward[0] : zslGetElementByRank(zsl, start+1);
6439 }
6440
6441 /* Return the result in form of a multi-bulk reply */
6442 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
6443 withscores ? (rangelen*2) : rangelen));
6444 for (j = 0; j < rangelen; j++) {
6445 ele = ln->obj;
6446 addReplyBulk(c,ele);
6447 if (withscores)
6448 addReplyDouble(c,ln->score);
6449 ln = reverse ? ln->backward : ln->forward[0];
6450 }
6451 }
6452
6453 static void zrangeCommand(redisClient *c) {
6454 zrangeGenericCommand(c,0);
6455 }
6456
6457 static void zrevrangeCommand(redisClient *c) {
6458 zrangeGenericCommand(c,1);
6459 }
6460
6461 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
6462 * If justcount is non-zero, just the count is returned. */
6463 static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
6464 robj *o;
6465 double min, max;
6466 int minex = 0, maxex = 0; /* are min or max exclusive? */
6467 int offset = 0, limit = -1;
6468 int withscores = 0;
6469 int badsyntax = 0;
6470
6471 /* Parse the min-max interval. If one of the values is prefixed
6472 * by the "(" character, it's considered "open". For instance
6473 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6474 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6475 if (((char*)c->argv[2]->ptr)[0] == '(') {
6476 min = strtod((char*)c->argv[2]->ptr+1,NULL);
6477 minex = 1;
6478 } else {
6479 min = strtod(c->argv[2]->ptr,NULL);
6480 }
6481 if (((char*)c->argv[3]->ptr)[0] == '(') {
6482 max = strtod((char*)c->argv[3]->ptr+1,NULL);
6483 maxex = 1;
6484 } else {
6485 max = strtod(c->argv[3]->ptr,NULL);
6486 }
6487
6488 /* Parse "WITHSCORES": note that if the command was called with
6489 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6490 * enter the following paths to parse WITHSCORES and LIMIT. */
6491 if (c->argc == 5 || c->argc == 8) {
6492 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
6493 withscores = 1;
6494 else
6495 badsyntax = 1;
6496 }
6497 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
6498 badsyntax = 1;
6499 if (badsyntax) {
6500 addReplySds(c,
6501 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
6502 return;
6503 }
6504
6505 /* Parse "LIMIT" */
6506 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
6507 addReply(c,shared.syntaxerr);
6508 return;
6509 } else if (c->argc == (7 + withscores)) {
6510 offset = atoi(c->argv[5]->ptr);
6511 limit = atoi(c->argv[6]->ptr);
6512 if (offset < 0) offset = 0;
6513 }
6514
6515 /* Ok, lookup the key and get the range */
6516 o = lookupKeyRead(c->db,c->argv[1]);
6517 if (o == NULL) {
6518 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
6519 } else {
6520 if (o->type != REDIS_ZSET) {
6521 addReply(c,shared.wrongtypeerr);
6522 } else {
6523 zset *zsetobj = o->ptr;
6524 zskiplist *zsl = zsetobj->zsl;
6525 zskiplistNode *ln;
6526 robj *ele, *lenobj = NULL;
6527 unsigned long rangelen = 0;
6528
6529 /* Get the first node with the score >= min, or with
6530 * score > min if 'minex' is true. */
6531 ln = zslFirstWithScore(zsl,min);
6532 while (minex && ln && ln->score == min) ln = ln->forward[0];
6533
6534 if (ln == NULL) {
6535 /* No element matching the speciifed interval */
6536 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
6537 return;
6538 }
6539
6540 /* We don't know in advance how many matching elements there
6541 * are in the list, so we push this object that will represent
6542 * the multi-bulk length in the output buffer, and will "fix"
6543 * it later */
6544 if (!justcount) {
6545 lenobj = createObject(REDIS_STRING,NULL);
6546 addReply(c,lenobj);
6547 decrRefCount(lenobj);
6548 }
6549
6550 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
6551 if (offset) {
6552 offset--;
6553 ln = ln->forward[0];
6554 continue;
6555 }
6556 if (limit == 0) break;
6557 if (!justcount) {
6558 ele = ln->obj;
6559 addReplyBulk(c,ele);
6560 if (withscores)
6561 addReplyDouble(c,ln->score);
6562 }
6563 ln = ln->forward[0];
6564 rangelen++;
6565 if (limit > 0) limit--;
6566 }
6567 if (justcount) {
6568 addReplyLongLong(c,(long)rangelen);
6569 } else {
6570 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
6571 withscores ? (rangelen*2) : rangelen);
6572 }
6573 }
6574 }
6575 }
6576
6577 static void zrangebyscoreCommand(redisClient *c) {
6578 genericZrangebyscoreCommand(c,0);
6579 }
6580
6581 static void zcountCommand(redisClient *c) {
6582 genericZrangebyscoreCommand(c,1);
6583 }
6584
6585 static void zcardCommand(redisClient *c) {
6586 robj *o;
6587 zset *zs;
6588
6589 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6590 checkType(c,o,REDIS_ZSET)) return;
6591
6592 zs = o->ptr;
6593 addReplyUlong(c,zs->zsl->length);
6594 }
6595
6596 static void zscoreCommand(redisClient *c) {
6597 robj *o;
6598 zset *zs;
6599 dictEntry *de;
6600
6601 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6602 checkType(c,o,REDIS_ZSET)) return;
6603
6604 zs = o->ptr;
6605 de = dictFind(zs->dict,c->argv[2]);
6606 if (!de) {
6607 addReply(c,shared.nullbulk);
6608 } else {
6609 double *score = dictGetEntryVal(de);
6610
6611 addReplyDouble(c,*score);
6612 }
6613 }
6614
6615 static void zrankGenericCommand(redisClient *c, int reverse) {
6616 robj *o;
6617 zset *zs;
6618 zskiplist *zsl;
6619 dictEntry *de;
6620 unsigned long rank;
6621 double *score;
6622
6623 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6624 checkType(c,o,REDIS_ZSET)) return;
6625
6626 zs = o->ptr;
6627 zsl = zs->zsl;
6628 de = dictFind(zs->dict,c->argv[2]);
6629 if (!de) {
6630 addReply(c,shared.nullbulk);
6631 return;
6632 }
6633
6634 score = dictGetEntryVal(de);
6635 rank = zslGetRank(zsl, *score, c->argv[2]);
6636 if (rank) {
6637 if (reverse) {
6638 addReplyLongLong(c, zsl->length - rank);
6639 } else {
6640 addReplyLongLong(c, rank-1);
6641 }
6642 } else {
6643 addReply(c,shared.nullbulk);
6644 }
6645 }
6646
6647 static void zrankCommand(redisClient *c) {
6648 zrankGenericCommand(c, 0);
6649 }
6650
6651 static void zrevrankCommand(redisClient *c) {
6652 zrankGenericCommand(c, 1);
6653 }
6654
6655 /* ========================= Hashes utility functions ======================= */
6656 #define REDIS_HASH_KEY 1
6657 #define REDIS_HASH_VALUE 2
6658
6659 /* Check the length of a number of objects to see if we need to convert a
6660 * zipmap to a real hash. Note that we only check string encoded objects
6661 * as their string length can be queried in constant time. */
6662 static void hashTryConversion(robj *subject, robj **argv, int start, int end) {
6663 int i;
6664 if (subject->encoding != REDIS_ENCODING_ZIPMAP) return;
6665
6666 for (i = start; i <= end; i++) {
6667 if (argv[i]->encoding == REDIS_ENCODING_RAW &&
6668 sdslen(argv[i]->ptr) > server.hash_max_zipmap_value)
6669 {
6670 convertToRealHash(subject);
6671 return;
6672 }
6673 }
6674 }
6675
6676 /* Encode given objects in-place when the hash uses a dict. */
6677 static void hashTryObjectEncoding(robj *subject, robj **o1, robj **o2) {
6678 if (subject->encoding == REDIS_ENCODING_HT) {
6679 if (o1) *o1 = tryObjectEncoding(*o1);
6680 if (o2) *o2 = tryObjectEncoding(*o2);
6681 }
6682 }
6683
6684 /* Get the value from a hash identified by key. Returns either a string
6685 * object or NULL if the value cannot be found. The refcount of the object
6686 * is always increased by 1 when the value was found. */
6687 static robj *hashGet(robj *o, robj *key) {
6688 robj *value = NULL;
6689 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6690 unsigned char *v;
6691 unsigned int vlen;
6692 key = getDecodedObject(key);
6693 if (zipmapGet(o->ptr,key->ptr,sdslen(key->ptr),&v,&vlen)) {
6694 value = createStringObject((char*)v,vlen);
6695 }
6696 decrRefCount(key);
6697 } else {
6698 dictEntry *de = dictFind(o->ptr,key);
6699 if (de != NULL) {
6700 value = dictGetEntryVal(de);
6701 incrRefCount(value);
6702 }
6703 }
6704 return value;
6705 }
6706
6707 /* Test if the key exists in the given hash. Returns 1 if the key
6708 * exists and 0 when it doesn't. */
6709 static int hashExists(robj *o, robj *key) {
6710 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6711 key = getDecodedObject(key);
6712 if (zipmapExists(o->ptr,key->ptr,sdslen(key->ptr))) {
6713 decrRefCount(key);
6714 return 1;
6715 }
6716 decrRefCount(key);
6717 } else {
6718 if (dictFind(o->ptr,key) != NULL) {
6719 return 1;
6720 }
6721 }
6722 return 0;
6723 }
6724
6725 /* Add an element, discard the old if the key already exists.
6726 * Return 0 on insert and 1 on update. */
6727 static int hashSet(robj *o, robj *key, robj *value) {
6728 int update = 0;
6729 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6730 key = getDecodedObject(key);
6731 value = getDecodedObject(value);
6732 o->ptr = zipmapSet(o->ptr,
6733 key->ptr,sdslen(key->ptr),
6734 value->ptr,sdslen(value->ptr), &update);
6735 decrRefCount(key);
6736 decrRefCount(value);
6737
6738 /* Check if the zipmap needs to be upgraded to a real hash table */
6739 if (zipmapLen(o->ptr) > server.hash_max_zipmap_entries)
6740 convertToRealHash(o);
6741 } else {
6742 if (dictReplace(o->ptr,key,value)) {
6743 /* Insert */
6744 incrRefCount(key);
6745 } else {
6746 /* Update */
6747 update = 1;
6748 }
6749 incrRefCount(value);
6750 }
6751 return update;
6752 }
6753
6754 /* Delete an element from a hash.
6755 * Return 1 on deleted and 0 on not found. */
6756 static int hashDelete(robj *o, robj *key) {
6757 int deleted = 0;
6758 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6759 key = getDecodedObject(key);
6760 o->ptr = zipmapDel(o->ptr,key->ptr,sdslen(key->ptr), &deleted);
6761 decrRefCount(key);
6762 } else {
6763 deleted = dictDelete((dict*)o->ptr,key) == DICT_OK;
6764 /* Always check if the dictionary needs a resize after a delete. */
6765 if (deleted && htNeedsResize(o->ptr)) dictResize(o->ptr);
6766 }
6767 return deleted;
6768 }
6769
6770 /* Return the number of elements in a hash. */
6771 static unsigned long hashLength(robj *o) {
6772 return (o->encoding == REDIS_ENCODING_ZIPMAP) ?
6773 zipmapLen((unsigned char*)o->ptr) : dictSize((dict*)o->ptr);
6774 }
6775
6776 /* Structure to hold hash iteration abstration. Note that iteration over
6777 * hashes involves both fields and values. Because it is possible that
6778 * not both are required, store pointers in the iterator to avoid
6779 * unnecessary memory allocation for fields/values. */
6780 typedef struct {
6781 int encoding;
6782 unsigned char *zi;
6783 unsigned char *zk, *zv;
6784 unsigned int zklen, zvlen;
6785
6786 dictIterator *di;
6787 dictEntry *de;
6788 } hashIterator;
6789
6790 static hashIterator *hashInitIterator(robj *subject) {
6791 hashIterator *hi = zmalloc(sizeof(hashIterator));
6792 hi->encoding = subject->encoding;
6793 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6794 hi->zi = zipmapRewind(subject->ptr);
6795 } else if (hi->encoding == REDIS_ENCODING_HT) {
6796 hi->di = dictGetIterator(subject->ptr);
6797 } else {
6798 redisAssert(NULL);
6799 }
6800 return hi;
6801 }
6802
6803 static void hashReleaseIterator(hashIterator *hi) {
6804 if (hi->encoding == REDIS_ENCODING_HT) {
6805 dictReleaseIterator(hi->di);
6806 }
6807 zfree(hi);
6808 }
6809
6810 /* Move to the next entry in the hash. Return REDIS_OK when the next entry
6811 * could be found and REDIS_ERR when the iterator reaches the end. */
6812 static int hashNext(hashIterator *hi) {
6813 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6814 if ((hi->zi = zipmapNext(hi->zi, &hi->zk, &hi->zklen,
6815 &hi->zv, &hi->zvlen)) == NULL) return REDIS_ERR;
6816 } else {
6817 if ((hi->de = dictNext(hi->di)) == NULL) return REDIS_ERR;
6818 }
6819 return REDIS_OK;
6820 }
6821
6822 /* Get key or value object at current iteration position.
6823 * This increases the refcount of the field object by 1. */
6824 static robj *hashCurrent(hashIterator *hi, int what) {
6825 robj *o;
6826 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6827 if (what & REDIS_HASH_KEY) {
6828 o = createStringObject((char*)hi->zk,hi->zklen);
6829 } else {
6830 o = createStringObject((char*)hi->zv,hi->zvlen);
6831 }
6832 } else {
6833 if (what & REDIS_HASH_KEY) {
6834 o = dictGetEntryKey(hi->de);
6835 } else {
6836 o = dictGetEntryVal(hi->de);
6837 }
6838 incrRefCount(o);
6839 }
6840 return o;
6841 }
6842
6843 static robj *hashLookupWriteOrCreate(redisClient *c, robj *key) {
6844 robj *o = lookupKeyWrite(c->db,key);
6845 if (o == NULL) {
6846 o = createHashObject();
6847 dictAdd(c->db->dict,key,o);
6848 incrRefCount(key);
6849 } else {
6850 if (o->type != REDIS_HASH) {
6851 addReply(c,shared.wrongtypeerr);
6852 return NULL;
6853 }
6854 }
6855 return o;
6856 }
6857
6858 /* ============================= Hash commands ============================== */
6859 static void hsetCommand(redisClient *c) {
6860 int update;
6861 robj *o;
6862
6863 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6864 hashTryConversion(o,c->argv,2,3);
6865 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
6866 update = hashSet(o,c->argv[2],c->argv[3]);
6867 addReply(c, update ? shared.czero : shared.cone);
6868 server.dirty++;
6869 }
6870
6871 static void hsetnxCommand(redisClient *c) {
6872 robj *o;
6873 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6874 hashTryConversion(o,c->argv,2,3);
6875
6876 if (hashExists(o, c->argv[2])) {
6877 addReply(c, shared.czero);
6878 } else {
6879 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
6880 hashSet(o,c->argv[2],c->argv[3]);
6881 addReply(c, shared.cone);
6882 server.dirty++;
6883 }
6884 }
6885
6886 static void hmsetCommand(redisClient *c) {
6887 int i;
6888 robj *o;
6889
6890 if ((c->argc % 2) == 1) {
6891 addReplySds(c,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6892 return;
6893 }
6894
6895 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6896 hashTryConversion(o,c->argv,2,c->argc-1);
6897 for (i = 2; i < c->argc; i += 2) {
6898 hashTryObjectEncoding(o,&c->argv[i], &c->argv[i+1]);
6899 hashSet(o,c->argv[i],c->argv[i+1]);
6900 }
6901 addReply(c, shared.ok);
6902 server.dirty++;
6903 }
6904
6905 static void hincrbyCommand(redisClient *c) {
6906 long long value, incr;
6907 robj *o, *current, *new;
6908
6909 if (getLongLongFromObjectOrReply(c,c->argv[3],&incr,NULL) != REDIS_OK) return;
6910 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6911 if ((current = hashGet(o,c->argv[2])) != NULL) {
6912 if (getLongLongFromObjectOrReply(c,current,&value,
6913 "hash value is not an integer") != REDIS_OK) {
6914 decrRefCount(current);
6915 return;
6916 }
6917 decrRefCount(current);
6918 } else {
6919 value = 0;
6920 }
6921
6922 value += incr;
6923 new = createStringObjectFromLongLong(value);
6924 hashTryObjectEncoding(o,&c->argv[2],NULL);
6925 hashSet(o,c->argv[2],new);
6926 decrRefCount(new);
6927 addReplyLongLong(c,value);
6928 server.dirty++;
6929 }
6930
6931 static void hgetCommand(redisClient *c) {
6932 robj *o, *value;
6933 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6934 checkType(c,o,REDIS_HASH)) return;
6935
6936 if ((value = hashGet(o,c->argv[2])) != NULL) {
6937 addReplyBulk(c,value);
6938 decrRefCount(value);
6939 } else {
6940 addReply(c,shared.nullbulk);
6941 }
6942 }
6943
6944 static void hmgetCommand(redisClient *c) {
6945 int i;
6946 robj *o, *value;
6947 o = lookupKeyRead(c->db,c->argv[1]);
6948 if (o != NULL && o->type != REDIS_HASH) {
6949 addReply(c,shared.wrongtypeerr);
6950 }
6951
6952 /* Note the check for o != NULL happens inside the loop. This is
6953 * done because objects that cannot be found are considered to be
6954 * an empty hash. The reply should then be a series of NULLs. */
6955 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-2));
6956 for (i = 2; i < c->argc; i++) {
6957 if (o != NULL && (value = hashGet(o,c->argv[i])) != NULL) {
6958 addReplyBulk(c,value);
6959 decrRefCount(value);
6960 } else {
6961 addReply(c,shared.nullbulk);
6962 }
6963 }
6964 }
6965
6966 static void hdelCommand(redisClient *c) {
6967 robj *o;
6968 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6969 checkType(c,o,REDIS_HASH)) return;
6970
6971 if (hashDelete(o,c->argv[2])) {
6972 if (hashLength(o) == 0) deleteKey(c->db,c->argv[1]);
6973 addReply(c,shared.cone);
6974 server.dirty++;
6975 } else {
6976 addReply(c,shared.czero);
6977 }
6978 }
6979
6980 static void hlenCommand(redisClient *c) {
6981 robj *o;
6982 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6983 checkType(c,o,REDIS_HASH)) return;
6984
6985 addReplyUlong(c,hashLength(o));
6986 }
6987
6988 static void genericHgetallCommand(redisClient *c, int flags) {
6989 robj *o, *lenobj, *obj;
6990 unsigned long count = 0;
6991 hashIterator *hi;
6992
6993 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6994 || checkType(c,o,REDIS_HASH)) return;
6995
6996 lenobj = createObject(REDIS_STRING,NULL);
6997 addReply(c,lenobj);
6998 decrRefCount(lenobj);
6999
7000 hi = hashInitIterator(o);
7001 while (hashNext(hi) != REDIS_ERR) {
7002 if (flags & REDIS_HASH_KEY) {
7003 obj = hashCurrent(hi,REDIS_HASH_KEY);
7004 addReplyBulk(c,obj);
7005 decrRefCount(obj);
7006 count++;
7007 }
7008 if (flags & REDIS_HASH_VALUE) {
7009 obj = hashCurrent(hi,REDIS_HASH_VALUE);
7010 addReplyBulk(c,obj);
7011 decrRefCount(obj);
7012 count++;
7013 }
7014 }
7015 hashReleaseIterator(hi);
7016
7017 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",count);
7018 }
7019
7020 static void hkeysCommand(redisClient *c) {
7021 genericHgetallCommand(c,REDIS_HASH_KEY);
7022 }
7023
7024 static void hvalsCommand(redisClient *c) {
7025 genericHgetallCommand(c,REDIS_HASH_VALUE);
7026 }
7027
7028 static void hgetallCommand(redisClient *c) {
7029 genericHgetallCommand(c,REDIS_HASH_KEY|REDIS_HASH_VALUE);
7030 }
7031
7032 static void hexistsCommand(redisClient *c) {
7033 robj *o;
7034 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
7035 checkType(c,o,REDIS_HASH)) return;
7036
7037 addReply(c, hashExists(o,c->argv[2]) ? shared.cone : shared.czero);
7038 }
7039
7040 static void convertToRealHash(robj *o) {
7041 unsigned char *key, *val, *p, *zm = o->ptr;
7042 unsigned int klen, vlen;
7043 dict *dict = dictCreate(&hashDictType,NULL);
7044
7045 assert(o->type == REDIS_HASH && o->encoding != REDIS_ENCODING_HT);
7046 p = zipmapRewind(zm);
7047 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
7048 robj *keyobj, *valobj;
7049
7050 keyobj = createStringObject((char*)key,klen);
7051 valobj = createStringObject((char*)val,vlen);
7052 keyobj = tryObjectEncoding(keyobj);
7053 valobj = tryObjectEncoding(valobj);
7054 dictAdd(dict,keyobj,valobj);
7055 }
7056 o->encoding = REDIS_ENCODING_HT;
7057 o->ptr = dict;
7058 zfree(zm);
7059 }
7060
7061 /* ========================= Non type-specific commands ==================== */
7062
7063 static void flushdbCommand(redisClient *c) {
7064 server.dirty += dictSize(c->db->dict);
7065 touchWatchedKeysOnFlush(c->db->id);
7066 dictEmpty(c->db->dict);
7067 dictEmpty(c->db->expires);
7068 addReply(c,shared.ok);
7069 }
7070
7071 static void flushallCommand(redisClient *c) {
7072 touchWatchedKeysOnFlush(-1);
7073 server.dirty += emptyDb();
7074 addReply(c,shared.ok);
7075 if (server.bgsavechildpid != -1) {
7076 kill(server.bgsavechildpid,SIGKILL);
7077 rdbRemoveTempFile(server.bgsavechildpid);
7078 }
7079 rdbSave(server.dbfilename);
7080 server.dirty++;
7081 }
7082
7083 static redisSortOperation *createSortOperation(int type, robj *pattern) {
7084 redisSortOperation *so = zmalloc(sizeof(*so));
7085 so->type = type;
7086 so->pattern = pattern;
7087 return so;
7088 }
7089
7090 /* Return the value associated to the key with a name obtained
7091 * substituting the first occurence of '*' in 'pattern' with 'subst'.
7092 * The returned object will always have its refcount increased by 1
7093 * when it is non-NULL. */
7094 static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
7095 char *p, *f;
7096 sds spat, ssub;
7097 robj keyobj, fieldobj, *o;
7098 int prefixlen, sublen, postfixlen, fieldlen;
7099 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
7100 struct {
7101 long len;
7102 long free;
7103 char buf[REDIS_SORTKEY_MAX+1];
7104 } keyname, fieldname;
7105
7106 /* If the pattern is "#" return the substitution object itself in order
7107 * to implement the "SORT ... GET #" feature. */
7108 spat = pattern->ptr;
7109 if (spat[0] == '#' && spat[1] == '\0') {
7110 incrRefCount(subst);
7111 return subst;
7112 }
7113
7114 /* The substitution object may be specially encoded. If so we create
7115 * a decoded object on the fly. Otherwise getDecodedObject will just
7116 * increment the ref count, that we'll decrement later. */
7117 subst = getDecodedObject(subst);
7118
7119 ssub = subst->ptr;
7120 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
7121 p = strchr(spat,'*');
7122 if (!p) {
7123 decrRefCount(subst);
7124 return NULL;
7125 }
7126
7127 /* Find out if we're dealing with a hash dereference. */
7128 if ((f = strstr(p+1, "->")) != NULL) {
7129 fieldlen = sdslen(spat)-(f-spat);
7130 /* this also copies \0 character */
7131 memcpy(fieldname.buf,f+2,fieldlen-1);
7132 fieldname.len = fieldlen-2;
7133 } else {
7134 fieldlen = 0;
7135 }
7136
7137 prefixlen = p-spat;
7138 sublen = sdslen(ssub);
7139 postfixlen = sdslen(spat)-(prefixlen+1)-fieldlen;
7140 memcpy(keyname.buf,spat,prefixlen);
7141 memcpy(keyname.buf+prefixlen,ssub,sublen);
7142 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
7143 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
7144 keyname.len = prefixlen+sublen+postfixlen;
7145 decrRefCount(subst);
7146
7147 /* Lookup substituted key */
7148 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2));
7149 o = lookupKeyRead(db,&keyobj);
7150 if (o == NULL) return NULL;
7151
7152 if (fieldlen > 0) {
7153 if (o->type != REDIS_HASH || fieldname.len < 1) return NULL;
7154
7155 /* Retrieve value from hash by the field name. This operation
7156 * already increases the refcount of the returned object. */
7157 initStaticStringObject(fieldobj,((char*)&fieldname)+(sizeof(long)*2));
7158 o = hashGet(o, &fieldobj);
7159 } else {
7160 if (o->type != REDIS_STRING) return NULL;
7161
7162 /* Every object that this function returns needs to have its refcount
7163 * increased. sortCommand decreases it again. */
7164 incrRefCount(o);
7165 }
7166
7167 return o;
7168 }
7169
7170 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
7171 * the additional parameter is not standard but a BSD-specific we have to
7172 * pass sorting parameters via the global 'server' structure */
7173 static int sortCompare(const void *s1, const void *s2) {
7174 const redisSortObject *so1 = s1, *so2 = s2;
7175 int cmp;
7176
7177 if (!server.sort_alpha) {
7178 /* Numeric sorting. Here it's trivial as we precomputed scores */
7179 if (so1->u.score > so2->u.score) {
7180 cmp = 1;
7181 } else if (so1->u.score < so2->u.score) {
7182 cmp = -1;
7183 } else {
7184 cmp = 0;
7185 }
7186 } else {
7187 /* Alphanumeric sorting */
7188 if (server.sort_bypattern) {
7189 if (!so1->u.cmpobj || !so2->u.cmpobj) {
7190 /* At least one compare object is NULL */
7191 if (so1->u.cmpobj == so2->u.cmpobj)
7192 cmp = 0;
7193 else if (so1->u.cmpobj == NULL)
7194 cmp = -1;
7195 else
7196 cmp = 1;
7197 } else {
7198 /* We have both the objects, use strcoll */
7199 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
7200 }
7201 } else {
7202 /* Compare elements directly. */
7203 cmp = compareStringObjects(so1->obj,so2->obj);
7204 }
7205 }
7206 return server.sort_desc ? -cmp : cmp;
7207 }
7208
7209 /* The SORT command is the most complex command in Redis. Warning: this code
7210 * is optimized for speed and a bit less for readability */
7211 static void sortCommand(redisClient *c) {
7212 list *operations;
7213 unsigned int outputlen = 0;
7214 int desc = 0, alpha = 0;
7215 int limit_start = 0, limit_count = -1, start, end;
7216 int j, dontsort = 0, vectorlen;
7217 int getop = 0; /* GET operation counter */
7218 robj *sortval, *sortby = NULL, *storekey = NULL;
7219 redisSortObject *vector; /* Resulting vector to sort */
7220
7221 /* Lookup the key to sort. It must be of the right types */
7222 sortval = lookupKeyRead(c->db,c->argv[1]);
7223 if (sortval == NULL) {
7224 addReply(c,shared.emptymultibulk);
7225 return;
7226 }
7227 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
7228 sortval->type != REDIS_ZSET)
7229 {
7230 addReply(c,shared.wrongtypeerr);
7231 return;
7232 }
7233
7234 /* Create a list of operations to perform for every sorted element.
7235 * Operations can be GET/DEL/INCR/DECR */
7236 operations = listCreate();
7237 listSetFreeMethod(operations,zfree);
7238 j = 2;
7239
7240 /* Now we need to protect sortval incrementing its count, in the future
7241 * SORT may have options able to overwrite/delete keys during the sorting
7242 * and the sorted key itself may get destroied */
7243 incrRefCount(sortval);
7244
7245 /* The SORT command has an SQL-alike syntax, parse it */
7246 while(j < c->argc) {
7247 int leftargs = c->argc-j-1;
7248 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
7249 desc = 0;
7250 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
7251 desc = 1;
7252 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
7253 alpha = 1;
7254 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
7255 limit_start = atoi(c->argv[j+1]->ptr);
7256 limit_count = atoi(c->argv[j+2]->ptr);
7257 j+=2;
7258 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
7259 storekey = c->argv[j+1];
7260 j++;
7261 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
7262 sortby = c->argv[j+1];
7263 /* If the BY pattern does not contain '*', i.e. it is constant,
7264 * we don't need to sort nor to lookup the weight keys. */
7265 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
7266 j++;
7267 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
7268 listAddNodeTail(operations,createSortOperation(
7269 REDIS_SORT_GET,c->argv[j+1]));
7270 getop++;
7271 j++;
7272 } else {
7273 decrRefCount(sortval);
7274 listRelease(operations);
7275 addReply(c,shared.syntaxerr);
7276 return;
7277 }
7278 j++;
7279 }
7280
7281 /* Load the sorting vector with all the objects to sort */
7282 switch(sortval->type) {
7283 case REDIS_LIST: vectorlen = lLength(sortval); break;
7284 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
7285 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
7286 default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
7287 }
7288 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
7289 j = 0;
7290
7291 if (sortval->type == REDIS_LIST) {
7292 lIterator *li = lInitIterator(sortval,0,REDIS_TAIL);
7293 lEntry entry;
7294 while(lNext(li,&entry)) {
7295 vector[j].obj = lGet(&entry);
7296 vector[j].u.score = 0;
7297 vector[j].u.cmpobj = NULL;
7298 j++;
7299 }
7300 lReleaseIterator(li);
7301 } else {
7302 dict *set;
7303 dictIterator *di;
7304 dictEntry *setele;
7305
7306 if (sortval->type == REDIS_SET) {
7307 set = sortval->ptr;
7308 } else {
7309 zset *zs = sortval->ptr;
7310 set = zs->dict;
7311 }
7312
7313 di = dictGetIterator(set);
7314 while((setele = dictNext(di)) != NULL) {
7315 vector[j].obj = dictGetEntryKey(setele);
7316 vector[j].u.score = 0;
7317 vector[j].u.cmpobj = NULL;
7318 j++;
7319 }
7320 dictReleaseIterator(di);
7321 }
7322 redisAssert(j == vectorlen);
7323
7324 /* Now it's time to load the right scores in the sorting vector */
7325 if (dontsort == 0) {
7326 for (j = 0; j < vectorlen; j++) {
7327 robj *byval;
7328 if (sortby) {
7329 /* lookup value to sort by */
7330 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
7331 if (!byval) continue;
7332 } else {
7333 /* use object itself to sort by */
7334 byval = vector[j].obj;
7335 }
7336
7337 if (alpha) {
7338 if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
7339 } else {
7340 if (byval->encoding == REDIS_ENCODING_RAW) {
7341 vector[j].u.score = strtod(byval->ptr,NULL);
7342 } else if (byval->encoding == REDIS_ENCODING_INT) {
7343 /* Don't need to decode the object if it's
7344 * integer-encoded (the only encoding supported) so
7345 * far. We can just cast it */
7346 vector[j].u.score = (long)byval->ptr;
7347 } else {
7348 redisAssert(1 != 1);
7349 }
7350 }
7351
7352 /* when the object was retrieved using lookupKeyByPattern,
7353 * its refcount needs to be decreased. */
7354 if (sortby) {
7355 decrRefCount(byval);
7356 }
7357 }
7358 }
7359
7360 /* We are ready to sort the vector... perform a bit of sanity check
7361 * on the LIMIT option too. We'll use a partial version of quicksort. */
7362 start = (limit_start < 0) ? 0 : limit_start;
7363 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
7364 if (start >= vectorlen) {
7365 start = vectorlen-1;
7366 end = vectorlen-2;
7367 }
7368 if (end >= vectorlen) end = vectorlen-1;
7369
7370 if (dontsort == 0) {
7371 server.sort_desc = desc;
7372 server.sort_alpha = alpha;
7373 server.sort_bypattern = sortby ? 1 : 0;
7374 if (sortby && (start != 0 || end != vectorlen-1))
7375 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
7376 else
7377 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
7378 }
7379
7380 /* Send command output to the output buffer, performing the specified
7381 * GET/DEL/INCR/DECR operations if any. */
7382 outputlen = getop ? getop*(end-start+1) : end-start+1;
7383 if (storekey == NULL) {
7384 /* STORE option not specified, sent the sorting result to client */
7385 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
7386 for (j = start; j <= end; j++) {
7387 listNode *ln;
7388 listIter li;
7389
7390 if (!getop) addReplyBulk(c,vector[j].obj);
7391 listRewind(operations,&li);
7392 while((ln = listNext(&li))) {
7393 redisSortOperation *sop = ln->value;
7394 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7395 vector[j].obj);
7396
7397 if (sop->type == REDIS_SORT_GET) {
7398 if (!val) {
7399 addReply(c,shared.nullbulk);
7400 } else {
7401 addReplyBulk(c,val);
7402 decrRefCount(val);
7403 }
7404 } else {
7405 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
7406 }
7407 }
7408 }
7409 } else {
7410 robj *sobj;
7411 if (outputlen > server.list_max_ziplist_entries) {
7412 sobj = createListObject();
7413 } else {
7414 sobj = createZiplistObject();
7415 }
7416
7417 /* STORE option specified, set the sorting result as a List object */
7418 for (j = start; j <= end; j++) {
7419 listNode *ln;
7420 listIter li;
7421
7422 if (!getop) {
7423 lPush(sobj,vector[j].obj,REDIS_TAIL);
7424 } else {
7425 listRewind(operations,&li);
7426 while((ln = listNext(&li))) {
7427 redisSortOperation *sop = ln->value;
7428 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7429 vector[j].obj);
7430
7431 if (sop->type == REDIS_SORT_GET) {
7432 if (!val) val = createStringObject("",0);
7433
7434 /* lPush does an incrRefCount, so we should take care
7435 * care of the incremented refcount caused by either
7436 * lookupKeyByPattern or createStringObject("",0) */
7437 lPush(sobj,val,REDIS_TAIL);
7438 decrRefCount(val);
7439 } else {
7440 /* always fails */
7441 redisAssert(sop->type == REDIS_SORT_GET);
7442 }
7443 }
7444 }
7445 }
7446 if (dictReplace(c->db->dict,storekey,sobj)) {
7447 incrRefCount(storekey);
7448 }
7449 /* Note: we add 1 because the DB is dirty anyway since even if the
7450 * SORT result is empty a new key is set and maybe the old content
7451 * replaced. */
7452 server.dirty += 1+outputlen;
7453 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
7454 }
7455
7456 /* Cleanup */
7457 if (sortval->type == REDIS_LIST)
7458 for (j = 0; j < vectorlen; j++)
7459 decrRefCount(vector[j].obj);
7460 decrRefCount(sortval);
7461 listRelease(operations);
7462 for (j = 0; j < vectorlen; j++) {
7463 if (alpha && vector[j].u.cmpobj)
7464 decrRefCount(vector[j].u.cmpobj);
7465 }
7466 zfree(vector);
7467 }
7468
7469 /* Convert an amount of bytes into a human readable string in the form
7470 * of 100B, 2G, 100M, 4K, and so forth. */
7471 static void bytesToHuman(char *s, unsigned long long n) {
7472 double d;
7473
7474 if (n < 1024) {
7475 /* Bytes */
7476 sprintf(s,"%lluB",n);
7477 return;
7478 } else if (n < (1024*1024)) {
7479 d = (double)n/(1024);
7480 sprintf(s,"%.2fK",d);
7481 } else if (n < (1024LL*1024*1024)) {
7482 d = (double)n/(1024*1024);
7483 sprintf(s,"%.2fM",d);
7484 } else if (n < (1024LL*1024*1024*1024)) {
7485 d = (double)n/(1024LL*1024*1024);
7486 sprintf(s,"%.2fG",d);
7487 }
7488 }
7489
7490 /* Create the string returned by the INFO command. This is decoupled
7491 * by the INFO command itself as we need to report the same information
7492 * on memory corruption problems. */
7493 static sds genRedisInfoString(void) {
7494 sds info;
7495 time_t uptime = time(NULL)-server.stat_starttime;
7496 int j;
7497 char hmem[64];
7498
7499 bytesToHuman(hmem,zmalloc_used_memory());
7500 info = sdscatprintf(sdsempty(),
7501 "redis_version:%s\r\n"
7502 "redis_git_sha1:%s\r\n"
7503 "redis_git_dirty:%d\r\n"
7504 "arch_bits:%s\r\n"
7505 "multiplexing_api:%s\r\n"
7506 "process_id:%ld\r\n"
7507 "uptime_in_seconds:%ld\r\n"
7508 "uptime_in_days:%ld\r\n"
7509 "connected_clients:%d\r\n"
7510 "connected_slaves:%d\r\n"
7511 "blocked_clients:%d\r\n"
7512 "used_memory:%zu\r\n"
7513 "used_memory_human:%s\r\n"
7514 "changes_since_last_save:%lld\r\n"
7515 "bgsave_in_progress:%d\r\n"
7516 "last_save_time:%ld\r\n"
7517 "bgrewriteaof_in_progress:%d\r\n"
7518 "total_connections_received:%lld\r\n"
7519 "total_commands_processed:%lld\r\n"
7520 "expired_keys:%lld\r\n"
7521 "hash_max_zipmap_entries:%zu\r\n"
7522 "hash_max_zipmap_value:%zu\r\n"
7523 "pubsub_channels:%ld\r\n"
7524 "pubsub_patterns:%u\r\n"
7525 "vm_enabled:%d\r\n"
7526 "role:%s\r\n"
7527 ,REDIS_VERSION,
7528 REDIS_GIT_SHA1,
7529 strtol(REDIS_GIT_DIRTY,NULL,10) > 0,
7530 (sizeof(long) == 8) ? "64" : "32",
7531 aeGetApiName(),
7532 (long) getpid(),
7533 uptime,
7534 uptime/(3600*24),
7535 listLength(server.clients)-listLength(server.slaves),
7536 listLength(server.slaves),
7537 server.blpop_blocked_clients,
7538 zmalloc_used_memory(),
7539 hmem,
7540 server.dirty,
7541 server.bgsavechildpid != -1,
7542 server.lastsave,
7543 server.bgrewritechildpid != -1,
7544 server.stat_numconnections,
7545 server.stat_numcommands,
7546 server.stat_expiredkeys,
7547 server.hash_max_zipmap_entries,
7548 server.hash_max_zipmap_value,
7549 dictSize(server.pubsub_channels),
7550 listLength(server.pubsub_patterns),
7551 server.vm_enabled != 0,
7552 server.masterhost == NULL ? "master" : "slave"
7553 );
7554 if (server.masterhost) {
7555 info = sdscatprintf(info,
7556 "master_host:%s\r\n"
7557 "master_port:%d\r\n"
7558 "master_link_status:%s\r\n"
7559 "master_last_io_seconds_ago:%d\r\n"
7560 ,server.masterhost,
7561 server.masterport,
7562 (server.replstate == REDIS_REPL_CONNECTED) ?
7563 "up" : "down",
7564 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
7565 );
7566 }
7567 if (server.vm_enabled) {
7568 lockThreadedIO();
7569 info = sdscatprintf(info,
7570 "vm_conf_max_memory:%llu\r\n"
7571 "vm_conf_page_size:%llu\r\n"
7572 "vm_conf_pages:%llu\r\n"
7573 "vm_stats_used_pages:%llu\r\n"
7574 "vm_stats_swapped_objects:%llu\r\n"
7575 "vm_stats_swappin_count:%llu\r\n"
7576 "vm_stats_swappout_count:%llu\r\n"
7577 "vm_stats_io_newjobs_len:%lu\r\n"
7578 "vm_stats_io_processing_len:%lu\r\n"
7579 "vm_stats_io_processed_len:%lu\r\n"
7580 "vm_stats_io_active_threads:%lu\r\n"
7581 "vm_stats_blocked_clients:%lu\r\n"
7582 ,(unsigned long long) server.vm_max_memory,
7583 (unsigned long long) server.vm_page_size,
7584 (unsigned long long) server.vm_pages,
7585 (unsigned long long) server.vm_stats_used_pages,
7586 (unsigned long long) server.vm_stats_swapped_objects,
7587 (unsigned long long) server.vm_stats_swapins,
7588 (unsigned long long) server.vm_stats_swapouts,
7589 (unsigned long) listLength(server.io_newjobs),
7590 (unsigned long) listLength(server.io_processing),
7591 (unsigned long) listLength(server.io_processed),
7592 (unsigned long) server.io_active_threads,
7593 (unsigned long) server.vm_blocked_clients
7594 );
7595 unlockThreadedIO();
7596 }
7597 for (j = 0; j < server.dbnum; j++) {
7598 long long keys, vkeys;
7599
7600 keys = dictSize(server.db[j].dict);
7601 vkeys = dictSize(server.db[j].expires);
7602 if (keys || vkeys) {
7603 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
7604 j, keys, vkeys);
7605 }
7606 }
7607 return info;
7608 }
7609
7610 static void infoCommand(redisClient *c) {
7611 sds info = genRedisInfoString();
7612 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
7613 (unsigned long)sdslen(info)));
7614 addReplySds(c,info);
7615 addReply(c,shared.crlf);
7616 }
7617
7618 static void monitorCommand(redisClient *c) {
7619 /* ignore MONITOR if aleady slave or in monitor mode */
7620 if (c->flags & REDIS_SLAVE) return;
7621
7622 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
7623 c->slaveseldb = 0;
7624 listAddNodeTail(server.monitors,c);
7625 addReply(c,shared.ok);
7626 }
7627
7628 /* ================================= Expire ================================= */
7629 static int removeExpire(redisDb *db, robj *key) {
7630 if (dictDelete(db->expires,key) == DICT_OK) {
7631 return 1;
7632 } else {
7633 return 0;
7634 }
7635 }
7636
7637 static int setExpire(redisDb *db, robj *key, time_t when) {
7638 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
7639 return 0;
7640 } else {
7641 incrRefCount(key);
7642 return 1;
7643 }
7644 }
7645
7646 /* Return the expire time of the specified key, or -1 if no expire
7647 * is associated with this key (i.e. the key is non volatile) */
7648 static time_t getExpire(redisDb *db, robj *key) {
7649 dictEntry *de;
7650
7651 /* No expire? return ASAP */
7652 if (dictSize(db->expires) == 0 ||
7653 (de = dictFind(db->expires,key)) == NULL) return -1;
7654
7655 return (time_t) dictGetEntryVal(de);
7656 }
7657
7658 static int expireIfNeeded(redisDb *db, robj *key) {
7659 time_t when;
7660 dictEntry *de;
7661
7662 /* No expire? return ASAP */
7663 if (dictSize(db->expires) == 0 ||
7664 (de = dictFind(db->expires,key)) == NULL) return 0;
7665
7666 /* Lookup the expire */
7667 when = (time_t) dictGetEntryVal(de);
7668 if (time(NULL) <= when) return 0;
7669
7670 /* Delete the key */
7671 dictDelete(db->expires,key);
7672 server.stat_expiredkeys++;
7673 return dictDelete(db->dict,key) == DICT_OK;
7674 }
7675
7676 static int deleteIfVolatile(redisDb *db, robj *key) {
7677 dictEntry *de;
7678
7679 /* No expire? return ASAP */
7680 if (dictSize(db->expires) == 0 ||
7681 (de = dictFind(db->expires,key)) == NULL) return 0;
7682
7683 /* Delete the key */
7684 server.dirty++;
7685 server.stat_expiredkeys++;
7686 dictDelete(db->expires,key);
7687 return dictDelete(db->dict,key) == DICT_OK;
7688 }
7689
7690 static void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
7691 dictEntry *de;
7692 time_t seconds;
7693
7694 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
7695
7696 seconds -= offset;
7697
7698 de = dictFind(c->db->dict,key);
7699 if (de == NULL) {
7700 addReply(c,shared.czero);
7701 return;
7702 }
7703 if (seconds <= 0) {
7704 if (deleteKey(c->db,key)) server.dirty++;
7705 addReply(c, shared.cone);
7706 return;
7707 } else {
7708 time_t when = time(NULL)+seconds;
7709 if (setExpire(c->db,key,when)) {
7710 addReply(c,shared.cone);
7711 server.dirty++;
7712 } else {
7713 addReply(c,shared.czero);
7714 }
7715 return;
7716 }
7717 }
7718
7719 static void expireCommand(redisClient *c) {
7720 expireGenericCommand(c,c->argv[1],c->argv[2],0);
7721 }
7722
7723 static void expireatCommand(redisClient *c) {
7724 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
7725 }
7726
7727 static void ttlCommand(redisClient *c) {
7728 time_t expire;
7729 int ttl = -1;
7730
7731 expire = getExpire(c->db,c->argv[1]);
7732 if (expire != -1) {
7733 ttl = (int) (expire-time(NULL));
7734 if (ttl < 0) ttl = -1;
7735 }
7736 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
7737 }
7738
7739 /* ================================ MULTI/EXEC ============================== */
7740
7741 /* Client state initialization for MULTI/EXEC */
7742 static void initClientMultiState(redisClient *c) {
7743 c->mstate.commands = NULL;
7744 c->mstate.count = 0;
7745 }
7746
7747 /* Release all the resources associated with MULTI/EXEC state */
7748 static void freeClientMultiState(redisClient *c) {
7749 int j;
7750
7751 for (j = 0; j < c->mstate.count; j++) {
7752 int i;
7753 multiCmd *mc = c->mstate.commands+j;
7754
7755 for (i = 0; i < mc->argc; i++)
7756 decrRefCount(mc->argv[i]);
7757 zfree(mc->argv);
7758 }
7759 zfree(c->mstate.commands);
7760 }
7761
7762 /* Add a new command into the MULTI commands queue */
7763 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
7764 multiCmd *mc;
7765 int j;
7766
7767 c->mstate.commands = zrealloc(c->mstate.commands,
7768 sizeof(multiCmd)*(c->mstate.count+1));
7769 mc = c->mstate.commands+c->mstate.count;
7770 mc->cmd = cmd;
7771 mc->argc = c->argc;
7772 mc->argv = zmalloc(sizeof(robj*)*c->argc);
7773 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
7774 for (j = 0; j < c->argc; j++)
7775 incrRefCount(mc->argv[j]);
7776 c->mstate.count++;
7777 }
7778
7779 static void multiCommand(redisClient *c) {
7780 if (c->flags & REDIS_MULTI) {
7781 addReplySds(c,sdsnew("-ERR MULTI calls can not be nested\r\n"));
7782 return;
7783 }
7784 c->flags |= REDIS_MULTI;
7785 addReply(c,shared.ok);
7786 }
7787
7788 static void discardCommand(redisClient *c) {
7789 if (!(c->flags & REDIS_MULTI)) {
7790 addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
7791 return;
7792 }
7793
7794 freeClientMultiState(c);
7795 initClientMultiState(c);
7796 c->flags &= (~REDIS_MULTI);
7797 addReply(c,shared.ok);
7798 }
7799
7800 /* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7801 * implememntation for more information. */
7802 static void execCommandReplicateMulti(redisClient *c) {
7803 struct redisCommand *cmd;
7804 robj *multistring = createStringObject("MULTI",5);
7805
7806 cmd = lookupCommand("multi");
7807 if (server.appendonly)
7808 feedAppendOnlyFile(cmd,c->db->id,&multistring,1);
7809 if (listLength(server.slaves))
7810 replicationFeedSlaves(server.slaves,c->db->id,&multistring,1);
7811 decrRefCount(multistring);
7812 }
7813
7814 static void execCommand(redisClient *c) {
7815 int j;
7816 robj **orig_argv;
7817 int orig_argc;
7818
7819 if (!(c->flags & REDIS_MULTI)) {
7820 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
7821 return;
7822 }
7823
7824 /* Check if we need to abort the EXEC if some WATCHed key was touched.
7825 * A failed EXEC will return a multi bulk nil object. */
7826 if (c->flags & REDIS_DIRTY_CAS) {
7827 freeClientMultiState(c);
7828 initClientMultiState(c);
7829 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
7830 unwatchAllKeys(c);
7831 addReply(c,shared.nullmultibulk);
7832 return;
7833 }
7834
7835 /* Replicate a MULTI request now that we are sure the block is executed.
7836 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7837 * both the AOF and the replication link will have the same consistency
7838 * and atomicity guarantees. */
7839 execCommandReplicateMulti(c);
7840
7841 /* Exec all the queued commands */
7842 unwatchAllKeys(c); /* Unwatch ASAP otherwise we'll waste CPU cycles */
7843 orig_argv = c->argv;
7844 orig_argc = c->argc;
7845 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
7846 for (j = 0; j < c->mstate.count; j++) {
7847 c->argc = c->mstate.commands[j].argc;
7848 c->argv = c->mstate.commands[j].argv;
7849 call(c,c->mstate.commands[j].cmd);
7850 }
7851 c->argv = orig_argv;
7852 c->argc = orig_argc;
7853 freeClientMultiState(c);
7854 initClientMultiState(c);
7855 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
7856 /* Make sure the EXEC command is always replicated / AOF, since we
7857 * always send the MULTI command (we can't know beforehand if the
7858 * next operations will contain at least a modification to the DB). */
7859 server.dirty++;
7860 }
7861
7862 /* =========================== Blocking Operations ========================= */
7863
7864 /* Currently Redis blocking operations support is limited to list POP ops,
7865 * so the current implementation is not fully generic, but it is also not
7866 * completely specific so it will not require a rewrite to support new
7867 * kind of blocking operations in the future.
7868 *
7869 * Still it's important to note that list blocking operations can be already
7870 * used as a notification mechanism in order to implement other blocking
7871 * operations at application level, so there must be a very strong evidence
7872 * of usefulness and generality before new blocking operations are implemented.
7873 *
7874 * This is how the current blocking POP works, we use BLPOP as example:
7875 * - If the user calls BLPOP and the key exists and contains a non empty list
7876 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7877 * if there is not to block.
7878 * - If instead BLPOP is called and the key does not exists or the list is
7879 * empty we need to block. In order to do so we remove the notification for
7880 * new data to read in the client socket (so that we'll not serve new
7881 * requests if the blocking request is not served). Also we put the client
7882 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
7883 * blocking for this keys.
7884 * - If a PUSH operation against a key with blocked clients waiting is
7885 * performed, we serve the first in the list: basically instead to push
7886 * the new element inside the list we return it to the (first / oldest)
7887 * blocking client, unblock the client, and remove it form the list.
7888 *
7889 * The above comment and the source code should be enough in order to understand
7890 * the implementation and modify / fix it later.
7891 */
7892
7893 /* Set a client in blocking mode for the specified key, with the specified
7894 * timeout */
7895 static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
7896 dictEntry *de;
7897 list *l;
7898 int j;
7899
7900 c->blocking_keys = zmalloc(sizeof(robj*)*numkeys);
7901 c->blocking_keys_num = numkeys;
7902 c->blockingto = timeout;
7903 for (j = 0; j < numkeys; j++) {
7904 /* Add the key in the client structure, to map clients -> keys */
7905 c->blocking_keys[j] = keys[j];
7906 incrRefCount(keys[j]);
7907
7908 /* And in the other "side", to map keys -> clients */
7909 de = dictFind(c->db->blocking_keys,keys[j]);
7910 if (de == NULL) {
7911 int retval;
7912
7913 /* For every key we take a list of clients blocked for it */
7914 l = listCreate();
7915 retval = dictAdd(c->db->blocking_keys,keys[j],l);
7916 incrRefCount(keys[j]);
7917 assert(retval == DICT_OK);
7918 } else {
7919 l = dictGetEntryVal(de);
7920 }
7921 listAddNodeTail(l,c);
7922 }
7923 /* Mark the client as a blocked client */
7924 c->flags |= REDIS_BLOCKED;
7925 server.blpop_blocked_clients++;
7926 }
7927
7928 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
7929 static void unblockClientWaitingData(redisClient *c) {
7930 dictEntry *de;
7931 list *l;
7932 int j;
7933
7934 assert(c->blocking_keys != NULL);
7935 /* The client may wait for multiple keys, so unblock it for every key. */
7936 for (j = 0; j < c->blocking_keys_num; j++) {
7937 /* Remove this client from the list of clients waiting for this key. */
7938 de = dictFind(c->db->blocking_keys,c->blocking_keys[j]);
7939 assert(de != NULL);
7940 l = dictGetEntryVal(de);
7941 listDelNode(l,listSearchKey(l,c));
7942 /* If the list is empty we need to remove it to avoid wasting memory */
7943 if (listLength(l) == 0)
7944 dictDelete(c->db->blocking_keys,c->blocking_keys[j]);
7945 decrRefCount(c->blocking_keys[j]);
7946 }
7947 /* Cleanup the client structure */
7948 zfree(c->blocking_keys);
7949 c->blocking_keys = NULL;
7950 c->flags &= (~REDIS_BLOCKED);
7951 server.blpop_blocked_clients--;
7952 /* We want to process data if there is some command waiting
7953 * in the input buffer. Note that this is safe even if
7954 * unblockClientWaitingData() gets called from freeClient() because
7955 * freeClient() will be smart enough to call this function
7956 * *after* c->querybuf was set to NULL. */
7957 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
7958 }
7959
7960 /* This should be called from any function PUSHing into lists.
7961 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7962 * 'ele' is the element pushed.
7963 *
7964 * If the function returns 0 there was no client waiting for a list push
7965 * against this key.
7966 *
7967 * If the function returns 1 there was a client waiting for a list push
7968 * against this key, the element was passed to this client thus it's not
7969 * needed to actually add it to the list and the caller should return asap. */
7970 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
7971 struct dictEntry *de;
7972 redisClient *receiver;
7973 list *l;
7974 listNode *ln;
7975
7976 de = dictFind(c->db->blocking_keys,key);
7977 if (de == NULL) return 0;
7978 l = dictGetEntryVal(de);
7979 ln = listFirst(l);
7980 assert(ln != NULL);
7981 receiver = ln->value;
7982
7983 addReplySds(receiver,sdsnew("*2\r\n"));
7984 addReplyBulk(receiver,key);
7985 addReplyBulk(receiver,ele);
7986 unblockClientWaitingData(receiver);
7987 return 1;
7988 }
7989
7990 /* Blocking RPOP/LPOP */
7991 static void blockingPopGenericCommand(redisClient *c, int where) {
7992 robj *o;
7993 time_t timeout;
7994 int j;
7995
7996 for (j = 1; j < c->argc-1; j++) {
7997 o = lookupKeyWrite(c->db,c->argv[j]);
7998 if (o != NULL) {
7999 if (o->type != REDIS_LIST) {
8000 addReply(c,shared.wrongtypeerr);
8001 return;
8002 } else {
8003 list *list = o->ptr;
8004 if (listLength(list) != 0) {
8005 /* If the list contains elements fall back to the usual
8006 * non-blocking POP operation */
8007 robj *argv[2], **orig_argv;
8008 int orig_argc;
8009
8010 /* We need to alter the command arguments before to call
8011 * popGenericCommand() as the command takes a single key. */
8012 orig_argv = c->argv;
8013 orig_argc = c->argc;
8014 argv[1] = c->argv[j];
8015 c->argv = argv;
8016 c->argc = 2;
8017
8018 /* Also the return value is different, we need to output
8019 * the multi bulk reply header and the key name. The
8020 * "real" command will add the last element (the value)
8021 * for us. If this souds like an hack to you it's just
8022 * because it is... */
8023 addReplySds(c,sdsnew("*2\r\n"));
8024 addReplyBulk(c,argv[1]);
8025 popGenericCommand(c,where);
8026
8027 /* Fix the client structure with the original stuff */
8028 c->argv = orig_argv;
8029 c->argc = orig_argc;
8030 return;
8031 }
8032 }
8033 }
8034 }
8035 /* If the list is empty or the key does not exists we must block */
8036 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
8037 if (timeout > 0) timeout += time(NULL);
8038 blockForKeys(c,c->argv+1,c->argc-2,timeout);
8039 }
8040
8041 static void blpopCommand(redisClient *c) {
8042 blockingPopGenericCommand(c,REDIS_HEAD);
8043 }
8044
8045 static void brpopCommand(redisClient *c) {
8046 blockingPopGenericCommand(c,REDIS_TAIL);
8047 }
8048
8049 /* =============================== Replication ============================= */
8050
8051 static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
8052 ssize_t nwritten, ret = size;
8053 time_t start = time(NULL);
8054
8055 timeout++;
8056 while(size) {
8057 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
8058 nwritten = write(fd,ptr,size);
8059 if (nwritten == -1) return -1;
8060 ptr += nwritten;
8061 size -= nwritten;
8062 }
8063 if ((time(NULL)-start) > timeout) {
8064 errno = ETIMEDOUT;
8065 return -1;
8066 }
8067 }
8068 return ret;
8069 }
8070
8071 static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
8072 ssize_t nread, totread = 0;
8073 time_t start = time(NULL);
8074
8075 timeout++;
8076 while(size) {
8077 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
8078 nread = read(fd,ptr,size);
8079 if (nread == -1) return -1;
8080 ptr += nread;
8081 size -= nread;
8082 totread += nread;
8083 }
8084 if ((time(NULL)-start) > timeout) {
8085 errno = ETIMEDOUT;
8086 return -1;
8087 }
8088 }
8089 return totread;
8090 }
8091
8092 static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
8093 ssize_t nread = 0;
8094
8095 size--;
8096 while(size) {
8097 char c;
8098
8099 if (syncRead(fd,&c,1,timeout) == -1) return -1;
8100 if (c == '\n') {
8101 *ptr = '\0';
8102 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
8103 return nread;
8104 } else {
8105 *ptr++ = c;
8106 *ptr = '\0';
8107 nread++;
8108 }
8109 }
8110 return nread;
8111 }
8112
8113 static void syncCommand(redisClient *c) {
8114 /* ignore SYNC if aleady slave or in monitor mode */
8115 if (c->flags & REDIS_SLAVE) return;
8116
8117 /* SYNC can't be issued when the server has pending data to send to
8118 * the client about already issued commands. We need a fresh reply
8119 * buffer registering the differences between the BGSAVE and the current
8120 * dataset, so that we can copy to other slaves if needed. */
8121 if (listLength(c->reply) != 0) {
8122 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
8123 return;
8124 }
8125
8126 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
8127 /* Here we need to check if there is a background saving operation
8128 * in progress, or if it is required to start one */
8129 if (server.bgsavechildpid != -1) {
8130 /* Ok a background save is in progress. Let's check if it is a good
8131 * one for replication, i.e. if there is another slave that is
8132 * registering differences since the server forked to save */
8133 redisClient *slave;
8134 listNode *ln;
8135 listIter li;
8136
8137 listRewind(server.slaves,&li);
8138 while((ln = listNext(&li))) {
8139 slave = ln->value;
8140 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
8141 }
8142 if (ln) {
8143 /* Perfect, the server is already registering differences for
8144 * another slave. Set the right state, and copy the buffer. */
8145 listRelease(c->reply);
8146 c->reply = listDup(slave->reply);
8147 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8148 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
8149 } else {
8150 /* No way, we need to wait for the next BGSAVE in order to
8151 * register differences */
8152 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
8153 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
8154 }
8155 } else {
8156 /* Ok we don't have a BGSAVE in progress, let's start one */
8157 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
8158 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
8159 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
8160 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
8161 return;
8162 }
8163 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8164 }
8165 c->repldbfd = -1;
8166 c->flags |= REDIS_SLAVE;
8167 c->slaveseldb = 0;
8168 listAddNodeTail(server.slaves,c);
8169 return;
8170 }
8171
8172 static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
8173 redisClient *slave = privdata;
8174 REDIS_NOTUSED(el);
8175 REDIS_NOTUSED(mask);
8176 char buf[REDIS_IOBUF_LEN];
8177 ssize_t nwritten, buflen;
8178
8179 if (slave->repldboff == 0) {
8180 /* Write the bulk write count before to transfer the DB. In theory here
8181 * we don't know how much room there is in the output buffer of the
8182 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
8183 * operations) will never be smaller than the few bytes we need. */
8184 sds bulkcount;
8185
8186 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
8187 slave->repldbsize);
8188 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
8189 {
8190 sdsfree(bulkcount);
8191 freeClient(slave);
8192 return;
8193 }
8194 sdsfree(bulkcount);
8195 }
8196 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
8197 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
8198 if (buflen <= 0) {
8199 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
8200 (buflen == 0) ? "premature EOF" : strerror(errno));
8201 freeClient(slave);
8202 return;
8203 }
8204 if ((nwritten = write(fd,buf,buflen)) == -1) {
8205 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
8206 strerror(errno));
8207 freeClient(slave);
8208 return;
8209 }
8210 slave->repldboff += nwritten;
8211 if (slave->repldboff == slave->repldbsize) {
8212 close(slave->repldbfd);
8213 slave->repldbfd = -1;
8214 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8215 slave->replstate = REDIS_REPL_ONLINE;
8216 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
8217 sendReplyToClient, slave) == AE_ERR) {
8218 freeClient(slave);
8219 return;
8220 }
8221 addReplySds(slave,sdsempty());
8222 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
8223 }
8224 }
8225
8226 /* This function is called at the end of every backgrond saving.
8227 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
8228 * otherwise REDIS_ERR is passed to the function.
8229 *
8230 * The goal of this function is to handle slaves waiting for a successful
8231 * background saving in order to perform non-blocking synchronization. */
8232 static void updateSlavesWaitingBgsave(int bgsaveerr) {
8233 listNode *ln;
8234 int startbgsave = 0;
8235 listIter li;
8236
8237 listRewind(server.slaves,&li);
8238 while((ln = listNext(&li))) {
8239 redisClient *slave = ln->value;
8240
8241 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
8242 startbgsave = 1;
8243 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8244 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
8245 struct redis_stat buf;
8246
8247 if (bgsaveerr != REDIS_OK) {
8248 freeClient(slave);
8249 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
8250 continue;
8251 }
8252 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
8253 redis_fstat(slave->repldbfd,&buf) == -1) {
8254 freeClient(slave);
8255 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
8256 continue;
8257 }
8258 slave->repldboff = 0;
8259 slave->repldbsize = buf.st_size;
8260 slave->replstate = REDIS_REPL_SEND_BULK;
8261 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8262 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
8263 freeClient(slave);
8264 continue;
8265 }
8266 }
8267 }
8268 if (startbgsave) {
8269 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
8270 listIter li;
8271
8272 listRewind(server.slaves,&li);
8273 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
8274 while((ln = listNext(&li))) {
8275 redisClient *slave = ln->value;
8276
8277 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
8278 freeClient(slave);
8279 }
8280 }
8281 }
8282 }
8283
8284 static int syncWithMaster(void) {
8285 char buf[1024], tmpfile[256], authcmd[1024];
8286 long dumpsize;
8287 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
8288 int dfd, maxtries = 5;
8289
8290 if (fd == -1) {
8291 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
8292 strerror(errno));
8293 return REDIS_ERR;
8294 }
8295
8296 /* AUTH with the master if required. */
8297 if(server.masterauth) {
8298 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
8299 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
8300 close(fd);
8301 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
8302 strerror(errno));
8303 return REDIS_ERR;
8304 }
8305 /* Read the AUTH result. */
8306 if (syncReadLine(fd,buf,1024,3600) == -1) {
8307 close(fd);
8308 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
8309 strerror(errno));
8310 return REDIS_ERR;
8311 }
8312 if (buf[0] != '+') {
8313 close(fd);
8314 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
8315 return REDIS_ERR;
8316 }
8317 }
8318
8319 /* Issue the SYNC command */
8320 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
8321 close(fd);
8322 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
8323 strerror(errno));
8324 return REDIS_ERR;
8325 }
8326 /* Read the bulk write count */
8327 if (syncReadLine(fd,buf,1024,3600) == -1) {
8328 close(fd);
8329 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
8330 strerror(errno));
8331 return REDIS_ERR;
8332 }
8333 if (buf[0] != '$') {
8334 close(fd);
8335 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8336 return REDIS_ERR;
8337 }
8338 dumpsize = strtol(buf+1,NULL,10);
8339 redisLog(REDIS_NOTICE,"Receiving %ld bytes data dump from MASTER",dumpsize);
8340 /* Read the bulk write data on a temp file */
8341 while(maxtries--) {
8342 snprintf(tmpfile,256,
8343 "temp-%d.%ld.rdb",(int)time(NULL),(long int)getpid());
8344 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
8345 if (dfd != -1) break;
8346 sleep(1);
8347 }
8348 if (dfd == -1) {
8349 close(fd);
8350 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
8351 return REDIS_ERR;
8352 }
8353 while(dumpsize) {
8354 int nread, nwritten;
8355
8356 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
8357 if (nread == -1) {
8358 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
8359 strerror(errno));
8360 close(fd);
8361 close(dfd);
8362 return REDIS_ERR;
8363 }
8364 nwritten = write(dfd,buf,nread);
8365 if (nwritten == -1) {
8366 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
8367 close(fd);
8368 close(dfd);
8369 return REDIS_ERR;
8370 }
8371 dumpsize -= nread;
8372 }
8373 close(dfd);
8374 if (rename(tmpfile,server.dbfilename) == -1) {
8375 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
8376 unlink(tmpfile);
8377 close(fd);
8378 return REDIS_ERR;
8379 }
8380 emptyDb();
8381 if (rdbLoad(server.dbfilename) != REDIS_OK) {
8382 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
8383 close(fd);
8384 return REDIS_ERR;
8385 }
8386 server.master = createClient(fd);
8387 server.master->flags |= REDIS_MASTER;
8388 server.master->authenticated = 1;
8389 server.replstate = REDIS_REPL_CONNECTED;
8390 return REDIS_OK;
8391 }
8392
8393 static void slaveofCommand(redisClient *c) {
8394 if (!strcasecmp(c->argv[1]->ptr,"no") &&
8395 !strcasecmp(c->argv[2]->ptr,"one")) {
8396 if (server.masterhost) {
8397 sdsfree(server.masterhost);
8398 server.masterhost = NULL;
8399 if (server.master) freeClient(server.master);
8400 server.replstate = REDIS_REPL_NONE;
8401 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
8402 }
8403 } else {
8404 sdsfree(server.masterhost);
8405 server.masterhost = sdsdup(c->argv[1]->ptr);
8406 server.masterport = atoi(c->argv[2]->ptr);
8407 if (server.master) freeClient(server.master);
8408 server.replstate = REDIS_REPL_CONNECT;
8409 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
8410 server.masterhost, server.masterport);
8411 }
8412 addReply(c,shared.ok);
8413 }
8414
8415 /* ============================ Maxmemory directive ======================== */
8416
8417 /* Try to free one object form the pre-allocated objects free list.
8418 * This is useful under low mem conditions as by default we take 1 million
8419 * free objects allocated. On success REDIS_OK is returned, otherwise
8420 * REDIS_ERR. */
8421 static int tryFreeOneObjectFromFreelist(void) {
8422 robj *o;
8423
8424 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
8425 if (listLength(server.objfreelist)) {
8426 listNode *head = listFirst(server.objfreelist);
8427 o = listNodeValue(head);
8428 listDelNode(server.objfreelist,head);
8429 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8430 zfree(o);
8431 return REDIS_OK;
8432 } else {
8433 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8434 return REDIS_ERR;
8435 }
8436 }
8437
8438 /* This function gets called when 'maxmemory' is set on the config file to limit
8439 * the max memory used by the server, and we are out of memory.
8440 * This function will try to, in order:
8441 *
8442 * - Free objects from the free list
8443 * - Try to remove keys with an EXPIRE set
8444 *
8445 * It is not possible to free enough memory to reach used-memory < maxmemory
8446 * the server will start refusing commands that will enlarge even more the
8447 * memory usage.
8448 */
8449 static void freeMemoryIfNeeded(void) {
8450 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
8451 int j, k, freed = 0;
8452
8453 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
8454 for (j = 0; j < server.dbnum; j++) {
8455 int minttl = -1;
8456 robj *minkey = NULL;
8457 struct dictEntry *de;
8458
8459 if (dictSize(server.db[j].expires)) {
8460 freed = 1;
8461 /* From a sample of three keys drop the one nearest to
8462 * the natural expire */
8463 for (k = 0; k < 3; k++) {
8464 time_t t;
8465
8466 de = dictGetRandomKey(server.db[j].expires);
8467 t = (time_t) dictGetEntryVal(de);
8468 if (minttl == -1 || t < minttl) {
8469 minkey = dictGetEntryKey(de);
8470 minttl = t;
8471 }
8472 }
8473 deleteKey(server.db+j,minkey);
8474 }
8475 }
8476 if (!freed) return; /* nothing to free... */
8477 }
8478 }
8479
8480 /* ============================== Append Only file ========================== */
8481
8482 /* Write the append only file buffer on disk.
8483 *
8484 * Since we are required to write the AOF before replying to the client,
8485 * and the only way the client socket can get a write is entering when the
8486 * the event loop, we accumulate all the AOF writes in a memory
8487 * buffer and write it on disk using this function just before entering
8488 * the event loop again. */
8489 static void flushAppendOnlyFile(void) {
8490 time_t now;
8491 ssize_t nwritten;
8492
8493 if (sdslen(server.aofbuf) == 0) return;
8494
8495 /* We want to perform a single write. This should be guaranteed atomic
8496 * at least if the filesystem we are writing is a real physical one.
8497 * While this will save us against the server being killed I don't think
8498 * there is much to do about the whole server stopping for power problems
8499 * or alike */
8500 nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf));
8501 if (nwritten != (signed)sdslen(server.aofbuf)) {
8502 /* Ooops, we are in troubles. The best thing to do for now is
8503 * aborting instead of giving the illusion that everything is
8504 * working as expected. */
8505 if (nwritten == -1) {
8506 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
8507 } else {
8508 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
8509 }
8510 exit(1);
8511 }
8512 sdsfree(server.aofbuf);
8513 server.aofbuf = sdsempty();
8514
8515 /* Fsync if needed */
8516 now = time(NULL);
8517 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
8518 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
8519 now-server.lastfsync > 1))
8520 {
8521 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8522 * flushing metadata. */
8523 aof_fsync(server.appendfd); /* Let's try to get this data on the disk */
8524 server.lastfsync = now;
8525 }
8526 }
8527
8528 static sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) {
8529 int j;
8530 buf = sdscatprintf(buf,"*%d\r\n",argc);
8531 for (j = 0; j < argc; j++) {
8532 robj *o = getDecodedObject(argv[j]);
8533 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
8534 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
8535 buf = sdscatlen(buf,"\r\n",2);
8536 decrRefCount(o);
8537 }
8538 return buf;
8539 }
8540
8541 static sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) {
8542 int argc = 3;
8543 long when;
8544 robj *argv[3];
8545
8546 /* Make sure we can use strtol */
8547 seconds = getDecodedObject(seconds);
8548 when = time(NULL)+strtol(seconds->ptr,NULL,10);
8549 decrRefCount(seconds);
8550
8551 argv[0] = createStringObject("EXPIREAT",8);
8552 argv[1] = key;
8553 argv[2] = createObject(REDIS_STRING,
8554 sdscatprintf(sdsempty(),"%ld",when));
8555 buf = catAppendOnlyGenericCommand(buf, argc, argv);
8556 decrRefCount(argv[0]);
8557 decrRefCount(argv[2]);
8558 return buf;
8559 }
8560
8561 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
8562 sds buf = sdsempty();
8563 robj *tmpargv[3];
8564
8565 /* The DB this command was targetting is not the same as the last command
8566 * we appendend. To issue a SELECT command is needed. */
8567 if (dictid != server.appendseldb) {
8568 char seldb[64];
8569
8570 snprintf(seldb,sizeof(seldb),"%d",dictid);
8571 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
8572 (unsigned long)strlen(seldb),seldb);
8573 server.appendseldb = dictid;
8574 }
8575
8576 if (cmd->proc == expireCommand) {
8577 /* Translate EXPIRE into EXPIREAT */
8578 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8579 } else if (cmd->proc == setexCommand) {
8580 /* Translate SETEX to SET and EXPIREAT */
8581 tmpargv[0] = createStringObject("SET",3);
8582 tmpargv[1] = argv[1];
8583 tmpargv[2] = argv[3];
8584 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
8585 decrRefCount(tmpargv[0]);
8586 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8587 } else {
8588 buf = catAppendOnlyGenericCommand(buf,argc,argv);
8589 }
8590
8591 /* Append to the AOF buffer. This will be flushed on disk just before
8592 * of re-entering the event loop, so before the client will get a
8593 * positive reply about the operation performed. */
8594 server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf));
8595
8596 /* If a background append only file rewriting is in progress we want to
8597 * accumulate the differences between the child DB and the current one
8598 * in a buffer, so that when the child process will do its work we
8599 * can append the differences to the new append only file. */
8600 if (server.bgrewritechildpid != -1)
8601 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
8602
8603 sdsfree(buf);
8604 }
8605
8606 /* In Redis commands are always executed in the context of a client, so in
8607 * order to load the append only file we need to create a fake client. */
8608 static struct redisClient *createFakeClient(void) {
8609 struct redisClient *c = zmalloc(sizeof(*c));
8610
8611 selectDb(c,0);
8612 c->fd = -1;
8613 c->querybuf = sdsempty();
8614 c->argc = 0;
8615 c->argv = NULL;
8616 c->flags = 0;
8617 /* We set the fake client as a slave waiting for the synchronization
8618 * so that Redis will not try to send replies to this client. */
8619 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
8620 c->reply = listCreate();
8621 listSetFreeMethod(c->reply,decrRefCount);
8622 listSetDupMethod(c->reply,dupClientReplyValue);
8623 initClientMultiState(c);
8624 return c;
8625 }
8626
8627 static void freeFakeClient(struct redisClient *c) {
8628 sdsfree(c->querybuf);
8629 listRelease(c->reply);
8630 freeClientMultiState(c);
8631 zfree(c);
8632 }
8633
8634 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
8635 * error (the append only file is zero-length) REDIS_ERR is returned. On
8636 * fatal error an error message is logged and the program exists. */
8637 int loadAppendOnlyFile(char *filename) {
8638 struct redisClient *fakeClient;
8639 FILE *fp = fopen(filename,"r");
8640 struct redis_stat sb;
8641 unsigned long long loadedkeys = 0;
8642 int appendonly = server.appendonly;
8643
8644 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
8645 return REDIS_ERR;
8646
8647 if (fp == NULL) {
8648 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
8649 exit(1);
8650 }
8651
8652 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8653 * to the same file we're about to read. */
8654 server.appendonly = 0;
8655
8656 fakeClient = createFakeClient();
8657 while(1) {
8658 int argc, j;
8659 unsigned long len;
8660 robj **argv;
8661 char buf[128];
8662 sds argsds;
8663 struct redisCommand *cmd;
8664
8665 if (fgets(buf,sizeof(buf),fp) == NULL) {
8666 if (feof(fp))
8667 break;
8668 else
8669 goto readerr;
8670 }
8671 if (buf[0] != '*') goto fmterr;
8672 argc = atoi(buf+1);
8673 argv = zmalloc(sizeof(robj*)*argc);
8674 for (j = 0; j < argc; j++) {
8675 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
8676 if (buf[0] != '$') goto fmterr;
8677 len = strtol(buf+1,NULL,10);
8678 argsds = sdsnewlen(NULL,len);
8679 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
8680 argv[j] = createObject(REDIS_STRING,argsds);
8681 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
8682 }
8683
8684 /* Command lookup */
8685 cmd = lookupCommand(argv[0]->ptr);
8686 if (!cmd) {
8687 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
8688 exit(1);
8689 }
8690 /* Try object encoding */
8691 if (cmd->flags & REDIS_CMD_BULK)
8692 argv[argc-1] = tryObjectEncoding(argv[argc-1]);
8693 /* Run the command in the context of a fake client */
8694 fakeClient->argc = argc;
8695 fakeClient->argv = argv;
8696 cmd->proc(fakeClient);
8697 /* Discard the reply objects list from the fake client */
8698 while(listLength(fakeClient->reply))
8699 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
8700 /* Clean up, ready for the next command */
8701 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
8702 zfree(argv);
8703 /* Handle swapping while loading big datasets when VM is on */
8704 loadedkeys++;
8705 if (server.vm_enabled && (loadedkeys % 5000) == 0) {
8706 while (zmalloc_used_memory() > server.vm_max_memory) {
8707 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
8708 }
8709 }
8710 }
8711
8712 /* This point can only be reached when EOF is reached without errors.
8713 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8714 if (fakeClient->flags & REDIS_MULTI) goto readerr;
8715
8716 fclose(fp);
8717 freeFakeClient(fakeClient);
8718 server.appendonly = appendonly;
8719 return REDIS_OK;
8720
8721 readerr:
8722 if (feof(fp)) {
8723 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
8724 } else {
8725 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
8726 }
8727 exit(1);
8728 fmterr:
8729 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
8730 exit(1);
8731 }
8732
8733 /* Write binary-safe string into a file in the bulkformat
8734 * $<count>\r\n<payload>\r\n */
8735 static int fwriteBulkString(FILE *fp, char *s, unsigned long len) {
8736 char cbuf[128];
8737 int clen;
8738 cbuf[0] = '$';
8739 clen = 1+ll2string(cbuf+1,sizeof(cbuf)-1,len);
8740 cbuf[clen++] = '\r';
8741 cbuf[clen++] = '\n';
8742 if (fwrite(cbuf,clen,1,fp) == 0) return 0;
8743 if (len > 0 && fwrite(s,len,1,fp) == 0) return 0;
8744 if (fwrite("\r\n",2,1,fp) == 0) return 0;
8745 return 1;
8746 }
8747
8748 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8749 static int fwriteBulkDouble(FILE *fp, double d) {
8750 char buf[128], dbuf[128];
8751
8752 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
8753 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
8754 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8755 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
8756 return 1;
8757 }
8758
8759 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8760 static int fwriteBulkLongLong(FILE *fp, long long l) {
8761 char bbuf[128], lbuf[128];
8762 unsigned int blen, llen;
8763 llen = ll2string(lbuf,32,l);
8764 blen = snprintf(bbuf,sizeof(bbuf),"$%u\r\n%s\r\n",llen,lbuf);
8765 if (fwrite(bbuf,blen,1,fp) == 0) return 0;
8766 return 1;
8767 }
8768
8769 /* Delegate writing an object to writing a bulk string or bulk long long. */
8770 static int fwriteBulkObject(FILE *fp, robj *obj) {
8771 /* Avoid using getDecodedObject to help copy-on-write (we are often
8772 * in a child process when this function is called). */
8773 if (obj->encoding == REDIS_ENCODING_INT) {
8774 return fwriteBulkLongLong(fp,(long)obj->ptr);
8775 } else if (obj->encoding == REDIS_ENCODING_RAW) {
8776 return fwriteBulkString(fp,obj->ptr,sdslen(obj->ptr));
8777 } else {
8778 redisPanic("Unknown string encoding");
8779 }
8780 }
8781
8782 /* Write a sequence of commands able to fully rebuild the dataset into
8783 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8784 static int rewriteAppendOnlyFile(char *filename) {
8785 dictIterator *di = NULL;
8786 dictEntry *de;
8787 FILE *fp;
8788 char tmpfile[256];
8789 int j;
8790 time_t now = time(NULL);
8791
8792 /* Note that we have to use a different temp name here compared to the
8793 * one used by rewriteAppendOnlyFileBackground() function. */
8794 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
8795 fp = fopen(tmpfile,"w");
8796 if (!fp) {
8797 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
8798 return REDIS_ERR;
8799 }
8800 for (j = 0; j < server.dbnum; j++) {
8801 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
8802 redisDb *db = server.db+j;
8803 dict *d = db->dict;
8804 if (dictSize(d) == 0) continue;
8805 di = dictGetIterator(d);
8806 if (!di) {
8807 fclose(fp);
8808 return REDIS_ERR;
8809 }
8810
8811 /* SELECT the new DB */
8812 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
8813 if (fwriteBulkLongLong(fp,j) == 0) goto werr;
8814
8815 /* Iterate this DB writing every entry */
8816 while((de = dictNext(di)) != NULL) {
8817 robj *key, *o;
8818 time_t expiretime;
8819 int swapped;
8820
8821 key = dictGetEntryKey(de);
8822 /* If the value for this key is swapped, load a preview in memory.
8823 * We use a "swapped" flag to remember if we need to free the
8824 * value object instead to just increment the ref count anyway
8825 * in order to avoid copy-on-write of pages if we are forked() */
8826 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
8827 key->storage == REDIS_VM_SWAPPING) {
8828 o = dictGetEntryVal(de);
8829 swapped = 0;
8830 } else {
8831 o = vmPreviewObject(key);
8832 swapped = 1;
8833 }
8834 expiretime = getExpire(db,key);
8835
8836 /* Save the key and associated value */
8837 if (o->type == REDIS_STRING) {
8838 /* Emit a SET command */
8839 char cmd[]="*3\r\n$3\r\nSET\r\n";
8840 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8841 /* Key and value */
8842 if (fwriteBulkObject(fp,key) == 0) goto werr;
8843 if (fwriteBulkObject(fp,o) == 0) goto werr;
8844 } else if (o->type == REDIS_LIST) {
8845 /* Emit the RPUSHes needed to rebuild the list */
8846 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
8847 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
8848 unsigned char *zl = o->ptr;
8849 unsigned char *p = ziplistIndex(zl,0);
8850 unsigned char *vstr;
8851 unsigned int vlen;
8852 long long vlong;
8853
8854 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
8855 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8856 if (fwriteBulkObject(fp,key) == 0) goto werr;
8857 if (vstr) {
8858 if (fwriteBulkString(fp,(char*)vstr,vlen) == 0)
8859 goto werr;
8860 } else {
8861 if (fwriteBulkLongLong(fp,vlong) == 0)
8862 goto werr;
8863 }
8864 p = ziplistNext(zl,p);
8865 }
8866 } else if (o->encoding == REDIS_ENCODING_LIST) {
8867 list *list = o->ptr;
8868 listNode *ln;
8869 listIter li;
8870
8871 listRewind(list,&li);
8872 while((ln = listNext(&li))) {
8873 robj *eleobj = listNodeValue(ln);
8874
8875 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8876 if (fwriteBulkObject(fp,key) == 0) goto werr;
8877 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8878 }
8879 } else {
8880 redisPanic("Unknown list encoding");
8881 }
8882 } else if (o->type == REDIS_SET) {
8883 /* Emit the SADDs needed to rebuild the set */
8884 dict *set = o->ptr;
8885 dictIterator *di = dictGetIterator(set);
8886 dictEntry *de;
8887
8888 while((de = dictNext(di)) != NULL) {
8889 char cmd[]="*3\r\n$4\r\nSADD\r\n";
8890 robj *eleobj = dictGetEntryKey(de);
8891
8892 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8893 if (fwriteBulkObject(fp,key) == 0) goto werr;
8894 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8895 }
8896 dictReleaseIterator(di);
8897 } else if (o->type == REDIS_ZSET) {
8898 /* Emit the ZADDs needed to rebuild the sorted set */
8899 zset *zs = o->ptr;
8900 dictIterator *di = dictGetIterator(zs->dict);
8901 dictEntry *de;
8902
8903 while((de = dictNext(di)) != NULL) {
8904 char cmd[]="*4\r\n$4\r\nZADD\r\n";
8905 robj *eleobj = dictGetEntryKey(de);
8906 double *score = dictGetEntryVal(de);
8907
8908 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8909 if (fwriteBulkObject(fp,key) == 0) goto werr;
8910 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
8911 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8912 }
8913 dictReleaseIterator(di);
8914 } else if (o->type == REDIS_HASH) {
8915 char cmd[]="*4\r\n$4\r\nHSET\r\n";
8916
8917 /* Emit the HSETs needed to rebuild the hash */
8918 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
8919 unsigned char *p = zipmapRewind(o->ptr);
8920 unsigned char *field, *val;
8921 unsigned int flen, vlen;
8922
8923 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
8924 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8925 if (fwriteBulkObject(fp,key) == 0) goto werr;
8926 if (fwriteBulkString(fp,(char*)field,flen) == -1)
8927 return -1;
8928 if (fwriteBulkString(fp,(char*)val,vlen) == -1)
8929 return -1;
8930 }
8931 } else {
8932 dictIterator *di = dictGetIterator(o->ptr);
8933 dictEntry *de;
8934
8935 while((de = dictNext(di)) != NULL) {
8936 robj *field = dictGetEntryKey(de);
8937 robj *val = dictGetEntryVal(de);
8938
8939 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8940 if (fwriteBulkObject(fp,key) == 0) goto werr;
8941 if (fwriteBulkObject(fp,field) == -1) return -1;
8942 if (fwriteBulkObject(fp,val) == -1) return -1;
8943 }
8944 dictReleaseIterator(di);
8945 }
8946 } else {
8947 redisPanic("Unknown object type");
8948 }
8949 /* Save the expire time */
8950 if (expiretime != -1) {
8951 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
8952 /* If this key is already expired skip it */
8953 if (expiretime < now) continue;
8954 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8955 if (fwriteBulkObject(fp,key) == 0) goto werr;
8956 if (fwriteBulkLongLong(fp,expiretime) == 0) goto werr;
8957 }
8958 if (swapped) decrRefCount(o);
8959 }
8960 dictReleaseIterator(di);
8961 }
8962
8963 /* Make sure data will not remain on the OS's output buffers */
8964 fflush(fp);
8965 fsync(fileno(fp));
8966 fclose(fp);
8967
8968 /* Use RENAME to make sure the DB file is changed atomically only
8969 * if the generate DB file is ok. */
8970 if (rename(tmpfile,filename) == -1) {
8971 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
8972 unlink(tmpfile);
8973 return REDIS_ERR;
8974 }
8975 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
8976 return REDIS_OK;
8977
8978 werr:
8979 fclose(fp);
8980 unlink(tmpfile);
8981 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
8982 if (di) dictReleaseIterator(di);
8983 return REDIS_ERR;
8984 }
8985
8986 /* This is how rewriting of the append only file in background works:
8987 *
8988 * 1) The user calls BGREWRITEAOF
8989 * 2) Redis calls this function, that forks():
8990 * 2a) the child rewrite the append only file in a temp file.
8991 * 2b) the parent accumulates differences in server.bgrewritebuf.
8992 * 3) When the child finished '2a' exists.
8993 * 4) The parent will trap the exit code, if it's OK, will append the
8994 * data accumulated into server.bgrewritebuf into the temp file, and
8995 * finally will rename(2) the temp file in the actual file name.
8996 * The the new file is reopened as the new append only file. Profit!
8997 */
8998 static int rewriteAppendOnlyFileBackground(void) {
8999 pid_t childpid;
9000
9001 if (server.bgrewritechildpid != -1) return REDIS_ERR;
9002 if (server.vm_enabled) waitEmptyIOJobsQueue();
9003 if ((childpid = fork()) == 0) {
9004 /* Child */
9005 char tmpfile[256];
9006
9007 if (server.vm_enabled) vmReopenSwapFile();
9008 close(server.fd);
9009 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
9010 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
9011 _exit(0);
9012 } else {
9013 _exit(1);
9014 }
9015 } else {
9016 /* Parent */
9017 if (childpid == -1) {
9018 redisLog(REDIS_WARNING,
9019 "Can't rewrite append only file in background: fork: %s",
9020 strerror(errno));
9021 return REDIS_ERR;
9022 }
9023 redisLog(REDIS_NOTICE,
9024 "Background append only file rewriting started by pid %d",childpid);
9025 server.bgrewritechildpid = childpid;
9026 updateDictResizePolicy();
9027 /* We set appendseldb to -1 in order to force the next call to the
9028 * feedAppendOnlyFile() to issue a SELECT command, so the differences
9029 * accumulated by the parent into server.bgrewritebuf will start
9030 * with a SELECT statement and it will be safe to merge. */
9031 server.appendseldb = -1;
9032 return REDIS_OK;
9033 }
9034 return REDIS_OK; /* unreached */
9035 }
9036
9037 static void bgrewriteaofCommand(redisClient *c) {
9038 if (server.bgrewritechildpid != -1) {
9039 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
9040 return;
9041 }
9042 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
9043 char *status = "+Background append only file rewriting started\r\n";
9044 addReplySds(c,sdsnew(status));
9045 } else {
9046 addReply(c,shared.err);
9047 }
9048 }
9049
9050 static void aofRemoveTempFile(pid_t childpid) {
9051 char tmpfile[256];
9052
9053 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
9054 unlink(tmpfile);
9055 }
9056
9057 /* Virtual Memory is composed mainly of two subsystems:
9058 * - Blocking Virutal Memory
9059 * - Threaded Virtual Memory I/O
9060 * The two parts are not fully decoupled, but functions are split among two
9061 * different sections of the source code (delimited by comments) in order to
9062 * make more clear what functionality is about the blocking VM and what about
9063 * the threaded (not blocking) VM.
9064 *
9065 * Redis VM design:
9066 *
9067 * Redis VM is a blocking VM (one that blocks reading swapped values from
9068 * disk into memory when a value swapped out is needed in memory) that is made
9069 * unblocking by trying to examine the command argument vector in order to
9070 * load in background values that will likely be needed in order to exec
9071 * the command. The command is executed only once all the relevant keys
9072 * are loaded into memory.
9073 *
9074 * This basically is almost as simple of a blocking VM, but almost as parallel
9075 * as a fully non-blocking VM.
9076 */
9077
9078 /* Called when the user switches from "appendonly yes" to "appendonly no"
9079 * at runtime using the CONFIG command. */
9080 static void stopAppendOnly(void) {
9081 flushAppendOnlyFile();
9082 fsync(server.appendfd);
9083 close(server.appendfd);
9084
9085 server.appendfd = -1;
9086 server.appendseldb = -1;
9087 server.appendonly = 0;
9088 /* rewrite operation in progress? kill it, wait child exit */
9089 if (server.bgsavechildpid != -1) {
9090 int statloc;
9091
9092 if (kill(server.bgsavechildpid,SIGKILL) != -1)
9093 wait3(&statloc,0,NULL);
9094 /* reset the buffer accumulating changes while the child saves */
9095 sdsfree(server.bgrewritebuf);
9096 server.bgrewritebuf = sdsempty();
9097 server.bgsavechildpid = -1;
9098 }
9099 }
9100
9101 /* Called when the user switches from "appendonly no" to "appendonly yes"
9102 * at runtime using the CONFIG command. */
9103 static int startAppendOnly(void) {
9104 server.appendonly = 1;
9105 server.lastfsync = time(NULL);
9106 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
9107 if (server.appendfd == -1) {
9108 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno));
9109 return REDIS_ERR;
9110 }
9111 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
9112 server.appendonly = 0;
9113 close(server.appendfd);
9114 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));
9115 return REDIS_ERR;
9116 }
9117 return REDIS_OK;
9118 }
9119
9120 /* =================== Virtual Memory - Blocking Side ====================== */
9121
9122 static void vmInit(void) {
9123 off_t totsize;
9124 int pipefds[2];
9125 size_t stacksize;
9126 struct flock fl;
9127
9128 if (server.vm_max_threads != 0)
9129 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
9130
9131 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
9132 /* Try to open the old swap file, otherwise create it */
9133 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
9134 server.vm_fp = fopen(server.vm_swap_file,"w+b");
9135 }
9136 if (server.vm_fp == NULL) {
9137 redisLog(REDIS_WARNING,
9138 "Can't open the swap file: %s. Exiting.",
9139 strerror(errno));
9140 exit(1);
9141 }
9142 server.vm_fd = fileno(server.vm_fp);
9143 /* Lock the swap file for writing, this is useful in order to avoid
9144 * another instance to use the same swap file for a config error. */
9145 fl.l_type = F_WRLCK;
9146 fl.l_whence = SEEK_SET;
9147 fl.l_start = fl.l_len = 0;
9148 if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
9149 redisLog(REDIS_WARNING,
9150 "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));
9151 exit(1);
9152 }
9153 /* Initialize */
9154 server.vm_next_page = 0;
9155 server.vm_near_pages = 0;
9156 server.vm_stats_used_pages = 0;
9157 server.vm_stats_swapped_objects = 0;
9158 server.vm_stats_swapouts = 0;
9159 server.vm_stats_swapins = 0;
9160 totsize = server.vm_pages*server.vm_page_size;
9161 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
9162 if (ftruncate(server.vm_fd,totsize) == -1) {
9163 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
9164 strerror(errno));
9165 exit(1);
9166 } else {
9167 redisLog(REDIS_NOTICE,"Swap file allocated with success");
9168 }
9169 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
9170 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
9171 (long long) (server.vm_pages+7)/8, server.vm_pages);
9172 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
9173
9174 /* Initialize threaded I/O (used by Virtual Memory) */
9175 server.io_newjobs = listCreate();
9176 server.io_processing = listCreate();
9177 server.io_processed = listCreate();
9178 server.io_ready_clients = listCreate();
9179 pthread_mutex_init(&server.io_mutex,NULL);
9180 pthread_mutex_init(&server.obj_freelist_mutex,NULL);
9181 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
9182 server.io_active_threads = 0;
9183 if (pipe(pipefds) == -1) {
9184 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
9185 ,strerror(errno));
9186 exit(1);
9187 }
9188 server.io_ready_pipe_read = pipefds[0];
9189 server.io_ready_pipe_write = pipefds[1];
9190 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
9191 /* LZF requires a lot of stack */
9192 pthread_attr_init(&server.io_threads_attr);
9193 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
9194 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
9195 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
9196 /* Listen for events in the threaded I/O pipe */
9197 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
9198 vmThreadedIOCompletedJob, NULL) == AE_ERR)
9199 oom("creating file event");
9200 }
9201
9202 /* Mark the page as used */
9203 static void vmMarkPageUsed(off_t page) {
9204 off_t byte = page/8;
9205 int bit = page&7;
9206 redisAssert(vmFreePage(page) == 1);
9207 server.vm_bitmap[byte] |= 1<<bit;
9208 }
9209
9210 /* Mark N contiguous pages as used, with 'page' being the first. */
9211 static void vmMarkPagesUsed(off_t page, off_t count) {
9212 off_t j;
9213
9214 for (j = 0; j < count; j++)
9215 vmMarkPageUsed(page+j);
9216 server.vm_stats_used_pages += count;
9217 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
9218 (long long)count, (long long)page);
9219 }
9220
9221 /* Mark the page as free */
9222 static void vmMarkPageFree(off_t page) {
9223 off_t byte = page/8;
9224 int bit = page&7;
9225 redisAssert(vmFreePage(page) == 0);
9226 server.vm_bitmap[byte] &= ~(1<<bit);
9227 }
9228
9229 /* Mark N contiguous pages as free, with 'page' being the first. */
9230 static void vmMarkPagesFree(off_t page, off_t count) {
9231 off_t j;
9232
9233 for (j = 0; j < count; j++)
9234 vmMarkPageFree(page+j);
9235 server.vm_stats_used_pages -= count;
9236 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
9237 (long long)count, (long long)page);
9238 }
9239
9240 /* Test if the page is free */
9241 static int vmFreePage(off_t page) {
9242 off_t byte = page/8;
9243 int bit = page&7;
9244 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
9245 }
9246
9247 /* Find N contiguous free pages storing the first page of the cluster in *first.
9248 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
9249 * REDIS_ERR is returned.
9250 *
9251 * This function uses a simple algorithm: we try to allocate
9252 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
9253 * again from the start of the swap file searching for free spaces.
9254 *
9255 * If it looks pretty clear that there are no free pages near our offset
9256 * we try to find less populated places doing a forward jump of
9257 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
9258 * without hurry, and then we jump again and so forth...
9259 *
9260 * This function can be improved using a free list to avoid to guess
9261 * too much, since we could collect data about freed pages.
9262 *
9263 * note: I implemented this function just after watching an episode of
9264 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
9265 */
9266 static int vmFindContiguousPages(off_t *first, off_t n) {
9267 off_t base, offset = 0, since_jump = 0, numfree = 0;
9268
9269 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
9270 server.vm_near_pages = 0;
9271 server.vm_next_page = 0;
9272 }
9273 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
9274 base = server.vm_next_page;
9275
9276 while(offset < server.vm_pages) {
9277 off_t this = base+offset;
9278
9279 /* If we overflow, restart from page zero */
9280 if (this >= server.vm_pages) {
9281 this -= server.vm_pages;
9282 if (this == 0) {
9283 /* Just overflowed, what we found on tail is no longer
9284 * interesting, as it's no longer contiguous. */
9285 numfree = 0;
9286 }
9287 }
9288 if (vmFreePage(this)) {
9289 /* This is a free page */
9290 numfree++;
9291 /* Already got N free pages? Return to the caller, with success */
9292 if (numfree == n) {
9293 *first = this-(n-1);
9294 server.vm_next_page = this+1;
9295 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
9296 return REDIS_OK;
9297 }
9298 } else {
9299 /* The current one is not a free page */
9300 numfree = 0;
9301 }
9302
9303 /* Fast-forward if the current page is not free and we already
9304 * searched enough near this place. */
9305 since_jump++;
9306 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
9307 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
9308 since_jump = 0;
9309 /* Note that even if we rewind after the jump, we are don't need
9310 * to make sure numfree is set to zero as we only jump *if* it
9311 * is set to zero. */
9312 } else {
9313 /* Otherwise just check the next page */
9314 offset++;
9315 }
9316 }
9317 return REDIS_ERR;
9318 }
9319
9320 /* Write the specified object at the specified page of the swap file */
9321 static int vmWriteObjectOnSwap(robj *o, off_t page) {
9322 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9323 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9324 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9325 redisLog(REDIS_WARNING,
9326 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
9327 strerror(errno));
9328 return REDIS_ERR;
9329 }
9330 rdbSaveObject(server.vm_fp,o);
9331 fflush(server.vm_fp);
9332 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9333 return REDIS_OK;
9334 }
9335
9336 /* Swap the 'val' object relative to 'key' into disk. Store all the information
9337 * needed to later retrieve the object into the key object.
9338 * If we can't find enough contiguous empty pages to swap the object on disk
9339 * REDIS_ERR is returned. */
9340 static int vmSwapObjectBlocking(robj *key, robj *val) {
9341 off_t pages = rdbSavedObjectPages(val,NULL);
9342 off_t page;
9343
9344 assert(key->storage == REDIS_VM_MEMORY);
9345 assert(key->refcount == 1);
9346 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return REDIS_ERR;
9347 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return REDIS_ERR;
9348 key->vm.page = page;
9349 key->vm.usedpages = pages;
9350 key->storage = REDIS_VM_SWAPPED;
9351 key->vtype = val->type;
9352 decrRefCount(val); /* Deallocate the object from memory. */
9353 vmMarkPagesUsed(page,pages);
9354 redisLog(REDIS_DEBUG,"VM: object %s swapped out at %lld (%lld pages)",
9355 (unsigned char*) key->ptr,
9356 (unsigned long long) page, (unsigned long long) pages);
9357 server.vm_stats_swapped_objects++;
9358 server.vm_stats_swapouts++;
9359 return REDIS_OK;
9360 }
9361
9362 static robj *vmReadObjectFromSwap(off_t page, int type) {
9363 robj *o;
9364
9365 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9366 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9367 redisLog(REDIS_WARNING,
9368 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
9369 strerror(errno));
9370 _exit(1);
9371 }
9372 o = rdbLoadObject(type,server.vm_fp);
9373 if (o == NULL) {
9374 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
9375 _exit(1);
9376 }
9377 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9378 return o;
9379 }
9380
9381 /* Load the value object relative to the 'key' object from swap to memory.
9382 * The newly allocated object is returned.
9383 *
9384 * If preview is true the unserialized object is returned to the caller but
9385 * no changes are made to the key object, nor the pages are marked as freed */
9386 static robj *vmGenericLoadObject(robj *key, int preview) {
9387 robj *val;
9388
9389 redisAssert(key->storage == REDIS_VM_SWAPPED || key->storage == REDIS_VM_LOADING);
9390 val = vmReadObjectFromSwap(key->vm.page,key->vtype);
9391 if (!preview) {
9392 key->storage = REDIS_VM_MEMORY;
9393 key->vm.atime = server.unixtime;
9394 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9395 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk",
9396 (unsigned char*) key->ptr);
9397 server.vm_stats_swapped_objects--;
9398 } else {
9399 redisLog(REDIS_DEBUG, "VM: object %s previewed from disk",
9400 (unsigned char*) key->ptr);
9401 }
9402 server.vm_stats_swapins++;
9403 return val;
9404 }
9405
9406 /* Plain object loading, from swap to memory */
9407 static robj *vmLoadObject(robj *key) {
9408 /* If we are loading the object in background, stop it, we
9409 * need to load this object synchronously ASAP. */
9410 if (key->storage == REDIS_VM_LOADING)
9411 vmCancelThreadedIOJob(key);
9412 return vmGenericLoadObject(key,0);
9413 }
9414
9415 /* Just load the value on disk, without to modify the key.
9416 * This is useful when we want to perform some operation on the value
9417 * without to really bring it from swap to memory, like while saving the
9418 * dataset or rewriting the append only log. */
9419 static robj *vmPreviewObject(robj *key) {
9420 return vmGenericLoadObject(key,1);
9421 }
9422
9423 /* How a good candidate is this object for swapping?
9424 * The better candidate it is, the greater the returned value.
9425 *
9426 * Currently we try to perform a fast estimation of the object size in
9427 * memory, and combine it with aging informations.
9428 *
9429 * Basically swappability = idle-time * log(estimated size)
9430 *
9431 * Bigger objects are preferred over smaller objects, but not
9432 * proportionally, this is why we use the logarithm. This algorithm is
9433 * just a first try and will probably be tuned later. */
9434 static double computeObjectSwappability(robj *o) {
9435 time_t age = server.unixtime - o->vm.atime;
9436 long asize = 0;
9437 list *l;
9438 dict *d;
9439 struct dictEntry *de;
9440 int z;
9441
9442 if (age <= 0) return 0;
9443 switch(o->type) {
9444 case REDIS_STRING:
9445 if (o->encoding != REDIS_ENCODING_RAW) {
9446 asize = sizeof(*o);
9447 } else {
9448 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
9449 }
9450 break;
9451 case REDIS_LIST:
9452 l = o->ptr;
9453 listNode *ln = listFirst(l);
9454
9455 asize = sizeof(list);
9456 if (ln) {
9457 robj *ele = ln->value;
9458 long elesize;
9459
9460 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9461 (sizeof(*o)+sdslen(ele->ptr)) :
9462 sizeof(*o);
9463 asize += (sizeof(listNode)+elesize)*listLength(l);
9464 }
9465 break;
9466 case REDIS_SET:
9467 case REDIS_ZSET:
9468 z = (o->type == REDIS_ZSET);
9469 d = z ? ((zset*)o->ptr)->dict : o->ptr;
9470
9471 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9472 if (z) asize += sizeof(zset)-sizeof(dict);
9473 if (dictSize(d)) {
9474 long elesize;
9475 robj *ele;
9476
9477 de = dictGetRandomKey(d);
9478 ele = dictGetEntryKey(de);
9479 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9480 (sizeof(*o)+sdslen(ele->ptr)) :
9481 sizeof(*o);
9482 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9483 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
9484 }
9485 break;
9486 case REDIS_HASH:
9487 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9488 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
9489 unsigned int len = zipmapLen((unsigned char*)o->ptr);
9490 unsigned int klen, vlen;
9491 unsigned char *key, *val;
9492
9493 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
9494 klen = 0;
9495 vlen = 0;
9496 }
9497 asize = len*(klen+vlen+3);
9498 } else if (o->encoding == REDIS_ENCODING_HT) {
9499 d = o->ptr;
9500 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9501 if (dictSize(d)) {
9502 long elesize;
9503 robj *ele;
9504
9505 de = dictGetRandomKey(d);
9506 ele = dictGetEntryKey(de);
9507 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9508 (sizeof(*o)+sdslen(ele->ptr)) :
9509 sizeof(*o);
9510 ele = dictGetEntryVal(de);
9511 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9512 (sizeof(*o)+sdslen(ele->ptr)) :
9513 sizeof(*o);
9514 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9515 }
9516 }
9517 break;
9518 }
9519 return (double)age*log(1+asize);
9520 }
9521
9522 /* Try to swap an object that's a good candidate for swapping.
9523 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
9524 * to swap any object at all.
9525 *
9526 * If 'usethreaded' is true, Redis will try to swap the object in background
9527 * using I/O threads. */
9528 static int vmSwapOneObject(int usethreads) {
9529 int j, i;
9530 struct dictEntry *best = NULL;
9531 double best_swappability = 0;
9532 redisDb *best_db = NULL;
9533 robj *key, *val;
9534
9535 for (j = 0; j < server.dbnum; j++) {
9536 redisDb *db = server.db+j;
9537 /* Why maxtries is set to 100?
9538 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9539 * are swappable objects */
9540 int maxtries = 100;
9541
9542 if (dictSize(db->dict) == 0) continue;
9543 for (i = 0; i < 5; i++) {
9544 dictEntry *de;
9545 double swappability;
9546
9547 if (maxtries) maxtries--;
9548 de = dictGetRandomKey(db->dict);
9549 key = dictGetEntryKey(de);
9550 val = dictGetEntryVal(de);
9551 /* Only swap objects that are currently in memory.
9552 *
9553 * Also don't swap shared objects if threaded VM is on, as we
9554 * try to ensure that the main thread does not touch the
9555 * object while the I/O thread is using it, but we can't
9556 * control other keys without adding additional mutex. */
9557 if (key->storage != REDIS_VM_MEMORY ||
9558 (server.vm_max_threads != 0 && val->refcount != 1)) {
9559 if (maxtries) i--; /* don't count this try */
9560 continue;
9561 }
9562 swappability = computeObjectSwappability(val);
9563 if (!best || swappability > best_swappability) {
9564 best = de;
9565 best_swappability = swappability;
9566 best_db = db;
9567 }
9568 }
9569 }
9570 if (best == NULL) return REDIS_ERR;
9571 key = dictGetEntryKey(best);
9572 val = dictGetEntryVal(best);
9573
9574 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
9575 key->ptr, best_swappability);
9576
9577 /* Unshare the key if needed */
9578 if (key->refcount > 1) {
9579 robj *newkey = dupStringObject(key);
9580 decrRefCount(key);
9581 key = dictGetEntryKey(best) = newkey;
9582 }
9583 /* Swap it */
9584 if (usethreads) {
9585 vmSwapObjectThreaded(key,val,best_db);
9586 return REDIS_OK;
9587 } else {
9588 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
9589 dictGetEntryVal(best) = NULL;
9590 return REDIS_OK;
9591 } else {
9592 return REDIS_ERR;
9593 }
9594 }
9595 }
9596
9597 static int vmSwapOneObjectBlocking() {
9598 return vmSwapOneObject(0);
9599 }
9600
9601 static int vmSwapOneObjectThreaded() {
9602 return vmSwapOneObject(1);
9603 }
9604
9605 /* Return true if it's safe to swap out objects in a given moment.
9606 * Basically we don't want to swap objects out while there is a BGSAVE
9607 * or a BGAEOREWRITE running in backgroud. */
9608 static int vmCanSwapOut(void) {
9609 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
9610 }
9611
9612 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
9613 * and was deleted. Otherwise 0 is returned. */
9614 static int deleteIfSwapped(redisDb *db, robj *key) {
9615 dictEntry *de;
9616 robj *foundkey;
9617
9618 if ((de = dictFind(db->dict,key)) == NULL) return 0;
9619 foundkey = dictGetEntryKey(de);
9620 if (foundkey->storage == REDIS_VM_MEMORY) return 0;
9621 deleteKey(db,key);
9622 return 1;
9623 }
9624
9625 /* =================== Virtual Memory - Threaded I/O ======================= */
9626
9627 static void freeIOJob(iojob *j) {
9628 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
9629 j->type == REDIS_IOJOB_DO_SWAP ||
9630 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
9631 decrRefCount(j->val);
9632 /* We don't decrRefCount the j->key field as we did't incremented
9633 * the count creating IO Jobs. This is because the key field here is
9634 * just used as an indentifier and if a key is removed the Job should
9635 * never be touched again. */
9636 zfree(j);
9637 }
9638
9639 /* Every time a thread finished a Job, it writes a byte into the write side
9640 * of an unix pipe in order to "awake" the main thread, and this function
9641 * is called. */
9642 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
9643 int mask)
9644 {
9645 char buf[1];
9646 int retval, processed = 0, toprocess = -1, trytoswap = 1;
9647 REDIS_NOTUSED(el);
9648 REDIS_NOTUSED(mask);
9649 REDIS_NOTUSED(privdata);
9650
9651 /* For every byte we read in the read side of the pipe, there is one
9652 * I/O job completed to process. */
9653 while((retval = read(fd,buf,1)) == 1) {
9654 iojob *j;
9655 listNode *ln;
9656 robj *key;
9657 struct dictEntry *de;
9658
9659 redisLog(REDIS_DEBUG,"Processing I/O completed job");
9660
9661 /* Get the processed element (the oldest one) */
9662 lockThreadedIO();
9663 assert(listLength(server.io_processed) != 0);
9664 if (toprocess == -1) {
9665 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
9666 if (toprocess <= 0) toprocess = 1;
9667 }
9668 ln = listFirst(server.io_processed);
9669 j = ln->value;
9670 listDelNode(server.io_processed,ln);
9671 unlockThreadedIO();
9672 /* If this job is marked as canceled, just ignore it */
9673 if (j->canceled) {
9674 freeIOJob(j);
9675 continue;
9676 }
9677 /* Post process it in the main thread, as there are things we
9678 * can do just here to avoid race conditions and/or invasive locks */
9679 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);
9680 de = dictFind(j->db->dict,j->key);
9681 assert(de != NULL);
9682 key = dictGetEntryKey(de);
9683 if (j->type == REDIS_IOJOB_LOAD) {
9684 redisDb *db;
9685
9686 /* Key loaded, bring it at home */
9687 key->storage = REDIS_VM_MEMORY;
9688 key->vm.atime = server.unixtime;
9689 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9690 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
9691 (unsigned char*) key->ptr);
9692 server.vm_stats_swapped_objects--;
9693 server.vm_stats_swapins++;
9694 dictGetEntryVal(de) = j->val;
9695 incrRefCount(j->val);
9696 db = j->db;
9697 freeIOJob(j);
9698 /* Handle clients waiting for this key to be loaded. */
9699 handleClientsBlockedOnSwappedKey(db,key);
9700 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9701 /* Now we know the amount of pages required to swap this object.
9702 * Let's find some space for it, and queue this task again
9703 * rebranded as REDIS_IOJOB_DO_SWAP. */
9704 if (!vmCanSwapOut() ||
9705 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
9706 {
9707 /* Ooops... no space or we can't swap as there is
9708 * a fork()ed Redis trying to save stuff on disk. */
9709 freeIOJob(j);
9710 key->storage = REDIS_VM_MEMORY; /* undo operation */
9711 } else {
9712 /* Note that we need to mark this pages as used now,
9713 * if the job will be canceled, we'll mark them as freed
9714 * again. */
9715 vmMarkPagesUsed(j->page,j->pages);
9716 j->type = REDIS_IOJOB_DO_SWAP;
9717 lockThreadedIO();
9718 queueIOJob(j);
9719 unlockThreadedIO();
9720 }
9721 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9722 robj *val;
9723
9724 /* Key swapped. We can finally free some memory. */
9725 if (key->storage != REDIS_VM_SWAPPING) {
9726 printf("key->storage: %d\n",key->storage);
9727 printf("key->name: %s\n",(char*)key->ptr);
9728 printf("key->refcount: %d\n",key->refcount);
9729 printf("val: %p\n",(void*)j->val);
9730 printf("val->type: %d\n",j->val->type);
9731 printf("val->ptr: %s\n",(char*)j->val->ptr);
9732 }
9733 redisAssert(key->storage == REDIS_VM_SWAPPING);
9734 val = dictGetEntryVal(de);
9735 key->vm.page = j->page;
9736 key->vm.usedpages = j->pages;
9737 key->storage = REDIS_VM_SWAPPED;
9738 key->vtype = j->val->type;
9739 decrRefCount(val); /* Deallocate the object from memory. */
9740 dictGetEntryVal(de) = NULL;
9741 redisLog(REDIS_DEBUG,
9742 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9743 (unsigned char*) key->ptr,
9744 (unsigned long long) j->page, (unsigned long long) j->pages);
9745 server.vm_stats_swapped_objects++;
9746 server.vm_stats_swapouts++;
9747 freeIOJob(j);
9748 /* Put a few more swap requests in queue if we are still
9749 * out of memory */
9750 if (trytoswap && vmCanSwapOut() &&
9751 zmalloc_used_memory() > server.vm_max_memory)
9752 {
9753 int more = 1;
9754 while(more) {
9755 lockThreadedIO();
9756 more = listLength(server.io_newjobs) <
9757 (unsigned) server.vm_max_threads;
9758 unlockThreadedIO();
9759 /* Don't waste CPU time if swappable objects are rare. */
9760 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
9761 trytoswap = 0;
9762 break;
9763 }
9764 }
9765 }
9766 }
9767 processed++;
9768 if (processed == toprocess) return;
9769 }
9770 if (retval < 0 && errno != EAGAIN) {
9771 redisLog(REDIS_WARNING,
9772 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9773 strerror(errno));
9774 }
9775 }
9776
9777 static void lockThreadedIO(void) {
9778 pthread_mutex_lock(&server.io_mutex);
9779 }
9780
9781 static void unlockThreadedIO(void) {
9782 pthread_mutex_unlock(&server.io_mutex);
9783 }
9784
9785 /* Remove the specified object from the threaded I/O queue if still not
9786 * processed, otherwise make sure to flag it as canceled. */
9787 static void vmCancelThreadedIOJob(robj *o) {
9788 list *lists[3] = {
9789 server.io_newjobs, /* 0 */
9790 server.io_processing, /* 1 */
9791 server.io_processed /* 2 */
9792 };
9793 int i;
9794
9795 assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
9796 again:
9797 lockThreadedIO();
9798 /* Search for a matching key in one of the queues */
9799 for (i = 0; i < 3; i++) {
9800 listNode *ln;
9801 listIter li;
9802
9803 listRewind(lists[i],&li);
9804 while ((ln = listNext(&li)) != NULL) {
9805 iojob *job = ln->value;
9806
9807 if (job->canceled) continue; /* Skip this, already canceled. */
9808 if (job->key == o) {
9809 redisLog(REDIS_DEBUG,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
9810 (void*)job, (char*)o->ptr, job->type, i);
9811 /* Mark the pages as free since the swap didn't happened
9812 * or happened but is now discarded. */
9813 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
9814 vmMarkPagesFree(job->page,job->pages);
9815 /* Cancel the job. It depends on the list the job is
9816 * living in. */
9817 switch(i) {
9818 case 0: /* io_newjobs */
9819 /* If the job was yet not processed the best thing to do
9820 * is to remove it from the queue at all */
9821 freeIOJob(job);
9822 listDelNode(lists[i],ln);
9823 break;
9824 case 1: /* io_processing */
9825 /* Oh Shi- the thread is messing with the Job:
9826 *
9827 * Probably it's accessing the object if this is a
9828 * PREPARE_SWAP or DO_SWAP job.
9829 * If it's a LOAD job it may be reading from disk and
9830 * if we don't wait for the job to terminate before to
9831 * cancel it, maybe in a few microseconds data can be
9832 * corrupted in this pages. So the short story is:
9833 *
9834 * Better to wait for the job to move into the
9835 * next queue (processed)... */
9836
9837 /* We try again and again until the job is completed. */
9838 unlockThreadedIO();
9839 /* But let's wait some time for the I/O thread
9840 * to finish with this job. After all this condition
9841 * should be very rare. */
9842 usleep(1);
9843 goto again;
9844 case 2: /* io_processed */
9845 /* The job was already processed, that's easy...
9846 * just mark it as canceled so that we'll ignore it
9847 * when processing completed jobs. */
9848 job->canceled = 1;
9849 break;
9850 }
9851 /* Finally we have to adjust the storage type of the object
9852 * in order to "UNDO" the operaiton. */
9853 if (o->storage == REDIS_VM_LOADING)
9854 o->storage = REDIS_VM_SWAPPED;
9855 else if (o->storage == REDIS_VM_SWAPPING)
9856 o->storage = REDIS_VM_MEMORY;
9857 unlockThreadedIO();
9858 return;
9859 }
9860 }
9861 }
9862 unlockThreadedIO();
9863 assert(1 != 1); /* We should never reach this */
9864 }
9865
9866 static void *IOThreadEntryPoint(void *arg) {
9867 iojob *j;
9868 listNode *ln;
9869 REDIS_NOTUSED(arg);
9870
9871 pthread_detach(pthread_self());
9872 while(1) {
9873 /* Get a new job to process */
9874 lockThreadedIO();
9875 if (listLength(server.io_newjobs) == 0) {
9876 /* No new jobs in queue, exit. */
9877 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
9878 (long) pthread_self());
9879 server.io_active_threads--;
9880 unlockThreadedIO();
9881 return NULL;
9882 }
9883 ln = listFirst(server.io_newjobs);
9884 j = ln->value;
9885 listDelNode(server.io_newjobs,ln);
9886 /* Add the job in the processing queue */
9887 j->thread = pthread_self();
9888 listAddNodeTail(server.io_processing,j);
9889 ln = listLast(server.io_processing); /* We use ln later to remove it */
9890 unlockThreadedIO();
9891 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
9892 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
9893
9894 /* Process the Job */
9895 if (j->type == REDIS_IOJOB_LOAD) {
9896 j->val = vmReadObjectFromSwap(j->page,j->key->vtype);
9897 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9898 FILE *fp = fopen("/dev/null","w+");
9899 j->pages = rdbSavedObjectPages(j->val,fp);
9900 fclose(fp);
9901 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9902 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
9903 j->canceled = 1;
9904 }
9905
9906 /* Done: insert the job into the processed queue */
9907 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
9908 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
9909 lockThreadedIO();
9910 listDelNode(server.io_processing,ln);
9911 listAddNodeTail(server.io_processed,j);
9912 unlockThreadedIO();
9913
9914 /* Signal the main thread there is new stuff to process */
9915 assert(write(server.io_ready_pipe_write,"x",1) == 1);
9916 }
9917 return NULL; /* never reached */
9918 }
9919
9920 static void spawnIOThread(void) {
9921 pthread_t thread;
9922 sigset_t mask, omask;
9923 int err;
9924
9925 sigemptyset(&mask);
9926 sigaddset(&mask,SIGCHLD);
9927 sigaddset(&mask,SIGHUP);
9928 sigaddset(&mask,SIGPIPE);
9929 pthread_sigmask(SIG_SETMASK, &mask, &omask);
9930 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
9931 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
9932 strerror(err));
9933 usleep(1000000);
9934 }
9935 pthread_sigmask(SIG_SETMASK, &omask, NULL);
9936 server.io_active_threads++;
9937 }
9938
9939 /* We need to wait for the last thread to exit before we are able to
9940 * fork() in order to BGSAVE or BGREWRITEAOF. */
9941 static void waitEmptyIOJobsQueue(void) {
9942 while(1) {
9943 int io_processed_len;
9944
9945 lockThreadedIO();
9946 if (listLength(server.io_newjobs) == 0 &&
9947 listLength(server.io_processing) == 0 &&
9948 server.io_active_threads == 0)
9949 {
9950 unlockThreadedIO();
9951 return;
9952 }
9953 /* While waiting for empty jobs queue condition we post-process some
9954 * finshed job, as I/O threads may be hanging trying to write against
9955 * the io_ready_pipe_write FD but there are so much pending jobs that
9956 * it's blocking. */
9957 io_processed_len = listLength(server.io_processed);
9958 unlockThreadedIO();
9959 if (io_processed_len) {
9960 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
9961 usleep(1000); /* 1 millisecond */
9962 } else {
9963 usleep(10000); /* 10 milliseconds */
9964 }
9965 }
9966 }
9967
9968 static void vmReopenSwapFile(void) {
9969 /* Note: we don't close the old one as we are in the child process
9970 * and don't want to mess at all with the original file object. */
9971 server.vm_fp = fopen(server.vm_swap_file,"r+b");
9972 if (server.vm_fp == NULL) {
9973 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
9974 server.vm_swap_file);
9975 _exit(1);
9976 }
9977 server.vm_fd = fileno(server.vm_fp);
9978 }
9979
9980 /* This function must be called while with threaded IO locked */
9981 static void queueIOJob(iojob *j) {
9982 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
9983 (void*)j, j->type, (char*)j->key->ptr);
9984 listAddNodeTail(server.io_newjobs,j);
9985 if (server.io_active_threads < server.vm_max_threads)
9986 spawnIOThread();
9987 }
9988
9989 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
9990 iojob *j;
9991
9992 assert(key->storage == REDIS_VM_MEMORY);
9993 assert(key->refcount == 1);
9994
9995 j = zmalloc(sizeof(*j));
9996 j->type = REDIS_IOJOB_PREPARE_SWAP;
9997 j->db = db;
9998 j->key = key;
9999 j->val = val;
10000 incrRefCount(val);
10001 j->canceled = 0;
10002 j->thread = (pthread_t) -1;
10003 key->storage = REDIS_VM_SWAPPING;
10004
10005 lockThreadedIO();
10006 queueIOJob(j);
10007 unlockThreadedIO();
10008 return REDIS_OK;
10009 }
10010
10011 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
10012
10013 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
10014 * If there is not already a job loading the key, it is craeted.
10015 * The key is added to the io_keys list in the client structure, and also
10016 * in the hash table mapping swapped keys to waiting clients, that is,
10017 * server.io_waited_keys. */
10018 static int waitForSwappedKey(redisClient *c, robj *key) {
10019 struct dictEntry *de;
10020 robj *o;
10021 list *l;
10022
10023 /* If the key does not exist or is already in RAM we don't need to
10024 * block the client at all. */
10025 de = dictFind(c->db->dict,key);
10026 if (de == NULL) return 0;
10027 o = dictGetEntryKey(de);
10028 if (o->storage == REDIS_VM_MEMORY) {
10029 return 0;
10030 } else if (o->storage == REDIS_VM_SWAPPING) {
10031 /* We were swapping the key, undo it! */
10032 vmCancelThreadedIOJob(o);
10033 return 0;
10034 }
10035
10036 /* OK: the key is either swapped, or being loaded just now. */
10037
10038 /* Add the key to the list of keys this client is waiting for.
10039 * This maps clients to keys they are waiting for. */
10040 listAddNodeTail(c->io_keys,key);
10041 incrRefCount(key);
10042
10043 /* Add the client to the swapped keys => clients waiting map. */
10044 de = dictFind(c->db->io_keys,key);
10045 if (de == NULL) {
10046 int retval;
10047
10048 /* For every key we take a list of clients blocked for it */
10049 l = listCreate();
10050 retval = dictAdd(c->db->io_keys,key,l);
10051 incrRefCount(key);
10052 assert(retval == DICT_OK);
10053 } else {
10054 l = dictGetEntryVal(de);
10055 }
10056 listAddNodeTail(l,c);
10057
10058 /* Are we already loading the key from disk? If not create a job */
10059 if (o->storage == REDIS_VM_SWAPPED) {
10060 iojob *j;
10061
10062 o->storage = REDIS_VM_LOADING;
10063 j = zmalloc(sizeof(*j));
10064 j->type = REDIS_IOJOB_LOAD;
10065 j->db = c->db;
10066 j->key = o;
10067 j->key->vtype = o->vtype;
10068 j->page = o->vm.page;
10069 j->val = NULL;
10070 j->canceled = 0;
10071 j->thread = (pthread_t) -1;
10072 lockThreadedIO();
10073 queueIOJob(j);
10074 unlockThreadedIO();
10075 }
10076 return 1;
10077 }
10078
10079 /* Preload keys for any command with first, last and step values for
10080 * the command keys prototype, as defined in the command table. */
10081 static void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10082 int j, last;
10083 if (cmd->vm_firstkey == 0) return;
10084 last = cmd->vm_lastkey;
10085 if (last < 0) last = argc+last;
10086 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
10087 redisAssert(j < argc);
10088 waitForSwappedKey(c,argv[j]);
10089 }
10090 }
10091
10092 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
10093 * Note that the number of keys to preload is user-defined, so we need to
10094 * apply a sanity check against argc. */
10095 static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10096 int i, num;
10097 REDIS_NOTUSED(cmd);
10098
10099 num = atoi(argv[2]->ptr);
10100 if (num > (argc-3)) return;
10101 for (i = 0; i < num; i++) {
10102 waitForSwappedKey(c,argv[3+i]);
10103 }
10104 }
10105
10106 /* Preload keys needed to execute the entire MULTI/EXEC block.
10107 *
10108 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
10109 * and will block the client when any command requires a swapped out value. */
10110 static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10111 int i, margc;
10112 struct redisCommand *mcmd;
10113 robj **margv;
10114 REDIS_NOTUSED(cmd);
10115 REDIS_NOTUSED(argc);
10116 REDIS_NOTUSED(argv);
10117
10118 if (!(c->flags & REDIS_MULTI)) return;
10119 for (i = 0; i < c->mstate.count; i++) {
10120 mcmd = c->mstate.commands[i].cmd;
10121 margc = c->mstate.commands[i].argc;
10122 margv = c->mstate.commands[i].argv;
10123
10124 if (mcmd->vm_preload_proc != NULL) {
10125 mcmd->vm_preload_proc(c,mcmd,margc,margv);
10126 } else {
10127 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
10128 }
10129 }
10130 }
10131
10132 /* Is this client attempting to run a command against swapped keys?
10133 * If so, block it ASAP, load the keys in background, then resume it.
10134 *
10135 * The important idea about this function is that it can fail! If keys will
10136 * still be swapped when the client is resumed, this key lookups will
10137 * just block loading keys from disk. In practical terms this should only
10138 * happen with SORT BY command or if there is a bug in this function.
10139 *
10140 * Return 1 if the client is marked as blocked, 0 if the client can
10141 * continue as the keys it is going to access appear to be in memory. */
10142 static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
10143 if (cmd->vm_preload_proc != NULL) {
10144 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
10145 } else {
10146 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
10147 }
10148
10149 /* If the client was blocked for at least one key, mark it as blocked. */
10150 if (listLength(c->io_keys)) {
10151 c->flags |= REDIS_IO_WAIT;
10152 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
10153 server.vm_blocked_clients++;
10154 return 1;
10155 } else {
10156 return 0;
10157 }
10158 }
10159
10160 /* Remove the 'key' from the list of blocked keys for a given client.
10161 *
10162 * The function returns 1 when there are no longer blocking keys after
10163 * the current one was removed (and the client can be unblocked). */
10164 static int dontWaitForSwappedKey(redisClient *c, robj *key) {
10165 list *l;
10166 listNode *ln;
10167 listIter li;
10168 struct dictEntry *de;
10169
10170 /* Remove the key from the list of keys this client is waiting for. */
10171 listRewind(c->io_keys,&li);
10172 while ((ln = listNext(&li)) != NULL) {
10173 if (equalStringObjects(ln->value,key)) {
10174 listDelNode(c->io_keys,ln);
10175 break;
10176 }
10177 }
10178 assert(ln != NULL);
10179
10180 /* Remove the client form the key => waiting clients map. */
10181 de = dictFind(c->db->io_keys,key);
10182 assert(de != NULL);
10183 l = dictGetEntryVal(de);
10184 ln = listSearchKey(l,c);
10185 assert(ln != NULL);
10186 listDelNode(l,ln);
10187 if (listLength(l) == 0)
10188 dictDelete(c->db->io_keys,key);
10189
10190 return listLength(c->io_keys) == 0;
10191 }
10192
10193 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
10194 struct dictEntry *de;
10195 list *l;
10196 listNode *ln;
10197 int len;
10198
10199 de = dictFind(db->io_keys,key);
10200 if (!de) return;
10201
10202 l = dictGetEntryVal(de);
10203 len = listLength(l);
10204 /* Note: we can't use something like while(listLength(l)) as the list
10205 * can be freed by the calling function when we remove the last element. */
10206 while (len--) {
10207 ln = listFirst(l);
10208 redisClient *c = ln->value;
10209
10210 if (dontWaitForSwappedKey(c,key)) {
10211 /* Put the client in the list of clients ready to go as we
10212 * loaded all the keys about it. */
10213 listAddNodeTail(server.io_ready_clients,c);
10214 }
10215 }
10216 }
10217
10218 /* =========================== Remote Configuration ========================= */
10219
10220 static void configSetCommand(redisClient *c) {
10221 robj *o = getDecodedObject(c->argv[3]);
10222 long long ll;
10223
10224 if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
10225 zfree(server.dbfilename);
10226 server.dbfilename = zstrdup(o->ptr);
10227 } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
10228 zfree(server.requirepass);
10229 server.requirepass = zstrdup(o->ptr);
10230 } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
10231 zfree(server.masterauth);
10232 server.masterauth = zstrdup(o->ptr);
10233 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
10234 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10235 ll < 0) goto badfmt;
10236 server.maxmemory = ll;
10237 } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
10238 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10239 ll < 0 || ll > LONG_MAX) goto badfmt;
10240 server.maxidletime = ll;
10241 } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
10242 if (!strcasecmp(o->ptr,"no")) {
10243 server.appendfsync = APPENDFSYNC_NO;
10244 } else if (!strcasecmp(o->ptr,"everysec")) {
10245 server.appendfsync = APPENDFSYNC_EVERYSEC;
10246 } else if (!strcasecmp(o->ptr,"always")) {
10247 server.appendfsync = APPENDFSYNC_ALWAYS;
10248 } else {
10249 goto badfmt;
10250 }
10251 } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
10252 int old = server.appendonly;
10253 int new = yesnotoi(o->ptr);
10254
10255 if (new == -1) goto badfmt;
10256 if (old != new) {
10257 if (new == 0) {
10258 stopAppendOnly();
10259 } else {
10260 if (startAppendOnly() == REDIS_ERR) {
10261 addReplySds(c,sdscatprintf(sdsempty(),
10262 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
10263 decrRefCount(o);
10264 return;
10265 }
10266 }
10267 }
10268 } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
10269 int vlen, j;
10270 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
10271
10272 /* Perform sanity check before setting the new config:
10273 * - Even number of args
10274 * - Seconds >= 1, changes >= 0 */
10275 if (vlen & 1) {
10276 sdsfreesplitres(v,vlen);
10277 goto badfmt;
10278 }
10279 for (j = 0; j < vlen; j++) {
10280 char *eptr;
10281 long val;
10282
10283 val = strtoll(v[j], &eptr, 10);
10284 if (eptr[0] != '\0' ||
10285 ((j & 1) == 0 && val < 1) ||
10286 ((j & 1) == 1 && val < 0)) {
10287 sdsfreesplitres(v,vlen);
10288 goto badfmt;
10289 }
10290 }
10291 /* Finally set the new config */
10292 resetServerSaveParams();
10293 for (j = 0; j < vlen; j += 2) {
10294 time_t seconds;
10295 int changes;
10296
10297 seconds = strtoll(v[j],NULL,10);
10298 changes = strtoll(v[j+1],NULL,10);
10299 appendServerSaveParams(seconds, changes);
10300 }
10301 sdsfreesplitres(v,vlen);
10302 } else {
10303 addReplySds(c,sdscatprintf(sdsempty(),
10304 "-ERR not supported CONFIG parameter %s\r\n",
10305 (char*)c->argv[2]->ptr));
10306 decrRefCount(o);
10307 return;
10308 }
10309 decrRefCount(o);
10310 addReply(c,shared.ok);
10311 return;
10312
10313 badfmt: /* Bad format errors */
10314 addReplySds(c,sdscatprintf(sdsempty(),
10315 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
10316 (char*)o->ptr,
10317 (char*)c->argv[2]->ptr));
10318 decrRefCount(o);
10319 }
10320
10321 static void configGetCommand(redisClient *c) {
10322 robj *o = getDecodedObject(c->argv[2]);
10323 robj *lenobj = createObject(REDIS_STRING,NULL);
10324 char *pattern = o->ptr;
10325 int matches = 0;
10326
10327 addReply(c,lenobj);
10328 decrRefCount(lenobj);
10329
10330 if (stringmatch(pattern,"dbfilename",0)) {
10331 addReplyBulkCString(c,"dbfilename");
10332 addReplyBulkCString(c,server.dbfilename);
10333 matches++;
10334 }
10335 if (stringmatch(pattern,"requirepass",0)) {
10336 addReplyBulkCString(c,"requirepass");
10337 addReplyBulkCString(c,server.requirepass);
10338 matches++;
10339 }
10340 if (stringmatch(pattern,"masterauth",0)) {
10341 addReplyBulkCString(c,"masterauth");
10342 addReplyBulkCString(c,server.masterauth);
10343 matches++;
10344 }
10345 if (stringmatch(pattern,"maxmemory",0)) {
10346 char buf[128];
10347
10348 ll2string(buf,128,server.maxmemory);
10349 addReplyBulkCString(c,"maxmemory");
10350 addReplyBulkCString(c,buf);
10351 matches++;
10352 }
10353 if (stringmatch(pattern,"timeout",0)) {
10354 char buf[128];
10355
10356 ll2string(buf,128,server.maxidletime);
10357 addReplyBulkCString(c,"timeout");
10358 addReplyBulkCString(c,buf);
10359 matches++;
10360 }
10361 if (stringmatch(pattern,"appendonly",0)) {
10362 addReplyBulkCString(c,"appendonly");
10363 addReplyBulkCString(c,server.appendonly ? "yes" : "no");
10364 matches++;
10365 }
10366 if (stringmatch(pattern,"appendfsync",0)) {
10367 char *policy;
10368
10369 switch(server.appendfsync) {
10370 case APPENDFSYNC_NO: policy = "no"; break;
10371 case APPENDFSYNC_EVERYSEC: policy = "everysec"; break;
10372 case APPENDFSYNC_ALWAYS: policy = "always"; break;
10373 default: policy = "unknown"; break; /* too harmless to panic */
10374 }
10375 addReplyBulkCString(c,"appendfsync");
10376 addReplyBulkCString(c,policy);
10377 matches++;
10378 }
10379 if (stringmatch(pattern,"save",0)) {
10380 sds buf = sdsempty();
10381 int j;
10382
10383 for (j = 0; j < server.saveparamslen; j++) {
10384 buf = sdscatprintf(buf,"%ld %d",
10385 server.saveparams[j].seconds,
10386 server.saveparams[j].changes);
10387 if (j != server.saveparamslen-1)
10388 buf = sdscatlen(buf," ",1);
10389 }
10390 addReplyBulkCString(c,"save");
10391 addReplyBulkCString(c,buf);
10392 sdsfree(buf);
10393 matches++;
10394 }
10395 decrRefCount(o);
10396 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",matches*2);
10397 }
10398
10399 static void configCommand(redisClient *c) {
10400 if (!strcasecmp(c->argv[1]->ptr,"set")) {
10401 if (c->argc != 4) goto badarity;
10402 configSetCommand(c);
10403 } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
10404 if (c->argc != 3) goto badarity;
10405 configGetCommand(c);
10406 } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
10407 if (c->argc != 2) goto badarity;
10408 server.stat_numcommands = 0;
10409 server.stat_numconnections = 0;
10410 server.stat_expiredkeys = 0;
10411 server.stat_starttime = time(NULL);
10412 addReply(c,shared.ok);
10413 } else {
10414 addReplySds(c,sdscatprintf(sdsempty(),
10415 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10416 }
10417 return;
10418
10419 badarity:
10420 addReplySds(c,sdscatprintf(sdsempty(),
10421 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10422 (char*) c->argv[1]->ptr));
10423 }
10424
10425 /* =========================== Pubsub implementation ======================== */
10426
10427 static void freePubsubPattern(void *p) {
10428 pubsubPattern *pat = p;
10429
10430 decrRefCount(pat->pattern);
10431 zfree(pat);
10432 }
10433
10434 static int listMatchPubsubPattern(void *a, void *b) {
10435 pubsubPattern *pa = a, *pb = b;
10436
10437 return (pa->client == pb->client) &&
10438 (equalStringObjects(pa->pattern,pb->pattern));
10439 }
10440
10441 /* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10442 * 0 if the client was already subscribed to that channel. */
10443 static int pubsubSubscribeChannel(redisClient *c, robj *channel) {
10444 struct dictEntry *de;
10445 list *clients = NULL;
10446 int retval = 0;
10447
10448 /* Add the channel to the client -> channels hash table */
10449 if (dictAdd(c->pubsub_channels,channel,NULL) == DICT_OK) {
10450 retval = 1;
10451 incrRefCount(channel);
10452 /* Add the client to the channel -> list of clients hash table */
10453 de = dictFind(server.pubsub_channels,channel);
10454 if (de == NULL) {
10455 clients = listCreate();
10456 dictAdd(server.pubsub_channels,channel,clients);
10457 incrRefCount(channel);
10458 } else {
10459 clients = dictGetEntryVal(de);
10460 }
10461 listAddNodeTail(clients,c);
10462 }
10463 /* Notify the client */
10464 addReply(c,shared.mbulk3);
10465 addReply(c,shared.subscribebulk);
10466 addReplyBulk(c,channel);
10467 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10468 return retval;
10469 }
10470
10471 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10472 * 0 if the client was not subscribed to the specified channel. */
10473 static int pubsubUnsubscribeChannel(redisClient *c, robj *channel, int notify) {
10474 struct dictEntry *de;
10475 list *clients;
10476 listNode *ln;
10477 int retval = 0;
10478
10479 /* Remove the channel from the client -> channels hash table */
10480 incrRefCount(channel); /* channel may be just a pointer to the same object
10481 we have in the hash tables. Protect it... */
10482 if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
10483 retval = 1;
10484 /* Remove the client from the channel -> clients list hash table */
10485 de = dictFind(server.pubsub_channels,channel);
10486 assert(de != NULL);
10487 clients = dictGetEntryVal(de);
10488 ln = listSearchKey(clients,c);
10489 assert(ln != NULL);
10490 listDelNode(clients,ln);
10491 if (listLength(clients) == 0) {
10492 /* Free the list and associated hash entry at all if this was
10493 * the latest client, so that it will be possible to abuse
10494 * Redis PUBSUB creating millions of channels. */
10495 dictDelete(server.pubsub_channels,channel);
10496 }
10497 }
10498 /* Notify the client */
10499 if (notify) {
10500 addReply(c,shared.mbulk3);
10501 addReply(c,shared.unsubscribebulk);
10502 addReplyBulk(c,channel);
10503 addReplyLongLong(c,dictSize(c->pubsub_channels)+
10504 listLength(c->pubsub_patterns));
10505
10506 }
10507 decrRefCount(channel); /* it is finally safe to release it */
10508 return retval;
10509 }
10510
10511 /* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10512 static int pubsubSubscribePattern(redisClient *c, robj *pattern) {
10513 int retval = 0;
10514
10515 if (listSearchKey(c->pubsub_patterns,pattern) == NULL) {
10516 retval = 1;
10517 pubsubPattern *pat;
10518 listAddNodeTail(c->pubsub_patterns,pattern);
10519 incrRefCount(pattern);
10520 pat = zmalloc(sizeof(*pat));
10521 pat->pattern = getDecodedObject(pattern);
10522 pat->client = c;
10523 listAddNodeTail(server.pubsub_patterns,pat);
10524 }
10525 /* Notify the client */
10526 addReply(c,shared.mbulk3);
10527 addReply(c,shared.psubscribebulk);
10528 addReplyBulk(c,pattern);
10529 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10530 return retval;
10531 }
10532
10533 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10534 * 0 if the client was not subscribed to the specified channel. */
10535 static int pubsubUnsubscribePattern(redisClient *c, robj *pattern, int notify) {
10536 listNode *ln;
10537 pubsubPattern pat;
10538 int retval = 0;
10539
10540 incrRefCount(pattern); /* Protect the object. May be the same we remove */
10541 if ((ln = listSearchKey(c->pubsub_patterns,pattern)) != NULL) {
10542 retval = 1;
10543 listDelNode(c->pubsub_patterns,ln);
10544 pat.client = c;
10545 pat.pattern = pattern;
10546 ln = listSearchKey(server.pubsub_patterns,&pat);
10547 listDelNode(server.pubsub_patterns,ln);
10548 }
10549 /* Notify the client */
10550 if (notify) {
10551 addReply(c,shared.mbulk3);
10552 addReply(c,shared.punsubscribebulk);
10553 addReplyBulk(c,pattern);
10554 addReplyLongLong(c,dictSize(c->pubsub_channels)+
10555 listLength(c->pubsub_patterns));
10556 }
10557 decrRefCount(pattern);
10558 return retval;
10559 }
10560
10561 /* Unsubscribe from all the channels. Return the number of channels the
10562 * client was subscribed from. */
10563 static int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
10564 dictIterator *di = dictGetIterator(c->pubsub_channels);
10565 dictEntry *de;
10566 int count = 0;
10567
10568 while((de = dictNext(di)) != NULL) {
10569 robj *channel = dictGetEntryKey(de);
10570
10571 count += pubsubUnsubscribeChannel(c,channel,notify);
10572 }
10573 dictReleaseIterator(di);
10574 return count;
10575 }
10576
10577 /* Unsubscribe from all the patterns. Return the number of patterns the
10578 * client was subscribed from. */
10579 static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify) {
10580 listNode *ln;
10581 listIter li;
10582 int count = 0;
10583
10584 listRewind(c->pubsub_patterns,&li);
10585 while ((ln = listNext(&li)) != NULL) {
10586 robj *pattern = ln->value;
10587
10588 count += pubsubUnsubscribePattern(c,pattern,notify);
10589 }
10590 return count;
10591 }
10592
10593 /* Publish a message */
10594 static int pubsubPublishMessage(robj *channel, robj *message) {
10595 int receivers = 0;
10596 struct dictEntry *de;
10597 listNode *ln;
10598 listIter li;
10599
10600 /* Send to clients listening for that channel */
10601 de = dictFind(server.pubsub_channels,channel);
10602 if (de) {
10603 list *list = dictGetEntryVal(de);
10604 listNode *ln;
10605 listIter li;
10606
10607 listRewind(list,&li);
10608 while ((ln = listNext(&li)) != NULL) {
10609 redisClient *c = ln->value;
10610
10611 addReply(c,shared.mbulk3);
10612 addReply(c,shared.messagebulk);
10613 addReplyBulk(c,channel);
10614 addReplyBulk(c,message);
10615 receivers++;
10616 }
10617 }
10618 /* Send to clients listening to matching channels */
10619 if (listLength(server.pubsub_patterns)) {
10620 listRewind(server.pubsub_patterns,&li);
10621 channel = getDecodedObject(channel);
10622 while ((ln = listNext(&li)) != NULL) {
10623 pubsubPattern *pat = ln->value;
10624
10625 if (stringmatchlen((char*)pat->pattern->ptr,
10626 sdslen(pat->pattern->ptr),
10627 (char*)channel->ptr,
10628 sdslen(channel->ptr),0)) {
10629 addReply(pat->client,shared.mbulk4);
10630 addReply(pat->client,shared.pmessagebulk);
10631 addReplyBulk(pat->client,pat->pattern);
10632 addReplyBulk(pat->client,channel);
10633 addReplyBulk(pat->client,message);
10634 receivers++;
10635 }
10636 }
10637 decrRefCount(channel);
10638 }
10639 return receivers;
10640 }
10641
10642 static void subscribeCommand(redisClient *c) {
10643 int j;
10644
10645 for (j = 1; j < c->argc; j++)
10646 pubsubSubscribeChannel(c,c->argv[j]);
10647 }
10648
10649 static void unsubscribeCommand(redisClient *c) {
10650 if (c->argc == 1) {
10651 pubsubUnsubscribeAllChannels(c,1);
10652 return;
10653 } else {
10654 int j;
10655
10656 for (j = 1; j < c->argc; j++)
10657 pubsubUnsubscribeChannel(c,c->argv[j],1);
10658 }
10659 }
10660
10661 static void psubscribeCommand(redisClient *c) {
10662 int j;
10663
10664 for (j = 1; j < c->argc; j++)
10665 pubsubSubscribePattern(c,c->argv[j]);
10666 }
10667
10668 static void punsubscribeCommand(redisClient *c) {
10669 if (c->argc == 1) {
10670 pubsubUnsubscribeAllPatterns(c,1);
10671 return;
10672 } else {
10673 int j;
10674
10675 for (j = 1; j < c->argc; j++)
10676 pubsubUnsubscribePattern(c,c->argv[j],1);
10677 }
10678 }
10679
10680 static void publishCommand(redisClient *c) {
10681 int receivers = pubsubPublishMessage(c->argv[1],c->argv[2]);
10682 addReplyLongLong(c,receivers);
10683 }
10684
10685 /* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
10686 *
10687 * The implementation uses a per-DB hash table mapping keys to list of clients
10688 * WATCHing those keys, so that given a key that is going to be modified
10689 * we can mark all the associated clients as dirty.
10690 *
10691 * Also every client contains a list of WATCHed keys so that's possible to
10692 * un-watch such keys when the client is freed or when UNWATCH is called. */
10693
10694 /* In the client->watched_keys list we need to use watchedKey structures
10695 * as in order to identify a key in Redis we need both the key name and the
10696 * DB */
10697 typedef struct watchedKey {
10698 robj *key;
10699 redisDb *db;
10700 } watchedKey;
10701
10702 /* Watch for the specified key */
10703 static void watchForKey(redisClient *c, robj *key) {
10704 list *clients = NULL;
10705 listIter li;
10706 listNode *ln;
10707 watchedKey *wk;
10708
10709 /* Check if we are already watching for this key */
10710 listRewind(c->watched_keys,&li);
10711 while((ln = listNext(&li))) {
10712 wk = listNodeValue(ln);
10713 if (wk->db == c->db && equalStringObjects(key,wk->key))
10714 return; /* Key already watched */
10715 }
10716 /* This key is not already watched in this DB. Let's add it */
10717 clients = dictFetchValue(c->db->watched_keys,key);
10718 if (!clients) {
10719 clients = listCreate();
10720 dictAdd(c->db->watched_keys,key,clients);
10721 incrRefCount(key);
10722 }
10723 listAddNodeTail(clients,c);
10724 /* Add the new key to the lits of keys watched by this client */
10725 wk = zmalloc(sizeof(*wk));
10726 wk->key = key;
10727 wk->db = c->db;
10728 incrRefCount(key);
10729 listAddNodeTail(c->watched_keys,wk);
10730 }
10731
10732 /* Unwatch all the keys watched by this client. To clean the EXEC dirty
10733 * flag is up to the caller. */
10734 static void unwatchAllKeys(redisClient *c) {
10735 listIter li;
10736 listNode *ln;
10737
10738 if (listLength(c->watched_keys) == 0) return;
10739 listRewind(c->watched_keys,&li);
10740 while((ln = listNext(&li))) {
10741 list *clients;
10742 watchedKey *wk;
10743
10744 /* Lookup the watched key -> clients list and remove the client
10745 * from the list */
10746 wk = listNodeValue(ln);
10747 clients = dictFetchValue(wk->db->watched_keys, wk->key);
10748 assert(clients != NULL);
10749 listDelNode(clients,listSearchKey(clients,c));
10750 /* Kill the entry at all if this was the only client */
10751 if (listLength(clients) == 0)
10752 dictDelete(wk->db->watched_keys, wk->key);
10753 /* Remove this watched key from the client->watched list */
10754 listDelNode(c->watched_keys,ln);
10755 decrRefCount(wk->key);
10756 zfree(wk);
10757 }
10758 }
10759
10760 /* "Touch" a key, so that if this key is being WATCHed by some client the
10761 * next EXEC will fail. */
10762 static void touchWatchedKey(redisDb *db, robj *key) {
10763 list *clients;
10764 listIter li;
10765 listNode *ln;
10766
10767 if (dictSize(db->watched_keys) == 0) return;
10768 clients = dictFetchValue(db->watched_keys, key);
10769 if (!clients) return;
10770
10771 /* Mark all the clients watching this key as REDIS_DIRTY_CAS */
10772 /* Check if we are already watching for this key */
10773 listRewind(clients,&li);
10774 while((ln = listNext(&li))) {
10775 redisClient *c = listNodeValue(ln);
10776
10777 c->flags |= REDIS_DIRTY_CAS;
10778 }
10779 }
10780
10781 /* On FLUSHDB or FLUSHALL all the watched keys that are present before the
10782 * flush but will be deleted as effect of the flushing operation should
10783 * be touched. "dbid" is the DB that's getting the flush. -1 if it is
10784 * a FLUSHALL operation (all the DBs flushed). */
10785 static void touchWatchedKeysOnFlush(int dbid) {
10786 listIter li1, li2;
10787 listNode *ln;
10788
10789 /* For every client, check all the waited keys */
10790 listRewind(server.clients,&li1);
10791 while((ln = listNext(&li1))) {
10792 redisClient *c = listNodeValue(ln);
10793 listRewind(c->watched_keys,&li2);
10794 while((ln = listNext(&li2))) {
10795 watchedKey *wk = listNodeValue(ln);
10796
10797 /* For every watched key matching the specified DB, if the
10798 * key exists, mark the client as dirty, as the key will be
10799 * removed. */
10800 if (dbid == -1 || wk->db->id == dbid) {
10801 if (dictFind(wk->db->dict, wk->key) != NULL)
10802 c->flags |= REDIS_DIRTY_CAS;
10803 }
10804 }
10805 }
10806 }
10807
10808 static void watchCommand(redisClient *c) {
10809 int j;
10810
10811 if (c->flags & REDIS_MULTI) {
10812 addReplySds(c,sdsnew("-ERR WATCH inside MULTI is not allowed\r\n"));
10813 return;
10814 }
10815 for (j = 1; j < c->argc; j++)
10816 watchForKey(c,c->argv[j]);
10817 addReply(c,shared.ok);
10818 }
10819
10820 static void unwatchCommand(redisClient *c) {
10821 unwatchAllKeys(c);
10822 c->flags &= (~REDIS_DIRTY_CAS);
10823 addReply(c,shared.ok);
10824 }
10825
10826 /* ================================= Debugging ============================== */
10827
10828 /* Compute the sha1 of string at 's' with 'len' bytes long.
10829 * The SHA1 is then xored againt the string pointed by digest.
10830 * Since xor is commutative, this operation is used in order to
10831 * "add" digests relative to unordered elements.
10832 *
10833 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10834 static void xorDigest(unsigned char *digest, void *ptr, size_t len) {
10835 SHA1_CTX ctx;
10836 unsigned char hash[20], *s = ptr;
10837 int j;
10838
10839 SHA1Init(&ctx);
10840 SHA1Update(&ctx,s,len);
10841 SHA1Final(hash,&ctx);
10842
10843 for (j = 0; j < 20; j++)
10844 digest[j] ^= hash[j];
10845 }
10846
10847 static void xorObjectDigest(unsigned char *digest, robj *o) {
10848 o = getDecodedObject(o);
10849 xorDigest(digest,o->ptr,sdslen(o->ptr));
10850 decrRefCount(o);
10851 }
10852
10853 /* This function instead of just computing the SHA1 and xoring it
10854 * against diget, also perform the digest of "digest" itself and
10855 * replace the old value with the new one.
10856 *
10857 * So the final digest will be:
10858 *
10859 * digest = SHA1(digest xor SHA1(data))
10860 *
10861 * This function is used every time we want to preserve the order so
10862 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
10863 *
10864 * Also note that mixdigest("foo") followed by mixdigest("bar")
10865 * will lead to a different digest compared to "fo", "obar".
10866 */
10867 static void mixDigest(unsigned char *digest, void *ptr, size_t len) {
10868 SHA1_CTX ctx;
10869 char *s = ptr;
10870
10871 xorDigest(digest,s,len);
10872 SHA1Init(&ctx);
10873 SHA1Update(&ctx,digest,20);
10874 SHA1Final(digest,&ctx);
10875 }
10876
10877 static void mixObjectDigest(unsigned char *digest, robj *o) {
10878 o = getDecodedObject(o);
10879 mixDigest(digest,o->ptr,sdslen(o->ptr));
10880 decrRefCount(o);
10881 }
10882
10883 /* Compute the dataset digest. Since keys, sets elements, hashes elements
10884 * are not ordered, we use a trick: every aggregate digest is the xor
10885 * of the digests of their elements. This way the order will not change
10886 * the result. For list instead we use a feedback entering the output digest
10887 * as input in order to ensure that a different ordered list will result in
10888 * a different digest. */
10889 static void computeDatasetDigest(unsigned char *final) {
10890 unsigned char digest[20];
10891 char buf[128];
10892 dictIterator *di = NULL;
10893 dictEntry *de;
10894 int j;
10895 uint32_t aux;
10896
10897 memset(final,0,20); /* Start with a clean result */
10898
10899 for (j = 0; j < server.dbnum; j++) {
10900 redisDb *db = server.db+j;
10901
10902 if (dictSize(db->dict) == 0) continue;
10903 di = dictGetIterator(db->dict);
10904
10905 /* hash the DB id, so the same dataset moved in a different
10906 * DB will lead to a different digest */
10907 aux = htonl(j);
10908 mixDigest(final,&aux,sizeof(aux));
10909
10910 /* Iterate this DB writing every entry */
10911 while((de = dictNext(di)) != NULL) {
10912 robj *key, *o, *kcopy;
10913 time_t expiretime;
10914
10915 memset(digest,0,20); /* This key-val digest */
10916 key = dictGetEntryKey(de);
10917
10918 if (!server.vm_enabled) {
10919 mixObjectDigest(digest,key);
10920 o = dictGetEntryVal(de);
10921 } else {
10922 /* Don't work with the key directly as when VM is active
10923 * this is unsafe: TODO: fix decrRefCount to check if the
10924 * count really reached 0 to avoid this mess */
10925 kcopy = dupStringObject(key);
10926 mixObjectDigest(digest,kcopy);
10927 o = lookupKeyRead(db,kcopy);
10928 decrRefCount(kcopy);
10929 }
10930 aux = htonl(o->type);
10931 mixDigest(digest,&aux,sizeof(aux));
10932 expiretime = getExpire(db,key);
10933
10934 /* Save the key and associated value */
10935 if (o->type == REDIS_STRING) {
10936 mixObjectDigest(digest,o);
10937 } else if (o->type == REDIS_LIST) {
10938 lIterator *li = lInitIterator(o,0,REDIS_TAIL);
10939 lEntry entry;
10940 while(lNext(li,&entry)) {
10941 robj *eleobj = lGet(&entry);
10942 mixObjectDigest(digest,eleobj);
10943 decrRefCount(eleobj);
10944 }
10945 lReleaseIterator(li);
10946 } else if (o->type == REDIS_SET) {
10947 dict *set = o->ptr;
10948 dictIterator *di = dictGetIterator(set);
10949 dictEntry *de;
10950
10951 while((de = dictNext(di)) != NULL) {
10952 robj *eleobj = dictGetEntryKey(de);
10953
10954 xorObjectDigest(digest,eleobj);
10955 }
10956 dictReleaseIterator(di);
10957 } else if (o->type == REDIS_ZSET) {
10958 zset *zs = o->ptr;
10959 dictIterator *di = dictGetIterator(zs->dict);
10960 dictEntry *de;
10961
10962 while((de = dictNext(di)) != NULL) {
10963 robj *eleobj = dictGetEntryKey(de);
10964 double *score = dictGetEntryVal(de);
10965 unsigned char eledigest[20];
10966
10967 snprintf(buf,sizeof(buf),"%.17g",*score);
10968 memset(eledigest,0,20);
10969 mixObjectDigest(eledigest,eleobj);
10970 mixDigest(eledigest,buf,strlen(buf));
10971 xorDigest(digest,eledigest,20);
10972 }
10973 dictReleaseIterator(di);
10974 } else if (o->type == REDIS_HASH) {
10975 hashIterator *hi;
10976 robj *obj;
10977
10978 hi = hashInitIterator(o);
10979 while (hashNext(hi) != REDIS_ERR) {
10980 unsigned char eledigest[20];
10981
10982 memset(eledigest,0,20);
10983 obj = hashCurrent(hi,REDIS_HASH_KEY);
10984 mixObjectDigest(eledigest,obj);
10985 decrRefCount(obj);
10986 obj = hashCurrent(hi,REDIS_HASH_VALUE);
10987 mixObjectDigest(eledigest,obj);
10988 decrRefCount(obj);
10989 xorDigest(digest,eledigest,20);
10990 }
10991 hashReleaseIterator(hi);
10992 } else {
10993 redisPanic("Unknown object type");
10994 }
10995 /* If the key has an expire, add it to the mix */
10996 if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
10997 /* We can finally xor the key-val digest to the final digest */
10998 xorDigest(final,digest,20);
10999 }
11000 dictReleaseIterator(di);
11001 }
11002 }
11003
11004 static void debugCommand(redisClient *c) {
11005 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
11006 *((char*)-1) = 'x';
11007 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
11008 if (rdbSave(server.dbfilename) != REDIS_OK) {
11009 addReply(c,shared.err);
11010 return;
11011 }
11012 emptyDb();
11013 if (rdbLoad(server.dbfilename) != REDIS_OK) {
11014 addReply(c,shared.err);
11015 return;
11016 }
11017 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
11018 addReply(c,shared.ok);
11019 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
11020 emptyDb();
11021 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
11022 addReply(c,shared.err);
11023 return;
11024 }
11025 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
11026 addReply(c,shared.ok);
11027 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
11028 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
11029 robj *key, *val;
11030
11031 if (!de) {
11032 addReply(c,shared.nokeyerr);
11033 return;
11034 }
11035 key = dictGetEntryKey(de);
11036 val = dictGetEntryVal(de);
11037 if (!server.vm_enabled || (key->storage == REDIS_VM_MEMORY ||
11038 key->storage == REDIS_VM_SWAPPING)) {
11039 char *strenc;
11040 char buf[128];
11041
11042 if (val->encoding < (sizeof(strencoding)/sizeof(char*))) {
11043 strenc = strencoding[val->encoding];
11044 } else {
11045 snprintf(buf,64,"unknown encoding %d\n", val->encoding);
11046 strenc = buf;
11047 }
11048 addReplySds(c,sdscatprintf(sdsempty(),
11049 "+Key at:%p refcount:%d, value at:%p refcount:%d "
11050 "encoding:%s serializedlength:%lld\r\n",
11051 (void*)key, key->refcount, (void*)val, val->refcount,
11052 strenc, (long long) rdbSavedObjectLen(val,NULL)));
11053 } else {
11054 addReplySds(c,sdscatprintf(sdsempty(),
11055 "+Key at:%p refcount:%d, value swapped at: page %llu "
11056 "using %llu pages\r\n",
11057 (void*)key, key->refcount, (unsigned long long) key->vm.page,
11058 (unsigned long long) key->vm.usedpages));
11059 }
11060 } else if (!strcasecmp(c->argv[1]->ptr,"swapin") && c->argc == 3) {
11061 lookupKeyRead(c->db,c->argv[2]);
11062 addReply(c,shared.ok);
11063 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
11064 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
11065 robj *key, *val;
11066
11067 if (!server.vm_enabled) {
11068 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
11069 return;
11070 }
11071 if (!de) {
11072 addReply(c,shared.nokeyerr);
11073 return;
11074 }
11075 key = dictGetEntryKey(de);
11076 val = dictGetEntryVal(de);
11077 /* If the key is shared we want to create a copy */
11078 if (key->refcount > 1) {
11079 robj *newkey = dupStringObject(key);
11080 decrRefCount(key);
11081 key = dictGetEntryKey(de) = newkey;
11082 }
11083 /* Swap it */
11084 if (key->storage != REDIS_VM_MEMORY) {
11085 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
11086 } else if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
11087 dictGetEntryVal(de) = NULL;
11088 addReply(c,shared.ok);
11089 } else {
11090 addReply(c,shared.err);
11091 }
11092 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
11093 long keys, j;
11094 robj *key, *val;
11095 char buf[128];
11096
11097 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
11098 return;
11099 for (j = 0; j < keys; j++) {
11100 snprintf(buf,sizeof(buf),"key:%lu",j);
11101 key = createStringObject(buf,strlen(buf));
11102 if (lookupKeyRead(c->db,key) != NULL) {
11103 decrRefCount(key);
11104 continue;
11105 }
11106 snprintf(buf,sizeof(buf),"value:%lu",j);
11107 val = createStringObject(buf,strlen(buf));
11108 dictAdd(c->db->dict,key,val);
11109 }
11110 addReply(c,shared.ok);
11111 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
11112 unsigned char digest[20];
11113 sds d = sdsnew("+");
11114 int j;
11115
11116 computeDatasetDigest(digest);
11117 for (j = 0; j < 20; j++)
11118 d = sdscatprintf(d, "%02x",digest[j]);
11119
11120 d = sdscatlen(d,"\r\n",2);
11121 addReplySds(c,d);
11122 } else {
11123 addReplySds(c,sdsnew(
11124 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
11125 }
11126 }
11127
11128 static void _redisAssert(char *estr, char *file, int line) {
11129 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
11130 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
11131 #ifdef HAVE_BACKTRACE
11132 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
11133 *((char*)-1) = 'x';
11134 #endif
11135 }
11136
11137 static void _redisPanic(char *msg, char *file, int line) {
11138 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
11139 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
11140 #ifdef HAVE_BACKTRACE
11141 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
11142 *((char*)-1) = 'x';
11143 #endif
11144 }
11145
11146 /* =================================== Main! ================================ */
11147
11148 #ifdef __linux__
11149 int linuxOvercommitMemoryValue(void) {
11150 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
11151 char buf[64];
11152
11153 if (!fp) return -1;
11154 if (fgets(buf,64,fp) == NULL) {
11155 fclose(fp);
11156 return -1;
11157 }
11158 fclose(fp);
11159
11160 return atoi(buf);
11161 }
11162
11163 void linuxOvercommitMemoryWarning(void) {
11164 if (linuxOvercommitMemoryValue() == 0) {
11165 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.");
11166 }
11167 }
11168 #endif /* __linux__ */
11169
11170 static void daemonize(void) {
11171 int fd;
11172 FILE *fp;
11173
11174 if (fork() != 0) exit(0); /* parent exits */
11175 setsid(); /* create a new session */
11176
11177 /* Every output goes to /dev/null. If Redis is daemonized but
11178 * the 'logfile' is set to 'stdout' in the configuration file
11179 * it will not log at all. */
11180 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
11181 dup2(fd, STDIN_FILENO);
11182 dup2(fd, STDOUT_FILENO);
11183 dup2(fd, STDERR_FILENO);
11184 if (fd > STDERR_FILENO) close(fd);
11185 }
11186 /* Try to write the pid file */
11187 fp = fopen(server.pidfile,"w");
11188 if (fp) {
11189 fprintf(fp,"%d\n",getpid());
11190 fclose(fp);
11191 }
11192 }
11193
11194 static void version() {
11195 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
11196 REDIS_GIT_SHA1, atoi(REDIS_GIT_DIRTY) > 0);
11197 exit(0);
11198 }
11199
11200 static void usage() {
11201 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
11202 fprintf(stderr," ./redis-server - (read config from stdin)\n");
11203 exit(1);
11204 }
11205
11206 int main(int argc, char **argv) {
11207 time_t start;
11208
11209 initServerConfig();
11210 sortCommandTable();
11211 if (argc == 2) {
11212 if (strcmp(argv[1], "-v") == 0 ||
11213 strcmp(argv[1], "--version") == 0) version();
11214 if (strcmp(argv[1], "--help") == 0) usage();
11215 resetServerSaveParams();
11216 loadServerConfig(argv[1]);
11217 } else if ((argc > 2)) {
11218 usage();
11219 } else {
11220 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'");
11221 }
11222 if (server.daemonize) daemonize();
11223 initServer();
11224 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
11225 #ifdef __linux__
11226 linuxOvercommitMemoryWarning();
11227 #endif
11228 start = time(NULL);
11229 if (server.appendonly) {
11230 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
11231 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
11232 } else {
11233 if (rdbLoad(server.dbfilename) == REDIS_OK)
11234 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
11235 }
11236 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
11237 aeSetBeforeSleepProc(server.el,beforeSleep);
11238 aeMain(server.el);
11239 aeDeleteEventLoop(server.el);
11240 return 0;
11241 }
11242
11243 /* ============================= Backtrace support ========================= */
11244
11245 #ifdef HAVE_BACKTRACE
11246 static char *findFuncName(void *pointer, unsigned long *offset);
11247
11248 static void *getMcontextEip(ucontext_t *uc) {
11249 #if defined(__FreeBSD__)
11250 return (void*) uc->uc_mcontext.mc_eip;
11251 #elif defined(__dietlibc__)
11252 return (void*) uc->uc_mcontext.eip;
11253 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
11254 #if __x86_64__
11255 return (void*) uc->uc_mcontext->__ss.__rip;
11256 #else
11257 return (void*) uc->uc_mcontext->__ss.__eip;
11258 #endif
11259 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
11260 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
11261 return (void*) uc->uc_mcontext->__ss.__rip;
11262 #else
11263 return (void*) uc->uc_mcontext->__ss.__eip;
11264 #endif
11265 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
11266 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
11267 #elif defined(__ia64__) /* Linux IA64 */
11268 return (void*) uc->uc_mcontext.sc_ip;
11269 #else
11270 return NULL;
11271 #endif
11272 }
11273
11274 static void segvHandler(int sig, siginfo_t *info, void *secret) {
11275 void *trace[100];
11276 char **messages = NULL;
11277 int i, trace_size = 0;
11278 unsigned long offset=0;
11279 ucontext_t *uc = (ucontext_t*) secret;
11280 sds infostring;
11281 REDIS_NOTUSED(info);
11282
11283 redisLog(REDIS_WARNING,
11284 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
11285 infostring = genRedisInfoString();
11286 redisLog(REDIS_WARNING, "%s",infostring);
11287 /* It's not safe to sdsfree() the returned string under memory
11288 * corruption conditions. Let it leak as we are going to abort */
11289
11290 trace_size = backtrace(trace, 100);
11291 /* overwrite sigaction with caller's address */
11292 if (getMcontextEip(uc) != NULL) {
11293 trace[1] = getMcontextEip(uc);
11294 }
11295 messages = backtrace_symbols(trace, trace_size);
11296
11297 for (i=1; i<trace_size; ++i) {
11298 char *fn = findFuncName(trace[i], &offset), *p;
11299
11300 p = strchr(messages[i],'+');
11301 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
11302 redisLog(REDIS_WARNING,"%s", messages[i]);
11303 } else {
11304 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
11305 }
11306 }
11307 /* free(messages); Don't call free() with possibly corrupted memory. */
11308 _exit(0);
11309 }
11310
11311 static void sigtermHandler(int sig) {
11312 REDIS_NOTUSED(sig);
11313
11314 redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
11315 server.shutdown_asap = 1;
11316 }
11317
11318 static void setupSigSegvAction(void) {
11319 struct sigaction act;
11320
11321 sigemptyset (&act.sa_mask);
11322 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
11323 * is used. Otherwise, sa_handler is used */
11324 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
11325 act.sa_sigaction = segvHandler;
11326 sigaction (SIGSEGV, &act, NULL);
11327 sigaction (SIGBUS, &act, NULL);
11328 sigaction (SIGFPE, &act, NULL);
11329 sigaction (SIGILL, &act, NULL);
11330 sigaction (SIGBUS, &act, NULL);
11331
11332 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
11333 act.sa_handler = sigtermHandler;
11334 sigaction (SIGTERM, &act, NULL);
11335 return;
11336 }
11337
11338 #include "staticsymbols.h"
11339 /* This function try to convert a pointer into a function name. It's used in
11340 * oreder to provide a backtrace under segmentation fault that's able to
11341 * display functions declared as static (otherwise the backtrace is useless). */
11342 static char *findFuncName(void *pointer, unsigned long *offset){
11343 int i, ret = -1;
11344 unsigned long off, minoff = 0;
11345
11346 /* Try to match against the Symbol with the smallest offset */
11347 for (i=0; symsTable[i].pointer; i++) {
11348 unsigned long lp = (unsigned long) pointer;
11349
11350 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
11351 off=lp-symsTable[i].pointer;
11352 if (ret < 0 || off < minoff) {
11353 minoff=off;
11354 ret=i;
11355 }
11356 }
11357 }
11358 if (ret == -1) return NULL;
11359 *offset = minoff;
11360 return symsTable[ret].name;
11361 }
11362 #else /* HAVE_BACKTRACE */
11363 static void setupSigSegvAction(void) {
11364 }
11365 #endif /* HAVE_BACKTRACE */
11366
11367
11368
11369 /* The End */
11370
11371
11372