]> git.saurik.com Git - redis.git/blob - redis.c
bc67235714f51c041f225c4404f699d48cc3e4aa
[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 "sha1.h" /* SHA1 is used for DEBUG DIGEST */
79 #include "release.h" /* Release and/or git repository information */
80
81 /* Error codes */
82 #define REDIS_OK 0
83 #define REDIS_ERR -1
84
85 /* Static server configuration */
86 #define REDIS_SERVERPORT 6379 /* TCP port */
87 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
88 #define REDIS_IOBUF_LEN 1024
89 #define REDIS_LOADBUF_LEN 1024
90 #define REDIS_STATIC_ARGS 8
91 #define REDIS_DEFAULT_DBNUM 16
92 #define REDIS_CONFIGLINE_MAX 1024
93 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
94 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
95 #define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
96 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
97 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
98
99 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
100 #define REDIS_WRITEV_THRESHOLD 3
101 /* Max number of iovecs used for each writev call */
102 #define REDIS_WRITEV_IOVEC_COUNT 256
103
104 /* Hash table parameters */
105 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
106
107 /* Command flags */
108 #define REDIS_CMD_BULK 1 /* Bulk write command */
109 #define REDIS_CMD_INLINE 2 /* Inline command */
110 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
111 this flags will return an error when the 'maxmemory' option is set in the
112 config file and the server is using more than maxmemory bytes of memory.
113 In short this commands are denied on low memory conditions. */
114 #define REDIS_CMD_DENYOOM 4
115 #define REDIS_CMD_FORCE_REPLICATION 8 /* Force replication even if dirty is 0 */
116
117 /* Object types */
118 #define REDIS_STRING 0
119 #define REDIS_LIST 1
120 #define REDIS_SET 2
121 #define REDIS_ZSET 3
122 #define REDIS_HASH 4
123 #define REDIS_VMPOINTER 8
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_ZIPMAP 2 /* Encoded as zipmap */
131 #define REDIS_ENCODING_HT 3 /* Encoded as an hash table */
132
133 static char* strencoding[] = {
134 "raw", "int", "zipmap", "hashtable"
135 };
136
137 /* Object types only used for dumping to disk */
138 #define REDIS_EXPIRETIME 253
139 #define REDIS_SELECTDB 254
140 #define REDIS_EOF 255
141
142 /* Defines related to the dump file format. To store 32 bits lengths for short
143 * keys requires a lot of space, so we check the most significant 2 bits of
144 * the first byte to interpreter the length:
145 *
146 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
147 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
148 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
149 * 11|000000 this means: specially encoded object will follow. The six bits
150 * number specify the kind of object that follows.
151 * See the REDIS_RDB_ENC_* defines.
152 *
153 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
154 * values, will fit inside. */
155 #define REDIS_RDB_6BITLEN 0
156 #define REDIS_RDB_14BITLEN 1
157 #define REDIS_RDB_32BITLEN 2
158 #define REDIS_RDB_ENCVAL 3
159 #define REDIS_RDB_LENERR UINT_MAX
160
161 /* When a length of a string object stored on disk has the first two bits
162 * set, the remaining two bits specify a special encoding for the object
163 * accordingly to the following defines: */
164 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
165 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
166 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
167 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
168
169 /* Virtual memory object->where field. */
170 #define REDIS_VM_MEMORY 0 /* The object is on memory */
171 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
172 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
173 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
174
175 /* Virtual memory static configuration stuff.
176 * Check vmFindContiguousPages() to know more about this magic numbers. */
177 #define REDIS_VM_MAX_NEAR_PAGES 65536
178 #define REDIS_VM_MAX_RANDOM_JUMP 4096
179 #define REDIS_VM_MAX_THREADS 32
180 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
181 /* The following is the *percentage* of completed I/O jobs to process when the
182 * handelr is called. While Virtual Memory I/O operations are performed by
183 * threads, this operations must be processed by the main thread when completed
184 * in order to take effect. */
185 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
186
187 /* Client flags */
188 #define REDIS_SLAVE 1 /* This client is a slave server */
189 #define REDIS_MASTER 2 /* This client is a master server */
190 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
191 #define REDIS_MULTI 8 /* This client is in a MULTI context */
192 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
193 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
194 #define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
195
196 /* Slave replication state - slave side */
197 #define REDIS_REPL_NONE 0 /* No active replication */
198 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
199 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
200
201 /* Slave replication state - from the point of view of master
202 * Note that in SEND_BULK and ONLINE state the slave receives new updates
203 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
204 * to start the next background saving in order to send updates to it. */
205 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
206 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
207 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
208 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
209
210 /* List related stuff */
211 #define REDIS_HEAD 0
212 #define REDIS_TAIL 1
213
214 /* Sort operations */
215 #define REDIS_SORT_GET 0
216 #define REDIS_SORT_ASC 1
217 #define REDIS_SORT_DESC 2
218 #define REDIS_SORTKEY_MAX 1024
219
220 /* Log levels */
221 #define REDIS_DEBUG 0
222 #define REDIS_VERBOSE 1
223 #define REDIS_NOTICE 2
224 #define REDIS_WARNING 3
225
226 /* Anti-warning macro... */
227 #define REDIS_NOTUSED(V) ((void) V)
228
229 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
230 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
231
232 /* Append only defines */
233 #define APPENDFSYNC_NO 0
234 #define APPENDFSYNC_ALWAYS 1
235 #define APPENDFSYNC_EVERYSEC 2
236
237 /* Hashes related defaults */
238 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
239 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
240
241 /* We can print the stacktrace, so our assert is defined this way: */
242 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
243 #define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
244 static void _redisAssert(char *estr, char *file, int line);
245 static void _redisPanic(char *msg, char *file, int line);
246
247 /*================================= Data types ============================== */
248
249 /* A redis object, that is a type able to hold a string / list / set */
250
251 /* The actual Redis Object */
252 typedef struct redisObject {
253 unsigned type:4;
254 unsigned storage:2; /* REDIS_VM_MEMORY or REDIS_VM_SWAPPING */
255 unsigned encoding:4;
256 unsigned lru:22; /* lru time (relative to server.lruclock) */
257 int refcount;
258 void *ptr;
259 /* VM fields, this are only allocated if VM is active, otherwise the
260 * object allocation function will just allocate
261 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
262 * Redis without VM active will not have any overhead. */
263 } robj;
264
265 /* The VM pointer structure - identifies an object in the swap file.
266 *
267 * This object is stored in place of the value
268 * object in the main key->value hash table representing a database.
269 * Note that the first fields (type, storage) are the same as the redisObject
270 * structure so that vmPointer strucuters can be accessed even when casted
271 * as redisObject structures.
272 *
273 * This is useful as we don't know if a value object is or not on disk, but we
274 * are always free of accessing obj->storage to check this. For vmPointer
275 * structures "type" is set to REDIS_VMPOINTER (even if without this field
276 * is still possible to check the kind of object from the value of 'storage').*/
277 typedef struct vmPointer {
278 unsigned type:4;
279 unsigned storage:2; /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
280 unsigned notused:26;
281 unsigned int vtype; /* type of the object stored in the swap file */
282 off_t page; /* the page at witch the object is stored on disk */
283 off_t usedpages; /* number of pages used on disk */
284 } vmpointer;
285
286 /* Macro used to initalize a Redis object allocated on the stack.
287 * Note that this macro is taken near the structure definition to make sure
288 * we'll update it when the structure is changed, to avoid bugs like
289 * bug #85 introduced exactly in this way. */
290 #define initStaticStringObject(_var,_ptr) do { \
291 _var.refcount = 1; \
292 _var.type = REDIS_STRING; \
293 _var.encoding = REDIS_ENCODING_RAW; \
294 _var.ptr = _ptr; \
295 _var.storage = REDIS_VM_MEMORY; \
296 } while(0);
297
298 typedef struct redisDb {
299 dict *dict; /* The keyspace for this DB */
300 dict *expires; /* Timeout of keys with a timeout set */
301 dict *blocking_keys; /* Keys with clients waiting for data (BLPOP) */
302 dict *io_keys; /* Keys with clients waiting for VM I/O */
303 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
304 int id;
305 } redisDb;
306
307 /* Client MULTI/EXEC state */
308 typedef struct multiCmd {
309 robj **argv;
310 int argc;
311 struct redisCommand *cmd;
312 } multiCmd;
313
314 typedef struct multiState {
315 multiCmd *commands; /* Array of MULTI commands */
316 int count; /* Total number of MULTI commands */
317 } multiState;
318
319 /* With multiplexing we need to take per-clinet state.
320 * Clients are taken in a liked list. */
321 typedef struct redisClient {
322 int fd;
323 redisDb *db;
324 int dictid;
325 sds querybuf;
326 robj **argv, **mbargv;
327 int argc, mbargc;
328 int bulklen; /* bulk read len. -1 if not in bulk read mode */
329 int multibulk; /* multi bulk command format active */
330 list *reply;
331 int sentlen;
332 time_t lastinteraction; /* time of the last interaction, used for timeout */
333 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
334 int slaveseldb; /* slave selected db, if this client is a slave */
335 int authenticated; /* when requirepass is non-NULL */
336 int replstate; /* replication state if this is a slave */
337 int repldbfd; /* replication DB file descriptor */
338 long repldboff; /* replication DB file offset */
339 off_t repldbsize; /* replication DB file size */
340 multiState mstate; /* MULTI/EXEC state */
341 robj **blocking_keys; /* The key we are waiting to terminate a blocking
342 * operation such as BLPOP. Otherwise NULL. */
343 int blocking_keys_num; /* Number of blocking keys */
344 time_t blockingto; /* Blocking operation timeout. If UNIX current time
345 * is >= blockingto then the operation timed out. */
346 list *io_keys; /* Keys this client is waiting to be loaded from the
347 * swap file in order to continue. */
348 list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */
349 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
350 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
351 } redisClient;
352
353 struct saveparam {
354 time_t seconds;
355 int changes;
356 };
357
358 /* Global server state structure */
359 struct redisServer {
360 int port;
361 int fd;
362 redisDb *db;
363 long long dirty; /* changes to DB from the last save */
364 list *clients;
365 list *slaves, *monitors;
366 char neterr[ANET_ERR_LEN];
367 aeEventLoop *el;
368 int cronloops; /* number of times the cron function run */
369 list *objfreelist; /* A list of freed objects to avoid malloc() */
370 time_t lastsave; /* Unix time of last save succeeede */
371 /* Fields used only for stats */
372 time_t stat_starttime; /* server start time */
373 long long stat_numcommands; /* number of processed commands */
374 long long stat_numconnections; /* number of connections received */
375 long long stat_expiredkeys; /* number of expired keys */
376 /* Configuration */
377 int verbosity;
378 int glueoutputbuf;
379 int maxidletime;
380 int dbnum;
381 int daemonize;
382 int appendonly;
383 int appendfsync;
384 int no_appendfsync_on_rewrite;
385 int shutdown_asap;
386 time_t lastfsync;
387 int appendfd;
388 int appendseldb;
389 char *pidfile;
390 pid_t bgsavechildpid;
391 pid_t bgrewritechildpid;
392 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
393 sds aofbuf; /* AOF buffer, written before entering the event loop */
394 struct saveparam *saveparams;
395 int saveparamslen;
396 char *logfile;
397 char *bindaddr;
398 char *dbfilename;
399 char *appendfilename;
400 char *requirepass;
401 int rdbcompression;
402 int activerehashing;
403 /* Replication related */
404 int isslave;
405 char *masterauth;
406 char *masterhost;
407 int masterport;
408 redisClient *master; /* client that is master for this slave */
409 int replstate;
410 unsigned int maxclients;
411 unsigned long long maxmemory;
412 unsigned int blpop_blocked_clients;
413 unsigned int vm_blocked_clients;
414 /* Sort parameters - qsort_r() is only available under BSD so we
415 * have to take this state global, in order to pass it to sortCompare() */
416 int sort_desc;
417 int sort_alpha;
418 int sort_bypattern;
419 /* Virtual memory configuration */
420 int vm_enabled;
421 char *vm_swap_file;
422 off_t vm_page_size;
423 off_t vm_pages;
424 unsigned long long vm_max_memory;
425 /* Hashes config */
426 size_t hash_max_zipmap_entries;
427 size_t hash_max_zipmap_value;
428 /* Virtual memory state */
429 FILE *vm_fp;
430 int vm_fd;
431 off_t vm_next_page; /* Next probably empty page */
432 off_t vm_near_pages; /* Number of pages allocated sequentially */
433 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
434 time_t unixtime; /* Unix time sampled every second. */
435 /* Virtual memory I/O threads stuff */
436 /* An I/O thread process an element taken from the io_jobs queue and
437 * put the result of the operation in the io_done list. While the
438 * job is being processed, it's put on io_processing queue. */
439 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
440 list *io_processing; /* List of VM I/O jobs being processed */
441 list *io_processed; /* List of VM I/O jobs already processed */
442 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
443 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
444 pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
445 pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
446 pthread_attr_t io_threads_attr; /* attributes for threads creation */
447 int io_active_threads; /* Number of running I/O threads */
448 int vm_max_threads; /* Max number of I/O threads running at the same time */
449 /* Our main thread is blocked on the event loop, locking for sockets ready
450 * to be read or written, so when a threaded I/O operation is ready to be
451 * processed by the main thread, the I/O thread will use a unix pipe to
452 * awake the main thread. The followings are the two pipe FDs. */
453 int io_ready_pipe_read;
454 int io_ready_pipe_write;
455 /* Virtual memory stats */
456 unsigned long long vm_stats_used_pages;
457 unsigned long long vm_stats_swapped_objects;
458 unsigned long long vm_stats_swapouts;
459 unsigned long long vm_stats_swapins;
460 /* Pubsub */
461 dict *pubsub_channels; /* Map channels to list of subscribed clients */
462 list *pubsub_patterns; /* A list of pubsub_patterns */
463 /* Misc */
464 FILE *devnull;
465 unsigned lruclock:22; /* clock incrementing every minute, for LRU */
466 unsigned lruclock_padding:10;
467 };
468
469 typedef struct pubsubPattern {
470 redisClient *client;
471 robj *pattern;
472 } pubsubPattern;
473
474 typedef void redisCommandProc(redisClient *c);
475 typedef void redisVmPreloadProc(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
476 struct redisCommand {
477 char *name;
478 redisCommandProc *proc;
479 int arity;
480 int flags;
481 /* Use a function to determine which keys need to be loaded
482 * in the background prior to executing this command. Takes precedence
483 * over vm_firstkey and others, ignored when NULL */
484 redisVmPreloadProc *vm_preload_proc;
485 /* What keys should be loaded in background when calling this command? */
486 int vm_firstkey; /* The first argument that's a key (0 = no keys) */
487 int vm_lastkey; /* THe last argument that's a key */
488 int vm_keystep; /* The step between first and last key */
489 };
490
491 struct redisFunctionSym {
492 char *name;
493 unsigned long pointer;
494 };
495
496 typedef struct _redisSortObject {
497 robj *obj;
498 union {
499 double score;
500 robj *cmpobj;
501 } u;
502 } redisSortObject;
503
504 typedef struct _redisSortOperation {
505 int type;
506 robj *pattern;
507 } redisSortOperation;
508
509 /* ZSETs use a specialized version of Skiplists */
510
511 typedef struct zskiplistNode {
512 struct zskiplistNode **forward;
513 struct zskiplistNode *backward;
514 unsigned int *span;
515 double score;
516 robj *obj;
517 } zskiplistNode;
518
519 typedef struct zskiplist {
520 struct zskiplistNode *header, *tail;
521 unsigned long length;
522 int level;
523 } zskiplist;
524
525 typedef struct zset {
526 dict *dict;
527 zskiplist *zsl;
528 } zset;
529
530 /* Our shared "common" objects */
531
532 #define REDIS_SHARED_INTEGERS 10000
533 struct sharedObjectsStruct {
534 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
535 *colon, *nullbulk, *nullmultibulk, *queued,
536 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
537 *outofrangeerr, *plus,
538 *select0, *select1, *select2, *select3, *select4,
539 *select5, *select6, *select7, *select8, *select9,
540 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk, *mbulk3,
541 *mbulk4, *psubscribebulk, *punsubscribebulk,
542 *integers[REDIS_SHARED_INTEGERS];
543 } shared;
544
545 /* Global vars that are actally used as constants. The following double
546 * values are used for double on-disk serialization, and are initialized
547 * at runtime to avoid strange compiler optimizations. */
548
549 static double R_Zero, R_PosInf, R_NegInf, R_Nan;
550
551 /* VM threaded I/O request message */
552 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
553 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
554 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
555 typedef struct iojob {
556 int type; /* Request type, REDIS_IOJOB_* */
557 redisDb *db;/* Redis database */
558 robj *key; /* This I/O request is about swapping this key */
559 robj *id; /* Unique identifier of this job:
560 this is the object to swap for REDIS_IOREQ_*_SWAP, or the
561 vmpointer objct for REDIS_IOREQ_LOAD. */
562 robj *val; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
563 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
564 off_t page; /* Swap page where to read/write the object */
565 off_t pages; /* Swap pages needed to save object. PREPARE_SWAP return val */
566 int canceled; /* True if this command was canceled by blocking side of VM */
567 pthread_t thread; /* ID of the thread processing this entry */
568 } iojob;
569
570 /*================================ Prototypes =============================== */
571
572 static void freeStringObject(robj *o);
573 static void freeListObject(robj *o);
574 static void freeSetObject(robj *o);
575 static void decrRefCount(void *o);
576 static robj *createObject(int type, void *ptr);
577 static void freeClient(redisClient *c);
578 static int rdbLoad(char *filename);
579 static void addReply(redisClient *c, robj *obj);
580 static void addReplySds(redisClient *c, sds s);
581 static void incrRefCount(robj *o);
582 static int rdbSaveBackground(char *filename);
583 static robj *createStringObject(char *ptr, size_t len);
584 static robj *dupStringObject(robj *o);
585 static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
586 static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
587 static void flushAppendOnlyFile(void);
588 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
589 static int syncWithMaster(void);
590 static robj *tryObjectEncoding(robj *o);
591 static robj *getDecodedObject(robj *o);
592 static int removeExpire(redisDb *db, robj *key);
593 static int expireIfNeeded(redisDb *db, robj *key);
594 static int deleteIfVolatile(redisDb *db, robj *key);
595 static int deleteIfSwapped(redisDb *db, robj *key);
596 static int deleteKey(redisDb *db, robj *key);
597 static time_t getExpire(redisDb *db, robj *key);
598 static int setExpire(redisDb *db, robj *key, time_t when);
599 static void updateSlavesWaitingBgsave(int bgsaveerr);
600 static void freeMemoryIfNeeded(void);
601 static int processCommand(redisClient *c);
602 static void setupSigSegvAction(void);
603 static void rdbRemoveTempFile(pid_t childpid);
604 static void aofRemoveTempFile(pid_t childpid);
605 static size_t stringObjectLen(robj *o);
606 static void processInputBuffer(redisClient *c);
607 static zskiplist *zslCreate(void);
608 static void zslFree(zskiplist *zsl);
609 static void zslInsert(zskiplist *zsl, double score, robj *obj);
610 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
611 static void initClientMultiState(redisClient *c);
612 static void freeClientMultiState(redisClient *c);
613 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
614 static void unblockClientWaitingData(redisClient *c);
615 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
616 static void vmInit(void);
617 static void vmMarkPagesFree(off_t page, off_t count);
618 static robj *vmLoadObject(robj *o);
619 static robj *vmPreviewObject(robj *o);
620 static int vmSwapOneObjectBlocking(void);
621 static int vmSwapOneObjectThreaded(void);
622 static int vmCanSwapOut(void);
623 static int tryFreeOneObjectFromFreelist(void);
624 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
625 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
626 static void vmCancelThreadedIOJob(robj *o);
627 static void lockThreadedIO(void);
628 static void unlockThreadedIO(void);
629 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
630 static void freeIOJob(iojob *j);
631 static void queueIOJob(iojob *j);
632 static int vmWriteObjectOnSwap(robj *o, off_t page);
633 static robj *vmReadObjectFromSwap(off_t page, int type);
634 static void waitEmptyIOJobsQueue(void);
635 static void vmReopenSwapFile(void);
636 static int vmFreePage(off_t page);
637 static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
638 static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
639 static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd);
640 static int dontWaitForSwappedKey(redisClient *c, robj *key);
641 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
642 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
643 static struct redisCommand *lookupCommand(char *name);
644 static void call(redisClient *c, struct redisCommand *cmd);
645 static void resetClient(redisClient *c);
646 static void convertToRealHash(robj *o);
647 static int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
648 static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
649 static void freePubsubPattern(void *p);
650 static int listMatchPubsubPattern(void *a, void *b);
651 static int compareStringObjects(robj *a, robj *b);
652 static int equalStringObjects(robj *a, robj *b);
653 static void usage();
654 static int rewriteAppendOnlyFileBackground(void);
655 static vmpointer *vmSwapObjectBlocking(robj *val);
656 static int prepareForShutdown();
657 static void touchWatchedKey(redisDb *db, robj *key);
658 static void touchWatchedKeysOnFlush(int dbid);
659 static void unwatchAllKeys(redisClient *c);
660
661 static void authCommand(redisClient *c);
662 static void pingCommand(redisClient *c);
663 static void echoCommand(redisClient *c);
664 static void setCommand(redisClient *c);
665 static void setnxCommand(redisClient *c);
666 static void setexCommand(redisClient *c);
667 static void getCommand(redisClient *c);
668 static void delCommand(redisClient *c);
669 static void existsCommand(redisClient *c);
670 static void incrCommand(redisClient *c);
671 static void decrCommand(redisClient *c);
672 static void incrbyCommand(redisClient *c);
673 static void decrbyCommand(redisClient *c);
674 static void selectCommand(redisClient *c);
675 static void randomkeyCommand(redisClient *c);
676 static void keysCommand(redisClient *c);
677 static void dbsizeCommand(redisClient *c);
678 static void lastsaveCommand(redisClient *c);
679 static void saveCommand(redisClient *c);
680 static void bgsaveCommand(redisClient *c);
681 static void bgrewriteaofCommand(redisClient *c);
682 static void shutdownCommand(redisClient *c);
683 static void moveCommand(redisClient *c);
684 static void renameCommand(redisClient *c);
685 static void renamenxCommand(redisClient *c);
686 static void lpushCommand(redisClient *c);
687 static void rpushCommand(redisClient *c);
688 static void lpopCommand(redisClient *c);
689 static void rpopCommand(redisClient *c);
690 static void llenCommand(redisClient *c);
691 static void lindexCommand(redisClient *c);
692 static void lrangeCommand(redisClient *c);
693 static void ltrimCommand(redisClient *c);
694 static void typeCommand(redisClient *c);
695 static void lsetCommand(redisClient *c);
696 static void saddCommand(redisClient *c);
697 static void sremCommand(redisClient *c);
698 static void smoveCommand(redisClient *c);
699 static void sismemberCommand(redisClient *c);
700 static void scardCommand(redisClient *c);
701 static void spopCommand(redisClient *c);
702 static void srandmemberCommand(redisClient *c);
703 static void sinterCommand(redisClient *c);
704 static void sinterstoreCommand(redisClient *c);
705 static void sunionCommand(redisClient *c);
706 static void sunionstoreCommand(redisClient *c);
707 static void sdiffCommand(redisClient *c);
708 static void sdiffstoreCommand(redisClient *c);
709 static void syncCommand(redisClient *c);
710 static void flushdbCommand(redisClient *c);
711 static void flushallCommand(redisClient *c);
712 static void sortCommand(redisClient *c);
713 static void lremCommand(redisClient *c);
714 static void rpoplpushcommand(redisClient *c);
715 static void infoCommand(redisClient *c);
716 static void mgetCommand(redisClient *c);
717 static void monitorCommand(redisClient *c);
718 static void expireCommand(redisClient *c);
719 static void expireatCommand(redisClient *c);
720 static void getsetCommand(redisClient *c);
721 static void ttlCommand(redisClient *c);
722 static void slaveofCommand(redisClient *c);
723 static void debugCommand(redisClient *c);
724 static void msetCommand(redisClient *c);
725 static void msetnxCommand(redisClient *c);
726 static void zaddCommand(redisClient *c);
727 static void zincrbyCommand(redisClient *c);
728 static void zrangeCommand(redisClient *c);
729 static void zrangebyscoreCommand(redisClient *c);
730 static void zcountCommand(redisClient *c);
731 static void zrevrangeCommand(redisClient *c);
732 static void zcardCommand(redisClient *c);
733 static void zremCommand(redisClient *c);
734 static void zscoreCommand(redisClient *c);
735 static void zremrangebyscoreCommand(redisClient *c);
736 static void multiCommand(redisClient *c);
737 static void execCommand(redisClient *c);
738 static void discardCommand(redisClient *c);
739 static void blpopCommand(redisClient *c);
740 static void brpopCommand(redisClient *c);
741 static void appendCommand(redisClient *c);
742 static void substrCommand(redisClient *c);
743 static void zrankCommand(redisClient *c);
744 static void zrevrankCommand(redisClient *c);
745 static void hsetCommand(redisClient *c);
746 static void hsetnxCommand(redisClient *c);
747 static void hgetCommand(redisClient *c);
748 static void hmsetCommand(redisClient *c);
749 static void hmgetCommand(redisClient *c);
750 static void hdelCommand(redisClient *c);
751 static void hlenCommand(redisClient *c);
752 static void zremrangebyrankCommand(redisClient *c);
753 static void zunionstoreCommand(redisClient *c);
754 static void zinterstoreCommand(redisClient *c);
755 static void hkeysCommand(redisClient *c);
756 static void hvalsCommand(redisClient *c);
757 static void hgetallCommand(redisClient *c);
758 static void hexistsCommand(redisClient *c);
759 static void configCommand(redisClient *c);
760 static void hincrbyCommand(redisClient *c);
761 static void subscribeCommand(redisClient *c);
762 static void unsubscribeCommand(redisClient *c);
763 static void psubscribeCommand(redisClient *c);
764 static void punsubscribeCommand(redisClient *c);
765 static void publishCommand(redisClient *c);
766 static void watchCommand(redisClient *c);
767 static void unwatchCommand(redisClient *c);
768
769 /*================================= Globals ================================= */
770
771 /* Global vars */
772 static struct redisServer server; /* server global state */
773 static struct redisCommand *commandTable;
774 static struct redisCommand readonlyCommandTable[] = {
775 {"get",getCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
776 {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
777 {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
778 {"setex",setexCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
779 {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
780 {"substr",substrCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
781 {"del",delCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
782 {"exists",existsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
783 {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
784 {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
785 {"mget",mgetCommand,-2,REDIS_CMD_INLINE,NULL,1,-1,1},
786 {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
787 {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
788 {"rpop",rpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
789 {"lpop",lpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
790 {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
791 {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
792 {"llen",llenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
793 {"lindex",lindexCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
794 {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
795 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
796 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
797 {"lrem",lremCommand,4,REDIS_CMD_BULK,NULL,1,1,1},
798 {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,2,1},
799 {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
800 {"srem",sremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
801 {"smove",smoveCommand,4,REDIS_CMD_BULK,NULL,1,2,1},
802 {"sismember",sismemberCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
803 {"scard",scardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
804 {"spop",spopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
805 {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
806 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
807 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
808 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
809 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
810 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
811 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
812 {"smembers",sinterCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
813 {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
814 {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
815 {"zrem",zremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
816 {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
817 {"zremrangebyrank",zremrangebyrankCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
818 {"zunionstore",zunionstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
819 {"zinterstore",zinterstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
820 {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
821 {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
822 {"zcount",zcountCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
823 {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
824 {"zcard",zcardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
825 {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
826 {"zrank",zrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
827 {"zrevrank",zrevrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
828 {"hset",hsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
829 {"hsetnx",hsetnxCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
830 {"hget",hgetCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
831 {"hmset",hmsetCommand,-4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
832 {"hmget",hmgetCommand,-3,REDIS_CMD_BULK,NULL,1,1,1},
833 {"hincrby",hincrbyCommand,4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
834 {"hdel",hdelCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
835 {"hlen",hlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
836 {"hkeys",hkeysCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
837 {"hvals",hvalsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
838 {"hgetall",hgetallCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
839 {"hexists",hexistsCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
840 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
841 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
842 {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
843 {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
844 {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
845 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
846 {"select",selectCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
847 {"move",moveCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
848 {"rename",renameCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
849 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
850 {"expire",expireCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
851 {"expireat",expireatCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
852 {"keys",keysCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
853 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
854 {"auth",authCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
855 {"ping",pingCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
856 {"echo",echoCommand,2,REDIS_CMD_BULK,NULL,0,0,0},
857 {"save",saveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
858 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
859 {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
860 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
861 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
862 {"type",typeCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
863 {"multi",multiCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
864 {"exec",execCommand,1,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0},
865 {"discard",discardCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
866 {"sync",syncCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
867 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
868 {"flushall",flushallCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
869 {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
870 {"info",infoCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
871 {"monitor",monitorCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
872 {"ttl",ttlCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
873 {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
874 {"debug",debugCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
875 {"config",configCommand,-2,REDIS_CMD_BULK,NULL,0,0,0},
876 {"subscribe",subscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
877 {"unsubscribe",unsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
878 {"psubscribe",psubscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
879 {"punsubscribe",punsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
880 {"publish",publishCommand,3,REDIS_CMD_BULK|REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0},
881 {"watch",watchCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
882 {"unwatch",unwatchCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}
883 };
884
885 /*============================ Utility functions ============================ */
886
887 /* Glob-style pattern matching. */
888 static int stringmatchlen(const char *pattern, int patternLen,
889 const char *string, int stringLen, int nocase)
890 {
891 while(patternLen) {
892 switch(pattern[0]) {
893 case '*':
894 while (pattern[1] == '*') {
895 pattern++;
896 patternLen--;
897 }
898 if (patternLen == 1)
899 return 1; /* match */
900 while(stringLen) {
901 if (stringmatchlen(pattern+1, patternLen-1,
902 string, stringLen, nocase))
903 return 1; /* match */
904 string++;
905 stringLen--;
906 }
907 return 0; /* no match */
908 break;
909 case '?':
910 if (stringLen == 0)
911 return 0; /* no match */
912 string++;
913 stringLen--;
914 break;
915 case '[':
916 {
917 int not, match;
918
919 pattern++;
920 patternLen--;
921 not = pattern[0] == '^';
922 if (not) {
923 pattern++;
924 patternLen--;
925 }
926 match = 0;
927 while(1) {
928 if (pattern[0] == '\\') {
929 pattern++;
930 patternLen--;
931 if (pattern[0] == string[0])
932 match = 1;
933 } else if (pattern[0] == ']') {
934 break;
935 } else if (patternLen == 0) {
936 pattern--;
937 patternLen++;
938 break;
939 } else if (pattern[1] == '-' && patternLen >= 3) {
940 int start = pattern[0];
941 int end = pattern[2];
942 int c = string[0];
943 if (start > end) {
944 int t = start;
945 start = end;
946 end = t;
947 }
948 if (nocase) {
949 start = tolower(start);
950 end = tolower(end);
951 c = tolower(c);
952 }
953 pattern += 2;
954 patternLen -= 2;
955 if (c >= start && c <= end)
956 match = 1;
957 } else {
958 if (!nocase) {
959 if (pattern[0] == string[0])
960 match = 1;
961 } else {
962 if (tolower((int)pattern[0]) == tolower((int)string[0]))
963 match = 1;
964 }
965 }
966 pattern++;
967 patternLen--;
968 }
969 if (not)
970 match = !match;
971 if (!match)
972 return 0; /* no match */
973 string++;
974 stringLen--;
975 break;
976 }
977 case '\\':
978 if (patternLen >= 2) {
979 pattern++;
980 patternLen--;
981 }
982 /* fall through */
983 default:
984 if (!nocase) {
985 if (pattern[0] != string[0])
986 return 0; /* no match */
987 } else {
988 if (tolower((int)pattern[0]) != tolower((int)string[0]))
989 return 0; /* no match */
990 }
991 string++;
992 stringLen--;
993 break;
994 }
995 pattern++;
996 patternLen--;
997 if (stringLen == 0) {
998 while(*pattern == '*') {
999 pattern++;
1000 patternLen--;
1001 }
1002 break;
1003 }
1004 }
1005 if (patternLen == 0 && stringLen == 0)
1006 return 1;
1007 return 0;
1008 }
1009
1010 static int stringmatch(const char *pattern, const char *string, int nocase) {
1011 return stringmatchlen(pattern,strlen(pattern),string,strlen(string),nocase);
1012 }
1013
1014 /* Convert a string representing an amount of memory into the number of
1015 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
1016 * (1024*1024*1024).
1017 *
1018 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
1019 * set to 0 */
1020 static long long memtoll(const char *p, int *err) {
1021 const char *u;
1022 char buf[128];
1023 long mul; /* unit multiplier */
1024 long long val;
1025 unsigned int digits;
1026
1027 if (err) *err = 0;
1028 /* Search the first non digit character. */
1029 u = p;
1030 if (*u == '-') u++;
1031 while(*u && isdigit(*u)) u++;
1032 if (*u == '\0' || !strcasecmp(u,"b")) {
1033 mul = 1;
1034 } else if (!strcasecmp(u,"k")) {
1035 mul = 1000;
1036 } else if (!strcasecmp(u,"kb")) {
1037 mul = 1024;
1038 } else if (!strcasecmp(u,"m")) {
1039 mul = 1000*1000;
1040 } else if (!strcasecmp(u,"mb")) {
1041 mul = 1024*1024;
1042 } else if (!strcasecmp(u,"g")) {
1043 mul = 1000L*1000*1000;
1044 } else if (!strcasecmp(u,"gb")) {
1045 mul = 1024L*1024*1024;
1046 } else {
1047 if (err) *err = 1;
1048 mul = 1;
1049 }
1050 digits = u-p;
1051 if (digits >= sizeof(buf)) {
1052 if (err) *err = 1;
1053 return LLONG_MAX;
1054 }
1055 memcpy(buf,p,digits);
1056 buf[digits] = '\0';
1057 val = strtoll(buf,NULL,10);
1058 return val*mul;
1059 }
1060
1061 /* Convert a long long into a string. Returns the number of
1062 * characters needed to represent the number, that can be shorter if passed
1063 * buffer length is not enough to store the whole number. */
1064 static int ll2string(char *s, size_t len, long long value) {
1065 char buf[32], *p;
1066 unsigned long long v;
1067 size_t l;
1068
1069 if (len == 0) return 0;
1070 v = (value < 0) ? -value : value;
1071 p = buf+31; /* point to the last character */
1072 do {
1073 *p-- = '0'+(v%10);
1074 v /= 10;
1075 } while(v);
1076 if (value < 0) *p-- = '-';
1077 p++;
1078 l = 32-(p-buf);
1079 if (l+1 > len) l = len-1; /* Make sure it fits, including the nul term */
1080 memcpy(s,p,l);
1081 s[l] = '\0';
1082 return l;
1083 }
1084
1085 static void redisLog(int level, const char *fmt, ...) {
1086 va_list ap;
1087 FILE *fp;
1088
1089 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
1090 if (!fp) return;
1091
1092 va_start(ap, fmt);
1093 if (level >= server.verbosity) {
1094 char *c = ".-*#";
1095 char buf[64];
1096 time_t now;
1097
1098 now = time(NULL);
1099 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
1100 fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
1101 vfprintf(fp, fmt, ap);
1102 fprintf(fp,"\n");
1103 fflush(fp);
1104 }
1105 va_end(ap);
1106
1107 if (server.logfile) fclose(fp);
1108 }
1109
1110 /*====================== Hash table type implementation ==================== */
1111
1112 /* This is an hash table type that uses the SDS dynamic strings libary as
1113 * keys and radis objects as values (objects can hold SDS strings,
1114 * lists, sets). */
1115
1116 static void dictVanillaFree(void *privdata, void *val)
1117 {
1118 DICT_NOTUSED(privdata);
1119 zfree(val);
1120 }
1121
1122 static void dictListDestructor(void *privdata, void *val)
1123 {
1124 DICT_NOTUSED(privdata);
1125 listRelease((list*)val);
1126 }
1127
1128 static int sdsDictKeyCompare(void *privdata, const void *key1,
1129 const void *key2)
1130 {
1131 int l1,l2;
1132 DICT_NOTUSED(privdata);
1133
1134 l1 = sdslen((sds)key1);
1135 l2 = sdslen((sds)key2);
1136 if (l1 != l2) return 0;
1137 return memcmp(key1, key2, l1) == 0;
1138 }
1139
1140 static void dictRedisObjectDestructor(void *privdata, void *val)
1141 {
1142 DICT_NOTUSED(privdata);
1143
1144 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
1145 decrRefCount(val);
1146 }
1147
1148 static int dictObjKeyCompare(void *privdata, const void *key1,
1149 const void *key2)
1150 {
1151 const robj *o1 = key1, *o2 = key2;
1152 return sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1153 }
1154
1155 static unsigned int dictObjHash(const void *key) {
1156 const robj *o = key;
1157 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1158 }
1159
1160 static int dictEncObjKeyCompare(void *privdata, const void *key1,
1161 const void *key2)
1162 {
1163 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
1164 int cmp;
1165
1166 if (o1->encoding == REDIS_ENCODING_INT &&
1167 o2->encoding == REDIS_ENCODING_INT)
1168 return o1->ptr == o2->ptr;
1169
1170 o1 = getDecodedObject(o1);
1171 o2 = getDecodedObject(o2);
1172 cmp = sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1173 decrRefCount(o1);
1174 decrRefCount(o2);
1175 return cmp;
1176 }
1177
1178 static unsigned int dictEncObjHash(const void *key) {
1179 robj *o = (robj*) key;
1180
1181 if (o->encoding == REDIS_ENCODING_RAW) {
1182 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1183 } else {
1184 if (o->encoding == REDIS_ENCODING_INT) {
1185 char buf[32];
1186 int len;
1187
1188 len = ll2string(buf,32,(long)o->ptr);
1189 return dictGenHashFunction((unsigned char*)buf, len);
1190 } else {
1191 unsigned int hash;
1192
1193 o = getDecodedObject(o);
1194 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1195 decrRefCount(o);
1196 return hash;
1197 }
1198 }
1199 }
1200
1201 /* Sets type and expires */
1202 static dictType setDictType = {
1203 dictEncObjHash, /* hash function */
1204 NULL, /* key dup */
1205 NULL, /* val dup */
1206 dictEncObjKeyCompare, /* key compare */
1207 dictRedisObjectDestructor, /* key destructor */
1208 NULL /* val destructor */
1209 };
1210
1211 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1212 static dictType zsetDictType = {
1213 dictEncObjHash, /* hash function */
1214 NULL, /* key dup */
1215 NULL, /* val dup */
1216 dictEncObjKeyCompare, /* key compare */
1217 dictRedisObjectDestructor, /* key destructor */
1218 dictVanillaFree /* val destructor of malloc(sizeof(double)) */
1219 };
1220
1221 /* Db->dict */
1222 static dictType dbDictType = {
1223 dictObjHash, /* hash function */
1224 NULL, /* key dup */
1225 NULL, /* val dup */
1226 dictObjKeyCompare, /* key compare */
1227 dictRedisObjectDestructor, /* key destructor */
1228 dictRedisObjectDestructor /* val destructor */
1229 };
1230
1231 /* Db->expires */
1232 static dictType keyptrDictType = {
1233 dictObjHash, /* hash function */
1234 NULL, /* key dup */
1235 NULL, /* val dup */
1236 dictObjKeyCompare, /* key compare */
1237 dictRedisObjectDestructor, /* key destructor */
1238 NULL /* val destructor */
1239 };
1240
1241 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1242 static dictType hashDictType = {
1243 dictEncObjHash, /* hash function */
1244 NULL, /* key dup */
1245 NULL, /* val dup */
1246 dictEncObjKeyCompare, /* key compare */
1247 dictRedisObjectDestructor, /* key destructor */
1248 dictRedisObjectDestructor /* val destructor */
1249 };
1250
1251 /* Keylist hash table type has unencoded redis objects as keys and
1252 * lists as values. It's used for blocking operations (BLPOP) and to
1253 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1254 static dictType keylistDictType = {
1255 dictObjHash, /* hash function */
1256 NULL, /* key dup */
1257 NULL, /* val dup */
1258 dictObjKeyCompare, /* key compare */
1259 dictRedisObjectDestructor, /* key destructor */
1260 dictListDestructor /* val destructor */
1261 };
1262
1263 static void version();
1264
1265 /* ========================= Random utility functions ======================= */
1266
1267 /* Redis generally does not try to recover from out of memory conditions
1268 * when allocating objects or strings, it is not clear if it will be possible
1269 * to report this condition to the client since the networking layer itself
1270 * is based on heap allocation for send buffers, so we simply abort.
1271 * At least the code will be simpler to read... */
1272 static void oom(const char *msg) {
1273 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
1274 sleep(1);
1275 abort();
1276 }
1277
1278 /* ====================== Redis server networking stuff ===================== */
1279 static void closeTimedoutClients(void) {
1280 redisClient *c;
1281 listNode *ln;
1282 time_t now = time(NULL);
1283 listIter li;
1284
1285 listRewind(server.clients,&li);
1286 while ((ln = listNext(&li)) != NULL) {
1287 c = listNodeValue(ln);
1288 if (server.maxidletime &&
1289 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
1290 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
1291 dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
1292 listLength(c->pubsub_patterns) == 0 &&
1293 (now - c->lastinteraction > server.maxidletime))
1294 {
1295 redisLog(REDIS_VERBOSE,"Closing idle client");
1296 freeClient(c);
1297 } else if (c->flags & REDIS_BLOCKED) {
1298 if (c->blockingto != 0 && c->blockingto < now) {
1299 addReply(c,shared.nullmultibulk);
1300 unblockClientWaitingData(c);
1301 }
1302 }
1303 }
1304 }
1305
1306 static int htNeedsResize(dict *dict) {
1307 long long size, used;
1308
1309 size = dictSlots(dict);
1310 used = dictSize(dict);
1311 return (size && used && size > DICT_HT_INITIAL_SIZE &&
1312 (used*100/size < REDIS_HT_MINFILL));
1313 }
1314
1315 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1316 * we resize the hash table to save memory */
1317 static void tryResizeHashTables(void) {
1318 int j;
1319
1320 for (j = 0; j < server.dbnum; j++) {
1321 if (htNeedsResize(server.db[j].dict))
1322 dictResize(server.db[j].dict);
1323 if (htNeedsResize(server.db[j].expires))
1324 dictResize(server.db[j].expires);
1325 }
1326 }
1327
1328 /* Our hash table implementation performs rehashing incrementally while
1329 * we write/read from the hash table. Still if the server is idle, the hash
1330 * table will use two tables for a long time. So we try to use 1 millisecond
1331 * of CPU time at every serverCron() loop in order to rehash some key. */
1332 static void incrementallyRehash(void) {
1333 int j;
1334
1335 for (j = 0; j < server.dbnum; j++) {
1336 if (dictIsRehashing(server.db[j].dict)) {
1337 dictRehashMilliseconds(server.db[j].dict,1);
1338 break; /* already used our millisecond for this loop... */
1339 }
1340 }
1341 }
1342
1343 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1344 void backgroundSaveDoneHandler(int statloc) {
1345 int exitcode = WEXITSTATUS(statloc);
1346 int bysignal = WIFSIGNALED(statloc);
1347
1348 if (!bysignal && exitcode == 0) {
1349 redisLog(REDIS_NOTICE,
1350 "Background saving terminated with success");
1351 server.dirty = 0;
1352 server.lastsave = time(NULL);
1353 } else if (!bysignal && exitcode != 0) {
1354 redisLog(REDIS_WARNING, "Background saving error");
1355 } else {
1356 redisLog(REDIS_WARNING,
1357 "Background saving terminated by signal %d", WTERMSIG(statloc));
1358 rdbRemoveTempFile(server.bgsavechildpid);
1359 }
1360 server.bgsavechildpid = -1;
1361 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1362 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1363 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1364 }
1365
1366 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1367 * Handle this. */
1368 void backgroundRewriteDoneHandler(int statloc) {
1369 int exitcode = WEXITSTATUS(statloc);
1370 int bysignal = WIFSIGNALED(statloc);
1371
1372 if (!bysignal && exitcode == 0) {
1373 int fd;
1374 char tmpfile[256];
1375
1376 redisLog(REDIS_NOTICE,
1377 "Background append only file rewriting terminated with success");
1378 /* Now it's time to flush the differences accumulated by the parent */
1379 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
1380 fd = open(tmpfile,O_WRONLY|O_APPEND);
1381 if (fd == -1) {
1382 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
1383 goto cleanup;
1384 }
1385 /* Flush our data... */
1386 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
1387 (signed) sdslen(server.bgrewritebuf)) {
1388 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));
1389 close(fd);
1390 goto cleanup;
1391 }
1392 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
1393 /* Now our work is to rename the temp file into the stable file. And
1394 * switch the file descriptor used by the server for append only. */
1395 if (rename(tmpfile,server.appendfilename) == -1) {
1396 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
1397 close(fd);
1398 goto cleanup;
1399 }
1400 /* Mission completed... almost */
1401 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
1402 if (server.appendfd != -1) {
1403 /* If append only is actually enabled... */
1404 close(server.appendfd);
1405 server.appendfd = fd;
1406 if (server.appendfsync != APPENDFSYNC_NO) aof_fsync(fd);
1407 server.appendseldb = -1; /* Make sure it will issue SELECT */
1408 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
1409 } else {
1410 /* If append only is disabled we just generate a dump in this
1411 * format. Why not? */
1412 close(fd);
1413 }
1414 } else if (!bysignal && exitcode != 0) {
1415 redisLog(REDIS_WARNING, "Background append only file rewriting error");
1416 } else {
1417 redisLog(REDIS_WARNING,
1418 "Background append only file rewriting terminated by signal %d",
1419 WTERMSIG(statloc));
1420 }
1421 cleanup:
1422 sdsfree(server.bgrewritebuf);
1423 server.bgrewritebuf = sdsempty();
1424 aofRemoveTempFile(server.bgrewritechildpid);
1425 server.bgrewritechildpid = -1;
1426 }
1427
1428 /* This function is called once a background process of some kind terminates,
1429 * as we want to avoid resizing the hash tables when there is a child in order
1430 * to play well with copy-on-write (otherwise when a resize happens lots of
1431 * memory pages are copied). The goal of this function is to update the ability
1432 * for dict.c to resize the hash tables accordingly to the fact we have o not
1433 * running childs. */
1434 static void updateDictResizePolicy(void) {
1435 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
1436 dictEnableResize();
1437 else
1438 dictDisableResize();
1439 }
1440
1441 static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
1442 int j, loops = server.cronloops++;
1443 REDIS_NOTUSED(eventLoop);
1444 REDIS_NOTUSED(id);
1445 REDIS_NOTUSED(clientData);
1446
1447 /* We take a cached value of the unix time in the global state because
1448 * with virtual memory and aging there is to store the current time
1449 * in objects at every object access, and accuracy is not needed.
1450 * To access a global var is faster than calling time(NULL) */
1451 server.unixtime = time(NULL);
1452 /* We have just 21 bits per object for LRU information.
1453 * So we use an (eventually wrapping) LRU clock with minutes resolution.
1454 *
1455 * When we need to select what object to swap, we compute the minimum
1456 * time distance between the current lruclock and the object last access
1457 * lruclock info. Even if clocks will wrap on overflow, there is
1458 * the interesting property that we are sure that at least
1459 * ABS(A-B) minutes passed between current time and timestamp B.
1460 *
1461 * This is not precise but we don't need at all precision, but just
1462 * something statistically reasonable.
1463 */
1464 server.lruclock = (time(NULL)/60)&((1<<21)-1);
1465
1466 /* We received a SIGTERM, shutting down here in a safe way, as it is
1467 * not ok doing so inside the signal handler. */
1468 if (server.shutdown_asap) {
1469 if (prepareForShutdown() == REDIS_OK) exit(0);
1470 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
1471 }
1472
1473 /* Show some info about non-empty databases */
1474 for (j = 0; j < server.dbnum; j++) {
1475 long long size, used, vkeys;
1476
1477 size = dictSlots(server.db[j].dict);
1478 used = dictSize(server.db[j].dict);
1479 vkeys = dictSize(server.db[j].expires);
1480 if (!(loops % 50) && (used || vkeys)) {
1481 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
1482 /* dictPrintStats(server.dict); */
1483 }
1484 }
1485
1486 /* We don't want to resize the hash tables while a bacground saving
1487 * is in progress: the saving child is created using fork() that is
1488 * implemented with a copy-on-write semantic in most modern systems, so
1489 * if we resize the HT while there is the saving child at work actually
1490 * a lot of memory movements in the parent will cause a lot of pages
1491 * copied. */
1492 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
1493 if (!(loops % 10)) tryResizeHashTables();
1494 if (server.activerehashing) incrementallyRehash();
1495 }
1496
1497 /* Show information about connected clients */
1498 if (!(loops % 50)) {
1499 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
1500 listLength(server.clients)-listLength(server.slaves),
1501 listLength(server.slaves),
1502 zmalloc_used_memory());
1503 }
1504
1505 /* Close connections of timedout clients */
1506 if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients)
1507 closeTimedoutClients();
1508
1509 /* Check if a background saving or AOF rewrite in progress terminated */
1510 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
1511 int statloc;
1512 pid_t pid;
1513
1514 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
1515 if (pid == server.bgsavechildpid) {
1516 backgroundSaveDoneHandler(statloc);
1517 } else {
1518 backgroundRewriteDoneHandler(statloc);
1519 }
1520 updateDictResizePolicy();
1521 }
1522 } else {
1523 /* If there is not a background saving in progress check if
1524 * we have to save now */
1525 time_t now = time(NULL);
1526 for (j = 0; j < server.saveparamslen; j++) {
1527 struct saveparam *sp = server.saveparams+j;
1528
1529 if (server.dirty >= sp->changes &&
1530 now-server.lastsave > sp->seconds) {
1531 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
1532 sp->changes, sp->seconds);
1533 rdbSaveBackground(server.dbfilename);
1534 break;
1535 }
1536 }
1537 }
1538
1539 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1540 * will use few CPU cycles if there are few expiring keys, otherwise
1541 * it will get more aggressive to avoid that too much memory is used by
1542 * keys that can be removed from the keyspace. */
1543 for (j = 0; j < server.dbnum; j++) {
1544 int expired;
1545 redisDb *db = server.db+j;
1546
1547 /* Continue to expire if at the end of the cycle more than 25%
1548 * of the keys were expired. */
1549 do {
1550 long num = dictSize(db->expires);
1551 time_t now = time(NULL);
1552
1553 expired = 0;
1554 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
1555 num = REDIS_EXPIRELOOKUPS_PER_CRON;
1556 while (num--) {
1557 dictEntry *de;
1558 time_t t;
1559
1560 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
1561 t = (time_t) dictGetEntryVal(de);
1562 if (now > t) {
1563 deleteKey(db,dictGetEntryKey(de));
1564 expired++;
1565 server.stat_expiredkeys++;
1566 }
1567 }
1568 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
1569 }
1570
1571 /* Swap a few keys on disk if we are over the memory limit and VM
1572 * is enbled. Try to free objects from the free list first. */
1573 if (vmCanSwapOut()) {
1574 while (server.vm_enabled && zmalloc_used_memory() >
1575 server.vm_max_memory)
1576 {
1577 int retval;
1578
1579 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
1580 retval = (server.vm_max_threads == 0) ?
1581 vmSwapOneObjectBlocking() :
1582 vmSwapOneObjectThreaded();
1583 if (retval == REDIS_ERR && !(loops % 300) &&
1584 zmalloc_used_memory() >
1585 (server.vm_max_memory+server.vm_max_memory/10))
1586 {
1587 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1588 }
1589 /* Note that when using threade I/O we free just one object,
1590 * because anyway when the I/O thread in charge to swap this
1591 * object out will finish, the handler of completed jobs
1592 * will try to swap more objects if we are still out of memory. */
1593 if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
1594 }
1595 }
1596
1597 /* Check if we should connect to a MASTER */
1598 if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) {
1599 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
1600 if (syncWithMaster() == REDIS_OK) {
1601 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
1602 if (server.appendonly) rewriteAppendOnlyFileBackground();
1603 }
1604 }
1605 return 100;
1606 }
1607
1608 /* This function gets called every time Redis is entering the
1609 * main loop of the event driven library, that is, before to sleep
1610 * for ready file descriptors. */
1611 static void beforeSleep(struct aeEventLoop *eventLoop) {
1612 REDIS_NOTUSED(eventLoop);
1613
1614 /* Awake clients that got all the swapped keys they requested */
1615 if (server.vm_enabled && listLength(server.io_ready_clients)) {
1616 listIter li;
1617 listNode *ln;
1618
1619 listRewind(server.io_ready_clients,&li);
1620 while((ln = listNext(&li))) {
1621 redisClient *c = ln->value;
1622 struct redisCommand *cmd;
1623
1624 /* Resume the client. */
1625 listDelNode(server.io_ready_clients,ln);
1626 c->flags &= (~REDIS_IO_WAIT);
1627 server.vm_blocked_clients--;
1628 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1629 readQueryFromClient, c);
1630 cmd = lookupCommand(c->argv[0]->ptr);
1631 assert(cmd != NULL);
1632 call(c,cmd);
1633 resetClient(c);
1634 /* There may be more data to process in the input buffer. */
1635 if (c->querybuf && sdslen(c->querybuf) > 0)
1636 processInputBuffer(c);
1637 }
1638 }
1639 /* Write the AOF buffer on disk */
1640 flushAppendOnlyFile();
1641 }
1642
1643 static void createSharedObjects(void) {
1644 int j;
1645
1646 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
1647 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
1648 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
1649 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
1650 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
1651 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
1652 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
1653 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
1654 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
1655 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
1656 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
1657 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
1658 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1659 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
1660 "-ERR no such key\r\n"));
1661 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
1662 "-ERR syntax error\r\n"));
1663 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
1664 "-ERR source and destination objects are the same\r\n"));
1665 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
1666 "-ERR index out of range\r\n"));
1667 shared.space = createObject(REDIS_STRING,sdsnew(" "));
1668 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
1669 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
1670 shared.select0 = createStringObject("select 0\r\n",10);
1671 shared.select1 = createStringObject("select 1\r\n",10);
1672 shared.select2 = createStringObject("select 2\r\n",10);
1673 shared.select3 = createStringObject("select 3\r\n",10);
1674 shared.select4 = createStringObject("select 4\r\n",10);
1675 shared.select5 = createStringObject("select 5\r\n",10);
1676 shared.select6 = createStringObject("select 6\r\n",10);
1677 shared.select7 = createStringObject("select 7\r\n",10);
1678 shared.select8 = createStringObject("select 8\r\n",10);
1679 shared.select9 = createStringObject("select 9\r\n",10);
1680 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
1681 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
1682 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
1683 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
1684 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
1685 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
1686 shared.mbulk3 = createStringObject("*3\r\n",4);
1687 shared.mbulk4 = createStringObject("*4\r\n",4);
1688 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
1689 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
1690 shared.integers[j]->encoding = REDIS_ENCODING_INT;
1691 }
1692 }
1693
1694 static void appendServerSaveParams(time_t seconds, int changes) {
1695 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
1696 server.saveparams[server.saveparamslen].seconds = seconds;
1697 server.saveparams[server.saveparamslen].changes = changes;
1698 server.saveparamslen++;
1699 }
1700
1701 static void resetServerSaveParams() {
1702 zfree(server.saveparams);
1703 server.saveparams = NULL;
1704 server.saveparamslen = 0;
1705 }
1706
1707 static void initServerConfig() {
1708 server.dbnum = REDIS_DEFAULT_DBNUM;
1709 server.port = REDIS_SERVERPORT;
1710 server.verbosity = REDIS_VERBOSE;
1711 server.maxidletime = REDIS_MAXIDLETIME;
1712 server.saveparams = NULL;
1713 server.logfile = NULL; /* NULL = log on standard output */
1714 server.bindaddr = NULL;
1715 server.glueoutputbuf = 1;
1716 server.daemonize = 0;
1717 server.appendonly = 0;
1718 server.appendfsync = APPENDFSYNC_EVERYSEC;
1719 server.no_appendfsync_on_rewrite = 0;
1720 server.lastfsync = time(NULL);
1721 server.appendfd = -1;
1722 server.appendseldb = -1; /* Make sure the first time will not match */
1723 server.pidfile = zstrdup("/var/run/redis.pid");
1724 server.dbfilename = zstrdup("dump.rdb");
1725 server.appendfilename = zstrdup("appendonly.aof");
1726 server.requirepass = NULL;
1727 server.rdbcompression = 1;
1728 server.activerehashing = 1;
1729 server.maxclients = 0;
1730 server.blpop_blocked_clients = 0;
1731 server.maxmemory = 0;
1732 server.vm_enabled = 0;
1733 server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
1734 server.vm_page_size = 256; /* 256 bytes per page */
1735 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
1736 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
1737 server.vm_max_threads = 4;
1738 server.vm_blocked_clients = 0;
1739 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
1740 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
1741 server.shutdown_asap = 0;
1742
1743 resetServerSaveParams();
1744
1745 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1746 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1747 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1748 /* Replication related */
1749 server.isslave = 0;
1750 server.masterauth = NULL;
1751 server.masterhost = NULL;
1752 server.masterport = 6379;
1753 server.master = NULL;
1754 server.replstate = REDIS_REPL_NONE;
1755
1756 /* Double constants initialization */
1757 R_Zero = 0.0;
1758 R_PosInf = 1.0/R_Zero;
1759 R_NegInf = -1.0/R_Zero;
1760 R_Nan = R_Zero/R_Zero;
1761 }
1762
1763 static void initServer() {
1764 int j;
1765
1766 signal(SIGHUP, SIG_IGN);
1767 signal(SIGPIPE, SIG_IGN);
1768 setupSigSegvAction();
1769
1770 server.devnull = fopen("/dev/null","w");
1771 if (server.devnull == NULL) {
1772 redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr);
1773 exit(1);
1774 }
1775 server.clients = listCreate();
1776 server.slaves = listCreate();
1777 server.monitors = listCreate();
1778 server.objfreelist = listCreate();
1779 createSharedObjects();
1780 server.el = aeCreateEventLoop();
1781 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
1782 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
1783 if (server.fd == -1) {
1784 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
1785 exit(1);
1786 }
1787 for (j = 0; j < server.dbnum; j++) {
1788 server.db[j].dict = dictCreate(&dbDictType,NULL);
1789 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
1790 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
1791 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
1792 if (server.vm_enabled)
1793 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
1794 server.db[j].id = j;
1795 }
1796 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1797 server.pubsub_patterns = listCreate();
1798 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1799 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
1800 server.cronloops = 0;
1801 server.bgsavechildpid = -1;
1802 server.bgrewritechildpid = -1;
1803 server.bgrewritebuf = sdsempty();
1804 server.aofbuf = sdsempty();
1805 server.lastsave = time(NULL);
1806 server.dirty = 0;
1807 server.stat_numcommands = 0;
1808 server.stat_numconnections = 0;
1809 server.stat_expiredkeys = 0;
1810 server.stat_starttime = time(NULL);
1811 server.unixtime = time(NULL);
1812 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
1813 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
1814 acceptHandler, NULL) == AE_ERR) oom("creating file event");
1815
1816 if (server.appendonly) {
1817 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
1818 if (server.appendfd == -1) {
1819 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1820 strerror(errno));
1821 exit(1);
1822 }
1823 }
1824
1825 if (server.vm_enabled) vmInit();
1826 }
1827
1828 /* Empty the whole database */
1829 static long long emptyDb() {
1830 int j;
1831 long long removed = 0;
1832
1833 for (j = 0; j < server.dbnum; j++) {
1834 removed += dictSize(server.db[j].dict);
1835 dictEmpty(server.db[j].dict);
1836 dictEmpty(server.db[j].expires);
1837 }
1838 return removed;
1839 }
1840
1841 static int yesnotoi(char *s) {
1842 if (!strcasecmp(s,"yes")) return 1;
1843 else if (!strcasecmp(s,"no")) return 0;
1844 else return -1;
1845 }
1846
1847 /* I agree, this is a very rudimental way to load a configuration...
1848 will improve later if the config gets more complex */
1849 static void loadServerConfig(char *filename) {
1850 FILE *fp;
1851 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
1852 int linenum = 0;
1853 sds line = NULL;
1854
1855 if (filename[0] == '-' && filename[1] == '\0')
1856 fp = stdin;
1857 else {
1858 if ((fp = fopen(filename,"r")) == NULL) {
1859 redisLog(REDIS_WARNING, "Fatal error, can't open config file '%s'", filename);
1860 exit(1);
1861 }
1862 }
1863
1864 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1865 sds *argv;
1866 int argc, j;
1867
1868 linenum++;
1869 line = sdsnew(buf);
1870 line = sdstrim(line," \t\r\n");
1871
1872 /* Skip comments and blank lines*/
1873 if (line[0] == '#' || line[0] == '\0') {
1874 sdsfree(line);
1875 continue;
1876 }
1877
1878 /* Split into arguments */
1879 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
1880 sdstolower(argv[0]);
1881
1882 /* Execute config directives */
1883 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
1884 server.maxidletime = atoi(argv[1]);
1885 if (server.maxidletime < 0) {
1886 err = "Invalid timeout value"; goto loaderr;
1887 }
1888 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
1889 server.port = atoi(argv[1]);
1890 if (server.port < 1 || server.port > 65535) {
1891 err = "Invalid port"; goto loaderr;
1892 }
1893 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
1894 server.bindaddr = zstrdup(argv[1]);
1895 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
1896 int seconds = atoi(argv[1]);
1897 int changes = atoi(argv[2]);
1898 if (seconds < 1 || changes < 0) {
1899 err = "Invalid save parameters"; goto loaderr;
1900 }
1901 appendServerSaveParams(seconds,changes);
1902 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
1903 if (chdir(argv[1]) == -1) {
1904 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
1905 argv[1], strerror(errno));
1906 exit(1);
1907 }
1908 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
1909 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
1910 else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
1911 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
1912 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
1913 else {
1914 err = "Invalid log level. Must be one of debug, notice, warning";
1915 goto loaderr;
1916 }
1917 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
1918 FILE *logfp;
1919
1920 server.logfile = zstrdup(argv[1]);
1921 if (!strcasecmp(server.logfile,"stdout")) {
1922 zfree(server.logfile);
1923 server.logfile = NULL;
1924 }
1925 if (server.logfile) {
1926 /* Test if we are able to open the file. The server will not
1927 * be able to abort just for this problem later... */
1928 logfp = fopen(server.logfile,"a");
1929 if (logfp == NULL) {
1930 err = sdscatprintf(sdsempty(),
1931 "Can't open the log file: %s", strerror(errno));
1932 goto loaderr;
1933 }
1934 fclose(logfp);
1935 }
1936 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
1937 server.dbnum = atoi(argv[1]);
1938 if (server.dbnum < 1) {
1939 err = "Invalid number of databases"; goto loaderr;
1940 }
1941 } else if (!strcasecmp(argv[0],"include") && argc == 2) {
1942 loadServerConfig(argv[1]);
1943 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
1944 server.maxclients = atoi(argv[1]);
1945 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
1946 server.maxmemory = memtoll(argv[1],NULL);
1947 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
1948 server.masterhost = sdsnew(argv[1]);
1949 server.masterport = atoi(argv[2]);
1950 server.replstate = REDIS_REPL_CONNECT;
1951 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
1952 server.masterauth = zstrdup(argv[1]);
1953 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
1954 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
1955 err = "argument must be 'yes' or 'no'"; goto loaderr;
1956 }
1957 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
1958 if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
1959 err = "argument must be 'yes' or 'no'"; goto loaderr;
1960 }
1961 } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
1962 if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
1963 err = "argument must be 'yes' or 'no'"; goto loaderr;
1964 }
1965 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
1966 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
1967 err = "argument must be 'yes' or 'no'"; goto loaderr;
1968 }
1969 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
1970 if ((server.appendonly = yesnotoi(argv[1])) == -1) {
1971 err = "argument must be 'yes' or 'no'"; goto loaderr;
1972 }
1973 } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
1974 zfree(server.appendfilename);
1975 server.appendfilename = zstrdup(argv[1]);
1976 } else if (!strcasecmp(argv[0],"no-appendfsync-on-rewrite")
1977 && argc == 2) {
1978 if ((server.no_appendfsync_on_rewrite= yesnotoi(argv[1])) == -1) {
1979 err = "argument must be 'yes' or 'no'"; goto loaderr;
1980 }
1981 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
1982 if (!strcasecmp(argv[1],"no")) {
1983 server.appendfsync = APPENDFSYNC_NO;
1984 } else if (!strcasecmp(argv[1],"always")) {
1985 server.appendfsync = APPENDFSYNC_ALWAYS;
1986 } else if (!strcasecmp(argv[1],"everysec")) {
1987 server.appendfsync = APPENDFSYNC_EVERYSEC;
1988 } else {
1989 err = "argument must be 'no', 'always' or 'everysec'";
1990 goto loaderr;
1991 }
1992 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
1993 server.requirepass = zstrdup(argv[1]);
1994 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
1995 zfree(server.pidfile);
1996 server.pidfile = zstrdup(argv[1]);
1997 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
1998 zfree(server.dbfilename);
1999 server.dbfilename = zstrdup(argv[1]);
2000 } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
2001 if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
2002 err = "argument must be 'yes' or 'no'"; goto loaderr;
2003 }
2004 } else if (!strcasecmp(argv[0],"vm-swap-file") && argc == 2) {
2005 zfree(server.vm_swap_file);
2006 server.vm_swap_file = zstrdup(argv[1]);
2007 } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
2008 server.vm_max_memory = memtoll(argv[1],NULL);
2009 } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
2010 server.vm_page_size = memtoll(argv[1], NULL);
2011 } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
2012 server.vm_pages = memtoll(argv[1], NULL);
2013 } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
2014 server.vm_max_threads = strtoll(argv[1], NULL, 10);
2015 } else if (!strcasecmp(argv[0],"hash-max-zipmap-entries") && argc == 2){
2016 server.hash_max_zipmap_entries = memtoll(argv[1], NULL);
2017 } else if (!strcasecmp(argv[0],"hash-max-zipmap-value") && argc == 2){
2018 server.hash_max_zipmap_value = memtoll(argv[1], NULL);
2019 } else {
2020 err = "Bad directive or wrong number of arguments"; goto loaderr;
2021 }
2022 for (j = 0; j < argc; j++)
2023 sdsfree(argv[j]);
2024 zfree(argv);
2025 sdsfree(line);
2026 }
2027 if (fp != stdin) fclose(fp);
2028 return;
2029
2030 loaderr:
2031 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
2032 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
2033 fprintf(stderr, ">>> '%s'\n", line);
2034 fprintf(stderr, "%s\n", err);
2035 exit(1);
2036 }
2037
2038 static void freeClientArgv(redisClient *c) {
2039 int j;
2040
2041 for (j = 0; j < c->argc; j++)
2042 decrRefCount(c->argv[j]);
2043 for (j = 0; j < c->mbargc; j++)
2044 decrRefCount(c->mbargv[j]);
2045 c->argc = 0;
2046 c->mbargc = 0;
2047 }
2048
2049 static void freeClient(redisClient *c) {
2050 listNode *ln;
2051
2052 /* Note that if the client we are freeing is blocked into a blocking
2053 * call, we have to set querybuf to NULL *before* to call
2054 * unblockClientWaitingData() to avoid processInputBuffer() will get
2055 * called. Also it is important to remove the file events after
2056 * this, because this call adds the READABLE event. */
2057 sdsfree(c->querybuf);
2058 c->querybuf = NULL;
2059 if (c->flags & REDIS_BLOCKED)
2060 unblockClientWaitingData(c);
2061
2062 /* UNWATCH all the keys */
2063 unwatchAllKeys(c);
2064 listRelease(c->watched_keys);
2065 /* Unsubscribe from all the pubsub channels */
2066 pubsubUnsubscribeAllChannels(c,0);
2067 pubsubUnsubscribeAllPatterns(c,0);
2068 dictRelease(c->pubsub_channels);
2069 listRelease(c->pubsub_patterns);
2070 /* Obvious cleanup */
2071 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
2072 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2073 listRelease(c->reply);
2074 freeClientArgv(c);
2075 close(c->fd);
2076 /* Remove from the list of clients */
2077 ln = listSearchKey(server.clients,c);
2078 redisAssert(ln != NULL);
2079 listDelNode(server.clients,ln);
2080 /* Remove from the list of clients that are now ready to be restarted
2081 * after waiting for swapped keys */
2082 if (c->flags & REDIS_IO_WAIT && listLength(c->io_keys) == 0) {
2083 ln = listSearchKey(server.io_ready_clients,c);
2084 if (ln) {
2085 listDelNode(server.io_ready_clients,ln);
2086 server.vm_blocked_clients--;
2087 }
2088 }
2089 /* Remove from the list of clients waiting for swapped keys */
2090 while (server.vm_enabled && listLength(c->io_keys)) {
2091 ln = listFirst(c->io_keys);
2092 dontWaitForSwappedKey(c,ln->value);
2093 }
2094 listRelease(c->io_keys);
2095 /* Master/slave cleanup */
2096 if (c->flags & REDIS_SLAVE) {
2097 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
2098 close(c->repldbfd);
2099 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
2100 ln = listSearchKey(l,c);
2101 redisAssert(ln != NULL);
2102 listDelNode(l,ln);
2103 }
2104 if (c->flags & REDIS_MASTER) {
2105 server.master = NULL;
2106 server.replstate = REDIS_REPL_CONNECT;
2107 }
2108 /* Release memory */
2109 zfree(c->argv);
2110 zfree(c->mbargv);
2111 freeClientMultiState(c);
2112 zfree(c);
2113 }
2114
2115 #define GLUEREPLY_UP_TO (1024)
2116 static void glueReplyBuffersIfNeeded(redisClient *c) {
2117 int copylen = 0;
2118 char buf[GLUEREPLY_UP_TO];
2119 listNode *ln;
2120 listIter li;
2121 robj *o;
2122
2123 listRewind(c->reply,&li);
2124 while((ln = listNext(&li))) {
2125 int objlen;
2126
2127 o = ln->value;
2128 objlen = sdslen(o->ptr);
2129 if (copylen + objlen <= GLUEREPLY_UP_TO) {
2130 memcpy(buf+copylen,o->ptr,objlen);
2131 copylen += objlen;
2132 listDelNode(c->reply,ln);
2133 } else {
2134 if (copylen == 0) return;
2135 break;
2136 }
2137 }
2138 /* Now the output buffer is empty, add the new single element */
2139 o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
2140 listAddNodeHead(c->reply,o);
2141 }
2142
2143 static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2144 redisClient *c = privdata;
2145 int nwritten = 0, totwritten = 0, objlen;
2146 robj *o;
2147 REDIS_NOTUSED(el);
2148 REDIS_NOTUSED(mask);
2149
2150 /* Use writev() if we have enough buffers to send */
2151 if (!server.glueoutputbuf &&
2152 listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
2153 !(c->flags & REDIS_MASTER))
2154 {
2155 sendReplyToClientWritev(el, fd, privdata, mask);
2156 return;
2157 }
2158
2159 while(listLength(c->reply)) {
2160 if (server.glueoutputbuf && listLength(c->reply) > 1)
2161 glueReplyBuffersIfNeeded(c);
2162
2163 o = listNodeValue(listFirst(c->reply));
2164 objlen = sdslen(o->ptr);
2165
2166 if (objlen == 0) {
2167 listDelNode(c->reply,listFirst(c->reply));
2168 continue;
2169 }
2170
2171 if (c->flags & REDIS_MASTER) {
2172 /* Don't reply to a master */
2173 nwritten = objlen - c->sentlen;
2174 } else {
2175 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
2176 if (nwritten <= 0) break;
2177 }
2178 c->sentlen += nwritten;
2179 totwritten += nwritten;
2180 /* If we fully sent the object on head go to the next one */
2181 if (c->sentlen == objlen) {
2182 listDelNode(c->reply,listFirst(c->reply));
2183 c->sentlen = 0;
2184 }
2185 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
2186 * bytes, in a single threaded server it's a good idea to serve
2187 * other clients as well, even if a very large request comes from
2188 * super fast link that is always able to accept data (in real world
2189 * scenario think about 'KEYS *' against the loopback interfae) */
2190 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
2191 }
2192 if (nwritten == -1) {
2193 if (errno == EAGAIN) {
2194 nwritten = 0;
2195 } else {
2196 redisLog(REDIS_VERBOSE,
2197 "Error writing to client: %s", strerror(errno));
2198 freeClient(c);
2199 return;
2200 }
2201 }
2202 if (totwritten > 0) c->lastinteraction = time(NULL);
2203 if (listLength(c->reply) == 0) {
2204 c->sentlen = 0;
2205 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2206 }
2207 }
2208
2209 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
2210 {
2211 redisClient *c = privdata;
2212 int nwritten = 0, totwritten = 0, objlen, willwrite;
2213 robj *o;
2214 struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
2215 int offset, ion = 0;
2216 REDIS_NOTUSED(el);
2217 REDIS_NOTUSED(mask);
2218
2219 listNode *node;
2220 while (listLength(c->reply)) {
2221 offset = c->sentlen;
2222 ion = 0;
2223 willwrite = 0;
2224
2225 /* fill-in the iov[] array */
2226 for(node = listFirst(c->reply); node; node = listNextNode(node)) {
2227 o = listNodeValue(node);
2228 objlen = sdslen(o->ptr);
2229
2230 if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
2231 break;
2232
2233 if(ion == REDIS_WRITEV_IOVEC_COUNT)
2234 break; /* no more iovecs */
2235
2236 iov[ion].iov_base = ((char*)o->ptr) + offset;
2237 iov[ion].iov_len = objlen - offset;
2238 willwrite += objlen - offset;
2239 offset = 0; /* just for the first item */
2240 ion++;
2241 }
2242
2243 if(willwrite == 0)
2244 break;
2245
2246 /* write all collected blocks at once */
2247 if((nwritten = writev(fd, iov, ion)) < 0) {
2248 if (errno != EAGAIN) {
2249 redisLog(REDIS_VERBOSE,
2250 "Error writing to client: %s", strerror(errno));
2251 freeClient(c);
2252 return;
2253 }
2254 break;
2255 }
2256
2257 totwritten += nwritten;
2258 offset = c->sentlen;
2259
2260 /* remove written robjs from c->reply */
2261 while (nwritten && listLength(c->reply)) {
2262 o = listNodeValue(listFirst(c->reply));
2263 objlen = sdslen(o->ptr);
2264
2265 if(nwritten >= objlen - offset) {
2266 listDelNode(c->reply, listFirst(c->reply));
2267 nwritten -= objlen - offset;
2268 c->sentlen = 0;
2269 } else {
2270 /* partial write */
2271 c->sentlen += nwritten;
2272 break;
2273 }
2274 offset = 0;
2275 }
2276 }
2277
2278 if (totwritten > 0)
2279 c->lastinteraction = time(NULL);
2280
2281 if (listLength(c->reply) == 0) {
2282 c->sentlen = 0;
2283 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2284 }
2285 }
2286
2287 static int qsortRedisCommands(const void *r1, const void *r2) {
2288 return strcasecmp(
2289 ((struct redisCommand*)r1)->name,
2290 ((struct redisCommand*)r2)->name);
2291 }
2292
2293 static void sortCommandTable() {
2294 /* Copy and sort the read-only version of the command table */
2295 commandTable = (struct redisCommand*)malloc(sizeof(readonlyCommandTable));
2296 memcpy(commandTable,readonlyCommandTable,sizeof(readonlyCommandTable));
2297 qsort(commandTable,
2298 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
2299 sizeof(struct redisCommand),qsortRedisCommands);
2300 }
2301
2302 static struct redisCommand *lookupCommand(char *name) {
2303 struct redisCommand tmp = {name,NULL,0,0,NULL,0,0,0};
2304 return bsearch(
2305 &tmp,
2306 commandTable,
2307 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
2308 sizeof(struct redisCommand),
2309 qsortRedisCommands);
2310 }
2311
2312 /* resetClient prepare the client to process the next command */
2313 static void resetClient(redisClient *c) {
2314 freeClientArgv(c);
2315 c->bulklen = -1;
2316 c->multibulk = 0;
2317 }
2318
2319 /* Call() is the core of Redis execution of a command */
2320 static void call(redisClient *c, struct redisCommand *cmd) {
2321 long long dirty;
2322
2323 dirty = server.dirty;
2324 cmd->proc(c);
2325 dirty = server.dirty-dirty;
2326
2327 if (server.appendonly && dirty)
2328 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
2329 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
2330 listLength(server.slaves))
2331 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
2332 if (listLength(server.monitors))
2333 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
2334 server.stat_numcommands++;
2335 }
2336
2337 /* If this function gets called we already read a whole
2338 * command, argments are in the client argv/argc fields.
2339 * processCommand() execute the command or prepare the
2340 * server for a bulk read from the client.
2341 *
2342 * If 1 is returned the client is still alive and valid and
2343 * and other operations can be performed by the caller. Otherwise
2344 * if 0 is returned the client was destroied (i.e. after QUIT). */
2345 static int processCommand(redisClient *c) {
2346 struct redisCommand *cmd;
2347
2348 /* Free some memory if needed (maxmemory setting) */
2349 if (server.maxmemory) freeMemoryIfNeeded();
2350
2351 /* Handle the multi bulk command type. This is an alternative protocol
2352 * supported by Redis in order to receive commands that are composed of
2353 * multiple binary-safe "bulk" arguments. The latency of processing is
2354 * a bit higher but this allows things like multi-sets, so if this
2355 * protocol is used only for MSET and similar commands this is a big win. */
2356 if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
2357 c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
2358 if (c->multibulk <= 0) {
2359 resetClient(c);
2360 return 1;
2361 } else {
2362 decrRefCount(c->argv[c->argc-1]);
2363 c->argc--;
2364 return 1;
2365 }
2366 } else if (c->multibulk) {
2367 if (c->bulklen == -1) {
2368 if (((char*)c->argv[0]->ptr)[0] != '$') {
2369 addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
2370 resetClient(c);
2371 return 1;
2372 } else {
2373 int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
2374 decrRefCount(c->argv[0]);
2375 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2376 c->argc--;
2377 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2378 resetClient(c);
2379 return 1;
2380 }
2381 c->argc--;
2382 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2383 return 1;
2384 }
2385 } else {
2386 c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
2387 c->mbargv[c->mbargc] = c->argv[0];
2388 c->mbargc++;
2389 c->argc--;
2390 c->multibulk--;
2391 if (c->multibulk == 0) {
2392 robj **auxargv;
2393 int auxargc;
2394
2395 /* Here we need to swap the multi-bulk argc/argv with the
2396 * normal argc/argv of the client structure. */
2397 auxargv = c->argv;
2398 c->argv = c->mbargv;
2399 c->mbargv = auxargv;
2400
2401 auxargc = c->argc;
2402 c->argc = c->mbargc;
2403 c->mbargc = auxargc;
2404
2405 /* We need to set bulklen to something different than -1
2406 * in order for the code below to process the command without
2407 * to try to read the last argument of a bulk command as
2408 * a special argument. */
2409 c->bulklen = 0;
2410 /* continue below and process the command */
2411 } else {
2412 c->bulklen = -1;
2413 return 1;
2414 }
2415 }
2416 }
2417 /* -- end of multi bulk commands processing -- */
2418
2419 /* The QUIT command is handled as a special case. Normal command
2420 * procs are unable to close the client connection safely */
2421 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
2422 freeClient(c);
2423 return 0;
2424 }
2425
2426 /* Now lookup the command and check ASAP about trivial error conditions
2427 * such wrong arity, bad command name and so forth. */
2428 cmd = lookupCommand(c->argv[0]->ptr);
2429 if (!cmd) {
2430 addReplySds(c,
2431 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2432 (char*)c->argv[0]->ptr));
2433 resetClient(c);
2434 return 1;
2435 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
2436 (c->argc < -cmd->arity)) {
2437 addReplySds(c,
2438 sdscatprintf(sdsempty(),
2439 "-ERR wrong number of arguments for '%s' command\r\n",
2440 cmd->name));
2441 resetClient(c);
2442 return 1;
2443 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
2444 /* This is a bulk command, we have to read the last argument yet. */
2445 int bulklen = atoi(c->argv[c->argc-1]->ptr);
2446
2447 decrRefCount(c->argv[c->argc-1]);
2448 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2449 c->argc--;
2450 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2451 resetClient(c);
2452 return 1;
2453 }
2454 c->argc--;
2455 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2456 /* It is possible that the bulk read is already in the
2457 * buffer. Check this condition and handle it accordingly.
2458 * This is just a fast path, alternative to call processInputBuffer().
2459 * It's a good idea since the code is small and this condition
2460 * happens most of the times. */
2461 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
2462 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2463 c->argc++;
2464 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2465 } else {
2466 /* Otherwise return... there is to read the last argument
2467 * from the socket. */
2468 return 1;
2469 }
2470 }
2471 /* Let's try to encode the bulk object to save space. */
2472 if (cmd->flags & REDIS_CMD_BULK)
2473 c->argv[c->argc-1] = tryObjectEncoding(c->argv[c->argc-1]);
2474
2475 /* Check if the user is authenticated */
2476 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
2477 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
2478 resetClient(c);
2479 return 1;
2480 }
2481
2482 /* Handle the maxmemory directive */
2483 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
2484 zmalloc_used_memory() > server.maxmemory)
2485 {
2486 addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2487 resetClient(c);
2488 return 1;
2489 }
2490
2491 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
2492 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
2493 &&
2494 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
2495 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
2496 addReplySds(c,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
2497 resetClient(c);
2498 return 1;
2499 }
2500
2501 /* Exec the command */
2502 if (c->flags & REDIS_MULTI &&
2503 cmd->proc != execCommand && cmd->proc != discardCommand &&
2504 cmd->proc != multiCommand && cmd->proc != watchCommand)
2505 {
2506 queueMultiCommand(c,cmd);
2507 addReply(c,shared.queued);
2508 } else {
2509 if (server.vm_enabled && server.vm_max_threads > 0 &&
2510 blockClientOnSwappedKeys(c,cmd)) return 1;
2511 call(c,cmd);
2512 }
2513
2514 /* Prepare the client for the next command */
2515 resetClient(c);
2516 return 1;
2517 }
2518
2519 static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
2520 listNode *ln;
2521 listIter li;
2522 int outc = 0, j;
2523 robj **outv;
2524 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2525 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2526 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2527 robj *static_outv[REDIS_STATIC_ARGS*3+1];
2528 robj *lenobj;
2529
2530 if (argc <= REDIS_STATIC_ARGS) {
2531 outv = static_outv;
2532 } else {
2533 outv = zmalloc(sizeof(robj*)*(argc*3+1));
2534 }
2535
2536 lenobj = createObject(REDIS_STRING,
2537 sdscatprintf(sdsempty(), "*%d\r\n", argc));
2538 lenobj->refcount = 0;
2539 outv[outc++] = lenobj;
2540 for (j = 0; j < argc; j++) {
2541 lenobj = createObject(REDIS_STRING,
2542 sdscatprintf(sdsempty(),"$%lu\r\n",
2543 (unsigned long) stringObjectLen(argv[j])));
2544 lenobj->refcount = 0;
2545 outv[outc++] = lenobj;
2546 outv[outc++] = argv[j];
2547 outv[outc++] = shared.crlf;
2548 }
2549
2550 /* Increment all the refcounts at start and decrement at end in order to
2551 * be sure to free objects if there is no slave in a replication state
2552 * able to be feed with commands */
2553 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
2554 listRewind(slaves,&li);
2555 while((ln = listNext(&li))) {
2556 redisClient *slave = ln->value;
2557
2558 /* Don't feed slaves that are still waiting for BGSAVE to start */
2559 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
2560
2561 /* Feed all the other slaves, MONITORs and so on */
2562 if (slave->slaveseldb != dictid) {
2563 robj *selectcmd;
2564
2565 switch(dictid) {
2566 case 0: selectcmd = shared.select0; break;
2567 case 1: selectcmd = shared.select1; break;
2568 case 2: selectcmd = shared.select2; break;
2569 case 3: selectcmd = shared.select3; break;
2570 case 4: selectcmd = shared.select4; break;
2571 case 5: selectcmd = shared.select5; break;
2572 case 6: selectcmd = shared.select6; break;
2573 case 7: selectcmd = shared.select7; break;
2574 case 8: selectcmd = shared.select8; break;
2575 case 9: selectcmd = shared.select9; break;
2576 default:
2577 selectcmd = createObject(REDIS_STRING,
2578 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
2579 selectcmd->refcount = 0;
2580 break;
2581 }
2582 addReply(slave,selectcmd);
2583 slave->slaveseldb = dictid;
2584 }
2585 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
2586 }
2587 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
2588 if (outv != static_outv) zfree(outv);
2589 }
2590
2591 static sds sdscatrepr(sds s, char *p, size_t len) {
2592 s = sdscatlen(s,"\"",1);
2593 while(len--) {
2594 switch(*p) {
2595 case '\\':
2596 case '"':
2597 s = sdscatprintf(s,"\\%c",*p);
2598 break;
2599 case '\n': s = sdscatlen(s,"\\n",1); break;
2600 case '\r': s = sdscatlen(s,"\\r",1); break;
2601 case '\t': s = sdscatlen(s,"\\t",1); break;
2602 case '\a': s = sdscatlen(s,"\\a",1); break;
2603 case '\b': s = sdscatlen(s,"\\b",1); break;
2604 default:
2605 if (isprint(*p))
2606 s = sdscatprintf(s,"%c",*p);
2607 else
2608 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
2609 break;
2610 }
2611 p++;
2612 }
2613 return sdscatlen(s,"\"",1);
2614 }
2615
2616 static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc) {
2617 listNode *ln;
2618 listIter li;
2619 int j;
2620 sds cmdrepr = sdsnew("+");
2621 robj *cmdobj;
2622 struct timeval tv;
2623
2624 gettimeofday(&tv,NULL);
2625 cmdrepr = sdscatprintf(cmdrepr,"%ld.%ld ",(long)tv.tv_sec,(long)tv.tv_usec);
2626 if (dictid != 0) cmdrepr = sdscatprintf(cmdrepr,"(db %d) ", dictid);
2627
2628 for (j = 0; j < argc; j++) {
2629 if (argv[j]->encoding == REDIS_ENCODING_INT) {
2630 cmdrepr = sdscatprintf(cmdrepr, "%ld", (long)argv[j]->ptr);
2631 } else {
2632 cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
2633 sdslen(argv[j]->ptr));
2634 }
2635 if (j != argc-1)
2636 cmdrepr = sdscatlen(cmdrepr," ",1);
2637 }
2638 cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
2639 cmdobj = createObject(REDIS_STRING,cmdrepr);
2640
2641 listRewind(monitors,&li);
2642 while((ln = listNext(&li))) {
2643 redisClient *monitor = ln->value;
2644 addReply(monitor,cmdobj);
2645 }
2646 decrRefCount(cmdobj);
2647 }
2648
2649 static void processInputBuffer(redisClient *c) {
2650 again:
2651 /* Before to process the input buffer, make sure the client is not
2652 * waitig for a blocking operation such as BLPOP. Note that the first
2653 * iteration the client is never blocked, otherwise the processInputBuffer
2654 * would not be called at all, but after the execution of the first commands
2655 * in the input buffer the client may be blocked, and the "goto again"
2656 * will try to reiterate. The following line will make it return asap. */
2657 if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
2658 if (c->bulklen == -1) {
2659 /* Read the first line of the query */
2660 char *p = strchr(c->querybuf,'\n');
2661 size_t querylen;
2662
2663 if (p) {
2664 sds query, *argv;
2665 int argc, j;
2666
2667 query = c->querybuf;
2668 c->querybuf = sdsempty();
2669 querylen = 1+(p-(query));
2670 if (sdslen(query) > querylen) {
2671 /* leave data after the first line of the query in the buffer */
2672 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
2673 }
2674 *p = '\0'; /* remove "\n" */
2675 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
2676 sdsupdatelen(query);
2677
2678 /* Now we can split the query in arguments */
2679 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
2680 sdsfree(query);
2681
2682 if (c->argv) zfree(c->argv);
2683 c->argv = zmalloc(sizeof(robj*)*argc);
2684
2685 for (j = 0; j < argc; j++) {
2686 if (sdslen(argv[j])) {
2687 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
2688 c->argc++;
2689 } else {
2690 sdsfree(argv[j]);
2691 }
2692 }
2693 zfree(argv);
2694 if (c->argc) {
2695 /* Execute the command. If the client is still valid
2696 * after processCommand() return and there is something
2697 * on the query buffer try to process the next command. */
2698 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2699 } else {
2700 /* Nothing to process, argc == 0. Just process the query
2701 * buffer if it's not empty or return to the caller */
2702 if (sdslen(c->querybuf)) goto again;
2703 }
2704 return;
2705 } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
2706 redisLog(REDIS_VERBOSE, "Client protocol error");
2707 freeClient(c);
2708 return;
2709 }
2710 } else {
2711 /* Bulk read handling. Note that if we are at this point
2712 the client already sent a command terminated with a newline,
2713 we are reading the bulk data that is actually the last
2714 argument of the command. */
2715 int qbl = sdslen(c->querybuf);
2716
2717 if (c->bulklen <= qbl) {
2718 /* Copy everything but the final CRLF as final argument */
2719 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2720 c->argc++;
2721 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2722 /* Process the command. If the client is still valid after
2723 * the processing and there is more data in the buffer
2724 * try to parse it. */
2725 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2726 return;
2727 }
2728 }
2729 }
2730
2731 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2732 redisClient *c = (redisClient*) privdata;
2733 char buf[REDIS_IOBUF_LEN];
2734 int nread;
2735 REDIS_NOTUSED(el);
2736 REDIS_NOTUSED(mask);
2737
2738 nread = read(fd, buf, REDIS_IOBUF_LEN);
2739 if (nread == -1) {
2740 if (errno == EAGAIN) {
2741 nread = 0;
2742 } else {
2743 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
2744 freeClient(c);
2745 return;
2746 }
2747 } else if (nread == 0) {
2748 redisLog(REDIS_VERBOSE, "Client closed connection");
2749 freeClient(c);
2750 return;
2751 }
2752 if (nread) {
2753 c->querybuf = sdscatlen(c->querybuf, buf, nread);
2754 c->lastinteraction = time(NULL);
2755 } else {
2756 return;
2757 }
2758 processInputBuffer(c);
2759 }
2760
2761 static int selectDb(redisClient *c, int id) {
2762 if (id < 0 || id >= server.dbnum)
2763 return REDIS_ERR;
2764 c->db = &server.db[id];
2765 return REDIS_OK;
2766 }
2767
2768 static void *dupClientReplyValue(void *o) {
2769 incrRefCount((robj*)o);
2770 return o;
2771 }
2772
2773 static int listMatchObjects(void *a, void *b) {
2774 return equalStringObjects(a,b);
2775 }
2776
2777 static redisClient *createClient(int fd) {
2778 redisClient *c = zmalloc(sizeof(*c));
2779
2780 anetNonBlock(NULL,fd);
2781 anetTcpNoDelay(NULL,fd);
2782 if (!c) return NULL;
2783 selectDb(c,0);
2784 c->fd = fd;
2785 c->querybuf = sdsempty();
2786 c->argc = 0;
2787 c->argv = NULL;
2788 c->bulklen = -1;
2789 c->multibulk = 0;
2790 c->mbargc = 0;
2791 c->mbargv = NULL;
2792 c->sentlen = 0;
2793 c->flags = 0;
2794 c->lastinteraction = time(NULL);
2795 c->authenticated = 0;
2796 c->replstate = REDIS_REPL_NONE;
2797 c->reply = listCreate();
2798 listSetFreeMethod(c->reply,decrRefCount);
2799 listSetDupMethod(c->reply,dupClientReplyValue);
2800 c->blocking_keys = NULL;
2801 c->blocking_keys_num = 0;
2802 c->io_keys = listCreate();
2803 c->watched_keys = listCreate();
2804 listSetFreeMethod(c->io_keys,decrRefCount);
2805 c->pubsub_channels = dictCreate(&setDictType,NULL);
2806 c->pubsub_patterns = listCreate();
2807 listSetFreeMethod(c->pubsub_patterns,decrRefCount);
2808 listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
2809 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
2810 readQueryFromClient, c) == AE_ERR) {
2811 freeClient(c);
2812 return NULL;
2813 }
2814 listAddNodeTail(server.clients,c);
2815 initClientMultiState(c);
2816 return c;
2817 }
2818
2819 static void addReply(redisClient *c, robj *obj) {
2820 if (listLength(c->reply) == 0 &&
2821 (c->replstate == REDIS_REPL_NONE ||
2822 c->replstate == REDIS_REPL_ONLINE) &&
2823 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
2824 sendReplyToClient, c) == AE_ERR) return;
2825
2826 if (server.vm_enabled && obj->storage != REDIS_VM_MEMORY) {
2827 obj = dupStringObject(obj);
2828 obj->refcount = 0; /* getDecodedObject() will increment the refcount */
2829 }
2830 listAddNodeTail(c->reply,getDecodedObject(obj));
2831 }
2832
2833 static void addReplySds(redisClient *c, sds s) {
2834 robj *o = createObject(REDIS_STRING,s);
2835 addReply(c,o);
2836 decrRefCount(o);
2837 }
2838
2839 static void addReplyDouble(redisClient *c, double d) {
2840 char buf[128];
2841
2842 snprintf(buf,sizeof(buf),"%.17g",d);
2843 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2844 (unsigned long) strlen(buf),buf));
2845 }
2846
2847 static void addReplyLongLong(redisClient *c, long long ll) {
2848 char buf[128];
2849 size_t len;
2850
2851 if (ll == 0) {
2852 addReply(c,shared.czero);
2853 return;
2854 } else if (ll == 1) {
2855 addReply(c,shared.cone);
2856 return;
2857 }
2858 buf[0] = ':';
2859 len = ll2string(buf+1,sizeof(buf)-1,ll);
2860 buf[len+1] = '\r';
2861 buf[len+2] = '\n';
2862 addReplySds(c,sdsnewlen(buf,len+3));
2863 }
2864
2865 static void addReplyUlong(redisClient *c, unsigned long ul) {
2866 char buf[128];
2867 size_t len;
2868
2869 if (ul == 0) {
2870 addReply(c,shared.czero);
2871 return;
2872 } else if (ul == 1) {
2873 addReply(c,shared.cone);
2874 return;
2875 }
2876 len = snprintf(buf,sizeof(buf),":%lu\r\n",ul);
2877 addReplySds(c,sdsnewlen(buf,len));
2878 }
2879
2880 static void addReplyBulkLen(redisClient *c, robj *obj) {
2881 size_t len, intlen;
2882 char buf[128];
2883
2884 if (obj->encoding == REDIS_ENCODING_RAW) {
2885 len = sdslen(obj->ptr);
2886 } else {
2887 long n = (long)obj->ptr;
2888
2889 /* Compute how many bytes will take this integer as a radix 10 string */
2890 len = 1;
2891 if (n < 0) {
2892 len++;
2893 n = -n;
2894 }
2895 while((n = n/10) != 0) {
2896 len++;
2897 }
2898 }
2899 buf[0] = '$';
2900 intlen = ll2string(buf+1,sizeof(buf)-1,(long long)len);
2901 buf[intlen+1] = '\r';
2902 buf[intlen+2] = '\n';
2903 addReplySds(c,sdsnewlen(buf,intlen+3));
2904 }
2905
2906 static void addReplyBulk(redisClient *c, robj *obj) {
2907 addReplyBulkLen(c,obj);
2908 addReply(c,obj);
2909 addReply(c,shared.crlf);
2910 }
2911
2912 /* In the CONFIG command we need to add vanilla C string as bulk replies */
2913 static void addReplyBulkCString(redisClient *c, char *s) {
2914 if (s == NULL) {
2915 addReply(c,shared.nullbulk);
2916 } else {
2917 robj *o = createStringObject(s,strlen(s));
2918 addReplyBulk(c,o);
2919 decrRefCount(o);
2920 }
2921 }
2922
2923 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2924 int cport, cfd;
2925 char cip[128];
2926 redisClient *c;
2927 REDIS_NOTUSED(el);
2928 REDIS_NOTUSED(mask);
2929 REDIS_NOTUSED(privdata);
2930
2931 cfd = anetAccept(server.neterr, fd, cip, &cport);
2932 if (cfd == AE_ERR) {
2933 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
2934 return;
2935 }
2936 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
2937 if ((c = createClient(cfd)) == NULL) {
2938 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2939 close(cfd); /* May be already closed, just ingore errors */
2940 return;
2941 }
2942 /* If maxclient directive is set and this is one client more... close the
2943 * connection. Note that we create the client instead to check before
2944 * for this condition, since now the socket is already set in nonblocking
2945 * mode and we can send an error for free using the Kernel I/O */
2946 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2947 char *err = "-ERR max number of clients reached\r\n";
2948
2949 /* That's a best effort error message, don't check write errors */
2950 if (write(c->fd,err,strlen(err)) == -1) {
2951 /* Nothing to do, Just to avoid the warning... */
2952 }
2953 freeClient(c);
2954 return;
2955 }
2956 server.stat_numconnections++;
2957 }
2958
2959 /* ======================= Redis objects implementation ===================== */
2960
2961 static robj *createObject(int type, void *ptr) {
2962 robj *o;
2963
2964 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
2965 if (listLength(server.objfreelist)) {
2966 listNode *head = listFirst(server.objfreelist);
2967 o = listNodeValue(head);
2968 listDelNode(server.objfreelist,head);
2969 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
2970 } else {
2971 if (server.vm_enabled)
2972 pthread_mutex_unlock(&server.obj_freelist_mutex);
2973 o = zmalloc(sizeof(*o));
2974 }
2975 o->type = type;
2976 o->encoding = REDIS_ENCODING_RAW;
2977 o->ptr = ptr;
2978 o->refcount = 1;
2979 if (server.vm_enabled) {
2980 /* Note that this code may run in the context of an I/O thread
2981 * and accessing server.lruclock in theory is an error
2982 * (no locks). But in practice this is safe, and even if we read
2983 * garbage Redis will not fail. */
2984 o->lru = server.lruclock;
2985 o->storage = REDIS_VM_MEMORY;
2986 }
2987 return o;
2988 }
2989
2990 static robj *createStringObject(char *ptr, size_t len) {
2991 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
2992 }
2993
2994 static robj *createStringObjectFromLongLong(long long value) {
2995 robj *o;
2996 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
2997 incrRefCount(shared.integers[value]);
2998 o = shared.integers[value];
2999 } else {
3000 if (value >= LONG_MIN && value <= LONG_MAX) {
3001 o = createObject(REDIS_STRING, NULL);
3002 o->encoding = REDIS_ENCODING_INT;
3003 o->ptr = (void*)((long)value);
3004 } else {
3005 o = createObject(REDIS_STRING,sdsfromlonglong(value));
3006 }
3007 }
3008 return o;
3009 }
3010
3011 static robj *dupStringObject(robj *o) {
3012 assert(o->encoding == REDIS_ENCODING_RAW);
3013 return createStringObject(o->ptr,sdslen(o->ptr));
3014 }
3015
3016 static robj *createListObject(void) {
3017 list *l = listCreate();
3018
3019 listSetFreeMethod(l,decrRefCount);
3020 return createObject(REDIS_LIST,l);
3021 }
3022
3023 static robj *createSetObject(void) {
3024 dict *d = dictCreate(&setDictType,NULL);
3025 return createObject(REDIS_SET,d);
3026 }
3027
3028 static robj *createHashObject(void) {
3029 /* All the Hashes start as zipmaps. Will be automatically converted
3030 * into hash tables if there are enough elements or big elements
3031 * inside. */
3032 unsigned char *zm = zipmapNew();
3033 robj *o = createObject(REDIS_HASH,zm);
3034 o->encoding = REDIS_ENCODING_ZIPMAP;
3035 return o;
3036 }
3037
3038 static robj *createZsetObject(void) {
3039 zset *zs = zmalloc(sizeof(*zs));
3040
3041 zs->dict = dictCreate(&zsetDictType,NULL);
3042 zs->zsl = zslCreate();
3043 return createObject(REDIS_ZSET,zs);
3044 }
3045
3046 static void freeStringObject(robj *o) {
3047 if (o->encoding == REDIS_ENCODING_RAW) {
3048 sdsfree(o->ptr);
3049 }
3050 }
3051
3052 static void freeListObject(robj *o) {
3053 listRelease((list*) o->ptr);
3054 }
3055
3056 static void freeSetObject(robj *o) {
3057 dictRelease((dict*) o->ptr);
3058 }
3059
3060 static void freeZsetObject(robj *o) {
3061 zset *zs = o->ptr;
3062
3063 dictRelease(zs->dict);
3064 zslFree(zs->zsl);
3065 zfree(zs);
3066 }
3067
3068 static void freeHashObject(robj *o) {
3069 switch (o->encoding) {
3070 case REDIS_ENCODING_HT:
3071 dictRelease((dict*) o->ptr);
3072 break;
3073 case REDIS_ENCODING_ZIPMAP:
3074 zfree(o->ptr);
3075 break;
3076 default:
3077 redisPanic("Unknown hash encoding type");
3078 break;
3079 }
3080 }
3081
3082 static void incrRefCount(robj *o) {
3083 o->refcount++;
3084 }
3085
3086 static void decrRefCount(void *obj) {
3087 robj *o = obj;
3088
3089 /* Object is a swapped out value, or in the process of being loaded. */
3090 if (server.vm_enabled &&
3091 (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
3092 {
3093 vmpointer *vp = obj;
3094 if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(o);
3095 vmMarkPagesFree(vp->page,vp->usedpages);
3096 server.vm_stats_swapped_objects--;
3097 zfree(vp);
3098 return;
3099 }
3100
3101 if (o->refcount <= 0) redisPanic("decrRefCount against refcount <= 0");
3102 /* Object is in memory, or in the process of being swapped out.
3103 *
3104 * If the object is being swapped out, abort the operation on
3105 * decrRefCount even if the refcount does not drop to 0: the object
3106 * is referenced at least two times, as value of the key AND as
3107 * job->val in the iojob. So if we don't invalidate the iojob, when it is
3108 * done but the relevant key was removed in the meantime, the
3109 * complete jobs handler will not find the key about the job and the
3110 * assert will fail. */
3111 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
3112 vmCancelThreadedIOJob(o);
3113 if (--(o->refcount) == 0) {
3114 switch(o->type) {
3115 case REDIS_STRING: freeStringObject(o); break;
3116 case REDIS_LIST: freeListObject(o); break;
3117 case REDIS_SET: freeSetObject(o); break;
3118 case REDIS_ZSET: freeZsetObject(o); break;
3119 case REDIS_HASH: freeHashObject(o); break;
3120 default: redisPanic("Unknown object type"); break;
3121 }
3122 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
3123 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3124 !listAddNodeHead(server.objfreelist,o))
3125 zfree(o);
3126 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
3127 }
3128 }
3129
3130 static int checkType(redisClient *c, robj *o, int type) {
3131 if (o->type != type) {
3132 addReply(c,shared.wrongtypeerr);
3133 return 1;
3134 }
3135 return 0;
3136 }
3137
3138 /* Check if the nul-terminated string 's' can be represented by a long
3139 * (that is, is a number that fits into long without any other space or
3140 * character before or after the digits).
3141 *
3142 * If so, the function returns REDIS_OK and *longval is set to the value
3143 * of the number. Otherwise REDIS_ERR is returned */
3144 static int isStringRepresentableAsLong(sds s, long *longval) {
3145 char buf[32], *endptr;
3146 long value;
3147 int slen;
3148
3149 value = strtol(s, &endptr, 10);
3150 if (endptr[0] != '\0') return REDIS_ERR;
3151 slen = ll2string(buf,32,value);
3152
3153 /* If the number converted back into a string is not identical
3154 * then it's not possible to encode the string as integer */
3155 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
3156 if (longval) *longval = value;
3157 return REDIS_OK;
3158 }
3159
3160 /* Try to encode a string object in order to save space */
3161 static robj *tryObjectEncoding(robj *o) {
3162 long value;
3163 sds s = o->ptr;
3164
3165 if (o->encoding != REDIS_ENCODING_RAW)
3166 return o; /* Already encoded */
3167
3168 /* It's not safe to encode shared objects: shared objects can be shared
3169 * everywhere in the "object space" of Redis. Encoded objects can only
3170 * appear as "values" (and not, for instance, as keys) */
3171 if (o->refcount > 1) return o;
3172
3173 /* Currently we try to encode only strings */
3174 redisAssert(o->type == REDIS_STRING);
3175
3176 /* Check if we can represent this string as a long integer */
3177 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return o;
3178
3179 /* Ok, this object can be encoded */
3180 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3181 decrRefCount(o);
3182 incrRefCount(shared.integers[value]);
3183 return shared.integers[value];
3184 } else {
3185 o->encoding = REDIS_ENCODING_INT;
3186 sdsfree(o->ptr);
3187 o->ptr = (void*) value;
3188 return o;
3189 }
3190 }
3191
3192 /* Get a decoded version of an encoded object (returned as a new object).
3193 * If the object is already raw-encoded just increment the ref count. */
3194 static robj *getDecodedObject(robj *o) {
3195 robj *dec;
3196
3197 if (o->encoding == REDIS_ENCODING_RAW) {
3198 incrRefCount(o);
3199 return o;
3200 }
3201 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
3202 char buf[32];
3203
3204 ll2string(buf,32,(long)o->ptr);
3205 dec = createStringObject(buf,strlen(buf));
3206 return dec;
3207 } else {
3208 redisPanic("Unknown encoding type");
3209 }
3210 }
3211
3212 /* Compare two string objects via strcmp() or alike.
3213 * Note that the objects may be integer-encoded. In such a case we
3214 * use ll2string() to get a string representation of the numbers on the stack
3215 * and compare the strings, it's much faster than calling getDecodedObject().
3216 *
3217 * Important note: if objects are not integer encoded, but binary-safe strings,
3218 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3219 * binary safe. */
3220 static int compareStringObjects(robj *a, robj *b) {
3221 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
3222 char bufa[128], bufb[128], *astr, *bstr;
3223 int bothsds = 1;
3224
3225 if (a == b) return 0;
3226 if (a->encoding != REDIS_ENCODING_RAW) {
3227 ll2string(bufa,sizeof(bufa),(long) a->ptr);
3228 astr = bufa;
3229 bothsds = 0;
3230 } else {
3231 astr = a->ptr;
3232 }
3233 if (b->encoding != REDIS_ENCODING_RAW) {
3234 ll2string(bufb,sizeof(bufb),(long) b->ptr);
3235 bstr = bufb;
3236 bothsds = 0;
3237 } else {
3238 bstr = b->ptr;
3239 }
3240 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
3241 }
3242
3243 /* Equal string objects return 1 if the two objects are the same from the
3244 * point of view of a string comparison, otherwise 0 is returned. Note that
3245 * this function is faster then checking for (compareStringObject(a,b) == 0)
3246 * because it can perform some more optimization. */
3247 static int equalStringObjects(robj *a, robj *b) {
3248 if (a->encoding != REDIS_ENCODING_RAW && b->encoding != REDIS_ENCODING_RAW){
3249 return a->ptr == b->ptr;
3250 } else {
3251 return compareStringObjects(a,b) == 0;
3252 }
3253 }
3254
3255 static size_t stringObjectLen(robj *o) {
3256 redisAssert(o->type == REDIS_STRING);
3257 if (o->encoding == REDIS_ENCODING_RAW) {
3258 return sdslen(o->ptr);
3259 } else {
3260 char buf[32];
3261
3262 return ll2string(buf,32,(long)o->ptr);
3263 }
3264 }
3265
3266 static int getDoubleFromObject(robj *o, double *target) {
3267 double value;
3268 char *eptr;
3269
3270 if (o == NULL) {
3271 value = 0;
3272 } else {
3273 redisAssert(o->type == REDIS_STRING);
3274 if (o->encoding == REDIS_ENCODING_RAW) {
3275 value = strtod(o->ptr, &eptr);
3276 if (eptr[0] != '\0') return REDIS_ERR;
3277 } else if (o->encoding == REDIS_ENCODING_INT) {
3278 value = (long)o->ptr;
3279 } else {
3280 redisPanic("Unknown string encoding");
3281 }
3282 }
3283
3284 *target = value;
3285 return REDIS_OK;
3286 }
3287
3288 static int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg) {
3289 double value;
3290 if (getDoubleFromObject(o, &value) != REDIS_OK) {
3291 if (msg != NULL) {
3292 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3293 } else {
3294 addReplySds(c, sdsnew("-ERR value is not a double\r\n"));
3295 }
3296 return REDIS_ERR;
3297 }
3298
3299 *target = value;
3300 return REDIS_OK;
3301 }
3302
3303 static int getLongLongFromObject(robj *o, long long *target) {
3304 long long value;
3305 char *eptr;
3306
3307 if (o == NULL) {
3308 value = 0;
3309 } else {
3310 redisAssert(o->type == REDIS_STRING);
3311 if (o->encoding == REDIS_ENCODING_RAW) {
3312 value = strtoll(o->ptr, &eptr, 10);
3313 if (eptr[0] != '\0') return REDIS_ERR;
3314 } else if (o->encoding == REDIS_ENCODING_INT) {
3315 value = (long)o->ptr;
3316 } else {
3317 redisPanic("Unknown string encoding");
3318 }
3319 }
3320
3321 *target = value;
3322 return REDIS_OK;
3323 }
3324
3325 static int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg) {
3326 long long value;
3327 if (getLongLongFromObject(o, &value) != REDIS_OK) {
3328 if (msg != NULL) {
3329 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3330 } else {
3331 addReplySds(c, sdsnew("-ERR value is not an integer\r\n"));
3332 }
3333 return REDIS_ERR;
3334 }
3335
3336 *target = value;
3337 return REDIS_OK;
3338 }
3339
3340 static int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg) {
3341 long long value;
3342
3343 if (getLongLongFromObjectOrReply(c, o, &value, msg) != REDIS_OK) return REDIS_ERR;
3344 if (value < LONG_MIN || value > LONG_MAX) {
3345 if (msg != NULL) {
3346 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3347 } else {
3348 addReplySds(c, sdsnew("-ERR value is out of range\r\n"));
3349 }
3350 return REDIS_ERR;
3351 }
3352
3353 *target = value;
3354 return REDIS_OK;
3355 }
3356
3357 /* =========================== Keyspace access API ========================== */
3358
3359 static robj *lookupKey(redisDb *db, robj *key) {
3360 dictEntry *de = dictFind(db->dict,key);
3361 if (de) {
3362 robj *key = dictGetEntryKey(de);
3363 robj *val = dictGetEntryVal(de);
3364
3365 if (server.vm_enabled) {
3366 if (val->storage == REDIS_VM_MEMORY ||
3367 val->storage == REDIS_VM_SWAPPING)
3368 {
3369 /* If we were swapping the object out, cancel the operation */
3370 if (val->storage == REDIS_VM_SWAPPING)
3371 vmCancelThreadedIOJob(val);
3372 /* Update the access time of the key for the aging algorithm. */
3373 val->lru = server.lruclock;
3374 } else {
3375 int notify = (val->storage == REDIS_VM_LOADING);
3376
3377 /* Our value was swapped on disk. Bring it at home. */
3378 redisAssert(val->type == REDIS_VMPOINTER);
3379 val = vmLoadObject(val);
3380 dictGetEntryVal(de) = val;
3381
3382 /* Clients blocked by the VM subsystem may be waiting for
3383 * this key... */
3384 if (notify) handleClientsBlockedOnSwappedKey(db,key);
3385 }
3386 }
3387 return val;
3388 } else {
3389 return NULL;
3390 }
3391 }
3392
3393 static robj *lookupKeyRead(redisDb *db, robj *key) {
3394 expireIfNeeded(db,key);
3395 return lookupKey(db,key);
3396 }
3397
3398 static robj *lookupKeyWrite(redisDb *db, robj *key) {
3399 deleteIfVolatile(db,key);
3400 touchWatchedKey(db,key);
3401 return lookupKey(db,key);
3402 }
3403
3404 static robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
3405 robj *o = lookupKeyRead(c->db, key);
3406 if (!o) addReply(c,reply);
3407 return o;
3408 }
3409
3410 static robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
3411 robj *o = lookupKeyWrite(c->db, key);
3412 if (!o) addReply(c,reply);
3413 return o;
3414 }
3415
3416 static int deleteKey(redisDb *db, robj *key) {
3417 int retval;
3418
3419 /* We need to protect key from destruction: after the first dictDelete()
3420 * it may happen that 'key' is no longer valid if we don't increment
3421 * it's count. This may happen when we get the object reference directly
3422 * from the hash table with dictRandomKey() or dict iterators */
3423 incrRefCount(key);
3424 if (dictSize(db->expires)) dictDelete(db->expires,key);
3425 retval = dictDelete(db->dict,key);
3426 decrRefCount(key);
3427
3428 return retval == DICT_OK;
3429 }
3430
3431 /*============================ RDB saving/loading =========================== */
3432
3433 static int rdbSaveType(FILE *fp, unsigned char type) {
3434 if (fwrite(&type,1,1,fp) == 0) return -1;
3435 return 0;
3436 }
3437
3438 static int rdbSaveTime(FILE *fp, time_t t) {
3439 int32_t t32 = (int32_t) t;
3440 if (fwrite(&t32,4,1,fp) == 0) return -1;
3441 return 0;
3442 }
3443
3444 /* check rdbLoadLen() comments for more info */
3445 static int rdbSaveLen(FILE *fp, uint32_t len) {
3446 unsigned char buf[2];
3447
3448 if (len < (1<<6)) {
3449 /* Save a 6 bit len */
3450 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
3451 if (fwrite(buf,1,1,fp) == 0) return -1;
3452 } else if (len < (1<<14)) {
3453 /* Save a 14 bit len */
3454 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
3455 buf[1] = len&0xFF;
3456 if (fwrite(buf,2,1,fp) == 0) return -1;
3457 } else {
3458 /* Save a 32 bit len */
3459 buf[0] = (REDIS_RDB_32BITLEN<<6);
3460 if (fwrite(buf,1,1,fp) == 0) return -1;
3461 len = htonl(len);
3462 if (fwrite(&len,4,1,fp) == 0) return -1;
3463 }
3464 return 0;
3465 }
3466
3467 /* Encode 'value' as an integer if possible (if integer will fit the
3468 * supported range). If the function sucessful encoded the integer
3469 * then the (up to 5 bytes) encoded representation is written in the
3470 * string pointed by 'enc' and the length is returned. Otherwise
3471 * 0 is returned. */
3472 static int rdbEncodeInteger(long long value, unsigned char *enc) {
3473 /* Finally check if it fits in our ranges */
3474 if (value >= -(1<<7) && value <= (1<<7)-1) {
3475 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
3476 enc[1] = value&0xFF;
3477 return 2;
3478 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
3479 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
3480 enc[1] = value&0xFF;
3481 enc[2] = (value>>8)&0xFF;
3482 return 3;
3483 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
3484 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
3485 enc[1] = value&0xFF;
3486 enc[2] = (value>>8)&0xFF;
3487 enc[3] = (value>>16)&0xFF;
3488 enc[4] = (value>>24)&0xFF;
3489 return 5;
3490 } else {
3491 return 0;
3492 }
3493 }
3494
3495 /* String objects in the form "2391" "-100" without any space and with a
3496 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3497 * encoded as integers to save space */
3498 static int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
3499 long long value;
3500 char *endptr, buf[32];
3501
3502 /* Check if it's possible to encode this value as a number */
3503 value = strtoll(s, &endptr, 10);
3504 if (endptr[0] != '\0') return 0;
3505 ll2string(buf,32,value);
3506
3507 /* If the number converted back into a string is not identical
3508 * then it's not possible to encode the string as integer */
3509 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
3510
3511 return rdbEncodeInteger(value,enc);
3512 }
3513
3514 static int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
3515 size_t comprlen, outlen;
3516 unsigned char byte;
3517 void *out;
3518
3519 /* We require at least four bytes compression for this to be worth it */
3520 if (len <= 4) return 0;
3521 outlen = len-4;
3522 if ((out = zmalloc(outlen+1)) == NULL) return 0;
3523 comprlen = lzf_compress(s, len, out, outlen);
3524 if (comprlen == 0) {
3525 zfree(out);
3526 return 0;
3527 }
3528 /* Data compressed! Let's save it on disk */
3529 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
3530 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
3531 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
3532 if (rdbSaveLen(fp,len) == -1) goto writeerr;
3533 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
3534 zfree(out);
3535 return comprlen;
3536
3537 writeerr:
3538 zfree(out);
3539 return -1;
3540 }
3541
3542 /* Save a string objet as [len][data] on disk. If the object is a string
3543 * representation of an integer value we try to safe it in a special form */
3544 static int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
3545 int enclen;
3546
3547 /* Try integer encoding */
3548 if (len <= 11) {
3549 unsigned char buf[5];
3550 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
3551 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3552 return 0;
3553 }
3554 }
3555
3556 /* Try LZF compression - under 20 bytes it's unable to compress even
3557 * aaaaaaaaaaaaaaaaaa so skip it */
3558 if (server.rdbcompression && len > 20) {
3559 int retval;
3560
3561 retval = rdbSaveLzfStringObject(fp,s,len);
3562 if (retval == -1) return -1;
3563 if (retval > 0) return 0;
3564 /* retval == 0 means data can't be compressed, save the old way */
3565 }
3566
3567 /* Store verbatim */
3568 if (rdbSaveLen(fp,len) == -1) return -1;
3569 if (len && fwrite(s,len,1,fp) == 0) return -1;
3570 return 0;
3571 }
3572
3573 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3574 static int rdbSaveStringObject(FILE *fp, robj *obj) {
3575 int retval;
3576
3577 /* Avoid to decode the object, then encode it again, if the
3578 * object is alrady integer encoded. */
3579 if (obj->encoding == REDIS_ENCODING_INT) {
3580 long val = (long) obj->ptr;
3581 unsigned char buf[5];
3582 int enclen;
3583
3584 if ((enclen = rdbEncodeInteger(val,buf)) > 0) {
3585 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3586 return 0;
3587 }
3588 /* otherwise... fall throught and continue with the usual
3589 * code path. */
3590 }
3591
3592 /* Avoid incr/decr ref count business when possible.
3593 * This plays well with copy-on-write given that we are probably
3594 * in a child process (BGSAVE). Also this makes sure key objects
3595 * of swapped objects are not incRefCount-ed (an assert does not allow
3596 * this in order to avoid bugs) */
3597 if (obj->encoding != REDIS_ENCODING_RAW) {
3598 obj = getDecodedObject(obj);
3599 retval = rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
3600 decrRefCount(obj);
3601 } else {
3602 retval = rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
3603 }
3604 return retval;
3605 }
3606
3607 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3608 * 8 bit integer specifing the length of the representation.
3609 * This 8 bit integer has special values in order to specify the following
3610 * conditions:
3611 * 253: not a number
3612 * 254: + inf
3613 * 255: - inf
3614 */
3615 static int rdbSaveDoubleValue(FILE *fp, double val) {
3616 unsigned char buf[128];
3617 int len;
3618
3619 if (isnan(val)) {
3620 buf[0] = 253;
3621 len = 1;
3622 } else if (!isfinite(val)) {
3623 len = 1;
3624 buf[0] = (val < 0) ? 255 : 254;
3625 } else {
3626 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
3627 /* Check if the float is in a safe range to be casted into a
3628 * long long. We are assuming that long long is 64 bit here.
3629 * Also we are assuming that there are no implementations around where
3630 * double has precision < 52 bit.
3631 *
3632 * Under this assumptions we test if a double is inside an interval
3633 * where casting to long long is safe. Then using two castings we
3634 * make sure the decimal part is zero. If all this is true we use
3635 * integer printing function that is much faster. */
3636 double min = -4503599627370495; /* (2^52)-1 */
3637 double max = 4503599627370496; /* -(2^52) */
3638 if (val > min && val < max && val == ((double)((long long)val)))
3639 ll2string((char*)buf+1,sizeof(buf),(long long)val);
3640 else
3641 #endif
3642 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
3643 buf[0] = strlen((char*)buf+1);
3644 len = buf[0]+1;
3645 }
3646 if (fwrite(buf,len,1,fp) == 0) return -1;
3647 return 0;
3648 }
3649
3650 /* Save a Redis object. */
3651 static int rdbSaveObject(FILE *fp, robj *o) {
3652 if (o->type == REDIS_STRING) {
3653 /* Save a string value */
3654 if (rdbSaveStringObject(fp,o) == -1) return -1;
3655 } else if (o->type == REDIS_LIST) {
3656 /* Save a list value */
3657 list *list = o->ptr;
3658 listIter li;
3659 listNode *ln;
3660
3661 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
3662 listRewind(list,&li);
3663 while((ln = listNext(&li))) {
3664 robj *eleobj = listNodeValue(ln);
3665
3666 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3667 }
3668 } else if (o->type == REDIS_SET) {
3669 /* Save a set value */
3670 dict *set = o->ptr;
3671 dictIterator *di = dictGetIterator(set);
3672 dictEntry *de;
3673
3674 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
3675 while((de = dictNext(di)) != NULL) {
3676 robj *eleobj = dictGetEntryKey(de);
3677
3678 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3679 }
3680 dictReleaseIterator(di);
3681 } else if (o->type == REDIS_ZSET) {
3682 /* Save a set value */
3683 zset *zs = o->ptr;
3684 dictIterator *di = dictGetIterator(zs->dict);
3685 dictEntry *de;
3686
3687 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
3688 while((de = dictNext(di)) != NULL) {
3689 robj *eleobj = dictGetEntryKey(de);
3690 double *score = dictGetEntryVal(de);
3691
3692 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3693 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
3694 }
3695 dictReleaseIterator(di);
3696 } else if (o->type == REDIS_HASH) {
3697 /* Save a hash value */
3698 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3699 unsigned char *p = zipmapRewind(o->ptr);
3700 unsigned int count = zipmapLen(o->ptr);
3701 unsigned char *key, *val;
3702 unsigned int klen, vlen;
3703
3704 if (rdbSaveLen(fp,count) == -1) return -1;
3705 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
3706 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
3707 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
3708 }
3709 } else {
3710 dictIterator *di = dictGetIterator(o->ptr);
3711 dictEntry *de;
3712
3713 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
3714 while((de = dictNext(di)) != NULL) {
3715 robj *key = dictGetEntryKey(de);
3716 robj *val = dictGetEntryVal(de);
3717
3718 if (rdbSaveStringObject(fp,key) == -1) return -1;
3719 if (rdbSaveStringObject(fp,val) == -1) return -1;
3720 }
3721 dictReleaseIterator(di);
3722 }
3723 } else {
3724 redisPanic("Unknown object type");
3725 }
3726 return 0;
3727 }
3728
3729 /* Return the length the object will have on disk if saved with
3730 * the rdbSaveObject() function. Currently we use a trick to get
3731 * this length with very little changes to the code. In the future
3732 * we could switch to a faster solution. */
3733 static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
3734 if (fp == NULL) fp = server.devnull;
3735 rewind(fp);
3736 assert(rdbSaveObject(fp,o) != 1);
3737 return ftello(fp);
3738 }
3739
3740 /* Return the number of pages required to save this object in the swap file */
3741 static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
3742 off_t bytes = rdbSavedObjectLen(o,fp);
3743
3744 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
3745 }
3746
3747 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3748 static int rdbSave(char *filename) {
3749 dictIterator *di = NULL;
3750 dictEntry *de;
3751 FILE *fp;
3752 char tmpfile[256];
3753 int j;
3754 time_t now = time(NULL);
3755
3756 /* Wait for I/O therads to terminate, just in case this is a
3757 * foreground-saving, to avoid seeking the swap file descriptor at the
3758 * same time. */
3759 if (server.vm_enabled)
3760 waitEmptyIOJobsQueue();
3761
3762 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
3763 fp = fopen(tmpfile,"w");
3764 if (!fp) {
3765 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
3766 return REDIS_ERR;
3767 }
3768 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
3769 for (j = 0; j < server.dbnum; j++) {
3770 redisDb *db = server.db+j;
3771 dict *d = db->dict;
3772 if (dictSize(d) == 0) continue;
3773 di = dictGetIterator(d);
3774 if (!di) {
3775 fclose(fp);
3776 return REDIS_ERR;
3777 }
3778
3779 /* Write the SELECT DB opcode */
3780 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
3781 if (rdbSaveLen(fp,j) == -1) goto werr;
3782
3783 /* Iterate this DB writing every entry */
3784 while((de = dictNext(di)) != NULL) {
3785 robj *key = dictGetEntryKey(de);
3786 robj *o = dictGetEntryVal(de);
3787 time_t expiretime = getExpire(db,key);
3788
3789 /* Save the expire time */
3790 if (expiretime != -1) {
3791 /* If this key is already expired skip it */
3792 if (expiretime < now) continue;
3793 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
3794 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
3795 }
3796 /* Save the key and associated value. This requires special
3797 * handling if the value is swapped out. */
3798 if (!server.vm_enabled || o->storage == REDIS_VM_MEMORY ||
3799 o->storage == REDIS_VM_SWAPPING) {
3800 /* Save type, key, value */
3801 if (rdbSaveType(fp,o->type) == -1) goto werr;
3802 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3803 if (rdbSaveObject(fp,o) == -1) goto werr;
3804 } else {
3805 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3806 robj *po;
3807 /* Get a preview of the object in memory */
3808 po = vmPreviewObject(o);
3809 /* Save type, key, value */
3810 if (rdbSaveType(fp,po->type) == -1) goto werr;
3811 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3812 if (rdbSaveObject(fp,po) == -1) goto werr;
3813 /* Remove the loaded object from memory */
3814 decrRefCount(po);
3815 }
3816 }
3817 dictReleaseIterator(di);
3818 }
3819 /* EOF opcode */
3820 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
3821
3822 /* Make sure data will not remain on the OS's output buffers */
3823 fflush(fp);
3824 fsync(fileno(fp));
3825 fclose(fp);
3826
3827 /* Use RENAME to make sure the DB file is changed atomically only
3828 * if the generate DB file is ok. */
3829 if (rename(tmpfile,filename) == -1) {
3830 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
3831 unlink(tmpfile);
3832 return REDIS_ERR;
3833 }
3834 redisLog(REDIS_NOTICE,"DB saved on disk");
3835 server.dirty = 0;
3836 server.lastsave = time(NULL);
3837 return REDIS_OK;
3838
3839 werr:
3840 fclose(fp);
3841 unlink(tmpfile);
3842 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
3843 if (di) dictReleaseIterator(di);
3844 return REDIS_ERR;
3845 }
3846
3847 static int rdbSaveBackground(char *filename) {
3848 pid_t childpid;
3849
3850 if (server.bgsavechildpid != -1) return REDIS_ERR;
3851 if (server.vm_enabled) waitEmptyIOJobsQueue();
3852 if ((childpid = fork()) == 0) {
3853 /* Child */
3854 if (server.vm_enabled) vmReopenSwapFile();
3855 close(server.fd);
3856 if (rdbSave(filename) == REDIS_OK) {
3857 _exit(0);
3858 } else {
3859 _exit(1);
3860 }
3861 } else {
3862 /* Parent */
3863 if (childpid == -1) {
3864 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
3865 strerror(errno));
3866 return REDIS_ERR;
3867 }
3868 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
3869 server.bgsavechildpid = childpid;
3870 updateDictResizePolicy();
3871 return REDIS_OK;
3872 }
3873 return REDIS_OK; /* unreached */
3874 }
3875
3876 static void rdbRemoveTempFile(pid_t childpid) {
3877 char tmpfile[256];
3878
3879 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
3880 unlink(tmpfile);
3881 }
3882
3883 static int rdbLoadType(FILE *fp) {
3884 unsigned char type;
3885 if (fread(&type,1,1,fp) == 0) return -1;
3886 return type;
3887 }
3888
3889 static time_t rdbLoadTime(FILE *fp) {
3890 int32_t t32;
3891 if (fread(&t32,4,1,fp) == 0) return -1;
3892 return (time_t) t32;
3893 }
3894
3895 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3896 * of this file for a description of how this are stored on disk.
3897 *
3898 * isencoded is set to 1 if the readed length is not actually a length but
3899 * an "encoding type", check the above comments for more info */
3900 static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
3901 unsigned char buf[2];
3902 uint32_t len;
3903 int type;
3904
3905 if (isencoded) *isencoded = 0;
3906 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
3907 type = (buf[0]&0xC0)>>6;
3908 if (type == REDIS_RDB_6BITLEN) {
3909 /* Read a 6 bit len */
3910 return buf[0]&0x3F;
3911 } else if (type == REDIS_RDB_ENCVAL) {
3912 /* Read a 6 bit len encoding type */
3913 if (isencoded) *isencoded = 1;
3914 return buf[0]&0x3F;
3915 } else if (type == REDIS_RDB_14BITLEN) {
3916 /* Read a 14 bit len */
3917 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
3918 return ((buf[0]&0x3F)<<8)|buf[1];
3919 } else {
3920 /* Read a 32 bit len */
3921 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
3922 return ntohl(len);
3923 }
3924 }
3925
3926 /* Load an integer-encoded object from file 'fp', with the specified
3927 * encoding type 'enctype'. If encode is true the function may return
3928 * an integer-encoded object as reply, otherwise the returned object
3929 * will always be encoded as a raw string. */
3930 static robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
3931 unsigned char enc[4];
3932 long long val;
3933
3934 if (enctype == REDIS_RDB_ENC_INT8) {
3935 if (fread(enc,1,1,fp) == 0) return NULL;
3936 val = (signed char)enc[0];
3937 } else if (enctype == REDIS_RDB_ENC_INT16) {
3938 uint16_t v;
3939 if (fread(enc,2,1,fp) == 0) return NULL;
3940 v = enc[0]|(enc[1]<<8);
3941 val = (int16_t)v;
3942 } else if (enctype == REDIS_RDB_ENC_INT32) {
3943 uint32_t v;
3944 if (fread(enc,4,1,fp) == 0) return NULL;
3945 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
3946 val = (int32_t)v;
3947 } else {
3948 val = 0; /* anti-warning */
3949 redisPanic("Unknown RDB integer encoding type");
3950 }
3951 if (encode)
3952 return createStringObjectFromLongLong(val);
3953 else
3954 return createObject(REDIS_STRING,sdsfromlonglong(val));
3955 }
3956
3957 static robj *rdbLoadLzfStringObject(FILE*fp) {
3958 unsigned int len, clen;
3959 unsigned char *c = NULL;
3960 sds val = NULL;
3961
3962 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3963 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3964 if ((c = zmalloc(clen)) == NULL) goto err;
3965 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
3966 if (fread(c,clen,1,fp) == 0) goto err;
3967 if (lzf_decompress(c,clen,val,len) == 0) goto err;
3968 zfree(c);
3969 return createObject(REDIS_STRING,val);
3970 err:
3971 zfree(c);
3972 sdsfree(val);
3973 return NULL;
3974 }
3975
3976 static robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
3977 int isencoded;
3978 uint32_t len;
3979 sds val;
3980
3981 len = rdbLoadLen(fp,&isencoded);
3982 if (isencoded) {
3983 switch(len) {
3984 case REDIS_RDB_ENC_INT8:
3985 case REDIS_RDB_ENC_INT16:
3986 case REDIS_RDB_ENC_INT32:
3987 return rdbLoadIntegerObject(fp,len,encode);
3988 case REDIS_RDB_ENC_LZF:
3989 return rdbLoadLzfStringObject(fp);
3990 default:
3991 redisPanic("Unknown RDB encoding type");
3992 }
3993 }
3994
3995 if (len == REDIS_RDB_LENERR) return NULL;
3996 val = sdsnewlen(NULL,len);
3997 if (len && fread(val,len,1,fp) == 0) {
3998 sdsfree(val);
3999 return NULL;
4000 }
4001 return createObject(REDIS_STRING,val);
4002 }
4003
4004 static robj *rdbLoadStringObject(FILE *fp) {
4005 return rdbGenericLoadStringObject(fp,0);
4006 }
4007
4008 static robj *rdbLoadEncodedStringObject(FILE *fp) {
4009 return rdbGenericLoadStringObject(fp,1);
4010 }
4011
4012 /* For information about double serialization check rdbSaveDoubleValue() */
4013 static int rdbLoadDoubleValue(FILE *fp, double *val) {
4014 char buf[128];
4015 unsigned char len;
4016
4017 if (fread(&len,1,1,fp) == 0) return -1;
4018 switch(len) {
4019 case 255: *val = R_NegInf; return 0;
4020 case 254: *val = R_PosInf; return 0;
4021 case 253: *val = R_Nan; return 0;
4022 default:
4023 if (fread(buf,len,1,fp) == 0) return -1;
4024 buf[len] = '\0';
4025 sscanf(buf, "%lg", val);
4026 return 0;
4027 }
4028 }
4029
4030 /* Load a Redis object of the specified type from the specified file.
4031 * On success a newly allocated object is returned, otherwise NULL. */
4032 static robj *rdbLoadObject(int type, FILE *fp) {
4033 robj *o;
4034
4035 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
4036 if (type == REDIS_STRING) {
4037 /* Read string value */
4038 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4039 o = tryObjectEncoding(o);
4040 } else if (type == REDIS_LIST || type == REDIS_SET) {
4041 /* Read list/set value */
4042 uint32_t listlen;
4043
4044 if ((listlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4045 o = (type == REDIS_LIST) ? createListObject() : createSetObject();
4046 /* It's faster to expand the dict to the right size asap in order
4047 * to avoid rehashing */
4048 if (type == REDIS_SET && listlen > DICT_HT_INITIAL_SIZE)
4049 dictExpand(o->ptr,listlen);
4050 /* Load every single element of the list/set */
4051 while(listlen--) {
4052 robj *ele;
4053
4054 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4055 ele = tryObjectEncoding(ele);
4056 if (type == REDIS_LIST) {
4057 listAddNodeTail((list*)o->ptr,ele);
4058 } else {
4059 dictAdd((dict*)o->ptr,ele,NULL);
4060 }
4061 }
4062 } else if (type == REDIS_ZSET) {
4063 /* Read list/set value */
4064 size_t zsetlen;
4065 zset *zs;
4066
4067 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4068 o = createZsetObject();
4069 zs = o->ptr;
4070 /* Load every single element of the list/set */
4071 while(zsetlen--) {
4072 robj *ele;
4073 double *score = zmalloc(sizeof(double));
4074
4075 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4076 ele = tryObjectEncoding(ele);
4077 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
4078 dictAdd(zs->dict,ele,score);
4079 zslInsert(zs->zsl,*score,ele);
4080 incrRefCount(ele); /* added to skiplist */
4081 }
4082 } else if (type == REDIS_HASH) {
4083 size_t hashlen;
4084
4085 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4086 o = createHashObject();
4087 /* Too many entries? Use an hash table. */
4088 if (hashlen > server.hash_max_zipmap_entries)
4089 convertToRealHash(o);
4090 /* Load every key/value, then set it into the zipmap or hash
4091 * table, as needed. */
4092 while(hashlen--) {
4093 robj *key, *val;
4094
4095 if ((key = rdbLoadStringObject(fp)) == NULL) return NULL;
4096 if ((val = rdbLoadStringObject(fp)) == NULL) return NULL;
4097 /* If we are using a zipmap and there are too big values
4098 * the object is converted to real hash table encoding. */
4099 if (o->encoding != REDIS_ENCODING_HT &&
4100 (sdslen(key->ptr) > server.hash_max_zipmap_value ||
4101 sdslen(val->ptr) > server.hash_max_zipmap_value))
4102 {
4103 convertToRealHash(o);
4104 }
4105
4106 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
4107 unsigned char *zm = o->ptr;
4108
4109 zm = zipmapSet(zm,key->ptr,sdslen(key->ptr),
4110 val->ptr,sdslen(val->ptr),NULL);
4111 o->ptr = zm;
4112 decrRefCount(key);
4113 decrRefCount(val);
4114 } else {
4115 key = tryObjectEncoding(key);
4116 val = tryObjectEncoding(val);
4117 dictAdd((dict*)o->ptr,key,val);
4118 }
4119 }
4120 } else {
4121 redisPanic("Unknown object type");
4122 }
4123 return o;
4124 }
4125
4126 static int rdbLoad(char *filename) {
4127 FILE *fp;
4128 uint32_t dbid;
4129 int type, retval, rdbver;
4130 int swap_all_values = 0;
4131 dict *d = server.db[0].dict;
4132 redisDb *db = server.db+0;
4133 char buf[1024];
4134 time_t expiretime, now = time(NULL);
4135 long long loadedkeys = 0;
4136
4137 fp = fopen(filename,"r");
4138 if (!fp) return REDIS_ERR;
4139 if (fread(buf,9,1,fp) == 0) goto eoferr;
4140 buf[9] = '\0';
4141 if (memcmp(buf,"REDIS",5) != 0) {
4142 fclose(fp);
4143 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
4144 return REDIS_ERR;
4145 }
4146 rdbver = atoi(buf+5);
4147 if (rdbver != 1) {
4148 fclose(fp);
4149 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
4150 return REDIS_ERR;
4151 }
4152 while(1) {
4153 robj *key, *val;
4154
4155 expiretime = -1;
4156 /* Read type. */
4157 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4158 if (type == REDIS_EXPIRETIME) {
4159 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
4160 /* We read the time so we need to read the object type again */
4161 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4162 }
4163 if (type == REDIS_EOF) break;
4164 /* Handle SELECT DB opcode as a special case */
4165 if (type == REDIS_SELECTDB) {
4166 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
4167 goto eoferr;
4168 if (dbid >= (unsigned)server.dbnum) {
4169 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
4170 exit(1);
4171 }
4172 db = server.db+dbid;
4173 d = db->dict;
4174 continue;
4175 }
4176 /* Read key */
4177 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
4178 /* Read value */
4179 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
4180 /* Check if the key already expired */
4181 if (expiretime != -1 && expiretime < now) {
4182 decrRefCount(key);
4183 decrRefCount(val);
4184 continue;
4185 }
4186 /* Add the new object in the hash table */
4187 retval = dictAdd(d,key,val);
4188 if (retval == DICT_ERR) {
4189 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
4190 exit(1);
4191 }
4192 loadedkeys++;
4193 /* Set the expire time if needed */
4194 if (expiretime != -1) setExpire(db,key,expiretime);
4195
4196 /* Handle swapping while loading big datasets when VM is on */
4197
4198 /* If we detecter we are hopeless about fitting something in memory
4199 * we just swap every new key on disk. Directly...
4200 * Note that's important to check for this condition before resorting
4201 * to random sampling, otherwise we may try to swap already
4202 * swapped keys. */
4203 if (swap_all_values) {
4204 dictEntry *de = dictFind(d,key);
4205
4206 /* de may be NULL since the key already expired */
4207 if (de) {
4208 vmpointer *vp;
4209 key = dictGetEntryKey(de);
4210 val = dictGetEntryVal(de);
4211
4212 if (val->refcount == 1 &&
4213 (vp = vmSwapObjectBlocking(val)) != NULL)
4214 dictGetEntryVal(de) = vp;
4215 }
4216 continue;
4217 }
4218
4219 /* If we have still some hope of having some value fitting memory
4220 * then we try random sampling. */
4221 if (!swap_all_values && server.vm_enabled && (loadedkeys % 5000) == 0) {
4222 while (zmalloc_used_memory() > server.vm_max_memory) {
4223 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
4224 }
4225 if (zmalloc_used_memory() > server.vm_max_memory)
4226 swap_all_values = 1; /* We are already using too much mem */
4227 }
4228 }
4229 fclose(fp);
4230 return REDIS_OK;
4231
4232 eoferr: /* unexpected end of file is handled here with a fatal exit */
4233 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
4234 exit(1);
4235 return REDIS_ERR; /* Just to avoid warning */
4236 }
4237
4238 /*================================== Shutdown =============================== */
4239 static int prepareForShutdown() {
4240 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
4241 /* Kill the saving child if there is a background saving in progress.
4242 We want to avoid race conditions, for instance our saving child may
4243 overwrite the synchronous saving did by SHUTDOWN. */
4244 if (server.bgsavechildpid != -1) {
4245 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
4246 kill(server.bgsavechildpid,SIGKILL);
4247 rdbRemoveTempFile(server.bgsavechildpid);
4248 }
4249 if (server.appendonly) {
4250 /* Append only file: fsync() the AOF and exit */
4251 aof_fsync(server.appendfd);
4252 if (server.vm_enabled) unlink(server.vm_swap_file);
4253 } else {
4254 /* Snapshotting. Perform a SYNC SAVE and exit */
4255 if (rdbSave(server.dbfilename) == REDIS_OK) {
4256 if (server.daemonize)
4257 unlink(server.pidfile);
4258 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
4259 } else {
4260 /* Ooops.. error saving! The best we can do is to continue
4261 * operating. Note that if there was a background saving process,
4262 * in the next cron() Redis will be notified that the background
4263 * saving aborted, handling special stuff like slaves pending for
4264 * synchronization... */
4265 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
4266 return REDIS_ERR;
4267 }
4268 }
4269 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
4270 return REDIS_OK;
4271 }
4272
4273 /*================================== Commands =============================== */
4274
4275 static void authCommand(redisClient *c) {
4276 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
4277 c->authenticated = 1;
4278 addReply(c,shared.ok);
4279 } else {
4280 c->authenticated = 0;
4281 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
4282 }
4283 }
4284
4285 static void pingCommand(redisClient *c) {
4286 addReply(c,shared.pong);
4287 }
4288
4289 static void echoCommand(redisClient *c) {
4290 addReplyBulk(c,c->argv[1]);
4291 }
4292
4293 /*=================================== Strings =============================== */
4294
4295 static void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
4296 int retval;
4297 long seconds = 0; /* initialized to avoid an harmness warning */
4298
4299 if (expire) {
4300 if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
4301 return;
4302 if (seconds <= 0) {
4303 addReplySds(c,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4304 return;
4305 }
4306 }
4307
4308 touchWatchedKey(c->db,key);
4309 if (nx) deleteIfVolatile(c->db,key);
4310 retval = dictAdd(c->db->dict,key,val);
4311 if (retval == DICT_ERR) {
4312 if (!nx) {
4313 /* If the key is about a swapped value, we want a new key object
4314 * to overwrite the old. So we delete the old key in the database.
4315 * This will also make sure that swap pages about the old object
4316 * will be marked as free. */
4317 if (server.vm_enabled && deleteIfSwapped(c->db,key))
4318 incrRefCount(key);
4319 dictReplace(c->db->dict,key,val);
4320 incrRefCount(val);
4321 } else {
4322 addReply(c,shared.czero);
4323 return;
4324 }
4325 } else {
4326 incrRefCount(key);
4327 incrRefCount(val);
4328 }
4329 server.dirty++;
4330 removeExpire(c->db,key);
4331 if (expire) setExpire(c->db,key,time(NULL)+seconds);
4332 addReply(c, nx ? shared.cone : shared.ok);
4333 }
4334
4335 static void setCommand(redisClient *c) {
4336 setGenericCommand(c,0,c->argv[1],c->argv[2],NULL);
4337 }
4338
4339 static void setnxCommand(redisClient *c) {
4340 setGenericCommand(c,1,c->argv[1],c->argv[2],NULL);
4341 }
4342
4343 static void setexCommand(redisClient *c) {
4344 setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
4345 }
4346
4347 static int getGenericCommand(redisClient *c) {
4348 robj *o;
4349
4350 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
4351 return REDIS_OK;
4352
4353 if (o->type != REDIS_STRING) {
4354 addReply(c,shared.wrongtypeerr);
4355 return REDIS_ERR;
4356 } else {
4357 addReplyBulk(c,o);
4358 return REDIS_OK;
4359 }
4360 }
4361
4362 static void getCommand(redisClient *c) {
4363 getGenericCommand(c);
4364 }
4365
4366 static void getsetCommand(redisClient *c) {
4367 if (getGenericCommand(c) == REDIS_ERR) return;
4368 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
4369 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
4370 } else {
4371 incrRefCount(c->argv[1]);
4372 }
4373 incrRefCount(c->argv[2]);
4374 server.dirty++;
4375 removeExpire(c->db,c->argv[1]);
4376 }
4377
4378 static void mgetCommand(redisClient *c) {
4379 int j;
4380
4381 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
4382 for (j = 1; j < c->argc; j++) {
4383 robj *o = lookupKeyRead(c->db,c->argv[j]);
4384 if (o == NULL) {
4385 addReply(c,shared.nullbulk);
4386 } else {
4387 if (o->type != REDIS_STRING) {
4388 addReply(c,shared.nullbulk);
4389 } else {
4390 addReplyBulk(c,o);
4391 }
4392 }
4393 }
4394 }
4395
4396 static void msetGenericCommand(redisClient *c, int nx) {
4397 int j, busykeys = 0;
4398
4399 if ((c->argc % 2) == 0) {
4400 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
4401 return;
4402 }
4403 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4404 * set nothing at all if at least one already key exists. */
4405 if (nx) {
4406 for (j = 1; j < c->argc; j += 2) {
4407 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
4408 busykeys++;
4409 }
4410 }
4411 }
4412 if (busykeys) {
4413 addReply(c, shared.czero);
4414 return;
4415 }
4416
4417 for (j = 1; j < c->argc; j += 2) {
4418 int retval;
4419
4420 c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
4421 retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
4422 if (retval == DICT_ERR) {
4423 dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
4424 incrRefCount(c->argv[j+1]);
4425 } else {
4426 incrRefCount(c->argv[j]);
4427 incrRefCount(c->argv[j+1]);
4428 }
4429 removeExpire(c->db,c->argv[j]);
4430 }
4431 server.dirty += (c->argc-1)/2;
4432 addReply(c, nx ? shared.cone : shared.ok);
4433 }
4434
4435 static void msetCommand(redisClient *c) {
4436 msetGenericCommand(c,0);
4437 }
4438
4439 static void msetnxCommand(redisClient *c) {
4440 msetGenericCommand(c,1);
4441 }
4442
4443 static void incrDecrCommand(redisClient *c, long long incr) {
4444 long long value;
4445 int retval;
4446 robj *o;
4447
4448 o = lookupKeyWrite(c->db,c->argv[1]);
4449 if (o != NULL && checkType(c,o,REDIS_STRING)) return;
4450 if (getLongLongFromObjectOrReply(c,o,&value,NULL) != REDIS_OK) return;
4451
4452 value += incr;
4453 o = createStringObjectFromLongLong(value);
4454 retval = dictAdd(c->db->dict,c->argv[1],o);
4455 if (retval == DICT_ERR) {
4456 dictReplace(c->db->dict,c->argv[1],o);
4457 removeExpire(c->db,c->argv[1]);
4458 } else {
4459 incrRefCount(c->argv[1]);
4460 }
4461 server.dirty++;
4462 addReply(c,shared.colon);
4463 addReply(c,o);
4464 addReply(c,shared.crlf);
4465 }
4466
4467 static void incrCommand(redisClient *c) {
4468 incrDecrCommand(c,1);
4469 }
4470
4471 static void decrCommand(redisClient *c) {
4472 incrDecrCommand(c,-1);
4473 }
4474
4475 static void incrbyCommand(redisClient *c) {
4476 long long incr;
4477
4478 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
4479 incrDecrCommand(c,incr);
4480 }
4481
4482 static void decrbyCommand(redisClient *c) {
4483 long long incr;
4484
4485 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
4486 incrDecrCommand(c,-incr);
4487 }
4488
4489 static void appendCommand(redisClient *c) {
4490 int retval;
4491 size_t totlen;
4492 robj *o;
4493
4494 o = lookupKeyWrite(c->db,c->argv[1]);
4495 if (o == NULL) {
4496 /* Create the key */
4497 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
4498 incrRefCount(c->argv[1]);
4499 incrRefCount(c->argv[2]);
4500 totlen = stringObjectLen(c->argv[2]);
4501 } else {
4502 dictEntry *de;
4503
4504 de = dictFind(c->db->dict,c->argv[1]);
4505 assert(de != NULL);
4506
4507 o = dictGetEntryVal(de);
4508 if (o->type != REDIS_STRING) {
4509 addReply(c,shared.wrongtypeerr);
4510 return;
4511 }
4512 /* If the object is specially encoded or shared we have to make
4513 * a copy */
4514 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
4515 robj *decoded = getDecodedObject(o);
4516
4517 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
4518 decrRefCount(decoded);
4519 dictReplace(c->db->dict,c->argv[1],o);
4520 }
4521 /* APPEND! */
4522 if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
4523 o->ptr = sdscatlen(o->ptr,
4524 c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
4525 } else {
4526 o->ptr = sdscatprintf(o->ptr, "%ld",
4527 (unsigned long) c->argv[2]->ptr);
4528 }
4529 totlen = sdslen(o->ptr);
4530 }
4531 server.dirty++;
4532 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
4533 }
4534
4535 static void substrCommand(redisClient *c) {
4536 robj *o;
4537 long start = atoi(c->argv[2]->ptr);
4538 long end = atoi(c->argv[3]->ptr);
4539 size_t rangelen, strlen;
4540 sds range;
4541
4542 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4543 checkType(c,o,REDIS_STRING)) return;
4544
4545 o = getDecodedObject(o);
4546 strlen = sdslen(o->ptr);
4547
4548 /* convert negative indexes */
4549 if (start < 0) start = strlen+start;
4550 if (end < 0) end = strlen+end;
4551 if (start < 0) start = 0;
4552 if (end < 0) end = 0;
4553
4554 /* indexes sanity checks */
4555 if (start > end || (size_t)start >= strlen) {
4556 /* Out of range start or start > end result in null reply */
4557 addReply(c,shared.nullbulk);
4558 decrRefCount(o);
4559 return;
4560 }
4561 if ((size_t)end >= strlen) end = strlen-1;
4562 rangelen = (end-start)+1;
4563
4564 /* Return the result */
4565 addReplySds(c,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen));
4566 range = sdsnewlen((char*)o->ptr+start,rangelen);
4567 addReplySds(c,range);
4568 addReply(c,shared.crlf);
4569 decrRefCount(o);
4570 }
4571
4572 /* ========================= Type agnostic commands ========================= */
4573
4574 static void delCommand(redisClient *c) {
4575 int deleted = 0, j;
4576
4577 for (j = 1; j < c->argc; j++) {
4578 if (deleteKey(c->db,c->argv[j])) {
4579 touchWatchedKey(c->db,c->argv[j]);
4580 server.dirty++;
4581 deleted++;
4582 }
4583 }
4584 addReplyLongLong(c,deleted);
4585 }
4586
4587 static void existsCommand(redisClient *c) {
4588 expireIfNeeded(c->db,c->argv[1]);
4589 if (dictFind(c->db->dict,c->argv[1])) {
4590 addReply(c, shared.cone);
4591 } else {
4592 addReply(c, shared.czero);
4593 }
4594 }
4595
4596 static void selectCommand(redisClient *c) {
4597 int id = atoi(c->argv[1]->ptr);
4598
4599 if (selectDb(c,id) == REDIS_ERR) {
4600 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
4601 } else {
4602 addReply(c,shared.ok);
4603 }
4604 }
4605
4606 static void randomkeyCommand(redisClient *c) {
4607 dictEntry *de;
4608 robj *key;
4609
4610 while(1) {
4611 de = dictGetRandomKey(c->db->dict);
4612 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
4613 }
4614
4615 if (de == NULL) {
4616 addReply(c,shared.nullbulk);
4617 return;
4618 }
4619
4620 key = dictGetEntryKey(de);
4621 if (server.vm_enabled) {
4622 key = dupStringObject(key);
4623 addReplyBulk(c,key);
4624 decrRefCount(key);
4625 } else {
4626 addReplyBulk(c,key);
4627 }
4628 }
4629
4630 static void keysCommand(redisClient *c) {
4631 dictIterator *di;
4632 dictEntry *de;
4633 sds pattern = c->argv[1]->ptr;
4634 int plen = sdslen(pattern);
4635 unsigned long numkeys = 0;
4636 robj *lenobj = createObject(REDIS_STRING,NULL);
4637
4638 di = dictGetIterator(c->db->dict);
4639 addReply(c,lenobj);
4640 decrRefCount(lenobj);
4641 while((de = dictNext(di)) != NULL) {
4642 robj *keyobj = dictGetEntryKey(de);
4643
4644 sds key = keyobj->ptr;
4645 if ((pattern[0] == '*' && pattern[1] == '\0') ||
4646 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
4647 if (expireIfNeeded(c->db,keyobj) == 0) {
4648 addReplyBulk(c,keyobj);
4649 numkeys++;
4650 }
4651 }
4652 }
4653 dictReleaseIterator(di);
4654 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
4655 }
4656
4657 static void dbsizeCommand(redisClient *c) {
4658 addReplySds(c,
4659 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
4660 }
4661
4662 static void lastsaveCommand(redisClient *c) {
4663 addReplySds(c,
4664 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
4665 }
4666
4667 static void typeCommand(redisClient *c) {
4668 robj *o;
4669 char *type;
4670
4671 o = lookupKeyRead(c->db,c->argv[1]);
4672 if (o == NULL) {
4673 type = "+none";
4674 } else {
4675 switch(o->type) {
4676 case REDIS_STRING: type = "+string"; break;
4677 case REDIS_LIST: type = "+list"; break;
4678 case REDIS_SET: type = "+set"; break;
4679 case REDIS_ZSET: type = "+zset"; break;
4680 case REDIS_HASH: type = "+hash"; break;
4681 default: type = "+unknown"; break;
4682 }
4683 }
4684 addReplySds(c,sdsnew(type));
4685 addReply(c,shared.crlf);
4686 }
4687
4688 static void saveCommand(redisClient *c) {
4689 if (server.bgsavechildpid != -1) {
4690 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
4691 return;
4692 }
4693 if (rdbSave(server.dbfilename) == REDIS_OK) {
4694 addReply(c,shared.ok);
4695 } else {
4696 addReply(c,shared.err);
4697 }
4698 }
4699
4700 static void bgsaveCommand(redisClient *c) {
4701 if (server.bgsavechildpid != -1) {
4702 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
4703 return;
4704 }
4705 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
4706 char *status = "+Background saving started\r\n";
4707 addReplySds(c,sdsnew(status));
4708 } else {
4709 addReply(c,shared.err);
4710 }
4711 }
4712
4713 static void shutdownCommand(redisClient *c) {
4714 if (prepareForShutdown() == REDIS_OK)
4715 exit(0);
4716 addReplySds(c, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
4717 }
4718
4719 static void renameGenericCommand(redisClient *c, int nx) {
4720 robj *o;
4721
4722 /* To use the same key as src and dst is probably an error */
4723 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
4724 addReply(c,shared.sameobjecterr);
4725 return;
4726 }
4727
4728 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
4729 return;
4730
4731 incrRefCount(o);
4732 deleteIfVolatile(c->db,c->argv[2]);
4733 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
4734 if (nx) {
4735 decrRefCount(o);
4736 addReply(c,shared.czero);
4737 return;
4738 }
4739 dictReplace(c->db->dict,c->argv[2],o);
4740 } else {
4741 incrRefCount(c->argv[2]);
4742 }
4743 deleteKey(c->db,c->argv[1]);
4744 touchWatchedKey(c->db,c->argv[2]);
4745 server.dirty++;
4746 addReply(c,nx ? shared.cone : shared.ok);
4747 }
4748
4749 static void renameCommand(redisClient *c) {
4750 renameGenericCommand(c,0);
4751 }
4752
4753 static void renamenxCommand(redisClient *c) {
4754 renameGenericCommand(c,1);
4755 }
4756
4757 static void moveCommand(redisClient *c) {
4758 robj *o;
4759 redisDb *src, *dst;
4760 int srcid;
4761
4762 /* Obtain source and target DB pointers */
4763 src = c->db;
4764 srcid = c->db->id;
4765 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
4766 addReply(c,shared.outofrangeerr);
4767 return;
4768 }
4769 dst = c->db;
4770 selectDb(c,srcid); /* Back to the source DB */
4771
4772 /* If the user is moving using as target the same
4773 * DB as the source DB it is probably an error. */
4774 if (src == dst) {
4775 addReply(c,shared.sameobjecterr);
4776 return;
4777 }
4778
4779 /* Check if the element exists and get a reference */
4780 o = lookupKeyWrite(c->db,c->argv[1]);
4781 if (!o) {
4782 addReply(c,shared.czero);
4783 return;
4784 }
4785
4786 /* Try to add the element to the target DB */
4787 deleteIfVolatile(dst,c->argv[1]);
4788 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
4789 addReply(c,shared.czero);
4790 return;
4791 }
4792 incrRefCount(c->argv[1]);
4793 incrRefCount(o);
4794
4795 /* OK! key moved, free the entry in the source DB */
4796 deleteKey(src,c->argv[1]);
4797 server.dirty++;
4798 addReply(c,shared.cone);
4799 }
4800
4801 /* =================================== Lists ================================ */
4802 static void pushGenericCommand(redisClient *c, int where) {
4803 robj *lobj;
4804 list *list;
4805
4806 lobj = lookupKeyWrite(c->db,c->argv[1]);
4807 if (lobj == NULL) {
4808 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
4809 addReply(c,shared.cone);
4810 return;
4811 }
4812 lobj = createListObject();
4813 list = lobj->ptr;
4814 if (where == REDIS_HEAD) {
4815 listAddNodeHead(list,c->argv[2]);
4816 } else {
4817 listAddNodeTail(list,c->argv[2]);
4818 }
4819 dictAdd(c->db->dict,c->argv[1],lobj);
4820 incrRefCount(c->argv[1]);
4821 incrRefCount(c->argv[2]);
4822 } else {
4823 if (lobj->type != REDIS_LIST) {
4824 addReply(c,shared.wrongtypeerr);
4825 return;
4826 }
4827 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
4828 addReply(c,shared.cone);
4829 return;
4830 }
4831 list = lobj->ptr;
4832 if (where == REDIS_HEAD) {
4833 listAddNodeHead(list,c->argv[2]);
4834 } else {
4835 listAddNodeTail(list,c->argv[2]);
4836 }
4837 incrRefCount(c->argv[2]);
4838 }
4839 server.dirty++;
4840 addReplyLongLong(c,listLength(list));
4841 }
4842
4843 static void lpushCommand(redisClient *c) {
4844 pushGenericCommand(c,REDIS_HEAD);
4845 }
4846
4847 static void rpushCommand(redisClient *c) {
4848 pushGenericCommand(c,REDIS_TAIL);
4849 }
4850
4851 static void llenCommand(redisClient *c) {
4852 robj *o;
4853 list *l;
4854
4855 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
4856 checkType(c,o,REDIS_LIST)) return;
4857
4858 l = o->ptr;
4859 addReplyUlong(c,listLength(l));
4860 }
4861
4862 static void lindexCommand(redisClient *c) {
4863 robj *o;
4864 int index = atoi(c->argv[2]->ptr);
4865 list *list;
4866 listNode *ln;
4867
4868 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4869 checkType(c,o,REDIS_LIST)) return;
4870 list = o->ptr;
4871
4872 ln = listIndex(list, index);
4873 if (ln == NULL) {
4874 addReply(c,shared.nullbulk);
4875 } else {
4876 robj *ele = listNodeValue(ln);
4877 addReplyBulk(c,ele);
4878 }
4879 }
4880
4881 static void lsetCommand(redisClient *c) {
4882 robj *o;
4883 int index = atoi(c->argv[2]->ptr);
4884 list *list;
4885 listNode *ln;
4886
4887 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL ||
4888 checkType(c,o,REDIS_LIST)) return;
4889 list = o->ptr;
4890
4891 ln = listIndex(list, index);
4892 if (ln == NULL) {
4893 addReply(c,shared.outofrangeerr);
4894 } else {
4895 robj *ele = listNodeValue(ln);
4896
4897 decrRefCount(ele);
4898 listNodeValue(ln) = c->argv[3];
4899 incrRefCount(c->argv[3]);
4900 addReply(c,shared.ok);
4901 server.dirty++;
4902 }
4903 }
4904
4905 static void popGenericCommand(redisClient *c, int where) {
4906 robj *o;
4907 list *list;
4908 listNode *ln;
4909
4910 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4911 checkType(c,o,REDIS_LIST)) return;
4912 list = o->ptr;
4913
4914 if (where == REDIS_HEAD)
4915 ln = listFirst(list);
4916 else
4917 ln = listLast(list);
4918
4919 if (ln == NULL) {
4920 addReply(c,shared.nullbulk);
4921 } else {
4922 robj *ele = listNodeValue(ln);
4923 addReplyBulk(c,ele);
4924 listDelNode(list,ln);
4925 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
4926 server.dirty++;
4927 }
4928 }
4929
4930 static void lpopCommand(redisClient *c) {
4931 popGenericCommand(c,REDIS_HEAD);
4932 }
4933
4934 static void rpopCommand(redisClient *c) {
4935 popGenericCommand(c,REDIS_TAIL);
4936 }
4937
4938 static void lrangeCommand(redisClient *c) {
4939 robj *o;
4940 int start = atoi(c->argv[2]->ptr);
4941 int end = atoi(c->argv[3]->ptr);
4942 int llen;
4943 int rangelen, j;
4944 list *list;
4945 listNode *ln;
4946 robj *ele;
4947
4948 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
4949 || checkType(c,o,REDIS_LIST)) return;
4950 list = o->ptr;
4951 llen = listLength(list);
4952
4953 /* convert negative indexes */
4954 if (start < 0) start = llen+start;
4955 if (end < 0) end = llen+end;
4956 if (start < 0) start = 0;
4957 if (end < 0) end = 0;
4958
4959 /* indexes sanity checks */
4960 if (start > end || start >= llen) {
4961 /* Out of range start or start > end result in empty list */
4962 addReply(c,shared.emptymultibulk);
4963 return;
4964 }
4965 if (end >= llen) end = llen-1;
4966 rangelen = (end-start)+1;
4967
4968 /* Return the result in form of a multi-bulk reply */
4969 ln = listIndex(list, start);
4970 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
4971 for (j = 0; j < rangelen; j++) {
4972 ele = listNodeValue(ln);
4973 addReplyBulk(c,ele);
4974 ln = ln->next;
4975 }
4976 }
4977
4978 static void ltrimCommand(redisClient *c) {
4979 robj *o;
4980 int start = atoi(c->argv[2]->ptr);
4981 int end = atoi(c->argv[3]->ptr);
4982 int llen;
4983 int j, ltrim, rtrim;
4984 list *list;
4985 listNode *ln;
4986
4987 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
4988 checkType(c,o,REDIS_LIST)) return;
4989 list = o->ptr;
4990 llen = listLength(list);
4991
4992 /* convert negative indexes */
4993 if (start < 0) start = llen+start;
4994 if (end < 0) end = llen+end;
4995 if (start < 0) start = 0;
4996 if (end < 0) end = 0;
4997
4998 /* indexes sanity checks */
4999 if (start > end || start >= llen) {
5000 /* Out of range start or start > end result in empty list */
5001 ltrim = llen;
5002 rtrim = 0;
5003 } else {
5004 if (end >= llen) end = llen-1;
5005 ltrim = start;
5006 rtrim = llen-end-1;
5007 }
5008
5009 /* Remove list elements to perform the trim */
5010 for (j = 0; j < ltrim; j++) {
5011 ln = listFirst(list);
5012 listDelNode(list,ln);
5013 }
5014 for (j = 0; j < rtrim; j++) {
5015 ln = listLast(list);
5016 listDelNode(list,ln);
5017 }
5018 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
5019 server.dirty++;
5020 addReply(c,shared.ok);
5021 }
5022
5023 static void lremCommand(redisClient *c) {
5024 robj *o;
5025 list *list;
5026 listNode *ln, *next;
5027 int toremove = atoi(c->argv[2]->ptr);
5028 int removed = 0;
5029 int fromtail = 0;
5030
5031 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5032 checkType(c,o,REDIS_LIST)) return;
5033 list = o->ptr;
5034
5035 if (toremove < 0) {
5036 toremove = -toremove;
5037 fromtail = 1;
5038 }
5039 ln = fromtail ? list->tail : list->head;
5040 while (ln) {
5041 robj *ele = listNodeValue(ln);
5042
5043 next = fromtail ? ln->prev : ln->next;
5044 if (equalStringObjects(ele,c->argv[3])) {
5045 listDelNode(list,ln);
5046 server.dirty++;
5047 removed++;
5048 if (toremove && removed == toremove) break;
5049 }
5050 ln = next;
5051 }
5052 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
5053 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
5054 }
5055
5056 /* This is the semantic of this command:
5057 * RPOPLPUSH srclist dstlist:
5058 * IF LLEN(srclist) > 0
5059 * element = RPOP srclist
5060 * LPUSH dstlist element
5061 * RETURN element
5062 * ELSE
5063 * RETURN nil
5064 * END
5065 * END
5066 *
5067 * The idea is to be able to get an element from a list in a reliable way
5068 * since the element is not just returned but pushed against another list
5069 * as well. This command was originally proposed by Ezra Zygmuntowicz.
5070 */
5071 static void rpoplpushcommand(redisClient *c) {
5072 robj *sobj;
5073 list *srclist;
5074 listNode *ln;
5075
5076 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5077 checkType(c,sobj,REDIS_LIST)) return;
5078 srclist = sobj->ptr;
5079 ln = listLast(srclist);
5080
5081 if (ln == NULL) {
5082 addReply(c,shared.nullbulk);
5083 } else {
5084 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
5085 robj *ele = listNodeValue(ln);
5086 list *dstlist;
5087
5088 if (dobj && dobj->type != REDIS_LIST) {
5089 addReply(c,shared.wrongtypeerr);
5090 return;
5091 }
5092
5093 /* Add the element to the target list (unless it's directly
5094 * passed to some BLPOP-ing client */
5095 if (!handleClientsWaitingListPush(c,c->argv[2],ele)) {
5096 if (dobj == NULL) {
5097 /* Create the list if the key does not exist */
5098 dobj = createListObject();
5099 dictAdd(c->db->dict,c->argv[2],dobj);
5100 incrRefCount(c->argv[2]);
5101 }
5102 dstlist = dobj->ptr;
5103 listAddNodeHead(dstlist,ele);
5104 incrRefCount(ele);
5105 }
5106
5107 /* Send the element to the client as reply as well */
5108 addReplyBulk(c,ele);
5109
5110 /* Finally remove the element from the source list */
5111 listDelNode(srclist,ln);
5112 if (listLength(srclist) == 0) deleteKey(c->db,c->argv[1]);
5113 server.dirty++;
5114 }
5115 }
5116
5117 /* ==================================== Sets ================================ */
5118
5119 static void saddCommand(redisClient *c) {
5120 robj *set;
5121
5122 set = lookupKeyWrite(c->db,c->argv[1]);
5123 if (set == NULL) {
5124 set = createSetObject();
5125 dictAdd(c->db->dict,c->argv[1],set);
5126 incrRefCount(c->argv[1]);
5127 } else {
5128 if (set->type != REDIS_SET) {
5129 addReply(c,shared.wrongtypeerr);
5130 return;
5131 }
5132 }
5133 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
5134 incrRefCount(c->argv[2]);
5135 server.dirty++;
5136 addReply(c,shared.cone);
5137 } else {
5138 addReply(c,shared.czero);
5139 }
5140 }
5141
5142 static void sremCommand(redisClient *c) {
5143 robj *set;
5144
5145 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5146 checkType(c,set,REDIS_SET)) return;
5147
5148 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
5149 server.dirty++;
5150 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
5151 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
5152 addReply(c,shared.cone);
5153 } else {
5154 addReply(c,shared.czero);
5155 }
5156 }
5157
5158 static void smoveCommand(redisClient *c) {
5159 robj *srcset, *dstset;
5160
5161 srcset = lookupKeyWrite(c->db,c->argv[1]);
5162 dstset = lookupKeyWrite(c->db,c->argv[2]);
5163
5164 /* If the source key does not exist return 0, if it's of the wrong type
5165 * raise an error */
5166 if (srcset == NULL || srcset->type != REDIS_SET) {
5167 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
5168 return;
5169 }
5170 /* Error if the destination key is not a set as well */
5171 if (dstset && dstset->type != REDIS_SET) {
5172 addReply(c,shared.wrongtypeerr);
5173 return;
5174 }
5175 /* Remove the element from the source set */
5176 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
5177 /* Key not found in the src set! return zero */
5178 addReply(c,shared.czero);
5179 return;
5180 }
5181 if (dictSize((dict*)srcset->ptr) == 0 && srcset != dstset)
5182 deleteKey(c->db,c->argv[1]);
5183 server.dirty++;
5184 /* Add the element to the destination set */
5185 if (!dstset) {
5186 dstset = createSetObject();
5187 dictAdd(c->db->dict,c->argv[2],dstset);
5188 incrRefCount(c->argv[2]);
5189 }
5190 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
5191 incrRefCount(c->argv[3]);
5192 addReply(c,shared.cone);
5193 }
5194
5195 static void sismemberCommand(redisClient *c) {
5196 robj *set;
5197
5198 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5199 checkType(c,set,REDIS_SET)) return;
5200
5201 if (dictFind(set->ptr,c->argv[2]))
5202 addReply(c,shared.cone);
5203 else
5204 addReply(c,shared.czero);
5205 }
5206
5207 static void scardCommand(redisClient *c) {
5208 robj *o;
5209 dict *s;
5210
5211 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5212 checkType(c,o,REDIS_SET)) return;
5213
5214 s = o->ptr;
5215 addReplyUlong(c,dictSize(s));
5216 }
5217
5218 static void spopCommand(redisClient *c) {
5219 robj *set;
5220 dictEntry *de;
5221
5222 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5223 checkType(c,set,REDIS_SET)) return;
5224
5225 de = dictGetRandomKey(set->ptr);
5226 if (de == NULL) {
5227 addReply(c,shared.nullbulk);
5228 } else {
5229 robj *ele = dictGetEntryKey(de);
5230
5231 addReplyBulk(c,ele);
5232 dictDelete(set->ptr,ele);
5233 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
5234 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
5235 server.dirty++;
5236 }
5237 }
5238
5239 static void srandmemberCommand(redisClient *c) {
5240 robj *set;
5241 dictEntry *de;
5242
5243 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5244 checkType(c,set,REDIS_SET)) return;
5245
5246 de = dictGetRandomKey(set->ptr);
5247 if (de == NULL) {
5248 addReply(c,shared.nullbulk);
5249 } else {
5250 robj *ele = dictGetEntryKey(de);
5251
5252 addReplyBulk(c,ele);
5253 }
5254 }
5255
5256 static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
5257 dict **d1 = (void*) s1, **d2 = (void*) s2;
5258
5259 return dictSize(*d1)-dictSize(*d2);
5260 }
5261
5262 static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
5263 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5264 dictIterator *di;
5265 dictEntry *de;
5266 robj *lenobj = NULL, *dstset = NULL;
5267 unsigned long j, cardinality = 0;
5268
5269 for (j = 0; j < setsnum; j++) {
5270 robj *setobj;
5271
5272 setobj = dstkey ?
5273 lookupKeyWrite(c->db,setskeys[j]) :
5274 lookupKeyRead(c->db,setskeys[j]);
5275 if (!setobj) {
5276 zfree(dv);
5277 if (dstkey) {
5278 if (deleteKey(c->db,dstkey))
5279 server.dirty++;
5280 addReply(c,shared.czero);
5281 } else {
5282 addReply(c,shared.emptymultibulk);
5283 }
5284 return;
5285 }
5286 if (setobj->type != REDIS_SET) {
5287 zfree(dv);
5288 addReply(c,shared.wrongtypeerr);
5289 return;
5290 }
5291 dv[j] = setobj->ptr;
5292 }
5293 /* Sort sets from the smallest to largest, this will improve our
5294 * algorithm's performace */
5295 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
5296
5297 /* The first thing we should output is the total number of elements...
5298 * since this is a multi-bulk write, but at this stage we don't know
5299 * the intersection set size, so we use a trick, append an empty object
5300 * to the output list and save the pointer to later modify it with the
5301 * right length */
5302 if (!dstkey) {
5303 lenobj = createObject(REDIS_STRING,NULL);
5304 addReply(c,lenobj);
5305 decrRefCount(lenobj);
5306 } else {
5307 /* If we have a target key where to store the resulting set
5308 * create this key with an empty set inside */
5309 dstset = createSetObject();
5310 }
5311
5312 /* Iterate all the elements of the first (smallest) set, and test
5313 * the element against all the other sets, if at least one set does
5314 * not include the element it is discarded */
5315 di = dictGetIterator(dv[0]);
5316
5317 while((de = dictNext(di)) != NULL) {
5318 robj *ele;
5319
5320 for (j = 1; j < setsnum; j++)
5321 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
5322 if (j != setsnum)
5323 continue; /* at least one set does not contain the member */
5324 ele = dictGetEntryKey(de);
5325 if (!dstkey) {
5326 addReplyBulk(c,ele);
5327 cardinality++;
5328 } else {
5329 dictAdd(dstset->ptr,ele,NULL);
5330 incrRefCount(ele);
5331 }
5332 }
5333 dictReleaseIterator(di);
5334
5335 if (dstkey) {
5336 /* Store the resulting set into the target, if the intersection
5337 * is not an empty set. */
5338 deleteKey(c->db,dstkey);
5339 if (dictSize((dict*)dstset->ptr) > 0) {
5340 dictAdd(c->db->dict,dstkey,dstset);
5341 incrRefCount(dstkey);
5342 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
5343 } else {
5344 decrRefCount(dstset);
5345 addReply(c,shared.czero);
5346 }
5347 server.dirty++;
5348 } else {
5349 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
5350 }
5351 zfree(dv);
5352 }
5353
5354 static void sinterCommand(redisClient *c) {
5355 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
5356 }
5357
5358 static void sinterstoreCommand(redisClient *c) {
5359 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
5360 }
5361
5362 #define REDIS_OP_UNION 0
5363 #define REDIS_OP_DIFF 1
5364 #define REDIS_OP_INTER 2
5365
5366 static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
5367 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5368 dictIterator *di;
5369 dictEntry *de;
5370 robj *dstset = NULL;
5371 int j, cardinality = 0;
5372
5373 for (j = 0; j < setsnum; j++) {
5374 robj *setobj;
5375
5376 setobj = dstkey ?
5377 lookupKeyWrite(c->db,setskeys[j]) :
5378 lookupKeyRead(c->db,setskeys[j]);
5379 if (!setobj) {
5380 dv[j] = NULL;
5381 continue;
5382 }
5383 if (setobj->type != REDIS_SET) {
5384 zfree(dv);
5385 addReply(c,shared.wrongtypeerr);
5386 return;
5387 }
5388 dv[j] = setobj->ptr;
5389 }
5390
5391 /* We need a temp set object to store our union. If the dstkey
5392 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5393 * this set object will be the resulting object to set into the target key*/
5394 dstset = createSetObject();
5395
5396 /* Iterate all the elements of all the sets, add every element a single
5397 * time to the result set */
5398 for (j = 0; j < setsnum; j++) {
5399 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
5400 if (!dv[j]) continue; /* non existing keys are like empty sets */
5401
5402 di = dictGetIterator(dv[j]);
5403
5404 while((de = dictNext(di)) != NULL) {
5405 robj *ele;
5406
5407 /* dictAdd will not add the same element multiple times */
5408 ele = dictGetEntryKey(de);
5409 if (op == REDIS_OP_UNION || j == 0) {
5410 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
5411 incrRefCount(ele);
5412 cardinality++;
5413 }
5414 } else if (op == REDIS_OP_DIFF) {
5415 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
5416 cardinality--;
5417 }
5418 }
5419 }
5420 dictReleaseIterator(di);
5421
5422 /* result set is empty? Exit asap. */
5423 if (op == REDIS_OP_DIFF && cardinality == 0) break;
5424 }
5425
5426 /* Output the content of the resulting set, if not in STORE mode */
5427 if (!dstkey) {
5428 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
5429 di = dictGetIterator(dstset->ptr);
5430 while((de = dictNext(di)) != NULL) {
5431 robj *ele;
5432
5433 ele = dictGetEntryKey(de);
5434 addReplyBulk(c,ele);
5435 }
5436 dictReleaseIterator(di);
5437 decrRefCount(dstset);
5438 } else {
5439 /* If we have a target key where to store the resulting set
5440 * create this key with the result set inside */
5441 deleteKey(c->db,dstkey);
5442 if (dictSize((dict*)dstset->ptr) > 0) {
5443 dictAdd(c->db->dict,dstkey,dstset);
5444 incrRefCount(dstkey);
5445 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
5446 } else {
5447 decrRefCount(dstset);
5448 addReply(c,shared.czero);
5449 }
5450 server.dirty++;
5451 }
5452 zfree(dv);
5453 }
5454
5455 static void sunionCommand(redisClient *c) {
5456 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
5457 }
5458
5459 static void sunionstoreCommand(redisClient *c) {
5460 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
5461 }
5462
5463 static void sdiffCommand(redisClient *c) {
5464 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
5465 }
5466
5467 static void sdiffstoreCommand(redisClient *c) {
5468 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
5469 }
5470
5471 /* ==================================== ZSets =============================== */
5472
5473 /* ZSETs are ordered sets using two data structures to hold the same elements
5474 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5475 * data structure.
5476 *
5477 * The elements are added to an hash table mapping Redis objects to scores.
5478 * At the same time the elements are added to a skip list mapping scores
5479 * to Redis objects (so objects are sorted by scores in this "view"). */
5480
5481 /* This skiplist implementation is almost a C translation of the original
5482 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5483 * Alternative to Balanced Trees", modified in three ways:
5484 * a) this implementation allows for repeated values.
5485 * b) the comparison is not just by key (our 'score') but by satellite data.
5486 * c) there is a back pointer, so it's a doubly linked list with the back
5487 * pointers being only at "level 1". This allows to traverse the list
5488 * from tail to head, useful for ZREVRANGE. */
5489
5490 static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
5491 zskiplistNode *zn = zmalloc(sizeof(*zn));
5492
5493 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
5494 if (level > 1)
5495 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
5496 else
5497 zn->span = NULL;
5498 zn->score = score;
5499 zn->obj = obj;
5500 return zn;
5501 }
5502
5503 static zskiplist *zslCreate(void) {
5504 int j;
5505 zskiplist *zsl;
5506
5507 zsl = zmalloc(sizeof(*zsl));
5508 zsl->level = 1;
5509 zsl->length = 0;
5510 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
5511 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
5512 zsl->header->forward[j] = NULL;
5513
5514 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5515 if (j < ZSKIPLIST_MAXLEVEL-1)
5516 zsl->header->span[j] = 0;
5517 }
5518 zsl->header->backward = NULL;
5519 zsl->tail = NULL;
5520 return zsl;
5521 }
5522
5523 static void zslFreeNode(zskiplistNode *node) {
5524 decrRefCount(node->obj);
5525 zfree(node->forward);
5526 zfree(node->span);
5527 zfree(node);
5528 }
5529
5530 static void zslFree(zskiplist *zsl) {
5531 zskiplistNode *node = zsl->header->forward[0], *next;
5532
5533 zfree(zsl->header->forward);
5534 zfree(zsl->header->span);
5535 zfree(zsl->header);
5536 while(node) {
5537 next = node->forward[0];
5538 zslFreeNode(node);
5539 node = next;
5540 }
5541 zfree(zsl);
5542 }
5543
5544 static int zslRandomLevel(void) {
5545 int level = 1;
5546 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
5547 level += 1;
5548 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
5549 }
5550
5551 static void zslInsert(zskiplist *zsl, double score, robj *obj) {
5552 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5553 unsigned int rank[ZSKIPLIST_MAXLEVEL];
5554 int i, level;
5555
5556 x = zsl->header;
5557 for (i = zsl->level-1; i >= 0; i--) {
5558 /* store rank that is crossed to reach the insert position */
5559 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
5560
5561 while (x->forward[i] &&
5562 (x->forward[i]->score < score ||
5563 (x->forward[i]->score == score &&
5564 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
5565 rank[i] += i > 0 ? x->span[i-1] : 1;
5566 x = x->forward[i];
5567 }
5568 update[i] = x;
5569 }
5570 /* we assume the key is not already inside, since we allow duplicated
5571 * scores, and the re-insertion of score and redis object should never
5572 * happpen since the caller of zslInsert() should test in the hash table
5573 * if the element is already inside or not. */
5574 level = zslRandomLevel();
5575 if (level > zsl->level) {
5576 for (i = zsl->level; i < level; i++) {
5577 rank[i] = 0;
5578 update[i] = zsl->header;
5579 update[i]->span[i-1] = zsl->length;
5580 }
5581 zsl->level = level;
5582 }
5583 x = zslCreateNode(level,score,obj);
5584 for (i = 0; i < level; i++) {
5585 x->forward[i] = update[i]->forward[i];
5586 update[i]->forward[i] = x;
5587
5588 /* update span covered by update[i] as x is inserted here */
5589 if (i > 0) {
5590 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
5591 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
5592 }
5593 }
5594
5595 /* increment span for untouched levels */
5596 for (i = level; i < zsl->level; i++) {
5597 update[i]->span[i-1]++;
5598 }
5599
5600 x->backward = (update[0] == zsl->header) ? NULL : update[0];
5601 if (x->forward[0])
5602 x->forward[0]->backward = x;
5603 else
5604 zsl->tail = x;
5605 zsl->length++;
5606 }
5607
5608 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5609 void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
5610 int i;
5611 for (i = 0; i < zsl->level; i++) {
5612 if (update[i]->forward[i] == x) {
5613 if (i > 0) {
5614 update[i]->span[i-1] += x->span[i-1] - 1;
5615 }
5616 update[i]->forward[i] = x->forward[i];
5617 } else {
5618 /* invariant: i > 0, because update[0]->forward[0]
5619 * is always equal to x */
5620 update[i]->span[i-1] -= 1;
5621 }
5622 }
5623 if (x->forward[0]) {
5624 x->forward[0]->backward = x->backward;
5625 } else {
5626 zsl->tail = x->backward;
5627 }
5628 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
5629 zsl->level--;
5630 zsl->length--;
5631 }
5632
5633 /* Delete an element with matching score/object from the skiplist. */
5634 static int zslDelete(zskiplist *zsl, double score, robj *obj) {
5635 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5636 int i;
5637
5638 x = zsl->header;
5639 for (i = zsl->level-1; i >= 0; i--) {
5640 while (x->forward[i] &&
5641 (x->forward[i]->score < score ||
5642 (x->forward[i]->score == score &&
5643 compareStringObjects(x->forward[i]->obj,obj) < 0)))
5644 x = x->forward[i];
5645 update[i] = x;
5646 }
5647 /* We may have multiple elements with the same score, what we need
5648 * is to find the element with both the right score and object. */
5649 x = x->forward[0];
5650 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
5651 zslDeleteNode(zsl, x, update);
5652 zslFreeNode(x);
5653 return 1;
5654 } else {
5655 return 0; /* not found */
5656 }
5657 return 0; /* not found */
5658 }
5659
5660 /* Delete all the elements with score between min and max from the skiplist.
5661 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5662 * Note that this function takes the reference to the hash table view of the
5663 * sorted set, in order to remove the elements from the hash table too. */
5664 static unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
5665 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5666 unsigned long removed = 0;
5667 int i;
5668
5669 x = zsl->header;
5670 for (i = zsl->level-1; i >= 0; i--) {
5671 while (x->forward[i] && x->forward[i]->score < min)
5672 x = x->forward[i];
5673 update[i] = x;
5674 }
5675 /* We may have multiple elements with the same score, what we need
5676 * is to find the element with both the right score and object. */
5677 x = x->forward[0];
5678 while (x && x->score <= max) {
5679 zskiplistNode *next = x->forward[0];
5680 zslDeleteNode(zsl, x, update);
5681 dictDelete(dict,x->obj);
5682 zslFreeNode(x);
5683 removed++;
5684 x = next;
5685 }
5686 return removed; /* not found */
5687 }
5688
5689 /* Delete all the elements with rank between start and end from the skiplist.
5690 * Start and end are inclusive. Note that start and end need to be 1-based */
5691 static unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
5692 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5693 unsigned long traversed = 0, removed = 0;
5694 int i;
5695
5696 x = zsl->header;
5697 for (i = zsl->level-1; i >= 0; i--) {
5698 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
5699 traversed += i > 0 ? x->span[i-1] : 1;
5700 x = x->forward[i];
5701 }
5702 update[i] = x;
5703 }
5704
5705 traversed++;
5706 x = x->forward[0];
5707 while (x && traversed <= end) {
5708 zskiplistNode *next = x->forward[0];
5709 zslDeleteNode(zsl, x, update);
5710 dictDelete(dict,x->obj);
5711 zslFreeNode(x);
5712 removed++;
5713 traversed++;
5714 x = next;
5715 }
5716 return removed;
5717 }
5718
5719 /* Find the first node having a score equal or greater than the specified one.
5720 * Returns NULL if there is no match. */
5721 static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
5722 zskiplistNode *x;
5723 int i;
5724
5725 x = zsl->header;
5726 for (i = zsl->level-1; i >= 0; i--) {
5727 while (x->forward[i] && x->forward[i]->score < score)
5728 x = x->forward[i];
5729 }
5730 /* We may have multiple elements with the same score, what we need
5731 * is to find the element with both the right score and object. */
5732 return x->forward[0];
5733 }
5734
5735 /* Find the rank for an element by both score and key.
5736 * Returns 0 when the element cannot be found, rank otherwise.
5737 * Note that the rank is 1-based due to the span of zsl->header to the
5738 * first element. */
5739 static unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
5740 zskiplistNode *x;
5741 unsigned long rank = 0;
5742 int i;
5743
5744 x = zsl->header;
5745 for (i = zsl->level-1; i >= 0; i--) {
5746 while (x->forward[i] &&
5747 (x->forward[i]->score < score ||
5748 (x->forward[i]->score == score &&
5749 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
5750 rank += i > 0 ? x->span[i-1] : 1;
5751 x = x->forward[i];
5752 }
5753
5754 /* x might be equal to zsl->header, so test if obj is non-NULL */
5755 if (x->obj && equalStringObjects(x->obj,o)) {
5756 return rank;
5757 }
5758 }
5759 return 0;
5760 }
5761
5762 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5763 zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
5764 zskiplistNode *x;
5765 unsigned long traversed = 0;
5766 int i;
5767
5768 x = zsl->header;
5769 for (i = zsl->level-1; i >= 0; i--) {
5770 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
5771 {
5772 traversed += i > 0 ? x->span[i-1] : 1;
5773 x = x->forward[i];
5774 }
5775 if (traversed == rank) {
5776 return x;
5777 }
5778 }
5779 return NULL;
5780 }
5781
5782 /* The actual Z-commands implementations */
5783
5784 /* This generic command implements both ZADD and ZINCRBY.
5785 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5786 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5787 static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
5788 robj *zsetobj;
5789 zset *zs;
5790 double *score;
5791
5792 if (isnan(scoreval)) {
5793 addReplySds(c,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
5794 return;
5795 }
5796
5797 zsetobj = lookupKeyWrite(c->db,key);
5798 if (zsetobj == NULL) {
5799 zsetobj = createZsetObject();
5800 dictAdd(c->db->dict,key,zsetobj);
5801 incrRefCount(key);
5802 } else {
5803 if (zsetobj->type != REDIS_ZSET) {
5804 addReply(c,shared.wrongtypeerr);
5805 return;
5806 }
5807 }
5808 zs = zsetobj->ptr;
5809
5810 /* Ok now since we implement both ZADD and ZINCRBY here the code
5811 * needs to handle the two different conditions. It's all about setting
5812 * '*score', that is, the new score to set, to the right value. */
5813 score = zmalloc(sizeof(double));
5814 if (doincrement) {
5815 dictEntry *de;
5816
5817 /* Read the old score. If the element was not present starts from 0 */
5818 de = dictFind(zs->dict,ele);
5819 if (de) {
5820 double *oldscore = dictGetEntryVal(de);
5821 *score = *oldscore + scoreval;
5822 } else {
5823 *score = scoreval;
5824 }
5825 if (isnan(*score)) {
5826 addReplySds(c,
5827 sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
5828 zfree(score);
5829 /* Note that we don't need to check if the zset may be empty and
5830 * should be removed here, as we can only obtain Nan as score if
5831 * there was already an element in the sorted set. */
5832 return;
5833 }
5834 } else {
5835 *score = scoreval;
5836 }
5837
5838 /* What follows is a simple remove and re-insert operation that is common
5839 * to both ZADD and ZINCRBY... */
5840 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
5841 /* case 1: New element */
5842 incrRefCount(ele); /* added to hash */
5843 zslInsert(zs->zsl,*score,ele);
5844 incrRefCount(ele); /* added to skiplist */
5845 server.dirty++;
5846 if (doincrement)
5847 addReplyDouble(c,*score);
5848 else
5849 addReply(c,shared.cone);
5850 } else {
5851 dictEntry *de;
5852 double *oldscore;
5853
5854 /* case 2: Score update operation */
5855 de = dictFind(zs->dict,ele);
5856 redisAssert(de != NULL);
5857 oldscore = dictGetEntryVal(de);
5858 if (*score != *oldscore) {
5859 int deleted;
5860
5861 /* Remove and insert the element in the skip list with new score */
5862 deleted = zslDelete(zs->zsl,*oldscore,ele);
5863 redisAssert(deleted != 0);
5864 zslInsert(zs->zsl,*score,ele);
5865 incrRefCount(ele);
5866 /* Update the score in the hash table */
5867 dictReplace(zs->dict,ele,score);
5868 server.dirty++;
5869 } else {
5870 zfree(score);
5871 }
5872 if (doincrement)
5873 addReplyDouble(c,*score);
5874 else
5875 addReply(c,shared.czero);
5876 }
5877 }
5878
5879 static void zaddCommand(redisClient *c) {
5880 double scoreval;
5881
5882 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
5883 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
5884 }
5885
5886 static void zincrbyCommand(redisClient *c) {
5887 double scoreval;
5888
5889 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
5890 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
5891 }
5892
5893 static void zremCommand(redisClient *c) {
5894 robj *zsetobj;
5895 zset *zs;
5896 dictEntry *de;
5897 double *oldscore;
5898 int deleted;
5899
5900 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5901 checkType(c,zsetobj,REDIS_ZSET)) return;
5902
5903 zs = zsetobj->ptr;
5904 de = dictFind(zs->dict,c->argv[2]);
5905 if (de == NULL) {
5906 addReply(c,shared.czero);
5907 return;
5908 }
5909 /* Delete from the skiplist */
5910 oldscore = dictGetEntryVal(de);
5911 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
5912 redisAssert(deleted != 0);
5913
5914 /* Delete from the hash table */
5915 dictDelete(zs->dict,c->argv[2]);
5916 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
5917 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
5918 server.dirty++;
5919 addReply(c,shared.cone);
5920 }
5921
5922 static void zremrangebyscoreCommand(redisClient *c) {
5923 double min;
5924 double max;
5925 long deleted;
5926 robj *zsetobj;
5927 zset *zs;
5928
5929 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
5930 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
5931
5932 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5933 checkType(c,zsetobj,REDIS_ZSET)) return;
5934
5935 zs = zsetobj->ptr;
5936 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
5937 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
5938 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
5939 server.dirty += deleted;
5940 addReplyLongLong(c,deleted);
5941 }
5942
5943 static void zremrangebyrankCommand(redisClient *c) {
5944 long start;
5945 long end;
5946 int llen;
5947 long deleted;
5948 robj *zsetobj;
5949 zset *zs;
5950
5951 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
5952 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
5953
5954 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5955 checkType(c,zsetobj,REDIS_ZSET)) return;
5956 zs = zsetobj->ptr;
5957 llen = zs->zsl->length;
5958
5959 /* convert negative indexes */
5960 if (start < 0) start = llen+start;
5961 if (end < 0) end = llen+end;
5962 if (start < 0) start = 0;
5963 if (end < 0) end = 0;
5964
5965 /* indexes sanity checks */
5966 if (start > end || start >= llen) {
5967 addReply(c,shared.czero);
5968 return;
5969 }
5970 if (end >= llen) end = llen-1;
5971
5972 /* increment start and end because zsl*Rank functions
5973 * use 1-based rank */
5974 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
5975 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
5976 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
5977 server.dirty += deleted;
5978 addReplyLongLong(c, deleted);
5979 }
5980
5981 typedef struct {
5982 dict *dict;
5983 double weight;
5984 } zsetopsrc;
5985
5986 static int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
5987 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
5988 unsigned long size1, size2;
5989 size1 = d1->dict ? dictSize(d1->dict) : 0;
5990 size2 = d2->dict ? dictSize(d2->dict) : 0;
5991 return size1 - size2;
5992 }
5993
5994 #define REDIS_AGGR_SUM 1
5995 #define REDIS_AGGR_MIN 2
5996 #define REDIS_AGGR_MAX 3
5997 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
5998
5999 inline static void zunionInterAggregate(double *target, double val, int aggregate) {
6000 if (aggregate == REDIS_AGGR_SUM) {
6001 *target = *target + val;
6002 } else if (aggregate == REDIS_AGGR_MIN) {
6003 *target = val < *target ? val : *target;
6004 } else if (aggregate == REDIS_AGGR_MAX) {
6005 *target = val > *target ? val : *target;
6006 } else {
6007 /* safety net */
6008 redisPanic("Unknown ZUNION/INTER aggregate type");
6009 }
6010 }
6011
6012 static void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
6013 int i, j, setnum;
6014 int aggregate = REDIS_AGGR_SUM;
6015 zsetopsrc *src;
6016 robj *dstobj;
6017 zset *dstzset;
6018 dictIterator *di;
6019 dictEntry *de;
6020
6021 /* expect setnum input keys to be given */
6022 setnum = atoi(c->argv[2]->ptr);
6023 if (setnum < 1) {
6024 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
6025 return;
6026 }
6027
6028 /* test if the expected number of keys would overflow */
6029 if (3+setnum > c->argc) {
6030 addReply(c,shared.syntaxerr);
6031 return;
6032 }
6033
6034 /* read keys to be used for input */
6035 src = zmalloc(sizeof(zsetopsrc) * setnum);
6036 for (i = 0, j = 3; i < setnum; i++, j++) {
6037 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
6038 if (!obj) {
6039 src[i].dict = NULL;
6040 } else {
6041 if (obj->type == REDIS_ZSET) {
6042 src[i].dict = ((zset*)obj->ptr)->dict;
6043 } else if (obj->type == REDIS_SET) {
6044 src[i].dict = (obj->ptr);
6045 } else {
6046 zfree(src);
6047 addReply(c,shared.wrongtypeerr);
6048 return;
6049 }
6050 }
6051
6052 /* default all weights to 1 */
6053 src[i].weight = 1.0;
6054 }
6055
6056 /* parse optional extra arguments */
6057 if (j < c->argc) {
6058 int remaining = c->argc - j;
6059
6060 while (remaining) {
6061 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
6062 j++; remaining--;
6063 for (i = 0; i < setnum; i++, j++, remaining--) {
6064 if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK)
6065 return;
6066 }
6067 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
6068 j++; remaining--;
6069 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
6070 aggregate = REDIS_AGGR_SUM;
6071 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
6072 aggregate = REDIS_AGGR_MIN;
6073 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
6074 aggregate = REDIS_AGGR_MAX;
6075 } else {
6076 zfree(src);
6077 addReply(c,shared.syntaxerr);
6078 return;
6079 }
6080 j++; remaining--;
6081 } else {
6082 zfree(src);
6083 addReply(c,shared.syntaxerr);
6084 return;
6085 }
6086 }
6087 }
6088
6089 /* sort sets from the smallest to largest, this will improve our
6090 * algorithm's performance */
6091 qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);
6092
6093 dstobj = createZsetObject();
6094 dstzset = dstobj->ptr;
6095
6096 if (op == REDIS_OP_INTER) {
6097 /* skip going over all entries if the smallest zset is NULL or empty */
6098 if (src[0].dict && dictSize(src[0].dict) > 0) {
6099 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6100 * from small to large, all src[i > 0].dict are non-empty too */
6101 di = dictGetIterator(src[0].dict);
6102 while((de = dictNext(di)) != NULL) {
6103 double *score = zmalloc(sizeof(double)), value;
6104 *score = src[0].weight * zunionInterDictValue(de);
6105
6106 for (j = 1; j < setnum; j++) {
6107 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
6108 if (other) {
6109 value = src[j].weight * zunionInterDictValue(other);
6110 zunionInterAggregate(score, value, aggregate);
6111 } else {
6112 break;
6113 }
6114 }
6115
6116 /* skip entry when not present in every source dict */
6117 if (j != setnum) {
6118 zfree(score);
6119 } else {
6120 robj *o = dictGetEntryKey(de);
6121 dictAdd(dstzset->dict,o,score);
6122 incrRefCount(o); /* added to dictionary */
6123 zslInsert(dstzset->zsl,*score,o);
6124 incrRefCount(o); /* added to skiplist */
6125 }
6126 }
6127 dictReleaseIterator(di);
6128 }
6129 } else if (op == REDIS_OP_UNION) {
6130 for (i = 0; i < setnum; i++) {
6131 if (!src[i].dict) continue;
6132
6133 di = dictGetIterator(src[i].dict);
6134 while((de = dictNext(di)) != NULL) {
6135 /* skip key when already processed */
6136 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
6137
6138 double *score = zmalloc(sizeof(double)), value;
6139 *score = src[i].weight * zunionInterDictValue(de);
6140
6141 /* because the zsets are sorted by size, its only possible
6142 * for sets at larger indices to hold this entry */
6143 for (j = (i+1); j < setnum; j++) {
6144 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
6145 if (other) {
6146 value = src[j].weight * zunionInterDictValue(other);
6147 zunionInterAggregate(score, value, aggregate);
6148 }
6149 }
6150
6151 robj *o = dictGetEntryKey(de);
6152 dictAdd(dstzset->dict,o,score);
6153 incrRefCount(o); /* added to dictionary */
6154 zslInsert(dstzset->zsl,*score,o);
6155 incrRefCount(o); /* added to skiplist */
6156 }
6157 dictReleaseIterator(di);
6158 }
6159 } else {
6160 /* unknown operator */
6161 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
6162 }
6163
6164 deleteKey(c->db,dstkey);
6165 if (dstzset->zsl->length) {
6166 dictAdd(c->db->dict,dstkey,dstobj);
6167 incrRefCount(dstkey);
6168 addReplyLongLong(c, dstzset->zsl->length);
6169 server.dirty++;
6170 } else {
6171 decrRefCount(dstobj);
6172 addReply(c, shared.czero);
6173 }
6174 zfree(src);
6175 }
6176
6177 static void zunionstoreCommand(redisClient *c) {
6178 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
6179 }
6180
6181 static void zinterstoreCommand(redisClient *c) {
6182 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
6183 }
6184
6185 static void zrangeGenericCommand(redisClient *c, int reverse) {
6186 robj *o;
6187 long start;
6188 long end;
6189 int withscores = 0;
6190 int llen;
6191 int rangelen, j;
6192 zset *zsetobj;
6193 zskiplist *zsl;
6194 zskiplistNode *ln;
6195 robj *ele;
6196
6197 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6198 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
6199
6200 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
6201 withscores = 1;
6202 } else if (c->argc >= 5) {
6203 addReply(c,shared.syntaxerr);
6204 return;
6205 }
6206
6207 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6208 || checkType(c,o,REDIS_ZSET)) return;
6209 zsetobj = o->ptr;
6210 zsl = zsetobj->zsl;
6211 llen = zsl->length;
6212
6213 /* convert negative indexes */
6214 if (start < 0) start = llen+start;
6215 if (end < 0) end = llen+end;
6216 if (start < 0) start = 0;
6217 if (end < 0) end = 0;
6218
6219 /* indexes sanity checks */
6220 if (start > end || start >= llen) {
6221 /* Out of range start or start > end result in empty list */
6222 addReply(c,shared.emptymultibulk);
6223 return;
6224 }
6225 if (end >= llen) end = llen-1;
6226 rangelen = (end-start)+1;
6227
6228 /* check if starting point is trivial, before searching
6229 * the element in log(N) time */
6230 if (reverse) {
6231 ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start);
6232 } else {
6233 ln = start == 0 ?
6234 zsl->header->forward[0] : zslGetElementByRank(zsl, start+1);
6235 }
6236
6237 /* Return the result in form of a multi-bulk reply */
6238 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
6239 withscores ? (rangelen*2) : rangelen));
6240 for (j = 0; j < rangelen; j++) {
6241 ele = ln->obj;
6242 addReplyBulk(c,ele);
6243 if (withscores)
6244 addReplyDouble(c,ln->score);
6245 ln = reverse ? ln->backward : ln->forward[0];
6246 }
6247 }
6248
6249 static void zrangeCommand(redisClient *c) {
6250 zrangeGenericCommand(c,0);
6251 }
6252
6253 static void zrevrangeCommand(redisClient *c) {
6254 zrangeGenericCommand(c,1);
6255 }
6256
6257 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
6258 * If justcount is non-zero, just the count is returned. */
6259 static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
6260 robj *o;
6261 double min, max;
6262 int minex = 0, maxex = 0; /* are min or max exclusive? */
6263 int offset = 0, limit = -1;
6264 int withscores = 0;
6265 int badsyntax = 0;
6266
6267 /* Parse the min-max interval. If one of the values is prefixed
6268 * by the "(" character, it's considered "open". For instance
6269 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6270 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6271 if (((char*)c->argv[2]->ptr)[0] == '(') {
6272 min = strtod((char*)c->argv[2]->ptr+1,NULL);
6273 minex = 1;
6274 } else {
6275 min = strtod(c->argv[2]->ptr,NULL);
6276 }
6277 if (((char*)c->argv[3]->ptr)[0] == '(') {
6278 max = strtod((char*)c->argv[3]->ptr+1,NULL);
6279 maxex = 1;
6280 } else {
6281 max = strtod(c->argv[3]->ptr,NULL);
6282 }
6283
6284 /* Parse "WITHSCORES": note that if the command was called with
6285 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6286 * enter the following paths to parse WITHSCORES and LIMIT. */
6287 if (c->argc == 5 || c->argc == 8) {
6288 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
6289 withscores = 1;
6290 else
6291 badsyntax = 1;
6292 }
6293 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
6294 badsyntax = 1;
6295 if (badsyntax) {
6296 addReplySds(c,
6297 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
6298 return;
6299 }
6300
6301 /* Parse "LIMIT" */
6302 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
6303 addReply(c,shared.syntaxerr);
6304 return;
6305 } else if (c->argc == (7 + withscores)) {
6306 offset = atoi(c->argv[5]->ptr);
6307 limit = atoi(c->argv[6]->ptr);
6308 if (offset < 0) offset = 0;
6309 }
6310
6311 /* Ok, lookup the key and get the range */
6312 o = lookupKeyRead(c->db,c->argv[1]);
6313 if (o == NULL) {
6314 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
6315 } else {
6316 if (o->type != REDIS_ZSET) {
6317 addReply(c,shared.wrongtypeerr);
6318 } else {
6319 zset *zsetobj = o->ptr;
6320 zskiplist *zsl = zsetobj->zsl;
6321 zskiplistNode *ln;
6322 robj *ele, *lenobj = NULL;
6323 unsigned long rangelen = 0;
6324
6325 /* Get the first node with the score >= min, or with
6326 * score > min if 'minex' is true. */
6327 ln = zslFirstWithScore(zsl,min);
6328 while (minex && ln && ln->score == min) ln = ln->forward[0];
6329
6330 if (ln == NULL) {
6331 /* No element matching the speciifed interval */
6332 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
6333 return;
6334 }
6335
6336 /* We don't know in advance how many matching elements there
6337 * are in the list, so we push this object that will represent
6338 * the multi-bulk length in the output buffer, and will "fix"
6339 * it later */
6340 if (!justcount) {
6341 lenobj = createObject(REDIS_STRING,NULL);
6342 addReply(c,lenobj);
6343 decrRefCount(lenobj);
6344 }
6345
6346 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
6347 if (offset) {
6348 offset--;
6349 ln = ln->forward[0];
6350 continue;
6351 }
6352 if (limit == 0) break;
6353 if (!justcount) {
6354 ele = ln->obj;
6355 addReplyBulk(c,ele);
6356 if (withscores)
6357 addReplyDouble(c,ln->score);
6358 }
6359 ln = ln->forward[0];
6360 rangelen++;
6361 if (limit > 0) limit--;
6362 }
6363 if (justcount) {
6364 addReplyLongLong(c,(long)rangelen);
6365 } else {
6366 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
6367 withscores ? (rangelen*2) : rangelen);
6368 }
6369 }
6370 }
6371 }
6372
6373 static void zrangebyscoreCommand(redisClient *c) {
6374 genericZrangebyscoreCommand(c,0);
6375 }
6376
6377 static void zcountCommand(redisClient *c) {
6378 genericZrangebyscoreCommand(c,1);
6379 }
6380
6381 static void zcardCommand(redisClient *c) {
6382 robj *o;
6383 zset *zs;
6384
6385 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6386 checkType(c,o,REDIS_ZSET)) return;
6387
6388 zs = o->ptr;
6389 addReplyUlong(c,zs->zsl->length);
6390 }
6391
6392 static void zscoreCommand(redisClient *c) {
6393 robj *o;
6394 zset *zs;
6395 dictEntry *de;
6396
6397 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6398 checkType(c,o,REDIS_ZSET)) return;
6399
6400 zs = o->ptr;
6401 de = dictFind(zs->dict,c->argv[2]);
6402 if (!de) {
6403 addReply(c,shared.nullbulk);
6404 } else {
6405 double *score = dictGetEntryVal(de);
6406
6407 addReplyDouble(c,*score);
6408 }
6409 }
6410
6411 static void zrankGenericCommand(redisClient *c, int reverse) {
6412 robj *o;
6413 zset *zs;
6414 zskiplist *zsl;
6415 dictEntry *de;
6416 unsigned long rank;
6417 double *score;
6418
6419 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6420 checkType(c,o,REDIS_ZSET)) return;
6421
6422 zs = o->ptr;
6423 zsl = zs->zsl;
6424 de = dictFind(zs->dict,c->argv[2]);
6425 if (!de) {
6426 addReply(c,shared.nullbulk);
6427 return;
6428 }
6429
6430 score = dictGetEntryVal(de);
6431 rank = zslGetRank(zsl, *score, c->argv[2]);
6432 if (rank) {
6433 if (reverse) {
6434 addReplyLongLong(c, zsl->length - rank);
6435 } else {
6436 addReplyLongLong(c, rank-1);
6437 }
6438 } else {
6439 addReply(c,shared.nullbulk);
6440 }
6441 }
6442
6443 static void zrankCommand(redisClient *c) {
6444 zrankGenericCommand(c, 0);
6445 }
6446
6447 static void zrevrankCommand(redisClient *c) {
6448 zrankGenericCommand(c, 1);
6449 }
6450
6451 /* ========================= Hashes utility functions ======================= */
6452 #define REDIS_HASH_KEY 1
6453 #define REDIS_HASH_VALUE 2
6454
6455 /* Check the length of a number of objects to see if we need to convert a
6456 * zipmap to a real hash. Note that we only check string encoded objects
6457 * as their string length can be queried in constant time. */
6458 static void hashTryConversion(robj *subject, robj **argv, int start, int end) {
6459 int i;
6460 if (subject->encoding != REDIS_ENCODING_ZIPMAP) return;
6461
6462 for (i = start; i <= end; i++) {
6463 if (argv[i]->encoding == REDIS_ENCODING_RAW &&
6464 sdslen(argv[i]->ptr) > server.hash_max_zipmap_value)
6465 {
6466 convertToRealHash(subject);
6467 return;
6468 }
6469 }
6470 }
6471
6472 /* Encode given objects in-place when the hash uses a dict. */
6473 static void hashTryObjectEncoding(robj *subject, robj **o1, robj **o2) {
6474 if (subject->encoding == REDIS_ENCODING_HT) {
6475 if (o1) *o1 = tryObjectEncoding(*o1);
6476 if (o2) *o2 = tryObjectEncoding(*o2);
6477 }
6478 }
6479
6480 /* Get the value from a hash identified by key. Returns either a string
6481 * object or NULL if the value cannot be found. The refcount of the object
6482 * is always increased by 1 when the value was found. */
6483 static robj *hashGet(robj *o, robj *key) {
6484 robj *value = NULL;
6485 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6486 unsigned char *v;
6487 unsigned int vlen;
6488 key = getDecodedObject(key);
6489 if (zipmapGet(o->ptr,key->ptr,sdslen(key->ptr),&v,&vlen)) {
6490 value = createStringObject((char*)v,vlen);
6491 }
6492 decrRefCount(key);
6493 } else {
6494 dictEntry *de = dictFind(o->ptr,key);
6495 if (de != NULL) {
6496 value = dictGetEntryVal(de);
6497 incrRefCount(value);
6498 }
6499 }
6500 return value;
6501 }
6502
6503 /* Test if the key exists in the given hash. Returns 1 if the key
6504 * exists and 0 when it doesn't. */
6505 static int hashExists(robj *o, robj *key) {
6506 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6507 key = getDecodedObject(key);
6508 if (zipmapExists(o->ptr,key->ptr,sdslen(key->ptr))) {
6509 decrRefCount(key);
6510 return 1;
6511 }
6512 decrRefCount(key);
6513 } else {
6514 if (dictFind(o->ptr,key) != NULL) {
6515 return 1;
6516 }
6517 }
6518 return 0;
6519 }
6520
6521 /* Add an element, discard the old if the key already exists.
6522 * Return 0 on insert and 1 on update. */
6523 static int hashSet(robj *o, robj *key, robj *value) {
6524 int update = 0;
6525 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6526 key = getDecodedObject(key);
6527 value = getDecodedObject(value);
6528 o->ptr = zipmapSet(o->ptr,
6529 key->ptr,sdslen(key->ptr),
6530 value->ptr,sdslen(value->ptr), &update);
6531 decrRefCount(key);
6532 decrRefCount(value);
6533
6534 /* Check if the zipmap needs to be upgraded to a real hash table */
6535 if (zipmapLen(o->ptr) > server.hash_max_zipmap_entries)
6536 convertToRealHash(o);
6537 } else {
6538 if (dictReplace(o->ptr,key,value)) {
6539 /* Insert */
6540 incrRefCount(key);
6541 } else {
6542 /* Update */
6543 update = 1;
6544 }
6545 incrRefCount(value);
6546 }
6547 return update;
6548 }
6549
6550 /* Delete an element from a hash.
6551 * Return 1 on deleted and 0 on not found. */
6552 static int hashDelete(robj *o, robj *key) {
6553 int deleted = 0;
6554 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6555 key = getDecodedObject(key);
6556 o->ptr = zipmapDel(o->ptr,key->ptr,sdslen(key->ptr), &deleted);
6557 decrRefCount(key);
6558 } else {
6559 deleted = dictDelete((dict*)o->ptr,key) == DICT_OK;
6560 /* Always check if the dictionary needs a resize after a delete. */
6561 if (deleted && htNeedsResize(o->ptr)) dictResize(o->ptr);
6562 }
6563 return deleted;
6564 }
6565
6566 /* Return the number of elements in a hash. */
6567 static unsigned long hashLength(robj *o) {
6568 return (o->encoding == REDIS_ENCODING_ZIPMAP) ?
6569 zipmapLen((unsigned char*)o->ptr) : dictSize((dict*)o->ptr);
6570 }
6571
6572 /* Structure to hold hash iteration abstration. Note that iteration over
6573 * hashes involves both fields and values. Because it is possible that
6574 * not both are required, store pointers in the iterator to avoid
6575 * unnecessary memory allocation for fields/values. */
6576 typedef struct {
6577 int encoding;
6578 unsigned char *zi;
6579 unsigned char *zk, *zv;
6580 unsigned int zklen, zvlen;
6581
6582 dictIterator *di;
6583 dictEntry *de;
6584 } hashIterator;
6585
6586 static hashIterator *hashInitIterator(robj *subject) {
6587 hashIterator *hi = zmalloc(sizeof(hashIterator));
6588 hi->encoding = subject->encoding;
6589 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6590 hi->zi = zipmapRewind(subject->ptr);
6591 } else if (hi->encoding == REDIS_ENCODING_HT) {
6592 hi->di = dictGetIterator(subject->ptr);
6593 } else {
6594 redisAssert(NULL);
6595 }
6596 return hi;
6597 }
6598
6599 static void hashReleaseIterator(hashIterator *hi) {
6600 if (hi->encoding == REDIS_ENCODING_HT) {
6601 dictReleaseIterator(hi->di);
6602 }
6603 zfree(hi);
6604 }
6605
6606 /* Move to the next entry in the hash. Return REDIS_OK when the next entry
6607 * could be found and REDIS_ERR when the iterator reaches the end. */
6608 static int hashNext(hashIterator *hi) {
6609 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6610 if ((hi->zi = zipmapNext(hi->zi, &hi->zk, &hi->zklen,
6611 &hi->zv, &hi->zvlen)) == NULL) return REDIS_ERR;
6612 } else {
6613 if ((hi->de = dictNext(hi->di)) == NULL) return REDIS_ERR;
6614 }
6615 return REDIS_OK;
6616 }
6617
6618 /* Get key or value object at current iteration position.
6619 * This increases the refcount of the field object by 1. */
6620 static robj *hashCurrent(hashIterator *hi, int what) {
6621 robj *o;
6622 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6623 if (what & REDIS_HASH_KEY) {
6624 o = createStringObject((char*)hi->zk,hi->zklen);
6625 } else {
6626 o = createStringObject((char*)hi->zv,hi->zvlen);
6627 }
6628 } else {
6629 if (what & REDIS_HASH_KEY) {
6630 o = dictGetEntryKey(hi->de);
6631 } else {
6632 o = dictGetEntryVal(hi->de);
6633 }
6634 incrRefCount(o);
6635 }
6636 return o;
6637 }
6638
6639 static robj *hashLookupWriteOrCreate(redisClient *c, robj *key) {
6640 robj *o = lookupKeyWrite(c->db,key);
6641 if (o == NULL) {
6642 o = createHashObject();
6643 dictAdd(c->db->dict,key,o);
6644 incrRefCount(key);
6645 } else {
6646 if (o->type != REDIS_HASH) {
6647 addReply(c,shared.wrongtypeerr);
6648 return NULL;
6649 }
6650 }
6651 return o;
6652 }
6653
6654 /* ============================= Hash commands ============================== */
6655 static void hsetCommand(redisClient *c) {
6656 int update;
6657 robj *o;
6658
6659 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6660 hashTryConversion(o,c->argv,2,3);
6661 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
6662 update = hashSet(o,c->argv[2],c->argv[3]);
6663 addReply(c, update ? shared.czero : shared.cone);
6664 server.dirty++;
6665 }
6666
6667 static void hsetnxCommand(redisClient *c) {
6668 robj *o;
6669 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6670 hashTryConversion(o,c->argv,2,3);
6671
6672 if (hashExists(o, c->argv[2])) {
6673 addReply(c, shared.czero);
6674 } else {
6675 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
6676 hashSet(o,c->argv[2],c->argv[3]);
6677 addReply(c, shared.cone);
6678 server.dirty++;
6679 }
6680 }
6681
6682 static void hmsetCommand(redisClient *c) {
6683 int i;
6684 robj *o;
6685
6686 if ((c->argc % 2) == 1) {
6687 addReplySds(c,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6688 return;
6689 }
6690
6691 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6692 hashTryConversion(o,c->argv,2,c->argc-1);
6693 for (i = 2; i < c->argc; i += 2) {
6694 hashTryObjectEncoding(o,&c->argv[i], &c->argv[i+1]);
6695 hashSet(o,c->argv[i],c->argv[i+1]);
6696 }
6697 addReply(c, shared.ok);
6698 server.dirty++;
6699 }
6700
6701 static void hincrbyCommand(redisClient *c) {
6702 long long value, incr;
6703 robj *o, *current, *new;
6704
6705 if (getLongLongFromObjectOrReply(c,c->argv[3],&incr,NULL) != REDIS_OK) return;
6706 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6707 if ((current = hashGet(o,c->argv[2])) != NULL) {
6708 if (getLongLongFromObjectOrReply(c,current,&value,
6709 "hash value is not an integer") != REDIS_OK) {
6710 decrRefCount(current);
6711 return;
6712 }
6713 decrRefCount(current);
6714 } else {
6715 value = 0;
6716 }
6717
6718 value += incr;
6719 new = createStringObjectFromLongLong(value);
6720 hashTryObjectEncoding(o,&c->argv[2],NULL);
6721 hashSet(o,c->argv[2],new);
6722 decrRefCount(new);
6723 addReplyLongLong(c,value);
6724 server.dirty++;
6725 }
6726
6727 static void hgetCommand(redisClient *c) {
6728 robj *o, *value;
6729 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6730 checkType(c,o,REDIS_HASH)) return;
6731
6732 if ((value = hashGet(o,c->argv[2])) != NULL) {
6733 addReplyBulk(c,value);
6734 decrRefCount(value);
6735 } else {
6736 addReply(c,shared.nullbulk);
6737 }
6738 }
6739
6740 static void hmgetCommand(redisClient *c) {
6741 int i;
6742 robj *o, *value;
6743 o = lookupKeyRead(c->db,c->argv[1]);
6744 if (o != NULL && o->type != REDIS_HASH) {
6745 addReply(c,shared.wrongtypeerr);
6746 }
6747
6748 /* Note the check for o != NULL happens inside the loop. This is
6749 * done because objects that cannot be found are considered to be
6750 * an empty hash. The reply should then be a series of NULLs. */
6751 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-2));
6752 for (i = 2; i < c->argc; i++) {
6753 if (o != NULL && (value = hashGet(o,c->argv[i])) != NULL) {
6754 addReplyBulk(c,value);
6755 decrRefCount(value);
6756 } else {
6757 addReply(c,shared.nullbulk);
6758 }
6759 }
6760 }
6761
6762 static void hdelCommand(redisClient *c) {
6763 robj *o;
6764 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6765 checkType(c,o,REDIS_HASH)) return;
6766
6767 if (hashDelete(o,c->argv[2])) {
6768 if (hashLength(o) == 0) deleteKey(c->db,c->argv[1]);
6769 addReply(c,shared.cone);
6770 server.dirty++;
6771 } else {
6772 addReply(c,shared.czero);
6773 }
6774 }
6775
6776 static void hlenCommand(redisClient *c) {
6777 robj *o;
6778 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6779 checkType(c,o,REDIS_HASH)) return;
6780
6781 addReplyUlong(c,hashLength(o));
6782 }
6783
6784 static void genericHgetallCommand(redisClient *c, int flags) {
6785 robj *o, *lenobj, *obj;
6786 unsigned long count = 0;
6787 hashIterator *hi;
6788
6789 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6790 || checkType(c,o,REDIS_HASH)) return;
6791
6792 lenobj = createObject(REDIS_STRING,NULL);
6793 addReply(c,lenobj);
6794 decrRefCount(lenobj);
6795
6796 hi = hashInitIterator(o);
6797 while (hashNext(hi) != REDIS_ERR) {
6798 if (flags & REDIS_HASH_KEY) {
6799 obj = hashCurrent(hi,REDIS_HASH_KEY);
6800 addReplyBulk(c,obj);
6801 decrRefCount(obj);
6802 count++;
6803 }
6804 if (flags & REDIS_HASH_VALUE) {
6805 obj = hashCurrent(hi,REDIS_HASH_VALUE);
6806 addReplyBulk(c,obj);
6807 decrRefCount(obj);
6808 count++;
6809 }
6810 }
6811 hashReleaseIterator(hi);
6812
6813 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",count);
6814 }
6815
6816 static void hkeysCommand(redisClient *c) {
6817 genericHgetallCommand(c,REDIS_HASH_KEY);
6818 }
6819
6820 static void hvalsCommand(redisClient *c) {
6821 genericHgetallCommand(c,REDIS_HASH_VALUE);
6822 }
6823
6824 static void hgetallCommand(redisClient *c) {
6825 genericHgetallCommand(c,REDIS_HASH_KEY|REDIS_HASH_VALUE);
6826 }
6827
6828 static void hexistsCommand(redisClient *c) {
6829 robj *o;
6830 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6831 checkType(c,o,REDIS_HASH)) return;
6832
6833 addReply(c, hashExists(o,c->argv[2]) ? shared.cone : shared.czero);
6834 }
6835
6836 static void convertToRealHash(robj *o) {
6837 unsigned char *key, *val, *p, *zm = o->ptr;
6838 unsigned int klen, vlen;
6839 dict *dict = dictCreate(&hashDictType,NULL);
6840
6841 assert(o->type == REDIS_HASH && o->encoding != REDIS_ENCODING_HT);
6842 p = zipmapRewind(zm);
6843 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
6844 robj *keyobj, *valobj;
6845
6846 keyobj = createStringObject((char*)key,klen);
6847 valobj = createStringObject((char*)val,vlen);
6848 keyobj = tryObjectEncoding(keyobj);
6849 valobj = tryObjectEncoding(valobj);
6850 dictAdd(dict,keyobj,valobj);
6851 }
6852 o->encoding = REDIS_ENCODING_HT;
6853 o->ptr = dict;
6854 zfree(zm);
6855 }
6856
6857 /* ========================= Non type-specific commands ==================== */
6858
6859 static void flushdbCommand(redisClient *c) {
6860 server.dirty += dictSize(c->db->dict);
6861 touchWatchedKeysOnFlush(c->db->id);
6862 dictEmpty(c->db->dict);
6863 dictEmpty(c->db->expires);
6864 addReply(c,shared.ok);
6865 }
6866
6867 static void flushallCommand(redisClient *c) {
6868 touchWatchedKeysOnFlush(-1);
6869 server.dirty += emptyDb();
6870 addReply(c,shared.ok);
6871 if (server.bgsavechildpid != -1) {
6872 kill(server.bgsavechildpid,SIGKILL);
6873 rdbRemoveTempFile(server.bgsavechildpid);
6874 }
6875 rdbSave(server.dbfilename);
6876 server.dirty++;
6877 }
6878
6879 static redisSortOperation *createSortOperation(int type, robj *pattern) {
6880 redisSortOperation *so = zmalloc(sizeof(*so));
6881 so->type = type;
6882 so->pattern = pattern;
6883 return so;
6884 }
6885
6886 /* Return the value associated to the key with a name obtained
6887 * substituting the first occurence of '*' in 'pattern' with 'subst'.
6888 * The returned object will always have its refcount increased by 1
6889 * when it is non-NULL. */
6890 static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
6891 char *p, *f;
6892 sds spat, ssub;
6893 robj keyobj, fieldobj, *o;
6894 int prefixlen, sublen, postfixlen, fieldlen;
6895 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6896 struct {
6897 long len;
6898 long free;
6899 char buf[REDIS_SORTKEY_MAX+1];
6900 } keyname, fieldname;
6901
6902 /* If the pattern is "#" return the substitution object itself in order
6903 * to implement the "SORT ... GET #" feature. */
6904 spat = pattern->ptr;
6905 if (spat[0] == '#' && spat[1] == '\0') {
6906 incrRefCount(subst);
6907 return subst;
6908 }
6909
6910 /* The substitution object may be specially encoded. If so we create
6911 * a decoded object on the fly. Otherwise getDecodedObject will just
6912 * increment the ref count, that we'll decrement later. */
6913 subst = getDecodedObject(subst);
6914
6915 ssub = subst->ptr;
6916 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
6917 p = strchr(spat,'*');
6918 if (!p) {
6919 decrRefCount(subst);
6920 return NULL;
6921 }
6922
6923 /* Find out if we're dealing with a hash dereference. */
6924 if ((f = strstr(p+1, "->")) != NULL) {
6925 fieldlen = sdslen(spat)-(f-spat);
6926 /* this also copies \0 character */
6927 memcpy(fieldname.buf,f+2,fieldlen-1);
6928 fieldname.len = fieldlen-2;
6929 } else {
6930 fieldlen = 0;
6931 }
6932
6933 prefixlen = p-spat;
6934 sublen = sdslen(ssub);
6935 postfixlen = sdslen(spat)-(prefixlen+1)-fieldlen;
6936 memcpy(keyname.buf,spat,prefixlen);
6937 memcpy(keyname.buf+prefixlen,ssub,sublen);
6938 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
6939 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
6940 keyname.len = prefixlen+sublen+postfixlen;
6941 decrRefCount(subst);
6942
6943 /* Lookup substituted key */
6944 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2));
6945 o = lookupKeyRead(db,&keyobj);
6946 if (o == NULL) return NULL;
6947
6948 if (fieldlen > 0) {
6949 if (o->type != REDIS_HASH || fieldname.len < 1) return NULL;
6950
6951 /* Retrieve value from hash by the field name. This operation
6952 * already increases the refcount of the returned object. */
6953 initStaticStringObject(fieldobj,((char*)&fieldname)+(sizeof(long)*2));
6954 o = hashGet(o, &fieldobj);
6955 } else {
6956 if (o->type != REDIS_STRING) return NULL;
6957
6958 /* Every object that this function returns needs to have its refcount
6959 * increased. sortCommand decreases it again. */
6960 incrRefCount(o);
6961 }
6962
6963 return o;
6964 }
6965
6966 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6967 * the additional parameter is not standard but a BSD-specific we have to
6968 * pass sorting parameters via the global 'server' structure */
6969 static int sortCompare(const void *s1, const void *s2) {
6970 const redisSortObject *so1 = s1, *so2 = s2;
6971 int cmp;
6972
6973 if (!server.sort_alpha) {
6974 /* Numeric sorting. Here it's trivial as we precomputed scores */
6975 if (so1->u.score > so2->u.score) {
6976 cmp = 1;
6977 } else if (so1->u.score < so2->u.score) {
6978 cmp = -1;
6979 } else {
6980 cmp = 0;
6981 }
6982 } else {
6983 /* Alphanumeric sorting */
6984 if (server.sort_bypattern) {
6985 if (!so1->u.cmpobj || !so2->u.cmpobj) {
6986 /* At least one compare object is NULL */
6987 if (so1->u.cmpobj == so2->u.cmpobj)
6988 cmp = 0;
6989 else if (so1->u.cmpobj == NULL)
6990 cmp = -1;
6991 else
6992 cmp = 1;
6993 } else {
6994 /* We have both the objects, use strcoll */
6995 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
6996 }
6997 } else {
6998 /* Compare elements directly. */
6999 cmp = compareStringObjects(so1->obj,so2->obj);
7000 }
7001 }
7002 return server.sort_desc ? -cmp : cmp;
7003 }
7004
7005 /* The SORT command is the most complex command in Redis. Warning: this code
7006 * is optimized for speed and a bit less for readability */
7007 static void sortCommand(redisClient *c) {
7008 list *operations;
7009 int outputlen = 0;
7010 int desc = 0, alpha = 0;
7011 int limit_start = 0, limit_count = -1, start, end;
7012 int j, dontsort = 0, vectorlen;
7013 int getop = 0; /* GET operation counter */
7014 robj *sortval, *sortby = NULL, *storekey = NULL;
7015 redisSortObject *vector; /* Resulting vector to sort */
7016
7017 /* Lookup the key to sort. It must be of the right types */
7018 sortval = lookupKeyRead(c->db,c->argv[1]);
7019 if (sortval == NULL) {
7020 addReply(c,shared.emptymultibulk);
7021 return;
7022 }
7023 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
7024 sortval->type != REDIS_ZSET)
7025 {
7026 addReply(c,shared.wrongtypeerr);
7027 return;
7028 }
7029
7030 /* Create a list of operations to perform for every sorted element.
7031 * Operations can be GET/DEL/INCR/DECR */
7032 operations = listCreate();
7033 listSetFreeMethod(operations,zfree);
7034 j = 2;
7035
7036 /* Now we need to protect sortval incrementing its count, in the future
7037 * SORT may have options able to overwrite/delete keys during the sorting
7038 * and the sorted key itself may get destroied */
7039 incrRefCount(sortval);
7040
7041 /* The SORT command has an SQL-alike syntax, parse it */
7042 while(j < c->argc) {
7043 int leftargs = c->argc-j-1;
7044 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
7045 desc = 0;
7046 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
7047 desc = 1;
7048 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
7049 alpha = 1;
7050 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
7051 limit_start = atoi(c->argv[j+1]->ptr);
7052 limit_count = atoi(c->argv[j+2]->ptr);
7053 j+=2;
7054 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
7055 storekey = c->argv[j+1];
7056 j++;
7057 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
7058 sortby = c->argv[j+1];
7059 /* If the BY pattern does not contain '*', i.e. it is constant,
7060 * we don't need to sort nor to lookup the weight keys. */
7061 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
7062 j++;
7063 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
7064 listAddNodeTail(operations,createSortOperation(
7065 REDIS_SORT_GET,c->argv[j+1]));
7066 getop++;
7067 j++;
7068 } else {
7069 decrRefCount(sortval);
7070 listRelease(operations);
7071 addReply(c,shared.syntaxerr);
7072 return;
7073 }
7074 j++;
7075 }
7076
7077 /* Load the sorting vector with all the objects to sort */
7078 switch(sortval->type) {
7079 case REDIS_LIST: vectorlen = listLength((list*)sortval->ptr); break;
7080 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
7081 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
7082 default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
7083 }
7084 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
7085 j = 0;
7086
7087 if (sortval->type == REDIS_LIST) {
7088 list *list = sortval->ptr;
7089 listNode *ln;
7090 listIter li;
7091
7092 listRewind(list,&li);
7093 while((ln = listNext(&li))) {
7094 robj *ele = ln->value;
7095 vector[j].obj = ele;
7096 vector[j].u.score = 0;
7097 vector[j].u.cmpobj = NULL;
7098 j++;
7099 }
7100 } else {
7101 dict *set;
7102 dictIterator *di;
7103 dictEntry *setele;
7104
7105 if (sortval->type == REDIS_SET) {
7106 set = sortval->ptr;
7107 } else {
7108 zset *zs = sortval->ptr;
7109 set = zs->dict;
7110 }
7111
7112 di = dictGetIterator(set);
7113 while((setele = dictNext(di)) != NULL) {
7114 vector[j].obj = dictGetEntryKey(setele);
7115 vector[j].u.score = 0;
7116 vector[j].u.cmpobj = NULL;
7117 j++;
7118 }
7119 dictReleaseIterator(di);
7120 }
7121 redisAssert(j == vectorlen);
7122
7123 /* Now it's time to load the right scores in the sorting vector */
7124 if (dontsort == 0) {
7125 for (j = 0; j < vectorlen; j++) {
7126 robj *byval;
7127 if (sortby) {
7128 /* lookup value to sort by */
7129 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
7130 if (!byval) continue;
7131 } else {
7132 /* use object itself to sort by */
7133 byval = vector[j].obj;
7134 }
7135
7136 if (alpha) {
7137 if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
7138 } else {
7139 if (byval->encoding == REDIS_ENCODING_RAW) {
7140 vector[j].u.score = strtod(byval->ptr,NULL);
7141 } else if (byval->encoding == REDIS_ENCODING_INT) {
7142 /* Don't need to decode the object if it's
7143 * integer-encoded (the only encoding supported) so
7144 * far. We can just cast it */
7145 vector[j].u.score = (long)byval->ptr;
7146 } else {
7147 redisAssert(1 != 1);
7148 }
7149 }
7150
7151 /* when the object was retrieved using lookupKeyByPattern,
7152 * its refcount needs to be decreased. */
7153 if (sortby) {
7154 decrRefCount(byval);
7155 }
7156 }
7157 }
7158
7159 /* We are ready to sort the vector... perform a bit of sanity check
7160 * on the LIMIT option too. We'll use a partial version of quicksort. */
7161 start = (limit_start < 0) ? 0 : limit_start;
7162 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
7163 if (start >= vectorlen) {
7164 start = vectorlen-1;
7165 end = vectorlen-2;
7166 }
7167 if (end >= vectorlen) end = vectorlen-1;
7168
7169 if (dontsort == 0) {
7170 server.sort_desc = desc;
7171 server.sort_alpha = alpha;
7172 server.sort_bypattern = sortby ? 1 : 0;
7173 if (sortby && (start != 0 || end != vectorlen-1))
7174 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
7175 else
7176 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
7177 }
7178
7179 /* Send command output to the output buffer, performing the specified
7180 * GET/DEL/INCR/DECR operations if any. */
7181 outputlen = getop ? getop*(end-start+1) : end-start+1;
7182 if (storekey == NULL) {
7183 /* STORE option not specified, sent the sorting result to client */
7184 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
7185 for (j = start; j <= end; j++) {
7186 listNode *ln;
7187 listIter li;
7188
7189 if (!getop) addReplyBulk(c,vector[j].obj);
7190 listRewind(operations,&li);
7191 while((ln = listNext(&li))) {
7192 redisSortOperation *sop = ln->value;
7193 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7194 vector[j].obj);
7195
7196 if (sop->type == REDIS_SORT_GET) {
7197 if (!val) {
7198 addReply(c,shared.nullbulk);
7199 } else {
7200 addReplyBulk(c,val);
7201 decrRefCount(val);
7202 }
7203 } else {
7204 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
7205 }
7206 }
7207 }
7208 } else {
7209 robj *listObject = createListObject();
7210 list *listPtr = (list*) listObject->ptr;
7211
7212 /* STORE option specified, set the sorting result as a List object */
7213 for (j = start; j <= end; j++) {
7214 listNode *ln;
7215 listIter li;
7216
7217 if (!getop) {
7218 listAddNodeTail(listPtr,vector[j].obj);
7219 incrRefCount(vector[j].obj);
7220 }
7221 listRewind(operations,&li);
7222 while((ln = listNext(&li))) {
7223 redisSortOperation *sop = ln->value;
7224 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7225 vector[j].obj);
7226
7227 if (sop->type == REDIS_SORT_GET) {
7228 if (!val) {
7229 listAddNodeTail(listPtr,createStringObject("",0));
7230 } else {
7231 /* We should do a incrRefCount on val because it is
7232 * added to the list, but also a decrRefCount because
7233 * it is returned by lookupKeyByPattern. This results
7234 * in doing nothing at all. */
7235 listAddNodeTail(listPtr,val);
7236 }
7237 } else {
7238 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
7239 }
7240 }
7241 }
7242 if (dictReplace(c->db->dict,storekey,listObject)) {
7243 incrRefCount(storekey);
7244 }
7245 /* Note: we add 1 because the DB is dirty anyway since even if the
7246 * SORT result is empty a new key is set and maybe the old content
7247 * replaced. */
7248 server.dirty += 1+outputlen;
7249 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
7250 }
7251
7252 /* Cleanup */
7253 decrRefCount(sortval);
7254 listRelease(operations);
7255 for (j = 0; j < vectorlen; j++) {
7256 if (alpha && vector[j].u.cmpobj)
7257 decrRefCount(vector[j].u.cmpobj);
7258 }
7259 zfree(vector);
7260 }
7261
7262 /* Convert an amount of bytes into a human readable string in the form
7263 * of 100B, 2G, 100M, 4K, and so forth. */
7264 static void bytesToHuman(char *s, unsigned long long n) {
7265 double d;
7266
7267 if (n < 1024) {
7268 /* Bytes */
7269 sprintf(s,"%lluB",n);
7270 return;
7271 } else if (n < (1024*1024)) {
7272 d = (double)n/(1024);
7273 sprintf(s,"%.2fK",d);
7274 } else if (n < (1024LL*1024*1024)) {
7275 d = (double)n/(1024*1024);
7276 sprintf(s,"%.2fM",d);
7277 } else if (n < (1024LL*1024*1024*1024)) {
7278 d = (double)n/(1024LL*1024*1024);
7279 sprintf(s,"%.2fG",d);
7280 }
7281 }
7282
7283 /* Create the string returned by the INFO command. This is decoupled
7284 * by the INFO command itself as we need to report the same information
7285 * on memory corruption problems. */
7286 static sds genRedisInfoString(void) {
7287 sds info;
7288 time_t uptime = time(NULL)-server.stat_starttime;
7289 int j;
7290 char hmem[64];
7291
7292 bytesToHuman(hmem,zmalloc_used_memory());
7293 info = sdscatprintf(sdsempty(),
7294 "redis_version:%s\r\n"
7295 "redis_git_sha1:%s\r\n"
7296 "redis_git_dirty:%d\r\n"
7297 "arch_bits:%s\r\n"
7298 "multiplexing_api:%s\r\n"
7299 "process_id:%ld\r\n"
7300 "uptime_in_seconds:%ld\r\n"
7301 "uptime_in_days:%ld\r\n"
7302 "connected_clients:%d\r\n"
7303 "connected_slaves:%d\r\n"
7304 "blocked_clients:%d\r\n"
7305 "used_memory:%zu\r\n"
7306 "used_memory_human:%s\r\n"
7307 "changes_since_last_save:%lld\r\n"
7308 "bgsave_in_progress:%d\r\n"
7309 "last_save_time:%ld\r\n"
7310 "bgrewriteaof_in_progress:%d\r\n"
7311 "total_connections_received:%lld\r\n"
7312 "total_commands_processed:%lld\r\n"
7313 "expired_keys:%lld\r\n"
7314 "hash_max_zipmap_entries:%zu\r\n"
7315 "hash_max_zipmap_value:%zu\r\n"
7316 "pubsub_channels:%ld\r\n"
7317 "pubsub_patterns:%u\r\n"
7318 "vm_enabled:%d\r\n"
7319 "role:%s\r\n"
7320 ,REDIS_VERSION,
7321 REDIS_GIT_SHA1,
7322 strtol(REDIS_GIT_DIRTY,NULL,10) > 0,
7323 (sizeof(long) == 8) ? "64" : "32",
7324 aeGetApiName(),
7325 (long) getpid(),
7326 uptime,
7327 uptime/(3600*24),
7328 listLength(server.clients)-listLength(server.slaves),
7329 listLength(server.slaves),
7330 server.blpop_blocked_clients,
7331 zmalloc_used_memory(),
7332 hmem,
7333 server.dirty,
7334 server.bgsavechildpid != -1,
7335 server.lastsave,
7336 server.bgrewritechildpid != -1,
7337 server.stat_numconnections,
7338 server.stat_numcommands,
7339 server.stat_expiredkeys,
7340 server.hash_max_zipmap_entries,
7341 server.hash_max_zipmap_value,
7342 dictSize(server.pubsub_channels),
7343 listLength(server.pubsub_patterns),
7344 server.vm_enabled != 0,
7345 server.masterhost == NULL ? "master" : "slave"
7346 );
7347 if (server.masterhost) {
7348 info = sdscatprintf(info,
7349 "master_host:%s\r\n"
7350 "master_port:%d\r\n"
7351 "master_link_status:%s\r\n"
7352 "master_last_io_seconds_ago:%d\r\n"
7353 ,server.masterhost,
7354 server.masterport,
7355 (server.replstate == REDIS_REPL_CONNECTED) ?
7356 "up" : "down",
7357 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
7358 );
7359 }
7360 if (server.vm_enabled) {
7361 lockThreadedIO();
7362 info = sdscatprintf(info,
7363 "vm_conf_max_memory:%llu\r\n"
7364 "vm_conf_page_size:%llu\r\n"
7365 "vm_conf_pages:%llu\r\n"
7366 "vm_stats_used_pages:%llu\r\n"
7367 "vm_stats_swapped_objects:%llu\r\n"
7368 "vm_stats_swappin_count:%llu\r\n"
7369 "vm_stats_swappout_count:%llu\r\n"
7370 "vm_stats_io_newjobs_len:%lu\r\n"
7371 "vm_stats_io_processing_len:%lu\r\n"
7372 "vm_stats_io_processed_len:%lu\r\n"
7373 "vm_stats_io_active_threads:%lu\r\n"
7374 "vm_stats_blocked_clients:%lu\r\n"
7375 ,(unsigned long long) server.vm_max_memory,
7376 (unsigned long long) server.vm_page_size,
7377 (unsigned long long) server.vm_pages,
7378 (unsigned long long) server.vm_stats_used_pages,
7379 (unsigned long long) server.vm_stats_swapped_objects,
7380 (unsigned long long) server.vm_stats_swapins,
7381 (unsigned long long) server.vm_stats_swapouts,
7382 (unsigned long) listLength(server.io_newjobs),
7383 (unsigned long) listLength(server.io_processing),
7384 (unsigned long) listLength(server.io_processed),
7385 (unsigned long) server.io_active_threads,
7386 (unsigned long) server.vm_blocked_clients
7387 );
7388 unlockThreadedIO();
7389 }
7390 for (j = 0; j < server.dbnum; j++) {
7391 long long keys, vkeys;
7392
7393 keys = dictSize(server.db[j].dict);
7394 vkeys = dictSize(server.db[j].expires);
7395 if (keys || vkeys) {
7396 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
7397 j, keys, vkeys);
7398 }
7399 }
7400 return info;
7401 }
7402
7403 static void infoCommand(redisClient *c) {
7404 sds info = genRedisInfoString();
7405 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
7406 (unsigned long)sdslen(info)));
7407 addReplySds(c,info);
7408 addReply(c,shared.crlf);
7409 }
7410
7411 static void monitorCommand(redisClient *c) {
7412 /* ignore MONITOR if aleady slave or in monitor mode */
7413 if (c->flags & REDIS_SLAVE) return;
7414
7415 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
7416 c->slaveseldb = 0;
7417 listAddNodeTail(server.monitors,c);
7418 addReply(c,shared.ok);
7419 }
7420
7421 /* ================================= Expire ================================= */
7422 static int removeExpire(redisDb *db, robj *key) {
7423 if (dictDelete(db->expires,key) == DICT_OK) {
7424 return 1;
7425 } else {
7426 return 0;
7427 }
7428 }
7429
7430 static int setExpire(redisDb *db, robj *key, time_t when) {
7431 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
7432 return 0;
7433 } else {
7434 incrRefCount(key);
7435 return 1;
7436 }
7437 }
7438
7439 /* Return the expire time of the specified key, or -1 if no expire
7440 * is associated with this key (i.e. the key is non volatile) */
7441 static time_t getExpire(redisDb *db, robj *key) {
7442 dictEntry *de;
7443
7444 /* No expire? return ASAP */
7445 if (dictSize(db->expires) == 0 ||
7446 (de = dictFind(db->expires,key)) == NULL) return -1;
7447
7448 return (time_t) dictGetEntryVal(de);
7449 }
7450
7451 static int expireIfNeeded(redisDb *db, robj *key) {
7452 time_t when;
7453 dictEntry *de;
7454
7455 /* No expire? return ASAP */
7456 if (dictSize(db->expires) == 0 ||
7457 (de = dictFind(db->expires,key)) == NULL) return 0;
7458
7459 /* Lookup the expire */
7460 when = (time_t) dictGetEntryVal(de);
7461 if (time(NULL) <= when) return 0;
7462
7463 /* Delete the key */
7464 dictDelete(db->expires,key);
7465 server.stat_expiredkeys++;
7466 return dictDelete(db->dict,key) == DICT_OK;
7467 }
7468
7469 static int deleteIfVolatile(redisDb *db, robj *key) {
7470 dictEntry *de;
7471
7472 /* No expire? return ASAP */
7473 if (dictSize(db->expires) == 0 ||
7474 (de = dictFind(db->expires,key)) == NULL) return 0;
7475
7476 /* Delete the key */
7477 server.dirty++;
7478 server.stat_expiredkeys++;
7479 dictDelete(db->expires,key);
7480 return dictDelete(db->dict,key) == DICT_OK;
7481 }
7482
7483 static void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
7484 dictEntry *de;
7485 time_t seconds;
7486
7487 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
7488
7489 seconds -= offset;
7490
7491 de = dictFind(c->db->dict,key);
7492 if (de == NULL) {
7493 addReply(c,shared.czero);
7494 return;
7495 }
7496 if (seconds <= 0) {
7497 if (deleteKey(c->db,key)) server.dirty++;
7498 addReply(c, shared.cone);
7499 return;
7500 } else {
7501 time_t when = time(NULL)+seconds;
7502 if (setExpire(c->db,key,when)) {
7503 addReply(c,shared.cone);
7504 server.dirty++;
7505 } else {
7506 addReply(c,shared.czero);
7507 }
7508 return;
7509 }
7510 }
7511
7512 static void expireCommand(redisClient *c) {
7513 expireGenericCommand(c,c->argv[1],c->argv[2],0);
7514 }
7515
7516 static void expireatCommand(redisClient *c) {
7517 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
7518 }
7519
7520 static void ttlCommand(redisClient *c) {
7521 time_t expire;
7522 int ttl = -1;
7523
7524 expire = getExpire(c->db,c->argv[1]);
7525 if (expire != -1) {
7526 ttl = (int) (expire-time(NULL));
7527 if (ttl < 0) ttl = -1;
7528 }
7529 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
7530 }
7531
7532 /* ================================ MULTI/EXEC ============================== */
7533
7534 /* Client state initialization for MULTI/EXEC */
7535 static void initClientMultiState(redisClient *c) {
7536 c->mstate.commands = NULL;
7537 c->mstate.count = 0;
7538 }
7539
7540 /* Release all the resources associated with MULTI/EXEC state */
7541 static void freeClientMultiState(redisClient *c) {
7542 int j;
7543
7544 for (j = 0; j < c->mstate.count; j++) {
7545 int i;
7546 multiCmd *mc = c->mstate.commands+j;
7547
7548 for (i = 0; i < mc->argc; i++)
7549 decrRefCount(mc->argv[i]);
7550 zfree(mc->argv);
7551 }
7552 zfree(c->mstate.commands);
7553 }
7554
7555 /* Add a new command into the MULTI commands queue */
7556 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
7557 multiCmd *mc;
7558 int j;
7559
7560 c->mstate.commands = zrealloc(c->mstate.commands,
7561 sizeof(multiCmd)*(c->mstate.count+1));
7562 mc = c->mstate.commands+c->mstate.count;
7563 mc->cmd = cmd;
7564 mc->argc = c->argc;
7565 mc->argv = zmalloc(sizeof(robj*)*c->argc);
7566 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
7567 for (j = 0; j < c->argc; j++)
7568 incrRefCount(mc->argv[j]);
7569 c->mstate.count++;
7570 }
7571
7572 static void multiCommand(redisClient *c) {
7573 if (c->flags & REDIS_MULTI) {
7574 addReplySds(c,sdsnew("-ERR MULTI calls can not be nested\r\n"));
7575 return;
7576 }
7577 c->flags |= REDIS_MULTI;
7578 addReply(c,shared.ok);
7579 }
7580
7581 static void discardCommand(redisClient *c) {
7582 if (!(c->flags & REDIS_MULTI)) {
7583 addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
7584 return;
7585 }
7586
7587 freeClientMultiState(c);
7588 initClientMultiState(c);
7589 c->flags &= (~REDIS_MULTI);
7590 addReply(c,shared.ok);
7591 }
7592
7593 /* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7594 * implememntation for more information. */
7595 static void execCommandReplicateMulti(redisClient *c) {
7596 struct redisCommand *cmd;
7597 robj *multistring = createStringObject("MULTI",5);
7598
7599 cmd = lookupCommand("multi");
7600 if (server.appendonly)
7601 feedAppendOnlyFile(cmd,c->db->id,&multistring,1);
7602 if (listLength(server.slaves))
7603 replicationFeedSlaves(server.slaves,c->db->id,&multistring,1);
7604 decrRefCount(multistring);
7605 }
7606
7607 static void execCommand(redisClient *c) {
7608 int j;
7609 robj **orig_argv;
7610 int orig_argc;
7611
7612 if (!(c->flags & REDIS_MULTI)) {
7613 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
7614 return;
7615 }
7616
7617 /* Check if we need to abort the EXEC if some WATCHed key was touched.
7618 * A failed EXEC will return a multi bulk nil object. */
7619 if (c->flags & REDIS_DIRTY_CAS) {
7620 freeClientMultiState(c);
7621 initClientMultiState(c);
7622 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
7623 unwatchAllKeys(c);
7624 addReply(c,shared.nullmultibulk);
7625 return;
7626 }
7627
7628 /* Replicate a MULTI request now that we are sure the block is executed.
7629 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7630 * both the AOF and the replication link will have the same consistency
7631 * and atomicity guarantees. */
7632 execCommandReplicateMulti(c);
7633
7634 /* Exec all the queued commands */
7635 unwatchAllKeys(c); /* Unwatch ASAP otherwise we'll waste CPU cycles */
7636 orig_argv = c->argv;
7637 orig_argc = c->argc;
7638 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
7639 for (j = 0; j < c->mstate.count; j++) {
7640 c->argc = c->mstate.commands[j].argc;
7641 c->argv = c->mstate.commands[j].argv;
7642 call(c,c->mstate.commands[j].cmd);
7643 }
7644 c->argv = orig_argv;
7645 c->argc = orig_argc;
7646 freeClientMultiState(c);
7647 initClientMultiState(c);
7648 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
7649 /* Make sure the EXEC command is always replicated / AOF, since we
7650 * always send the MULTI command (we can't know beforehand if the
7651 * next operations will contain at least a modification to the DB). */
7652 server.dirty++;
7653 }
7654
7655 /* =========================== Blocking Operations ========================= */
7656
7657 /* Currently Redis blocking operations support is limited to list POP ops,
7658 * so the current implementation is not fully generic, but it is also not
7659 * completely specific so it will not require a rewrite to support new
7660 * kind of blocking operations in the future.
7661 *
7662 * Still it's important to note that list blocking operations can be already
7663 * used as a notification mechanism in order to implement other blocking
7664 * operations at application level, so there must be a very strong evidence
7665 * of usefulness and generality before new blocking operations are implemented.
7666 *
7667 * This is how the current blocking POP works, we use BLPOP as example:
7668 * - If the user calls BLPOP and the key exists and contains a non empty list
7669 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7670 * if there is not to block.
7671 * - If instead BLPOP is called and the key does not exists or the list is
7672 * empty we need to block. In order to do so we remove the notification for
7673 * new data to read in the client socket (so that we'll not serve new
7674 * requests if the blocking request is not served). Also we put the client
7675 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
7676 * blocking for this keys.
7677 * - If a PUSH operation against a key with blocked clients waiting is
7678 * performed, we serve the first in the list: basically instead to push
7679 * the new element inside the list we return it to the (first / oldest)
7680 * blocking client, unblock the client, and remove it form the list.
7681 *
7682 * The above comment and the source code should be enough in order to understand
7683 * the implementation and modify / fix it later.
7684 */
7685
7686 /* Set a client in blocking mode for the specified key, with the specified
7687 * timeout */
7688 static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
7689 dictEntry *de;
7690 list *l;
7691 int j;
7692
7693 c->blocking_keys = zmalloc(sizeof(robj*)*numkeys);
7694 c->blocking_keys_num = numkeys;
7695 c->blockingto = timeout;
7696 for (j = 0; j < numkeys; j++) {
7697 /* Add the key in the client structure, to map clients -> keys */
7698 c->blocking_keys[j] = keys[j];
7699 incrRefCount(keys[j]);
7700
7701 /* And in the other "side", to map keys -> clients */
7702 de = dictFind(c->db->blocking_keys,keys[j]);
7703 if (de == NULL) {
7704 int retval;
7705
7706 /* For every key we take a list of clients blocked for it */
7707 l = listCreate();
7708 retval = dictAdd(c->db->blocking_keys,keys[j],l);
7709 incrRefCount(keys[j]);
7710 assert(retval == DICT_OK);
7711 } else {
7712 l = dictGetEntryVal(de);
7713 }
7714 listAddNodeTail(l,c);
7715 }
7716 /* Mark the client as a blocked client */
7717 c->flags |= REDIS_BLOCKED;
7718 server.blpop_blocked_clients++;
7719 }
7720
7721 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
7722 static void unblockClientWaitingData(redisClient *c) {
7723 dictEntry *de;
7724 list *l;
7725 int j;
7726
7727 assert(c->blocking_keys != NULL);
7728 /* The client may wait for multiple keys, so unblock it for every key. */
7729 for (j = 0; j < c->blocking_keys_num; j++) {
7730 /* Remove this client from the list of clients waiting for this key. */
7731 de = dictFind(c->db->blocking_keys,c->blocking_keys[j]);
7732 assert(de != NULL);
7733 l = dictGetEntryVal(de);
7734 listDelNode(l,listSearchKey(l,c));
7735 /* If the list is empty we need to remove it to avoid wasting memory */
7736 if (listLength(l) == 0)
7737 dictDelete(c->db->blocking_keys,c->blocking_keys[j]);
7738 decrRefCount(c->blocking_keys[j]);
7739 }
7740 /* Cleanup the client structure */
7741 zfree(c->blocking_keys);
7742 c->blocking_keys = NULL;
7743 c->flags &= (~REDIS_BLOCKED);
7744 server.blpop_blocked_clients--;
7745 /* We want to process data if there is some command waiting
7746 * in the input buffer. Note that this is safe even if
7747 * unblockClientWaitingData() gets called from freeClient() because
7748 * freeClient() will be smart enough to call this function
7749 * *after* c->querybuf was set to NULL. */
7750 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
7751 }
7752
7753 /* This should be called from any function PUSHing into lists.
7754 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7755 * 'ele' is the element pushed.
7756 *
7757 * If the function returns 0 there was no client waiting for a list push
7758 * against this key.
7759 *
7760 * If the function returns 1 there was a client waiting for a list push
7761 * against this key, the element was passed to this client thus it's not
7762 * needed to actually add it to the list and the caller should return asap. */
7763 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
7764 struct dictEntry *de;
7765 redisClient *receiver;
7766 list *l;
7767 listNode *ln;
7768
7769 de = dictFind(c->db->blocking_keys,key);
7770 if (de == NULL) return 0;
7771 l = dictGetEntryVal(de);
7772 ln = listFirst(l);
7773 assert(ln != NULL);
7774 receiver = ln->value;
7775
7776 addReplySds(receiver,sdsnew("*2\r\n"));
7777 addReplyBulk(receiver,key);
7778 addReplyBulk(receiver,ele);
7779 unblockClientWaitingData(receiver);
7780 return 1;
7781 }
7782
7783 /* Blocking RPOP/LPOP */
7784 static void blockingPopGenericCommand(redisClient *c, int where) {
7785 robj *o;
7786 time_t timeout;
7787 int j;
7788
7789 for (j = 1; j < c->argc-1; j++) {
7790 o = lookupKeyWrite(c->db,c->argv[j]);
7791 if (o != NULL) {
7792 if (o->type != REDIS_LIST) {
7793 addReply(c,shared.wrongtypeerr);
7794 return;
7795 } else {
7796 list *list = o->ptr;
7797 if (listLength(list) != 0) {
7798 /* If the list contains elements fall back to the usual
7799 * non-blocking POP operation */
7800 robj *argv[2], **orig_argv;
7801 int orig_argc;
7802
7803 /* We need to alter the command arguments before to call
7804 * popGenericCommand() as the command takes a single key. */
7805 orig_argv = c->argv;
7806 orig_argc = c->argc;
7807 argv[1] = c->argv[j];
7808 c->argv = argv;
7809 c->argc = 2;
7810
7811 /* Also the return value is different, we need to output
7812 * the multi bulk reply header and the key name. The
7813 * "real" command will add the last element (the value)
7814 * for us. If this souds like an hack to you it's just
7815 * because it is... */
7816 addReplySds(c,sdsnew("*2\r\n"));
7817 addReplyBulk(c,argv[1]);
7818 popGenericCommand(c,where);
7819
7820 /* Fix the client structure with the original stuff */
7821 c->argv = orig_argv;
7822 c->argc = orig_argc;
7823 return;
7824 }
7825 }
7826 }
7827 }
7828 /* If the list is empty or the key does not exists we must block */
7829 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
7830 if (timeout > 0) timeout += time(NULL);
7831 blockForKeys(c,c->argv+1,c->argc-2,timeout);
7832 }
7833
7834 static void blpopCommand(redisClient *c) {
7835 blockingPopGenericCommand(c,REDIS_HEAD);
7836 }
7837
7838 static void brpopCommand(redisClient *c) {
7839 blockingPopGenericCommand(c,REDIS_TAIL);
7840 }
7841
7842 /* =============================== Replication ============================= */
7843
7844 static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
7845 ssize_t nwritten, ret = size;
7846 time_t start = time(NULL);
7847
7848 timeout++;
7849 while(size) {
7850 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
7851 nwritten = write(fd,ptr,size);
7852 if (nwritten == -1) return -1;
7853 ptr += nwritten;
7854 size -= nwritten;
7855 }
7856 if ((time(NULL)-start) > timeout) {
7857 errno = ETIMEDOUT;
7858 return -1;
7859 }
7860 }
7861 return ret;
7862 }
7863
7864 static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
7865 ssize_t nread, totread = 0;
7866 time_t start = time(NULL);
7867
7868 timeout++;
7869 while(size) {
7870 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
7871 nread = read(fd,ptr,size);
7872 if (nread == -1) return -1;
7873 ptr += nread;
7874 size -= nread;
7875 totread += nread;
7876 }
7877 if ((time(NULL)-start) > timeout) {
7878 errno = ETIMEDOUT;
7879 return -1;
7880 }
7881 }
7882 return totread;
7883 }
7884
7885 static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
7886 ssize_t nread = 0;
7887
7888 size--;
7889 while(size) {
7890 char c;
7891
7892 if (syncRead(fd,&c,1,timeout) == -1) return -1;
7893 if (c == '\n') {
7894 *ptr = '\0';
7895 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
7896 return nread;
7897 } else {
7898 *ptr++ = c;
7899 *ptr = '\0';
7900 nread++;
7901 }
7902 }
7903 return nread;
7904 }
7905
7906 static void syncCommand(redisClient *c) {
7907 /* ignore SYNC if aleady slave or in monitor mode */
7908 if (c->flags & REDIS_SLAVE) return;
7909
7910 /* SYNC can't be issued when the server has pending data to send to
7911 * the client about already issued commands. We need a fresh reply
7912 * buffer registering the differences between the BGSAVE and the current
7913 * dataset, so that we can copy to other slaves if needed. */
7914 if (listLength(c->reply) != 0) {
7915 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7916 return;
7917 }
7918
7919 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
7920 /* Here we need to check if there is a background saving operation
7921 * in progress, or if it is required to start one */
7922 if (server.bgsavechildpid != -1) {
7923 /* Ok a background save is in progress. Let's check if it is a good
7924 * one for replication, i.e. if there is another slave that is
7925 * registering differences since the server forked to save */
7926 redisClient *slave;
7927 listNode *ln;
7928 listIter li;
7929
7930 listRewind(server.slaves,&li);
7931 while((ln = listNext(&li))) {
7932 slave = ln->value;
7933 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
7934 }
7935 if (ln) {
7936 /* Perfect, the server is already registering differences for
7937 * another slave. Set the right state, and copy the buffer. */
7938 listRelease(c->reply);
7939 c->reply = listDup(slave->reply);
7940 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7941 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
7942 } else {
7943 /* No way, we need to wait for the next BGSAVE in order to
7944 * register differences */
7945 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
7946 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
7947 }
7948 } else {
7949 /* Ok we don't have a BGSAVE in progress, let's start one */
7950 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
7951 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
7952 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
7953 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
7954 return;
7955 }
7956 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7957 }
7958 c->repldbfd = -1;
7959 c->flags |= REDIS_SLAVE;
7960 c->slaveseldb = 0;
7961 listAddNodeTail(server.slaves,c);
7962 return;
7963 }
7964
7965 static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
7966 redisClient *slave = privdata;
7967 REDIS_NOTUSED(el);
7968 REDIS_NOTUSED(mask);
7969 char buf[REDIS_IOBUF_LEN];
7970 ssize_t nwritten, buflen;
7971
7972 if (slave->repldboff == 0) {
7973 /* Write the bulk write count before to transfer the DB. In theory here
7974 * we don't know how much room there is in the output buffer of the
7975 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7976 * operations) will never be smaller than the few bytes we need. */
7977 sds bulkcount;
7978
7979 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7980 slave->repldbsize);
7981 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
7982 {
7983 sdsfree(bulkcount);
7984 freeClient(slave);
7985 return;
7986 }
7987 sdsfree(bulkcount);
7988 }
7989 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
7990 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
7991 if (buflen <= 0) {
7992 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
7993 (buflen == 0) ? "premature EOF" : strerror(errno));
7994 freeClient(slave);
7995 return;
7996 }
7997 if ((nwritten = write(fd,buf,buflen)) == -1) {
7998 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
7999 strerror(errno));
8000 freeClient(slave);
8001 return;
8002 }
8003 slave->repldboff += nwritten;
8004 if (slave->repldboff == slave->repldbsize) {
8005 close(slave->repldbfd);
8006 slave->repldbfd = -1;
8007 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8008 slave->replstate = REDIS_REPL_ONLINE;
8009 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
8010 sendReplyToClient, slave) == AE_ERR) {
8011 freeClient(slave);
8012 return;
8013 }
8014 addReplySds(slave,sdsempty());
8015 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
8016 }
8017 }
8018
8019 /* This function is called at the end of every backgrond saving.
8020 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
8021 * otherwise REDIS_ERR is passed to the function.
8022 *
8023 * The goal of this function is to handle slaves waiting for a successful
8024 * background saving in order to perform non-blocking synchronization. */
8025 static void updateSlavesWaitingBgsave(int bgsaveerr) {
8026 listNode *ln;
8027 int startbgsave = 0;
8028 listIter li;
8029
8030 listRewind(server.slaves,&li);
8031 while((ln = listNext(&li))) {
8032 redisClient *slave = ln->value;
8033
8034 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
8035 startbgsave = 1;
8036 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8037 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
8038 struct redis_stat buf;
8039
8040 if (bgsaveerr != REDIS_OK) {
8041 freeClient(slave);
8042 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
8043 continue;
8044 }
8045 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
8046 redis_fstat(slave->repldbfd,&buf) == -1) {
8047 freeClient(slave);
8048 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
8049 continue;
8050 }
8051 slave->repldboff = 0;
8052 slave->repldbsize = buf.st_size;
8053 slave->replstate = REDIS_REPL_SEND_BULK;
8054 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8055 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
8056 freeClient(slave);
8057 continue;
8058 }
8059 }
8060 }
8061 if (startbgsave) {
8062 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
8063 listIter li;
8064
8065 listRewind(server.slaves,&li);
8066 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
8067 while((ln = listNext(&li))) {
8068 redisClient *slave = ln->value;
8069
8070 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
8071 freeClient(slave);
8072 }
8073 }
8074 }
8075 }
8076
8077 static int syncWithMaster(void) {
8078 char buf[1024], tmpfile[256], authcmd[1024];
8079 long dumpsize;
8080 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
8081 int dfd, maxtries = 5;
8082
8083 if (fd == -1) {
8084 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
8085 strerror(errno));
8086 return REDIS_ERR;
8087 }
8088
8089 /* AUTH with the master if required. */
8090 if(server.masterauth) {
8091 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
8092 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
8093 close(fd);
8094 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
8095 strerror(errno));
8096 return REDIS_ERR;
8097 }
8098 /* Read the AUTH result. */
8099 if (syncReadLine(fd,buf,1024,3600) == -1) {
8100 close(fd);
8101 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
8102 strerror(errno));
8103 return REDIS_ERR;
8104 }
8105 if (buf[0] != '+') {
8106 close(fd);
8107 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
8108 return REDIS_ERR;
8109 }
8110 }
8111
8112 /* Issue the SYNC command */
8113 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
8114 close(fd);
8115 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
8116 strerror(errno));
8117 return REDIS_ERR;
8118 }
8119 /* Read the bulk write count */
8120 if (syncReadLine(fd,buf,1024,3600) == -1) {
8121 close(fd);
8122 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
8123 strerror(errno));
8124 return REDIS_ERR;
8125 }
8126 if (buf[0] != '$') {
8127 close(fd);
8128 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8129 return REDIS_ERR;
8130 }
8131 dumpsize = strtol(buf+1,NULL,10);
8132 redisLog(REDIS_NOTICE,"Receiving %ld bytes data dump from MASTER",dumpsize);
8133 /* Read the bulk write data on a temp file */
8134 while(maxtries--) {
8135 snprintf(tmpfile,256,
8136 "temp-%d.%ld.rdb",(int)time(NULL),(long int)getpid());
8137 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
8138 if (dfd != -1) break;
8139 sleep(1);
8140 }
8141 if (dfd == -1) {
8142 close(fd);
8143 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
8144 return REDIS_ERR;
8145 }
8146 while(dumpsize) {
8147 int nread, nwritten;
8148
8149 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
8150 if (nread == -1) {
8151 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
8152 strerror(errno));
8153 close(fd);
8154 close(dfd);
8155 return REDIS_ERR;
8156 }
8157 nwritten = write(dfd,buf,nread);
8158 if (nwritten == -1) {
8159 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
8160 close(fd);
8161 close(dfd);
8162 return REDIS_ERR;
8163 }
8164 dumpsize -= nread;
8165 }
8166 close(dfd);
8167 if (rename(tmpfile,server.dbfilename) == -1) {
8168 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
8169 unlink(tmpfile);
8170 close(fd);
8171 return REDIS_ERR;
8172 }
8173 emptyDb();
8174 if (rdbLoad(server.dbfilename) != REDIS_OK) {
8175 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
8176 close(fd);
8177 return REDIS_ERR;
8178 }
8179 server.master = createClient(fd);
8180 server.master->flags |= REDIS_MASTER;
8181 server.master->authenticated = 1;
8182 server.replstate = REDIS_REPL_CONNECTED;
8183 return REDIS_OK;
8184 }
8185
8186 static void slaveofCommand(redisClient *c) {
8187 if (!strcasecmp(c->argv[1]->ptr,"no") &&
8188 !strcasecmp(c->argv[2]->ptr,"one")) {
8189 if (server.masterhost) {
8190 sdsfree(server.masterhost);
8191 server.masterhost = NULL;
8192 if (server.master) freeClient(server.master);
8193 server.replstate = REDIS_REPL_NONE;
8194 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
8195 }
8196 } else {
8197 sdsfree(server.masterhost);
8198 server.masterhost = sdsdup(c->argv[1]->ptr);
8199 server.masterport = atoi(c->argv[2]->ptr);
8200 if (server.master) freeClient(server.master);
8201 server.replstate = REDIS_REPL_CONNECT;
8202 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
8203 server.masterhost, server.masterport);
8204 }
8205 addReply(c,shared.ok);
8206 }
8207
8208 /* ============================ Maxmemory directive ======================== */
8209
8210 /* Try to free one object form the pre-allocated objects free list.
8211 * This is useful under low mem conditions as by default we take 1 million
8212 * free objects allocated. On success REDIS_OK is returned, otherwise
8213 * REDIS_ERR. */
8214 static int tryFreeOneObjectFromFreelist(void) {
8215 robj *o;
8216
8217 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
8218 if (listLength(server.objfreelist)) {
8219 listNode *head = listFirst(server.objfreelist);
8220 o = listNodeValue(head);
8221 listDelNode(server.objfreelist,head);
8222 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8223 zfree(o);
8224 return REDIS_OK;
8225 } else {
8226 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8227 return REDIS_ERR;
8228 }
8229 }
8230
8231 /* This function gets called when 'maxmemory' is set on the config file to limit
8232 * the max memory used by the server, and we are out of memory.
8233 * This function will try to, in order:
8234 *
8235 * - Free objects from the free list
8236 * - Try to remove keys with an EXPIRE set
8237 *
8238 * It is not possible to free enough memory to reach used-memory < maxmemory
8239 * the server will start refusing commands that will enlarge even more the
8240 * memory usage.
8241 */
8242 static void freeMemoryIfNeeded(void) {
8243 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
8244 int j, k, freed = 0;
8245
8246 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
8247 for (j = 0; j < server.dbnum; j++) {
8248 int minttl = -1;
8249 robj *minkey = NULL;
8250 struct dictEntry *de;
8251
8252 if (dictSize(server.db[j].expires)) {
8253 freed = 1;
8254 /* From a sample of three keys drop the one nearest to
8255 * the natural expire */
8256 for (k = 0; k < 3; k++) {
8257 time_t t;
8258
8259 de = dictGetRandomKey(server.db[j].expires);
8260 t = (time_t) dictGetEntryVal(de);
8261 if (minttl == -1 || t < minttl) {
8262 minkey = dictGetEntryKey(de);
8263 minttl = t;
8264 }
8265 }
8266 deleteKey(server.db+j,minkey);
8267 }
8268 }
8269 if (!freed) return; /* nothing to free... */
8270 }
8271 }
8272
8273 /* ============================== Append Only file ========================== */
8274
8275 /* Called when the user switches from "appendonly yes" to "appendonly no"
8276 * at runtime using the CONFIG command. */
8277 static void stopAppendOnly(void) {
8278 flushAppendOnlyFile();
8279 aof_fsync(server.appendfd);
8280 close(server.appendfd);
8281
8282 server.appendfd = -1;
8283 server.appendseldb = -1;
8284 server.appendonly = 0;
8285 /* rewrite operation in progress? kill it, wait child exit */
8286 if (server.bgsavechildpid != -1) {
8287 int statloc;
8288
8289 if (kill(server.bgsavechildpid,SIGKILL) != -1)
8290 wait3(&statloc,0,NULL);
8291 /* reset the buffer accumulating changes while the child saves */
8292 sdsfree(server.bgrewritebuf);
8293 server.bgrewritebuf = sdsempty();
8294 server.bgsavechildpid = -1;
8295 }
8296 }
8297
8298 /* Called when the user switches from "appendonly no" to "appendonly yes"
8299 * at runtime using the CONFIG command. */
8300 static int startAppendOnly(void) {
8301 server.appendonly = 1;
8302 server.lastfsync = time(NULL);
8303 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
8304 if (server.appendfd == -1) {
8305 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno));
8306 return REDIS_ERR;
8307 }
8308 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
8309 server.appendonly = 0;
8310 close(server.appendfd);
8311 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));
8312 return REDIS_ERR;
8313 }
8314 return REDIS_OK;
8315 }
8316
8317 /* Write the append only file buffer on disk.
8318 *
8319 * Since we are required to write the AOF before replying to the client,
8320 * and the only way the client socket can get a write is entering when the
8321 * the event loop, we accumulate all the AOF writes in a memory
8322 * buffer and write it on disk using this function just before entering
8323 * the event loop again. */
8324 static void flushAppendOnlyFile(void) {
8325 time_t now;
8326 ssize_t nwritten;
8327
8328 if (sdslen(server.aofbuf) == 0) return;
8329
8330 /* We want to perform a single write. This should be guaranteed atomic
8331 * at least if the filesystem we are writing is a real physical one.
8332 * While this will save us against the server being killed I don't think
8333 * there is much to do about the whole server stopping for power problems
8334 * or alike */
8335 nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf));
8336 if (nwritten != (signed)sdslen(server.aofbuf)) {
8337 /* Ooops, we are in troubles. The best thing to do for now is
8338 * aborting instead of giving the illusion that everything is
8339 * working as expected. */
8340 if (nwritten == -1) {
8341 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
8342 } else {
8343 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
8344 }
8345 exit(1);
8346 }
8347 sdsfree(server.aofbuf);
8348 server.aofbuf = sdsempty();
8349
8350 /* Don't Fsync if no-appendfsync-on-rewrite is set to yes and we have
8351 * childs performing heavy I/O on disk. */
8352 if (server.no_appendfsync_on_rewrite &&
8353 (server.bgrewritechildpid != -1 || server.bgsavechildpid != -1))
8354 return;
8355 /* Fsync if needed */
8356 now = time(NULL);
8357 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
8358 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
8359 now-server.lastfsync > 1))
8360 {
8361 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8362 * flushing metadata. */
8363 aof_fsync(server.appendfd); /* Let's try to get this data on the disk */
8364 server.lastfsync = now;
8365 }
8366 }
8367
8368 static sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) {
8369 int j;
8370 buf = sdscatprintf(buf,"*%d\r\n",argc);
8371 for (j = 0; j < argc; j++) {
8372 robj *o = getDecodedObject(argv[j]);
8373 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
8374 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
8375 buf = sdscatlen(buf,"\r\n",2);
8376 decrRefCount(o);
8377 }
8378 return buf;
8379 }
8380
8381 static sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) {
8382 int argc = 3;
8383 long when;
8384 robj *argv[3];
8385
8386 /* Make sure we can use strtol */
8387 seconds = getDecodedObject(seconds);
8388 when = time(NULL)+strtol(seconds->ptr,NULL,10);
8389 decrRefCount(seconds);
8390
8391 argv[0] = createStringObject("EXPIREAT",8);
8392 argv[1] = key;
8393 argv[2] = createObject(REDIS_STRING,
8394 sdscatprintf(sdsempty(),"%ld",when));
8395 buf = catAppendOnlyGenericCommand(buf, argc, argv);
8396 decrRefCount(argv[0]);
8397 decrRefCount(argv[2]);
8398 return buf;
8399 }
8400
8401 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
8402 sds buf = sdsempty();
8403 robj *tmpargv[3];
8404
8405 /* The DB this command was targetting is not the same as the last command
8406 * we appendend. To issue a SELECT command is needed. */
8407 if (dictid != server.appendseldb) {
8408 char seldb[64];
8409
8410 snprintf(seldb,sizeof(seldb),"%d",dictid);
8411 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
8412 (unsigned long)strlen(seldb),seldb);
8413 server.appendseldb = dictid;
8414 }
8415
8416 if (cmd->proc == expireCommand) {
8417 /* Translate EXPIRE into EXPIREAT */
8418 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8419 } else if (cmd->proc == setexCommand) {
8420 /* Translate SETEX to SET and EXPIREAT */
8421 tmpargv[0] = createStringObject("SET",3);
8422 tmpargv[1] = argv[1];
8423 tmpargv[2] = argv[3];
8424 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
8425 decrRefCount(tmpargv[0]);
8426 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8427 } else {
8428 buf = catAppendOnlyGenericCommand(buf,argc,argv);
8429 }
8430
8431 /* Append to the AOF buffer. This will be flushed on disk just before
8432 * of re-entering the event loop, so before the client will get a
8433 * positive reply about the operation performed. */
8434 server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf));
8435
8436 /* If a background append only file rewriting is in progress we want to
8437 * accumulate the differences between the child DB and the current one
8438 * in a buffer, so that when the child process will do its work we
8439 * can append the differences to the new append only file. */
8440 if (server.bgrewritechildpid != -1)
8441 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
8442
8443 sdsfree(buf);
8444 }
8445
8446 /* In Redis commands are always executed in the context of a client, so in
8447 * order to load the append only file we need to create a fake client. */
8448 static struct redisClient *createFakeClient(void) {
8449 struct redisClient *c = zmalloc(sizeof(*c));
8450
8451 selectDb(c,0);
8452 c->fd = -1;
8453 c->querybuf = sdsempty();
8454 c->argc = 0;
8455 c->argv = NULL;
8456 c->flags = 0;
8457 /* We set the fake client as a slave waiting for the synchronization
8458 * so that Redis will not try to send replies to this client. */
8459 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
8460 c->reply = listCreate();
8461 listSetFreeMethod(c->reply,decrRefCount);
8462 listSetDupMethod(c->reply,dupClientReplyValue);
8463 initClientMultiState(c);
8464 return c;
8465 }
8466
8467 static void freeFakeClient(struct redisClient *c) {
8468 sdsfree(c->querybuf);
8469 listRelease(c->reply);
8470 freeClientMultiState(c);
8471 zfree(c);
8472 }
8473
8474 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
8475 * error (the append only file is zero-length) REDIS_ERR is returned. On
8476 * fatal error an error message is logged and the program exists. */
8477 int loadAppendOnlyFile(char *filename) {
8478 struct redisClient *fakeClient;
8479 FILE *fp = fopen(filename,"r");
8480 struct redis_stat sb;
8481 unsigned long long loadedkeys = 0;
8482 int appendonly = server.appendonly;
8483
8484 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
8485 return REDIS_ERR;
8486
8487 if (fp == NULL) {
8488 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
8489 exit(1);
8490 }
8491
8492 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8493 * to the same file we're about to read. */
8494 server.appendonly = 0;
8495
8496 fakeClient = createFakeClient();
8497 while(1) {
8498 int argc, j;
8499 unsigned long len;
8500 robj **argv;
8501 char buf[128];
8502 sds argsds;
8503 struct redisCommand *cmd;
8504
8505 if (fgets(buf,sizeof(buf),fp) == NULL) {
8506 if (feof(fp))
8507 break;
8508 else
8509 goto readerr;
8510 }
8511 if (buf[0] != '*') goto fmterr;
8512 argc = atoi(buf+1);
8513 argv = zmalloc(sizeof(robj*)*argc);
8514 for (j = 0; j < argc; j++) {
8515 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
8516 if (buf[0] != '$') goto fmterr;
8517 len = strtol(buf+1,NULL,10);
8518 argsds = sdsnewlen(NULL,len);
8519 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
8520 argv[j] = createObject(REDIS_STRING,argsds);
8521 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
8522 }
8523
8524 /* Command lookup */
8525 cmd = lookupCommand(argv[0]->ptr);
8526 if (!cmd) {
8527 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
8528 exit(1);
8529 }
8530 /* Try object encoding */
8531 if (cmd->flags & REDIS_CMD_BULK)
8532 argv[argc-1] = tryObjectEncoding(argv[argc-1]);
8533 /* Run the command in the context of a fake client */
8534 fakeClient->argc = argc;
8535 fakeClient->argv = argv;
8536 cmd->proc(fakeClient);
8537 /* Discard the reply objects list from the fake client */
8538 while(listLength(fakeClient->reply))
8539 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
8540 /* Clean up, ready for the next command */
8541 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
8542 zfree(argv);
8543 /* Handle swapping while loading big datasets when VM is on */
8544 loadedkeys++;
8545 if (server.vm_enabled && (loadedkeys % 5000) == 0) {
8546 while (zmalloc_used_memory() > server.vm_max_memory) {
8547 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
8548 }
8549 }
8550 }
8551
8552 /* This point can only be reached when EOF is reached without errors.
8553 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8554 if (fakeClient->flags & REDIS_MULTI) goto readerr;
8555
8556 fclose(fp);
8557 freeFakeClient(fakeClient);
8558 server.appendonly = appendonly;
8559 return REDIS_OK;
8560
8561 readerr:
8562 if (feof(fp)) {
8563 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
8564 } else {
8565 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
8566 }
8567 exit(1);
8568 fmterr:
8569 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
8570 exit(1);
8571 }
8572
8573 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
8574 static int fwriteBulkObject(FILE *fp, robj *obj) {
8575 char buf[128];
8576 int decrrc = 0;
8577
8578 /* Avoid the incr/decr ref count business if possible to help
8579 * copy-on-write (we are often in a child process when this function
8580 * is called).
8581 * Also makes sure that key objects don't get incrRefCount-ed when VM
8582 * is enabled */
8583 if (obj->encoding != REDIS_ENCODING_RAW) {
8584 obj = getDecodedObject(obj);
8585 decrrc = 1;
8586 }
8587 snprintf(buf,sizeof(buf),"$%ld\r\n",(long)sdslen(obj->ptr));
8588 if (fwrite(buf,strlen(buf),1,fp) == 0) goto err;
8589 if (sdslen(obj->ptr) && fwrite(obj->ptr,sdslen(obj->ptr),1,fp) == 0)
8590 goto err;
8591 if (fwrite("\r\n",2,1,fp) == 0) goto err;
8592 if (decrrc) decrRefCount(obj);
8593 return 1;
8594 err:
8595 if (decrrc) decrRefCount(obj);
8596 return 0;
8597 }
8598
8599 /* Write binary-safe string into a file in the bulkformat
8600 * $<count>\r\n<payload>\r\n */
8601 static int fwriteBulkString(FILE *fp, char *s, unsigned long len) {
8602 char buf[128];
8603
8604 snprintf(buf,sizeof(buf),"$%ld\r\n",(unsigned long)len);
8605 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8606 if (len && fwrite(s,len,1,fp) == 0) return 0;
8607 if (fwrite("\r\n",2,1,fp) == 0) return 0;
8608 return 1;
8609 }
8610
8611 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8612 static int fwriteBulkDouble(FILE *fp, double d) {
8613 char buf[128], dbuf[128];
8614
8615 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
8616 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
8617 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8618 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
8619 return 1;
8620 }
8621
8622 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8623 static int fwriteBulkLong(FILE *fp, long l) {
8624 char buf[128], lbuf[128];
8625
8626 snprintf(lbuf,sizeof(lbuf),"%ld\r\n",l);
8627 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(lbuf)-2);
8628 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8629 if (fwrite(lbuf,strlen(lbuf),1,fp) == 0) return 0;
8630 return 1;
8631 }
8632
8633 /* Write a sequence of commands able to fully rebuild the dataset into
8634 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8635 static int rewriteAppendOnlyFile(char *filename) {
8636 dictIterator *di = NULL;
8637 dictEntry *de;
8638 FILE *fp;
8639 char tmpfile[256];
8640 int j;
8641 time_t now = time(NULL);
8642
8643 /* Note that we have to use a different temp name here compared to the
8644 * one used by rewriteAppendOnlyFileBackground() function. */
8645 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
8646 fp = fopen(tmpfile,"w");
8647 if (!fp) {
8648 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
8649 return REDIS_ERR;
8650 }
8651 for (j = 0; j < server.dbnum; j++) {
8652 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
8653 redisDb *db = server.db+j;
8654 dict *d = db->dict;
8655 if (dictSize(d) == 0) continue;
8656 di = dictGetIterator(d);
8657 if (!di) {
8658 fclose(fp);
8659 return REDIS_ERR;
8660 }
8661
8662 /* SELECT the new DB */
8663 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
8664 if (fwriteBulkLong(fp,j) == 0) goto werr;
8665
8666 /* Iterate this DB writing every entry */
8667 while((de = dictNext(di)) != NULL) {
8668 robj *key, *o;
8669 time_t expiretime;
8670 int swapped;
8671
8672 key = dictGetEntryKey(de);
8673 o = dictGetEntryVal(de);
8674 /* If the value for this key is swapped, load a preview in memory.
8675 * We use a "swapped" flag to remember if we need to free the
8676 * value object instead to just increment the ref count anyway
8677 * in order to avoid copy-on-write of pages if we are forked() */
8678 if (!server.vm_enabled || o->storage == REDIS_VM_MEMORY ||
8679 o->storage == REDIS_VM_SWAPPING) {
8680 swapped = 0;
8681 } else {
8682 o = vmPreviewObject(o);
8683 swapped = 1;
8684 }
8685 expiretime = getExpire(db,key);
8686
8687 /* Save the key and associated value */
8688 if (o->type == REDIS_STRING) {
8689 /* Emit a SET command */
8690 char cmd[]="*3\r\n$3\r\nSET\r\n";
8691 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8692 /* Key and value */
8693 if (fwriteBulkObject(fp,key) == 0) goto werr;
8694 if (fwriteBulkObject(fp,o) == 0) goto werr;
8695 } else if (o->type == REDIS_LIST) {
8696 /* Emit the RPUSHes needed to rebuild the list */
8697 list *list = o->ptr;
8698 listNode *ln;
8699 listIter li;
8700
8701 listRewind(list,&li);
8702 while((ln = listNext(&li))) {
8703 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
8704 robj *eleobj = listNodeValue(ln);
8705
8706 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8707 if (fwriteBulkObject(fp,key) == 0) goto werr;
8708 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8709 }
8710 } else if (o->type == REDIS_SET) {
8711 /* Emit the SADDs needed to rebuild the set */
8712 dict *set = o->ptr;
8713 dictIterator *di = dictGetIterator(set);
8714 dictEntry *de;
8715
8716 while((de = dictNext(di)) != NULL) {
8717 char cmd[]="*3\r\n$4\r\nSADD\r\n";
8718 robj *eleobj = dictGetEntryKey(de);
8719
8720 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8721 if (fwriteBulkObject(fp,key) == 0) goto werr;
8722 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8723 }
8724 dictReleaseIterator(di);
8725 } else if (o->type == REDIS_ZSET) {
8726 /* Emit the ZADDs needed to rebuild the sorted set */
8727 zset *zs = o->ptr;
8728 dictIterator *di = dictGetIterator(zs->dict);
8729 dictEntry *de;
8730
8731 while((de = dictNext(di)) != NULL) {
8732 char cmd[]="*4\r\n$4\r\nZADD\r\n";
8733 robj *eleobj = dictGetEntryKey(de);
8734 double *score = dictGetEntryVal(de);
8735
8736 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8737 if (fwriteBulkObject(fp,key) == 0) goto werr;
8738 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
8739 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8740 }
8741 dictReleaseIterator(di);
8742 } else if (o->type == REDIS_HASH) {
8743 char cmd[]="*4\r\n$4\r\nHSET\r\n";
8744
8745 /* Emit the HSETs needed to rebuild the hash */
8746 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
8747 unsigned char *p = zipmapRewind(o->ptr);
8748 unsigned char *field, *val;
8749 unsigned int flen, vlen;
8750
8751 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
8752 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8753 if (fwriteBulkObject(fp,key) == 0) goto werr;
8754 if (fwriteBulkString(fp,(char*)field,flen) == -1)
8755 return -1;
8756 if (fwriteBulkString(fp,(char*)val,vlen) == -1)
8757 return -1;
8758 }
8759 } else {
8760 dictIterator *di = dictGetIterator(o->ptr);
8761 dictEntry *de;
8762
8763 while((de = dictNext(di)) != NULL) {
8764 robj *field = dictGetEntryKey(de);
8765 robj *val = dictGetEntryVal(de);
8766
8767 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8768 if (fwriteBulkObject(fp,key) == 0) goto werr;
8769 if (fwriteBulkObject(fp,field) == -1) return -1;
8770 if (fwriteBulkObject(fp,val) == -1) return -1;
8771 }
8772 dictReleaseIterator(di);
8773 }
8774 } else {
8775 redisPanic("Unknown object type");
8776 }
8777 /* Save the expire time */
8778 if (expiretime != -1) {
8779 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
8780 /* If this key is already expired skip it */
8781 if (expiretime < now) continue;
8782 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8783 if (fwriteBulkObject(fp,key) == 0) goto werr;
8784 if (fwriteBulkLong(fp,expiretime) == 0) goto werr;
8785 }
8786 if (swapped) decrRefCount(o);
8787 }
8788 dictReleaseIterator(di);
8789 }
8790
8791 /* Make sure data will not remain on the OS's output buffers */
8792 fflush(fp);
8793 aof_fsync(fileno(fp));
8794 fclose(fp);
8795
8796 /* Use RENAME to make sure the DB file is changed atomically only
8797 * if the generate DB file is ok. */
8798 if (rename(tmpfile,filename) == -1) {
8799 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
8800 unlink(tmpfile);
8801 return REDIS_ERR;
8802 }
8803 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
8804 return REDIS_OK;
8805
8806 werr:
8807 fclose(fp);
8808 unlink(tmpfile);
8809 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
8810 if (di) dictReleaseIterator(di);
8811 return REDIS_ERR;
8812 }
8813
8814 /* This is how rewriting of the append only file in background works:
8815 *
8816 * 1) The user calls BGREWRITEAOF
8817 * 2) Redis calls this function, that forks():
8818 * 2a) the child rewrite the append only file in a temp file.
8819 * 2b) the parent accumulates differences in server.bgrewritebuf.
8820 * 3) When the child finished '2a' exists.
8821 * 4) The parent will trap the exit code, if it's OK, will append the
8822 * data accumulated into server.bgrewritebuf into the temp file, and
8823 * finally will rename(2) the temp file in the actual file name.
8824 * The the new file is reopened as the new append only file. Profit!
8825 */
8826 static int rewriteAppendOnlyFileBackground(void) {
8827 pid_t childpid;
8828
8829 if (server.bgrewritechildpid != -1) return REDIS_ERR;
8830 if (server.vm_enabled) waitEmptyIOJobsQueue();
8831 if ((childpid = fork()) == 0) {
8832 /* Child */
8833 char tmpfile[256];
8834
8835 if (server.vm_enabled) vmReopenSwapFile();
8836 close(server.fd);
8837 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
8838 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
8839 _exit(0);
8840 } else {
8841 _exit(1);
8842 }
8843 } else {
8844 /* Parent */
8845 if (childpid == -1) {
8846 redisLog(REDIS_WARNING,
8847 "Can't rewrite append only file in background: fork: %s",
8848 strerror(errno));
8849 return REDIS_ERR;
8850 }
8851 redisLog(REDIS_NOTICE,
8852 "Background append only file rewriting started by pid %d",childpid);
8853 server.bgrewritechildpid = childpid;
8854 updateDictResizePolicy();
8855 /* We set appendseldb to -1 in order to force the next call to the
8856 * feedAppendOnlyFile() to issue a SELECT command, so the differences
8857 * accumulated by the parent into server.bgrewritebuf will start
8858 * with a SELECT statement and it will be safe to merge. */
8859 server.appendseldb = -1;
8860 return REDIS_OK;
8861 }
8862 return REDIS_OK; /* unreached */
8863 }
8864
8865 static void bgrewriteaofCommand(redisClient *c) {
8866 if (server.bgrewritechildpid != -1) {
8867 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
8868 return;
8869 }
8870 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
8871 char *status = "+Background append only file rewriting started\r\n";
8872 addReplySds(c,sdsnew(status));
8873 } else {
8874 addReply(c,shared.err);
8875 }
8876 }
8877
8878 static void aofRemoveTempFile(pid_t childpid) {
8879 char tmpfile[256];
8880
8881 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
8882 unlink(tmpfile);
8883 }
8884
8885 /* Virtual Memory is composed mainly of two subsystems:
8886 * - Blocking Virutal Memory
8887 * - Threaded Virtual Memory I/O
8888 * The two parts are not fully decoupled, but functions are split among two
8889 * different sections of the source code (delimited by comments) in order to
8890 * make more clear what functionality is about the blocking VM and what about
8891 * the threaded (not blocking) VM.
8892 *
8893 * Redis VM design:
8894 *
8895 * Redis VM is a blocking VM (one that blocks reading swapped values from
8896 * disk into memory when a value swapped out is needed in memory) that is made
8897 * unblocking by trying to examine the command argument vector in order to
8898 * load in background values that will likely be needed in order to exec
8899 * the command. The command is executed only once all the relevant keys
8900 * are loaded into memory.
8901 *
8902 * This basically is almost as simple of a blocking VM, but almost as parallel
8903 * as a fully non-blocking VM.
8904 */
8905
8906 /* =================== Virtual Memory - Blocking Side ====================== */
8907
8908 /* Create a VM pointer object. This kind of objects are used in place of
8909 * values in the key -> value hash table, for swapped out objects. */
8910 static vmpointer *createVmPointer(int vtype) {
8911 vmpointer *vp = zmalloc(sizeof(vmpointer));
8912
8913 vp->type = REDIS_VMPOINTER;
8914 vp->storage = REDIS_VM_SWAPPED;
8915 vp->vtype = vtype;
8916 return vp;
8917 }
8918
8919 static void vmInit(void) {
8920 off_t totsize;
8921 int pipefds[2];
8922 size_t stacksize;
8923 struct flock fl;
8924
8925 if (server.vm_max_threads != 0)
8926 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
8927
8928 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
8929 /* Try to open the old swap file, otherwise create it */
8930 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
8931 server.vm_fp = fopen(server.vm_swap_file,"w+b");
8932 }
8933 if (server.vm_fp == NULL) {
8934 redisLog(REDIS_WARNING,
8935 "Can't open the swap file: %s. Exiting.",
8936 strerror(errno));
8937 exit(1);
8938 }
8939 server.vm_fd = fileno(server.vm_fp);
8940 /* Lock the swap file for writing, this is useful in order to avoid
8941 * another instance to use the same swap file for a config error. */
8942 fl.l_type = F_WRLCK;
8943 fl.l_whence = SEEK_SET;
8944 fl.l_start = fl.l_len = 0;
8945 if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
8946 redisLog(REDIS_WARNING,
8947 "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));
8948 exit(1);
8949 }
8950 /* Initialize */
8951 server.vm_next_page = 0;
8952 server.vm_near_pages = 0;
8953 server.vm_stats_used_pages = 0;
8954 server.vm_stats_swapped_objects = 0;
8955 server.vm_stats_swapouts = 0;
8956 server.vm_stats_swapins = 0;
8957 totsize = server.vm_pages*server.vm_page_size;
8958 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
8959 if (ftruncate(server.vm_fd,totsize) == -1) {
8960 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
8961 strerror(errno));
8962 exit(1);
8963 } else {
8964 redisLog(REDIS_NOTICE,"Swap file allocated with success");
8965 }
8966 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
8967 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
8968 (long long) (server.vm_pages+7)/8, server.vm_pages);
8969 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
8970
8971 /* Initialize threaded I/O (used by Virtual Memory) */
8972 server.io_newjobs = listCreate();
8973 server.io_processing = listCreate();
8974 server.io_processed = listCreate();
8975 server.io_ready_clients = listCreate();
8976 pthread_mutex_init(&server.io_mutex,NULL);
8977 pthread_mutex_init(&server.obj_freelist_mutex,NULL);
8978 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
8979 server.io_active_threads = 0;
8980 if (pipe(pipefds) == -1) {
8981 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
8982 ,strerror(errno));
8983 exit(1);
8984 }
8985 server.io_ready_pipe_read = pipefds[0];
8986 server.io_ready_pipe_write = pipefds[1];
8987 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
8988 /* LZF requires a lot of stack */
8989 pthread_attr_init(&server.io_threads_attr);
8990 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
8991 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
8992 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
8993 /* Listen for events in the threaded I/O pipe */
8994 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
8995 vmThreadedIOCompletedJob, NULL) == AE_ERR)
8996 oom("creating file event");
8997 }
8998
8999 /* Mark the page as used */
9000 static void vmMarkPageUsed(off_t page) {
9001 off_t byte = page/8;
9002 int bit = page&7;
9003 redisAssert(vmFreePage(page) == 1);
9004 server.vm_bitmap[byte] |= 1<<bit;
9005 }
9006
9007 /* Mark N contiguous pages as used, with 'page' being the first. */
9008 static void vmMarkPagesUsed(off_t page, off_t count) {
9009 off_t j;
9010
9011 for (j = 0; j < count; j++)
9012 vmMarkPageUsed(page+j);
9013 server.vm_stats_used_pages += count;
9014 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
9015 (long long)count, (long long)page);
9016 }
9017
9018 /* Mark the page as free */
9019 static void vmMarkPageFree(off_t page) {
9020 off_t byte = page/8;
9021 int bit = page&7;
9022 redisAssert(vmFreePage(page) == 0);
9023 server.vm_bitmap[byte] &= ~(1<<bit);
9024 }
9025
9026 /* Mark N contiguous pages as free, with 'page' being the first. */
9027 static void vmMarkPagesFree(off_t page, off_t count) {
9028 off_t j;
9029
9030 for (j = 0; j < count; j++)
9031 vmMarkPageFree(page+j);
9032 server.vm_stats_used_pages -= count;
9033 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
9034 (long long)count, (long long)page);
9035 }
9036
9037 /* Test if the page is free */
9038 static int vmFreePage(off_t page) {
9039 off_t byte = page/8;
9040 int bit = page&7;
9041 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
9042 }
9043
9044 /* Find N contiguous free pages storing the first page of the cluster in *first.
9045 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
9046 * REDIS_ERR is returned.
9047 *
9048 * This function uses a simple algorithm: we try to allocate
9049 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
9050 * again from the start of the swap file searching for free spaces.
9051 *
9052 * If it looks pretty clear that there are no free pages near our offset
9053 * we try to find less populated places doing a forward jump of
9054 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
9055 * without hurry, and then we jump again and so forth...
9056 *
9057 * This function can be improved using a free list to avoid to guess
9058 * too much, since we could collect data about freed pages.
9059 *
9060 * note: I implemented this function just after watching an episode of
9061 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
9062 */
9063 static int vmFindContiguousPages(off_t *first, off_t n) {
9064 off_t base, offset = 0, since_jump = 0, numfree = 0;
9065
9066 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
9067 server.vm_near_pages = 0;
9068 server.vm_next_page = 0;
9069 }
9070 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
9071 base = server.vm_next_page;
9072
9073 while(offset < server.vm_pages) {
9074 off_t this = base+offset;
9075
9076 /* If we overflow, restart from page zero */
9077 if (this >= server.vm_pages) {
9078 this -= server.vm_pages;
9079 if (this == 0) {
9080 /* Just overflowed, what we found on tail is no longer
9081 * interesting, as it's no longer contiguous. */
9082 numfree = 0;
9083 }
9084 }
9085 if (vmFreePage(this)) {
9086 /* This is a free page */
9087 numfree++;
9088 /* Already got N free pages? Return to the caller, with success */
9089 if (numfree == n) {
9090 *first = this-(n-1);
9091 server.vm_next_page = this+1;
9092 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
9093 return REDIS_OK;
9094 }
9095 } else {
9096 /* The current one is not a free page */
9097 numfree = 0;
9098 }
9099
9100 /* Fast-forward if the current page is not free and we already
9101 * searched enough near this place. */
9102 since_jump++;
9103 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
9104 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
9105 since_jump = 0;
9106 /* Note that even if we rewind after the jump, we are don't need
9107 * to make sure numfree is set to zero as we only jump *if* it
9108 * is set to zero. */
9109 } else {
9110 /* Otherwise just check the next page */
9111 offset++;
9112 }
9113 }
9114 return REDIS_ERR;
9115 }
9116
9117 /* Write the specified object at the specified page of the swap file */
9118 static int vmWriteObjectOnSwap(robj *o, off_t page) {
9119 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9120 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9121 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9122 redisLog(REDIS_WARNING,
9123 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
9124 strerror(errno));
9125 return REDIS_ERR;
9126 }
9127 rdbSaveObject(server.vm_fp,o);
9128 fflush(server.vm_fp);
9129 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9130 return REDIS_OK;
9131 }
9132
9133 /* Transfers the 'val' object to disk. Store all the information
9134 * a 'vmpointer' object containing all the information needed to load the
9135 * object back later is returned.
9136 *
9137 * If we can't find enough contiguous empty pages to swap the object on disk
9138 * NULL is returned. */
9139 static vmpointer *vmSwapObjectBlocking(robj *val) {
9140 off_t pages = rdbSavedObjectPages(val,NULL);
9141 off_t page;
9142 vmpointer *vp;
9143
9144 assert(val->storage == REDIS_VM_MEMORY);
9145 assert(val->refcount == 1);
9146 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return NULL;
9147 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return NULL;
9148
9149 vp = createVmPointer(val->type);
9150 vp->page = page;
9151 vp->usedpages = pages;
9152 decrRefCount(val); /* Deallocate the object from memory. */
9153 vmMarkPagesUsed(page,pages);
9154 redisLog(REDIS_DEBUG,"VM: object %p swapped out at %lld (%lld pages)",
9155 (void*) val,
9156 (unsigned long long) page, (unsigned long long) pages);
9157 server.vm_stats_swapped_objects++;
9158 server.vm_stats_swapouts++;
9159 return vp;
9160 }
9161
9162 static robj *vmReadObjectFromSwap(off_t page, int type) {
9163 robj *o;
9164
9165 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9166 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9167 redisLog(REDIS_WARNING,
9168 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
9169 strerror(errno));
9170 _exit(1);
9171 }
9172 o = rdbLoadObject(type,server.vm_fp);
9173 if (o == NULL) {
9174 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
9175 _exit(1);
9176 }
9177 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9178 return o;
9179 }
9180
9181 /* Load the specified object from swap to memory.
9182 * The newly allocated object is returned.
9183 *
9184 * If preview is true the unserialized object is returned to the caller but
9185 * the pages are not marked as freed, nor the vp object is freed. */
9186 static robj *vmGenericLoadObject(vmpointer *vp, int preview) {
9187 robj *val;
9188
9189 redisAssert(vp->type == REDIS_VMPOINTER &&
9190 (vp->storage == REDIS_VM_SWAPPED || vp->storage == REDIS_VM_LOADING));
9191 val = vmReadObjectFromSwap(vp->page,vp->vtype);
9192 if (!preview) {
9193 redisLog(REDIS_DEBUG, "VM: object %p loaded from disk", (void*)vp);
9194 vmMarkPagesFree(vp->page,vp->usedpages);
9195 zfree(vp);
9196 server.vm_stats_swapped_objects--;
9197 } else {
9198 redisLog(REDIS_DEBUG, "VM: object %p previewed from disk", (void*)vp);
9199 }
9200 server.vm_stats_swapins++;
9201 return val;
9202 }
9203
9204 /* Plain object loading, from swap to memory.
9205 *
9206 * 'o' is actually a redisVmPointer structure that will be freed by the call.
9207 * The return value is the loaded object. */
9208 static robj *vmLoadObject(robj *o) {
9209 /* If we are loading the object in background, stop it, we
9210 * need to load this object synchronously ASAP. */
9211 if (o->storage == REDIS_VM_LOADING)
9212 vmCancelThreadedIOJob(o);
9213 return vmGenericLoadObject((vmpointer*)o,0);
9214 }
9215
9216 /* Just load the value on disk, without to modify the key.
9217 * This is useful when we want to perform some operation on the value
9218 * without to really bring it from swap to memory, like while saving the
9219 * dataset or rewriting the append only log. */
9220 static robj *vmPreviewObject(robj *o) {
9221 return vmGenericLoadObject((vmpointer*)o,1);
9222 }
9223
9224 /* How a good candidate is this object for swapping?
9225 * The better candidate it is, the greater the returned value.
9226 *
9227 * Currently we try to perform a fast estimation of the object size in
9228 * memory, and combine it with aging informations.
9229 *
9230 * Basically swappability = idle-time * log(estimated size)
9231 *
9232 * Bigger objects are preferred over smaller objects, but not
9233 * proportionally, this is why we use the logarithm. This algorithm is
9234 * just a first try and will probably be tuned later. */
9235 static double computeObjectSwappability(robj *o) {
9236 /* actual age can be >= minage, but not < minage. As we use wrapping
9237 * 21 bit clocks with minutes resolution for the LRU. */
9238 time_t minage = abs(server.lruclock - o->lru);
9239 long asize = 0;
9240 list *l;
9241 dict *d;
9242 struct dictEntry *de;
9243 int z;
9244
9245 if (minage <= 0) return 0;
9246 switch(o->type) {
9247 case REDIS_STRING:
9248 if (o->encoding != REDIS_ENCODING_RAW) {
9249 asize = sizeof(*o);
9250 } else {
9251 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
9252 }
9253 break;
9254 case REDIS_LIST:
9255 l = o->ptr;
9256 listNode *ln = listFirst(l);
9257
9258 asize = sizeof(list);
9259 if (ln) {
9260 robj *ele = ln->value;
9261 long elesize;
9262
9263 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9264 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
9265 asize += (sizeof(listNode)+elesize)*listLength(l);
9266 }
9267 break;
9268 case REDIS_SET:
9269 case REDIS_ZSET:
9270 z = (o->type == REDIS_ZSET);
9271 d = z ? ((zset*)o->ptr)->dict : o->ptr;
9272
9273 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9274 if (z) asize += sizeof(zset)-sizeof(dict);
9275 if (dictSize(d)) {
9276 long elesize;
9277 robj *ele;
9278
9279 de = dictGetRandomKey(d);
9280 ele = dictGetEntryKey(de);
9281 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9282 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
9283 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9284 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
9285 }
9286 break;
9287 case REDIS_HASH:
9288 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9289 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
9290 unsigned int len = zipmapLen((unsigned char*)o->ptr);
9291 unsigned int klen, vlen;
9292 unsigned char *key, *val;
9293
9294 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
9295 klen = 0;
9296 vlen = 0;
9297 }
9298 asize = len*(klen+vlen+3);
9299 } else if (o->encoding == REDIS_ENCODING_HT) {
9300 d = o->ptr;
9301 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9302 if (dictSize(d)) {
9303 long elesize;
9304 robj *ele;
9305
9306 de = dictGetRandomKey(d);
9307 ele = dictGetEntryKey(de);
9308 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9309 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
9310 ele = dictGetEntryVal(de);
9311 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9312 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
9313 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9314 }
9315 }
9316 break;
9317 }
9318 return (double)minage*log(1+asize);
9319 }
9320
9321 /* Try to swap an object that's a good candidate for swapping.
9322 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
9323 * to swap any object at all.
9324 *
9325 * If 'usethreaded' is true, Redis will try to swap the object in background
9326 * using I/O threads. */
9327 static int vmSwapOneObject(int usethreads) {
9328 int j, i;
9329 struct dictEntry *best = NULL;
9330 double best_swappability = 0;
9331 redisDb *best_db = NULL;
9332 robj *key, *val;
9333
9334 for (j = 0; j < server.dbnum; j++) {
9335 redisDb *db = server.db+j;
9336 /* Why maxtries is set to 100?
9337 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9338 * are swappable objects */
9339 int maxtries = 100;
9340
9341 if (dictSize(db->dict) == 0) continue;
9342 for (i = 0; i < 5; i++) {
9343 dictEntry *de;
9344 double swappability;
9345
9346 if (maxtries) maxtries--;
9347 de = dictGetRandomKey(db->dict);
9348 key = dictGetEntryKey(de);
9349 val = dictGetEntryVal(de);
9350 /* Only swap objects that are currently in memory.
9351 *
9352 * Also don't swap shared objects: not a good idea in general and
9353 * we need to ensure that the main thread does not touch the
9354 * object while the I/O thread is using it, but we can't
9355 * control other keys without adding additional mutex. */
9356 if (val->storage != REDIS_VM_MEMORY || val->refcount != 1) {
9357 if (maxtries) i--; /* don't count this try */
9358 continue;
9359 }
9360 swappability = computeObjectSwappability(val);
9361 if (!best || swappability > best_swappability) {
9362 best = de;
9363 best_swappability = swappability;
9364 best_db = db;
9365 }
9366 }
9367 }
9368 if (best == NULL) return REDIS_ERR;
9369 key = dictGetEntryKey(best);
9370 val = dictGetEntryVal(best);
9371
9372 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
9373 key->ptr, best_swappability);
9374
9375 /* Swap it */
9376 if (usethreads) {
9377 vmSwapObjectThreaded(key,val,best_db);
9378 return REDIS_OK;
9379 } else {
9380 vmpointer *vp;
9381
9382 if ((vp = vmSwapObjectBlocking(val)) != NULL) {
9383 dictGetEntryVal(best) = vp;
9384 return REDIS_OK;
9385 } else {
9386 return REDIS_ERR;
9387 }
9388 }
9389 }
9390
9391 static int vmSwapOneObjectBlocking() {
9392 return vmSwapOneObject(0);
9393 }
9394
9395 static int vmSwapOneObjectThreaded() {
9396 return vmSwapOneObject(1);
9397 }
9398
9399 /* Return true if it's safe to swap out objects in a given moment.
9400 * Basically we don't want to swap objects out while there is a BGSAVE
9401 * or a BGAEOREWRITE running in backgroud. */
9402 static int vmCanSwapOut(void) {
9403 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
9404 }
9405
9406 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
9407 * and was deleted. Otherwise 0 is returned. */
9408 static int deleteIfSwapped(redisDb *db, robj *key) {
9409 robj *val;
9410
9411 if ((val = dictFetchValue(db->dict,key)) == NULL) return 0;
9412 if (val->storage == REDIS_VM_MEMORY) return 0;
9413 deleteKey(db,key);
9414 return 1;
9415 }
9416
9417 /* =================== Virtual Memory - Threaded I/O ======================= */
9418
9419 static void freeIOJob(iojob *j) {
9420 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
9421 j->type == REDIS_IOJOB_DO_SWAP ||
9422 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
9423 {
9424 /* we fix the storage type, otherwise decrRefCount() will try to
9425 * kill the I/O thread Job (that does no longer exists). */
9426 if (j->val->storage == REDIS_VM_SWAPPING)
9427 j->val->storage = REDIS_VM_MEMORY;
9428 decrRefCount(j->val);
9429 }
9430 decrRefCount(j->key);
9431 zfree(j);
9432 }
9433
9434 /* Every time a thread finished a Job, it writes a byte into the write side
9435 * of an unix pipe in order to "awake" the main thread, and this function
9436 * is called. */
9437 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
9438 int mask)
9439 {
9440 char buf[1];
9441 int retval, processed = 0, toprocess = -1, trytoswap = 1;
9442 REDIS_NOTUSED(el);
9443 REDIS_NOTUSED(mask);
9444 REDIS_NOTUSED(privdata);
9445
9446 /* For every byte we read in the read side of the pipe, there is one
9447 * I/O job completed to process. */
9448 while((retval = read(fd,buf,1)) == 1) {
9449 iojob *j;
9450 listNode *ln;
9451 struct dictEntry *de;
9452
9453 redisLog(REDIS_DEBUG,"Processing I/O completed job");
9454
9455 /* Get the processed element (the oldest one) */
9456 lockThreadedIO();
9457 assert(listLength(server.io_processed) != 0);
9458 if (toprocess == -1) {
9459 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
9460 if (toprocess <= 0) toprocess = 1;
9461 }
9462 ln = listFirst(server.io_processed);
9463 j = ln->value;
9464 listDelNode(server.io_processed,ln);
9465 unlockThreadedIO();
9466 /* If this job is marked as canceled, just ignore it */
9467 if (j->canceled) {
9468 freeIOJob(j);
9469 continue;
9470 }
9471 /* Post process it in the main thread, as there are things we
9472 * can do just here to avoid race conditions and/or invasive locks */
9473 redisLog(REDIS_DEBUG,"COMPLETED Job type: %d, ID %p, key: %s", j->type, (void*)j->id, (unsigned char*)j->key->ptr);
9474 de = dictFind(j->db->dict,j->key);
9475 redisAssert(de != NULL);
9476 if (j->type == REDIS_IOJOB_LOAD) {
9477 redisDb *db;
9478 vmpointer *vp = dictGetEntryVal(de);
9479
9480 /* Key loaded, bring it at home */
9481 vmMarkPagesFree(vp->page,vp->usedpages);
9482 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
9483 (unsigned char*) j->key->ptr);
9484 server.vm_stats_swapped_objects--;
9485 server.vm_stats_swapins++;
9486 dictGetEntryVal(de) = j->val;
9487 incrRefCount(j->val);
9488 db = j->db;
9489 /* Handle clients waiting for this key to be loaded. */
9490 handleClientsBlockedOnSwappedKey(db,j->key);
9491 freeIOJob(j);
9492 zfree(vp);
9493 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9494 /* Now we know the amount of pages required to swap this object.
9495 * Let's find some space for it, and queue this task again
9496 * rebranded as REDIS_IOJOB_DO_SWAP. */
9497 if (!vmCanSwapOut() ||
9498 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
9499 {
9500 /* Ooops... no space or we can't swap as there is
9501 * a fork()ed Redis trying to save stuff on disk. */
9502 j->val->storage = REDIS_VM_MEMORY; /* undo operation */
9503 freeIOJob(j);
9504 } else {
9505 /* Note that we need to mark this pages as used now,
9506 * if the job will be canceled, we'll mark them as freed
9507 * again. */
9508 vmMarkPagesUsed(j->page,j->pages);
9509 j->type = REDIS_IOJOB_DO_SWAP;
9510 lockThreadedIO();
9511 queueIOJob(j);
9512 unlockThreadedIO();
9513 }
9514 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9515 vmpointer *vp;
9516
9517 /* Key swapped. We can finally free some memory. */
9518 if (j->val->storage != REDIS_VM_SWAPPING) {
9519 vmpointer *vp = (vmpointer*) j->id;
9520 printf("storage: %d\n",vp->storage);
9521 printf("key->name: %s\n",(char*)j->key->ptr);
9522 printf("val: %p\n",(void*)j->val);
9523 printf("val->type: %d\n",j->val->type);
9524 printf("val->ptr: %s\n",(char*)j->val->ptr);
9525 }
9526 redisAssert(j->val->storage == REDIS_VM_SWAPPING);
9527 vp = createVmPointer(j->val->type);
9528 vp->page = j->page;
9529 vp->usedpages = j->pages;
9530 dictGetEntryVal(de) = vp;
9531 /* Fix the storage otherwise decrRefCount will attempt to
9532 * remove the associated I/O job */
9533 j->val->storage = REDIS_VM_MEMORY;
9534 decrRefCount(j->val);
9535 redisLog(REDIS_DEBUG,
9536 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9537 (unsigned char*) j->key->ptr,
9538 (unsigned long long) j->page, (unsigned long long) j->pages);
9539 server.vm_stats_swapped_objects++;
9540 server.vm_stats_swapouts++;
9541 freeIOJob(j);
9542 /* Put a few more swap requests in queue if we are still
9543 * out of memory */
9544 if (trytoswap && vmCanSwapOut() &&
9545 zmalloc_used_memory() > server.vm_max_memory)
9546 {
9547 int more = 1;
9548 while(more) {
9549 lockThreadedIO();
9550 more = listLength(server.io_newjobs) <
9551 (unsigned) server.vm_max_threads;
9552 unlockThreadedIO();
9553 /* Don't waste CPU time if swappable objects are rare. */
9554 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
9555 trytoswap = 0;
9556 break;
9557 }
9558 }
9559 }
9560 }
9561 processed++;
9562 if (processed == toprocess) return;
9563 }
9564 if (retval < 0 && errno != EAGAIN) {
9565 redisLog(REDIS_WARNING,
9566 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9567 strerror(errno));
9568 }
9569 }
9570
9571 static void lockThreadedIO(void) {
9572 pthread_mutex_lock(&server.io_mutex);
9573 }
9574
9575 static void unlockThreadedIO(void) {
9576 pthread_mutex_unlock(&server.io_mutex);
9577 }
9578
9579 /* Remove the specified object from the threaded I/O queue if still not
9580 * processed, otherwise make sure to flag it as canceled. */
9581 static void vmCancelThreadedIOJob(robj *o) {
9582 list *lists[3] = {
9583 server.io_newjobs, /* 0 */
9584 server.io_processing, /* 1 */
9585 server.io_processed /* 2 */
9586 };
9587 int i;
9588
9589 assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
9590 again:
9591 lockThreadedIO();
9592 /* Search for a matching object in one of the queues */
9593 for (i = 0; i < 3; i++) {
9594 listNode *ln;
9595 listIter li;
9596
9597 listRewind(lists[i],&li);
9598 while ((ln = listNext(&li)) != NULL) {
9599 iojob *job = ln->value;
9600
9601 if (job->canceled) continue; /* Skip this, already canceled. */
9602 if (job->id == o) {
9603 redisLog(REDIS_DEBUG,"*** CANCELED %p (key %s) (type %d) (LIST ID %d)\n",
9604 (void*)job, (char*)job->key->ptr, job->type, i);
9605 /* Mark the pages as free since the swap didn't happened
9606 * or happened but is now discarded. */
9607 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
9608 vmMarkPagesFree(job->page,job->pages);
9609 /* Cancel the job. It depends on the list the job is
9610 * living in. */
9611 switch(i) {
9612 case 0: /* io_newjobs */
9613 /* If the job was yet not processed the best thing to do
9614 * is to remove it from the queue at all */
9615 freeIOJob(job);
9616 listDelNode(lists[i],ln);
9617 break;
9618 case 1: /* io_processing */
9619 /* Oh Shi- the thread is messing with the Job:
9620 *
9621 * Probably it's accessing the object if this is a
9622 * PREPARE_SWAP or DO_SWAP job.
9623 * If it's a LOAD job it may be reading from disk and
9624 * if we don't wait for the job to terminate before to
9625 * cancel it, maybe in a few microseconds data can be
9626 * corrupted in this pages. So the short story is:
9627 *
9628 * Better to wait for the job to move into the
9629 * next queue (processed)... */
9630
9631 /* We try again and again until the job is completed. */
9632 unlockThreadedIO();
9633 /* But let's wait some time for the I/O thread
9634 * to finish with this job. After all this condition
9635 * should be very rare. */
9636 usleep(1);
9637 goto again;
9638 case 2: /* io_processed */
9639 /* The job was already processed, that's easy...
9640 * just mark it as canceled so that we'll ignore it
9641 * when processing completed jobs. */
9642 job->canceled = 1;
9643 break;
9644 }
9645 /* Finally we have to adjust the storage type of the object
9646 * in order to "UNDO" the operaiton. */
9647 if (o->storage == REDIS_VM_LOADING)
9648 o->storage = REDIS_VM_SWAPPED;
9649 else if (o->storage == REDIS_VM_SWAPPING)
9650 o->storage = REDIS_VM_MEMORY;
9651 unlockThreadedIO();
9652 redisLog(REDIS_DEBUG,"*** DONE");
9653 return;
9654 }
9655 }
9656 }
9657 unlockThreadedIO();
9658 printf("Not found: %p\n", (void*)o);
9659 redisAssert(1 != 1); /* We should never reach this */
9660 }
9661
9662 static void *IOThreadEntryPoint(void *arg) {
9663 iojob *j;
9664 listNode *ln;
9665 REDIS_NOTUSED(arg);
9666
9667 pthread_detach(pthread_self());
9668 while(1) {
9669 /* Get a new job to process */
9670 lockThreadedIO();
9671 if (listLength(server.io_newjobs) == 0) {
9672 /* No new jobs in queue, exit. */
9673 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
9674 (long) pthread_self());
9675 server.io_active_threads--;
9676 unlockThreadedIO();
9677 return NULL;
9678 }
9679 ln = listFirst(server.io_newjobs);
9680 j = ln->value;
9681 listDelNode(server.io_newjobs,ln);
9682 /* Add the job in the processing queue */
9683 j->thread = pthread_self();
9684 listAddNodeTail(server.io_processing,j);
9685 ln = listLast(server.io_processing); /* We use ln later to remove it */
9686 unlockThreadedIO();
9687 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
9688 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
9689
9690 /* Process the Job */
9691 if (j->type == REDIS_IOJOB_LOAD) {
9692 vmpointer *vp = (vmpointer*)j->id;
9693 j->val = vmReadObjectFromSwap(j->page,vp->vtype);
9694 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9695 FILE *fp = fopen("/dev/null","w+");
9696 j->pages = rdbSavedObjectPages(j->val,fp);
9697 fclose(fp);
9698 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9699 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
9700 j->canceled = 1;
9701 }
9702
9703 /* Done: insert the job into the processed queue */
9704 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
9705 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
9706 lockThreadedIO();
9707 listDelNode(server.io_processing,ln);
9708 listAddNodeTail(server.io_processed,j);
9709 unlockThreadedIO();
9710
9711 /* Signal the main thread there is new stuff to process */
9712 assert(write(server.io_ready_pipe_write,"x",1) == 1);
9713 }
9714 return NULL; /* never reached */
9715 }
9716
9717 static void spawnIOThread(void) {
9718 pthread_t thread;
9719 sigset_t mask, omask;
9720 int err;
9721
9722 sigemptyset(&mask);
9723 sigaddset(&mask,SIGCHLD);
9724 sigaddset(&mask,SIGHUP);
9725 sigaddset(&mask,SIGPIPE);
9726 pthread_sigmask(SIG_SETMASK, &mask, &omask);
9727 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
9728 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
9729 strerror(err));
9730 usleep(1000000);
9731 }
9732 pthread_sigmask(SIG_SETMASK, &omask, NULL);
9733 server.io_active_threads++;
9734 }
9735
9736 /* We need to wait for the last thread to exit before we are able to
9737 * fork() in order to BGSAVE or BGREWRITEAOF. */
9738 static void waitEmptyIOJobsQueue(void) {
9739 while(1) {
9740 int io_processed_len;
9741
9742 lockThreadedIO();
9743 if (listLength(server.io_newjobs) == 0 &&
9744 listLength(server.io_processing) == 0 &&
9745 server.io_active_threads == 0)
9746 {
9747 unlockThreadedIO();
9748 return;
9749 }
9750 /* While waiting for empty jobs queue condition we post-process some
9751 * finshed job, as I/O threads may be hanging trying to write against
9752 * the io_ready_pipe_write FD but there are so much pending jobs that
9753 * it's blocking. */
9754 io_processed_len = listLength(server.io_processed);
9755 unlockThreadedIO();
9756 if (io_processed_len) {
9757 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
9758 usleep(1000); /* 1 millisecond */
9759 } else {
9760 usleep(10000); /* 10 milliseconds */
9761 }
9762 }
9763 }
9764
9765 static void vmReopenSwapFile(void) {
9766 /* Note: we don't close the old one as we are in the child process
9767 * and don't want to mess at all with the original file object. */
9768 server.vm_fp = fopen(server.vm_swap_file,"r+b");
9769 if (server.vm_fp == NULL) {
9770 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
9771 server.vm_swap_file);
9772 _exit(1);
9773 }
9774 server.vm_fd = fileno(server.vm_fp);
9775 }
9776
9777 /* This function must be called while with threaded IO locked */
9778 static void queueIOJob(iojob *j) {
9779 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
9780 (void*)j, j->type, (char*)j->key->ptr);
9781 listAddNodeTail(server.io_newjobs,j);
9782 if (server.io_active_threads < server.vm_max_threads)
9783 spawnIOThread();
9784 }
9785
9786 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
9787 iojob *j;
9788
9789 assert(key->storage == REDIS_VM_MEMORY);
9790
9791 j = zmalloc(sizeof(*j));
9792 j->type = REDIS_IOJOB_PREPARE_SWAP;
9793 j->db = db;
9794 j->key = key;
9795 incrRefCount(key);
9796 j->id = j->val = val;
9797 incrRefCount(val);
9798 j->canceled = 0;
9799 j->thread = (pthread_t) -1;
9800 val->storage = REDIS_VM_SWAPPING;
9801
9802 lockThreadedIO();
9803 queueIOJob(j);
9804 unlockThreadedIO();
9805 return REDIS_OK;
9806 }
9807
9808 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
9809
9810 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
9811 * If there is not already a job loading the key, it is craeted.
9812 * The key is added to the io_keys list in the client structure, and also
9813 * in the hash table mapping swapped keys to waiting clients, that is,
9814 * server.io_waited_keys. */
9815 static int waitForSwappedKey(redisClient *c, robj *key) {
9816 struct dictEntry *de;
9817 robj *o;
9818 list *l;
9819
9820 /* If the key does not exist or is already in RAM we don't need to
9821 * block the client at all. */
9822 de = dictFind(c->db->dict,key);
9823 if (de == NULL) return 0;
9824 o = dictGetEntryVal(de);
9825 if (o->storage == REDIS_VM_MEMORY) {
9826 return 0;
9827 } else if (o->storage == REDIS_VM_SWAPPING) {
9828 /* We were swapping the key, undo it! */
9829 vmCancelThreadedIOJob(o);
9830 return 0;
9831 }
9832
9833 /* OK: the key is either swapped, or being loaded just now. */
9834
9835 /* Add the key to the list of keys this client is waiting for.
9836 * This maps clients to keys they are waiting for. */
9837 listAddNodeTail(c->io_keys,key);
9838 incrRefCount(key);
9839
9840 /* Add the client to the swapped keys => clients waiting map. */
9841 de = dictFind(c->db->io_keys,key);
9842 if (de == NULL) {
9843 int retval;
9844
9845 /* For every key we take a list of clients blocked for it */
9846 l = listCreate();
9847 retval = dictAdd(c->db->io_keys,key,l);
9848 incrRefCount(key);
9849 assert(retval == DICT_OK);
9850 } else {
9851 l = dictGetEntryVal(de);
9852 }
9853 listAddNodeTail(l,c);
9854
9855 /* Are we already loading the key from disk? If not create a job */
9856 if (o->storage == REDIS_VM_SWAPPED) {
9857 iojob *j;
9858 vmpointer *vp = (vmpointer*)o;
9859
9860 o->storage = REDIS_VM_LOADING;
9861 j = zmalloc(sizeof(*j));
9862 j->type = REDIS_IOJOB_LOAD;
9863 j->db = c->db;
9864 j->id = (robj*)vp;
9865 j->key = key;
9866 incrRefCount(key);
9867 j->page = vp->page;
9868 j->val = NULL;
9869 j->canceled = 0;
9870 j->thread = (pthread_t) -1;
9871 lockThreadedIO();
9872 queueIOJob(j);
9873 unlockThreadedIO();
9874 }
9875 return 1;
9876 }
9877
9878 /* Preload keys for any command with first, last and step values for
9879 * the command keys prototype, as defined in the command table. */
9880 static void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
9881 int j, last;
9882 if (cmd->vm_firstkey == 0) return;
9883 last = cmd->vm_lastkey;
9884 if (last < 0) last = argc+last;
9885 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
9886 redisAssert(j < argc);
9887 waitForSwappedKey(c,argv[j]);
9888 }
9889 }
9890
9891 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
9892 * Note that the number of keys to preload is user-defined, so we need to
9893 * apply a sanity check against argc. */
9894 static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
9895 int i, num;
9896 REDIS_NOTUSED(cmd);
9897
9898 num = atoi(argv[2]->ptr);
9899 if (num > (argc-3)) return;
9900 for (i = 0; i < num; i++) {
9901 waitForSwappedKey(c,argv[3+i]);
9902 }
9903 }
9904
9905 /* Preload keys needed to execute the entire MULTI/EXEC block.
9906 *
9907 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
9908 * and will block the client when any command requires a swapped out value. */
9909 static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
9910 int i, margc;
9911 struct redisCommand *mcmd;
9912 robj **margv;
9913 REDIS_NOTUSED(cmd);
9914 REDIS_NOTUSED(argc);
9915 REDIS_NOTUSED(argv);
9916
9917 if (!(c->flags & REDIS_MULTI)) return;
9918 for (i = 0; i < c->mstate.count; i++) {
9919 mcmd = c->mstate.commands[i].cmd;
9920 margc = c->mstate.commands[i].argc;
9921 margv = c->mstate.commands[i].argv;
9922
9923 if (mcmd->vm_preload_proc != NULL) {
9924 mcmd->vm_preload_proc(c,mcmd,margc,margv);
9925 } else {
9926 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
9927 }
9928 }
9929 }
9930
9931 /* Is this client attempting to run a command against swapped keys?
9932 * If so, block it ASAP, load the keys in background, then resume it.
9933 *
9934 * The important idea about this function is that it can fail! If keys will
9935 * still be swapped when the client is resumed, this key lookups will
9936 * just block loading keys from disk. In practical terms this should only
9937 * happen with SORT BY command or if there is a bug in this function.
9938 *
9939 * Return 1 if the client is marked as blocked, 0 if the client can
9940 * continue as the keys it is going to access appear to be in memory. */
9941 static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
9942 if (cmd->vm_preload_proc != NULL) {
9943 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
9944 } else {
9945 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
9946 }
9947
9948 /* If the client was blocked for at least one key, mark it as blocked. */
9949 if (listLength(c->io_keys)) {
9950 c->flags |= REDIS_IO_WAIT;
9951 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
9952 server.vm_blocked_clients++;
9953 return 1;
9954 } else {
9955 return 0;
9956 }
9957 }
9958
9959 /* Remove the 'key' from the list of blocked keys for a given client.
9960 *
9961 * The function returns 1 when there are no longer blocking keys after
9962 * the current one was removed (and the client can be unblocked). */
9963 static int dontWaitForSwappedKey(redisClient *c, robj *key) {
9964 list *l;
9965 listNode *ln;
9966 listIter li;
9967 struct dictEntry *de;
9968
9969 /* Remove the key from the list of keys this client is waiting for. */
9970 listRewind(c->io_keys,&li);
9971 while ((ln = listNext(&li)) != NULL) {
9972 if (equalStringObjects(ln->value,key)) {
9973 listDelNode(c->io_keys,ln);
9974 break;
9975 }
9976 }
9977 assert(ln != NULL);
9978
9979 /* Remove the client form the key => waiting clients map. */
9980 de = dictFind(c->db->io_keys,key);
9981 assert(de != NULL);
9982 l = dictGetEntryVal(de);
9983 ln = listSearchKey(l,c);
9984 assert(ln != NULL);
9985 listDelNode(l,ln);
9986 if (listLength(l) == 0)
9987 dictDelete(c->db->io_keys,key);
9988
9989 return listLength(c->io_keys) == 0;
9990 }
9991
9992 /* Every time we now a key was loaded back in memory, we handle clients
9993 * waiting for this key if any. */
9994 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
9995 struct dictEntry *de;
9996 list *l;
9997 listNode *ln;
9998 int len;
9999
10000 de = dictFind(db->io_keys,key);
10001 if (!de) return;
10002
10003 l = dictGetEntryVal(de);
10004 len = listLength(l);
10005 /* Note: we can't use something like while(listLength(l)) as the list
10006 * can be freed by the calling function when we remove the last element. */
10007 while (len--) {
10008 ln = listFirst(l);
10009 redisClient *c = ln->value;
10010
10011 if (dontWaitForSwappedKey(c,key)) {
10012 /* Put the client in the list of clients ready to go as we
10013 * loaded all the keys about it. */
10014 listAddNodeTail(server.io_ready_clients,c);
10015 }
10016 }
10017 }
10018
10019 /* =========================== Remote Configuration ========================= */
10020
10021 static void configSetCommand(redisClient *c) {
10022 robj *o = getDecodedObject(c->argv[3]);
10023 long long ll;
10024
10025 if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
10026 zfree(server.dbfilename);
10027 server.dbfilename = zstrdup(o->ptr);
10028 } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
10029 zfree(server.requirepass);
10030 server.requirepass = zstrdup(o->ptr);
10031 } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
10032 zfree(server.masterauth);
10033 server.masterauth = zstrdup(o->ptr);
10034 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
10035 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10036 ll < 0) goto badfmt;
10037 server.maxmemory = ll;
10038 } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
10039 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10040 ll < 0 || ll > LONG_MAX) goto badfmt;
10041 server.maxidletime = ll;
10042 } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
10043 if (!strcasecmp(o->ptr,"no")) {
10044 server.appendfsync = APPENDFSYNC_NO;
10045 } else if (!strcasecmp(o->ptr,"everysec")) {
10046 server.appendfsync = APPENDFSYNC_EVERYSEC;
10047 } else if (!strcasecmp(o->ptr,"always")) {
10048 server.appendfsync = APPENDFSYNC_ALWAYS;
10049 } else {
10050 goto badfmt;
10051 }
10052 } else if (!strcasecmp(c->argv[2]->ptr,"no-appendfsync-on-rewrite")) {
10053 int yn = yesnotoi(o->ptr);
10054
10055 if (yn == -1) goto badfmt;
10056 server.no_appendfsync_on_rewrite = yn;
10057 } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
10058 int old = server.appendonly;
10059 int new = yesnotoi(o->ptr);
10060
10061 if (new == -1) goto badfmt;
10062 if (old != new) {
10063 if (new == 0) {
10064 stopAppendOnly();
10065 } else {
10066 if (startAppendOnly() == REDIS_ERR) {
10067 addReplySds(c,sdscatprintf(sdsempty(),
10068 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
10069 decrRefCount(o);
10070 return;
10071 }
10072 }
10073 }
10074 } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
10075 int vlen, j;
10076 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
10077
10078 /* Perform sanity check before setting the new config:
10079 * - Even number of args
10080 * - Seconds >= 1, changes >= 0 */
10081 if (vlen & 1) {
10082 sdsfreesplitres(v,vlen);
10083 goto badfmt;
10084 }
10085 for (j = 0; j < vlen; j++) {
10086 char *eptr;
10087 long val;
10088
10089 val = strtoll(v[j], &eptr, 10);
10090 if (eptr[0] != '\0' ||
10091 ((j & 1) == 0 && val < 1) ||
10092 ((j & 1) == 1 && val < 0)) {
10093 sdsfreesplitres(v,vlen);
10094 goto badfmt;
10095 }
10096 }
10097 /* Finally set the new config */
10098 resetServerSaveParams();
10099 for (j = 0; j < vlen; j += 2) {
10100 time_t seconds;
10101 int changes;
10102
10103 seconds = strtoll(v[j],NULL,10);
10104 changes = strtoll(v[j+1],NULL,10);
10105 appendServerSaveParams(seconds, changes);
10106 }
10107 sdsfreesplitres(v,vlen);
10108 } else {
10109 addReplySds(c,sdscatprintf(sdsempty(),
10110 "-ERR not supported CONFIG parameter %s\r\n",
10111 (char*)c->argv[2]->ptr));
10112 decrRefCount(o);
10113 return;
10114 }
10115 decrRefCount(o);
10116 addReply(c,shared.ok);
10117 return;
10118
10119 badfmt: /* Bad format errors */
10120 addReplySds(c,sdscatprintf(sdsempty(),
10121 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
10122 (char*)o->ptr,
10123 (char*)c->argv[2]->ptr));
10124 decrRefCount(o);
10125 }
10126
10127 static void configGetCommand(redisClient *c) {
10128 robj *o = getDecodedObject(c->argv[2]);
10129 robj *lenobj = createObject(REDIS_STRING,NULL);
10130 char *pattern = o->ptr;
10131 int matches = 0;
10132
10133 addReply(c,lenobj);
10134 decrRefCount(lenobj);
10135
10136 if (stringmatch(pattern,"dbfilename",0)) {
10137 addReplyBulkCString(c,"dbfilename");
10138 addReplyBulkCString(c,server.dbfilename);
10139 matches++;
10140 }
10141 if (stringmatch(pattern,"requirepass",0)) {
10142 addReplyBulkCString(c,"requirepass");
10143 addReplyBulkCString(c,server.requirepass);
10144 matches++;
10145 }
10146 if (stringmatch(pattern,"masterauth",0)) {
10147 addReplyBulkCString(c,"masterauth");
10148 addReplyBulkCString(c,server.masterauth);
10149 matches++;
10150 }
10151 if (stringmatch(pattern,"maxmemory",0)) {
10152 char buf[128];
10153
10154 ll2string(buf,128,server.maxmemory);
10155 addReplyBulkCString(c,"maxmemory");
10156 addReplyBulkCString(c,buf);
10157 matches++;
10158 }
10159 if (stringmatch(pattern,"timeout",0)) {
10160 char buf[128];
10161
10162 ll2string(buf,128,server.maxidletime);
10163 addReplyBulkCString(c,"timeout");
10164 addReplyBulkCString(c,buf);
10165 matches++;
10166 }
10167 if (stringmatch(pattern,"appendonly",0)) {
10168 addReplyBulkCString(c,"appendonly");
10169 addReplyBulkCString(c,server.appendonly ? "yes" : "no");
10170 matches++;
10171 }
10172 if (stringmatch(pattern,"no-appendfsync-on-rewrite",0)) {
10173 addReplyBulkCString(c,"no-appendfsync-on-rewrite");
10174 addReplyBulkCString(c,server.no_appendfsync_on_rewrite ? "yes" : "no");
10175 matches++;
10176 }
10177 if (stringmatch(pattern,"appendfsync",0)) {
10178 char *policy;
10179
10180 switch(server.appendfsync) {
10181 case APPENDFSYNC_NO: policy = "no"; break;
10182 case APPENDFSYNC_EVERYSEC: policy = "everysec"; break;
10183 case APPENDFSYNC_ALWAYS: policy = "always"; break;
10184 default: policy = "unknown"; break; /* too harmless to panic */
10185 }
10186 addReplyBulkCString(c,"appendfsync");
10187 addReplyBulkCString(c,policy);
10188 matches++;
10189 }
10190 if (stringmatch(pattern,"save",0)) {
10191 sds buf = sdsempty();
10192 int j;
10193
10194 for (j = 0; j < server.saveparamslen; j++) {
10195 buf = sdscatprintf(buf,"%ld %d",
10196 server.saveparams[j].seconds,
10197 server.saveparams[j].changes);
10198 if (j != server.saveparamslen-1)
10199 buf = sdscatlen(buf," ",1);
10200 }
10201 addReplyBulkCString(c,"save");
10202 addReplyBulkCString(c,buf);
10203 sdsfree(buf);
10204 matches++;
10205 }
10206 decrRefCount(o);
10207 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",matches*2);
10208 }
10209
10210 static void configCommand(redisClient *c) {
10211 if (!strcasecmp(c->argv[1]->ptr,"set")) {
10212 if (c->argc != 4) goto badarity;
10213 configSetCommand(c);
10214 } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
10215 if (c->argc != 3) goto badarity;
10216 configGetCommand(c);
10217 } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
10218 if (c->argc != 2) goto badarity;
10219 server.stat_numcommands = 0;
10220 server.stat_numconnections = 0;
10221 server.stat_expiredkeys = 0;
10222 server.stat_starttime = time(NULL);
10223 addReply(c,shared.ok);
10224 } else {
10225 addReplySds(c,sdscatprintf(sdsempty(),
10226 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10227 }
10228 return;
10229
10230 badarity:
10231 addReplySds(c,sdscatprintf(sdsempty(),
10232 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10233 (char*) c->argv[1]->ptr));
10234 }
10235
10236 /* =========================== Pubsub implementation ======================== */
10237
10238 static void freePubsubPattern(void *p) {
10239 pubsubPattern *pat = p;
10240
10241 decrRefCount(pat->pattern);
10242 zfree(pat);
10243 }
10244
10245 static int listMatchPubsubPattern(void *a, void *b) {
10246 pubsubPattern *pa = a, *pb = b;
10247
10248 return (pa->client == pb->client) &&
10249 (equalStringObjects(pa->pattern,pb->pattern));
10250 }
10251
10252 /* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10253 * 0 if the client was already subscribed to that channel. */
10254 static int pubsubSubscribeChannel(redisClient *c, robj *channel) {
10255 struct dictEntry *de;
10256 list *clients = NULL;
10257 int retval = 0;
10258
10259 /* Add the channel to the client -> channels hash table */
10260 if (dictAdd(c->pubsub_channels,channel,NULL) == DICT_OK) {
10261 retval = 1;
10262 incrRefCount(channel);
10263 /* Add the client to the channel -> list of clients hash table */
10264 de = dictFind(server.pubsub_channels,channel);
10265 if (de == NULL) {
10266 clients = listCreate();
10267 dictAdd(server.pubsub_channels,channel,clients);
10268 incrRefCount(channel);
10269 } else {
10270 clients = dictGetEntryVal(de);
10271 }
10272 listAddNodeTail(clients,c);
10273 }
10274 /* Notify the client */
10275 addReply(c,shared.mbulk3);
10276 addReply(c,shared.subscribebulk);
10277 addReplyBulk(c,channel);
10278 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10279 return retval;
10280 }
10281
10282 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10283 * 0 if the client was not subscribed to the specified channel. */
10284 static int pubsubUnsubscribeChannel(redisClient *c, robj *channel, int notify) {
10285 struct dictEntry *de;
10286 list *clients;
10287 listNode *ln;
10288 int retval = 0;
10289
10290 /* Remove the channel from the client -> channels hash table */
10291 incrRefCount(channel); /* channel may be just a pointer to the same object
10292 we have in the hash tables. Protect it... */
10293 if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
10294 retval = 1;
10295 /* Remove the client from the channel -> clients list hash table */
10296 de = dictFind(server.pubsub_channels,channel);
10297 assert(de != NULL);
10298 clients = dictGetEntryVal(de);
10299 ln = listSearchKey(clients,c);
10300 assert(ln != NULL);
10301 listDelNode(clients,ln);
10302 if (listLength(clients) == 0) {
10303 /* Free the list and associated hash entry at all if this was
10304 * the latest client, so that it will be possible to abuse
10305 * Redis PUBSUB creating millions of channels. */
10306 dictDelete(server.pubsub_channels,channel);
10307 }
10308 }
10309 /* Notify the client */
10310 if (notify) {
10311 addReply(c,shared.mbulk3);
10312 addReply(c,shared.unsubscribebulk);
10313 addReplyBulk(c,channel);
10314 addReplyLongLong(c,dictSize(c->pubsub_channels)+
10315 listLength(c->pubsub_patterns));
10316
10317 }
10318 decrRefCount(channel); /* it is finally safe to release it */
10319 return retval;
10320 }
10321
10322 /* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10323 static int pubsubSubscribePattern(redisClient *c, robj *pattern) {
10324 int retval = 0;
10325
10326 if (listSearchKey(c->pubsub_patterns,pattern) == NULL) {
10327 retval = 1;
10328 pubsubPattern *pat;
10329 listAddNodeTail(c->pubsub_patterns,pattern);
10330 incrRefCount(pattern);
10331 pat = zmalloc(sizeof(*pat));
10332 pat->pattern = getDecodedObject(pattern);
10333 pat->client = c;
10334 listAddNodeTail(server.pubsub_patterns,pat);
10335 }
10336 /* Notify the client */
10337 addReply(c,shared.mbulk3);
10338 addReply(c,shared.psubscribebulk);
10339 addReplyBulk(c,pattern);
10340 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10341 return retval;
10342 }
10343
10344 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10345 * 0 if the client was not subscribed to the specified channel. */
10346 static int pubsubUnsubscribePattern(redisClient *c, robj *pattern, int notify) {
10347 listNode *ln;
10348 pubsubPattern pat;
10349 int retval = 0;
10350
10351 incrRefCount(pattern); /* Protect the object. May be the same we remove */
10352 if ((ln = listSearchKey(c->pubsub_patterns,pattern)) != NULL) {
10353 retval = 1;
10354 listDelNode(c->pubsub_patterns,ln);
10355 pat.client = c;
10356 pat.pattern = pattern;
10357 ln = listSearchKey(server.pubsub_patterns,&pat);
10358 listDelNode(server.pubsub_patterns,ln);
10359 }
10360 /* Notify the client */
10361 if (notify) {
10362 addReply(c,shared.mbulk3);
10363 addReply(c,shared.punsubscribebulk);
10364 addReplyBulk(c,pattern);
10365 addReplyLongLong(c,dictSize(c->pubsub_channels)+
10366 listLength(c->pubsub_patterns));
10367 }
10368 decrRefCount(pattern);
10369 return retval;
10370 }
10371
10372 /* Unsubscribe from all the channels. Return the number of channels the
10373 * client was subscribed from. */
10374 static int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
10375 dictIterator *di = dictGetIterator(c->pubsub_channels);
10376 dictEntry *de;
10377 int count = 0;
10378
10379 while((de = dictNext(di)) != NULL) {
10380 robj *channel = dictGetEntryKey(de);
10381
10382 count += pubsubUnsubscribeChannel(c,channel,notify);
10383 }
10384 dictReleaseIterator(di);
10385 return count;
10386 }
10387
10388 /* Unsubscribe from all the patterns. Return the number of patterns the
10389 * client was subscribed from. */
10390 static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify) {
10391 listNode *ln;
10392 listIter li;
10393 int count = 0;
10394
10395 listRewind(c->pubsub_patterns,&li);
10396 while ((ln = listNext(&li)) != NULL) {
10397 robj *pattern = ln->value;
10398
10399 count += pubsubUnsubscribePattern(c,pattern,notify);
10400 }
10401 return count;
10402 }
10403
10404 /* Publish a message */
10405 static int pubsubPublishMessage(robj *channel, robj *message) {
10406 int receivers = 0;
10407 struct dictEntry *de;
10408 listNode *ln;
10409 listIter li;
10410
10411 /* Send to clients listening for that channel */
10412 de = dictFind(server.pubsub_channels,channel);
10413 if (de) {
10414 list *list = dictGetEntryVal(de);
10415 listNode *ln;
10416 listIter li;
10417
10418 listRewind(list,&li);
10419 while ((ln = listNext(&li)) != NULL) {
10420 redisClient *c = ln->value;
10421
10422 addReply(c,shared.mbulk3);
10423 addReply(c,shared.messagebulk);
10424 addReplyBulk(c,channel);
10425 addReplyBulk(c,message);
10426 receivers++;
10427 }
10428 }
10429 /* Send to clients listening to matching channels */
10430 if (listLength(server.pubsub_patterns)) {
10431 listRewind(server.pubsub_patterns,&li);
10432 channel = getDecodedObject(channel);
10433 while ((ln = listNext(&li)) != NULL) {
10434 pubsubPattern *pat = ln->value;
10435
10436 if (stringmatchlen((char*)pat->pattern->ptr,
10437 sdslen(pat->pattern->ptr),
10438 (char*)channel->ptr,
10439 sdslen(channel->ptr),0)) {
10440 addReply(pat->client,shared.mbulk4);
10441 addReply(pat->client,shared.pmessagebulk);
10442 addReplyBulk(pat->client,pat->pattern);
10443 addReplyBulk(pat->client,channel);
10444 addReplyBulk(pat->client,message);
10445 receivers++;
10446 }
10447 }
10448 decrRefCount(channel);
10449 }
10450 return receivers;
10451 }
10452
10453 static void subscribeCommand(redisClient *c) {
10454 int j;
10455
10456 for (j = 1; j < c->argc; j++)
10457 pubsubSubscribeChannel(c,c->argv[j]);
10458 }
10459
10460 static void unsubscribeCommand(redisClient *c) {
10461 if (c->argc == 1) {
10462 pubsubUnsubscribeAllChannels(c,1);
10463 return;
10464 } else {
10465 int j;
10466
10467 for (j = 1; j < c->argc; j++)
10468 pubsubUnsubscribeChannel(c,c->argv[j],1);
10469 }
10470 }
10471
10472 static void psubscribeCommand(redisClient *c) {
10473 int j;
10474
10475 for (j = 1; j < c->argc; j++)
10476 pubsubSubscribePattern(c,c->argv[j]);
10477 }
10478
10479 static void punsubscribeCommand(redisClient *c) {
10480 if (c->argc == 1) {
10481 pubsubUnsubscribeAllPatterns(c,1);
10482 return;
10483 } else {
10484 int j;
10485
10486 for (j = 1; j < c->argc; j++)
10487 pubsubUnsubscribePattern(c,c->argv[j],1);
10488 }
10489 }
10490
10491 static void publishCommand(redisClient *c) {
10492 int receivers = pubsubPublishMessage(c->argv[1],c->argv[2]);
10493 addReplyLongLong(c,receivers);
10494 }
10495
10496 /* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
10497 *
10498 * The implementation uses a per-DB hash table mapping keys to list of clients
10499 * WATCHing those keys, so that given a key that is going to be modified
10500 * we can mark all the associated clients as dirty.
10501 *
10502 * Also every client contains a list of WATCHed keys so that's possible to
10503 * un-watch such keys when the client is freed or when UNWATCH is called. */
10504
10505 /* In the client->watched_keys list we need to use watchedKey structures
10506 * as in order to identify a key in Redis we need both the key name and the
10507 * DB */
10508 typedef struct watchedKey {
10509 robj *key;
10510 redisDb *db;
10511 } watchedKey;
10512
10513 /* Watch for the specified key */
10514 static void watchForKey(redisClient *c, robj *key) {
10515 list *clients = NULL;
10516 listIter li;
10517 listNode *ln;
10518 watchedKey *wk;
10519
10520 /* Check if we are already watching for this key */
10521 listRewind(c->watched_keys,&li);
10522 while((ln = listNext(&li))) {
10523 wk = listNodeValue(ln);
10524 if (wk->db == c->db && equalStringObjects(key,wk->key))
10525 return; /* Key already watched */
10526 }
10527 /* This key is not already watched in this DB. Let's add it */
10528 clients = dictFetchValue(c->db->watched_keys,key);
10529 if (!clients) {
10530 clients = listCreate();
10531 dictAdd(c->db->watched_keys,key,clients);
10532 incrRefCount(key);
10533 }
10534 listAddNodeTail(clients,c);
10535 /* Add the new key to the lits of keys watched by this client */
10536 wk = zmalloc(sizeof(*wk));
10537 wk->key = key;
10538 wk->db = c->db;
10539 incrRefCount(key);
10540 listAddNodeTail(c->watched_keys,wk);
10541 }
10542
10543 /* Unwatch all the keys watched by this client. To clean the EXEC dirty
10544 * flag is up to the caller. */
10545 static void unwatchAllKeys(redisClient *c) {
10546 listIter li;
10547 listNode *ln;
10548
10549 if (listLength(c->watched_keys) == 0) return;
10550 listRewind(c->watched_keys,&li);
10551 while((ln = listNext(&li))) {
10552 list *clients;
10553 watchedKey *wk;
10554
10555 /* Lookup the watched key -> clients list and remove the client
10556 * from the list */
10557 wk = listNodeValue(ln);
10558 clients = dictFetchValue(wk->db->watched_keys, wk->key);
10559 assert(clients != NULL);
10560 listDelNode(clients,listSearchKey(clients,c));
10561 /* Kill the entry at all if this was the only client */
10562 if (listLength(clients) == 0)
10563 dictDelete(wk->db->watched_keys, wk->key);
10564 /* Remove this watched key from the client->watched list */
10565 listDelNode(c->watched_keys,ln);
10566 decrRefCount(wk->key);
10567 zfree(wk);
10568 }
10569 }
10570
10571 /* "Touch" a key, so that if this key is being WATCHed by some client the
10572 * next EXEC will fail. */
10573 static void touchWatchedKey(redisDb *db, robj *key) {
10574 list *clients;
10575 listIter li;
10576 listNode *ln;
10577
10578 if (dictSize(db->watched_keys) == 0) return;
10579 clients = dictFetchValue(db->watched_keys, key);
10580 if (!clients) return;
10581
10582 /* Mark all the clients watching this key as REDIS_DIRTY_CAS */
10583 /* Check if we are already watching for this key */
10584 listRewind(clients,&li);
10585 while((ln = listNext(&li))) {
10586 redisClient *c = listNodeValue(ln);
10587
10588 c->flags |= REDIS_DIRTY_CAS;
10589 }
10590 }
10591
10592 /* On FLUSHDB or FLUSHALL all the watched keys that are present before the
10593 * flush but will be deleted as effect of the flushing operation should
10594 * be touched. "dbid" is the DB that's getting the flush. -1 if it is
10595 * a FLUSHALL operation (all the DBs flushed). */
10596 static void touchWatchedKeysOnFlush(int dbid) {
10597 listIter li1, li2;
10598 listNode *ln;
10599
10600 /* For every client, check all the waited keys */
10601 listRewind(server.clients,&li1);
10602 while((ln = listNext(&li1))) {
10603 redisClient *c = listNodeValue(ln);
10604 listRewind(c->watched_keys,&li2);
10605 while((ln = listNext(&li2))) {
10606 watchedKey *wk = listNodeValue(ln);
10607
10608 /* For every watched key matching the specified DB, if the
10609 * key exists, mark the client as dirty, as the key will be
10610 * removed. */
10611 if (dbid == -1 || wk->db->id == dbid) {
10612 if (dictFind(wk->db->dict, wk->key) != NULL)
10613 c->flags |= REDIS_DIRTY_CAS;
10614 }
10615 }
10616 }
10617 }
10618
10619 static void watchCommand(redisClient *c) {
10620 int j;
10621
10622 if (c->flags & REDIS_MULTI) {
10623 addReplySds(c,sdsnew("-ERR WATCH inside MULTI is not allowed\r\n"));
10624 return;
10625 }
10626 for (j = 1; j < c->argc; j++)
10627 watchForKey(c,c->argv[j]);
10628 addReply(c,shared.ok);
10629 }
10630
10631 static void unwatchCommand(redisClient *c) {
10632 unwatchAllKeys(c);
10633 c->flags &= (~REDIS_DIRTY_CAS);
10634 addReply(c,shared.ok);
10635 }
10636
10637 /* ================================= Debugging ============================== */
10638
10639 /* Compute the sha1 of string at 's' with 'len' bytes long.
10640 * The SHA1 is then xored againt the string pointed by digest.
10641 * Since xor is commutative, this operation is used in order to
10642 * "add" digests relative to unordered elements.
10643 *
10644 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10645 static void xorDigest(unsigned char *digest, void *ptr, size_t len) {
10646 SHA1_CTX ctx;
10647 unsigned char hash[20], *s = ptr;
10648 int j;
10649
10650 SHA1Init(&ctx);
10651 SHA1Update(&ctx,s,len);
10652 SHA1Final(hash,&ctx);
10653
10654 for (j = 0; j < 20; j++)
10655 digest[j] ^= hash[j];
10656 }
10657
10658 static void xorObjectDigest(unsigned char *digest, robj *o) {
10659 o = getDecodedObject(o);
10660 xorDigest(digest,o->ptr,sdslen(o->ptr));
10661 decrRefCount(o);
10662 }
10663
10664 /* This function instead of just computing the SHA1 and xoring it
10665 * against diget, also perform the digest of "digest" itself and
10666 * replace the old value with the new one.
10667 *
10668 * So the final digest will be:
10669 *
10670 * digest = SHA1(digest xor SHA1(data))
10671 *
10672 * This function is used every time we want to preserve the order so
10673 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
10674 *
10675 * Also note that mixdigest("foo") followed by mixdigest("bar")
10676 * will lead to a different digest compared to "fo", "obar".
10677 */
10678 static void mixDigest(unsigned char *digest, void *ptr, size_t len) {
10679 SHA1_CTX ctx;
10680 char *s = ptr;
10681
10682 xorDigest(digest,s,len);
10683 SHA1Init(&ctx);
10684 SHA1Update(&ctx,digest,20);
10685 SHA1Final(digest,&ctx);
10686 }
10687
10688 static void mixObjectDigest(unsigned char *digest, robj *o) {
10689 o = getDecodedObject(o);
10690 mixDigest(digest,o->ptr,sdslen(o->ptr));
10691 decrRefCount(o);
10692 }
10693
10694 /* Compute the dataset digest. Since keys, sets elements, hashes elements
10695 * are not ordered, we use a trick: every aggregate digest is the xor
10696 * of the digests of their elements. This way the order will not change
10697 * the result. For list instead we use a feedback entering the output digest
10698 * as input in order to ensure that a different ordered list will result in
10699 * a different digest. */
10700 static void computeDatasetDigest(unsigned char *final) {
10701 unsigned char digest[20];
10702 char buf[128];
10703 dictIterator *di = NULL;
10704 dictEntry *de;
10705 int j;
10706 uint32_t aux;
10707
10708 memset(final,0,20); /* Start with a clean result */
10709
10710 for (j = 0; j < server.dbnum; j++) {
10711 redisDb *db = server.db+j;
10712
10713 if (dictSize(db->dict) == 0) continue;
10714 di = dictGetIterator(db->dict);
10715
10716 /* hash the DB id, so the same dataset moved in a different
10717 * DB will lead to a different digest */
10718 aux = htonl(j);
10719 mixDigest(final,&aux,sizeof(aux));
10720
10721 /* Iterate this DB writing every entry */
10722 while((de = dictNext(di)) != NULL) {
10723 robj *key, *o, *kcopy;
10724 time_t expiretime;
10725
10726 memset(digest,0,20); /* This key-val digest */
10727 key = dictGetEntryKey(de);
10728
10729 if (!server.vm_enabled) {
10730 mixObjectDigest(digest,key);
10731 o = dictGetEntryVal(de);
10732 } else {
10733 /* Don't work with the key directly as when VM is active
10734 * this is unsafe: TODO: fix decrRefCount to check if the
10735 * count really reached 0 to avoid this mess */
10736 kcopy = dupStringObject(key);
10737 mixObjectDigest(digest,kcopy);
10738 o = lookupKeyRead(db,kcopy);
10739 decrRefCount(kcopy);
10740 }
10741 aux = htonl(o->type);
10742 mixDigest(digest,&aux,sizeof(aux));
10743 expiretime = getExpire(db,key);
10744
10745 /* Save the key and associated value */
10746 if (o->type == REDIS_STRING) {
10747 mixObjectDigest(digest,o);
10748 } else if (o->type == REDIS_LIST) {
10749 list *list = o->ptr;
10750 listNode *ln;
10751 listIter li;
10752
10753 listRewind(list,&li);
10754 while((ln = listNext(&li))) {
10755 robj *eleobj = listNodeValue(ln);
10756
10757 mixObjectDigest(digest,eleobj);
10758 }
10759 } else if (o->type == REDIS_SET) {
10760 dict *set = o->ptr;
10761 dictIterator *di = dictGetIterator(set);
10762 dictEntry *de;
10763
10764 while((de = dictNext(di)) != NULL) {
10765 robj *eleobj = dictGetEntryKey(de);
10766
10767 xorObjectDigest(digest,eleobj);
10768 }
10769 dictReleaseIterator(di);
10770 } else if (o->type == REDIS_ZSET) {
10771 zset *zs = o->ptr;
10772 dictIterator *di = dictGetIterator(zs->dict);
10773 dictEntry *de;
10774
10775 while((de = dictNext(di)) != NULL) {
10776 robj *eleobj = dictGetEntryKey(de);
10777 double *score = dictGetEntryVal(de);
10778 unsigned char eledigest[20];
10779
10780 snprintf(buf,sizeof(buf),"%.17g",*score);
10781 memset(eledigest,0,20);
10782 mixObjectDigest(eledigest,eleobj);
10783 mixDigest(eledigest,buf,strlen(buf));
10784 xorDigest(digest,eledigest,20);
10785 }
10786 dictReleaseIterator(di);
10787 } else if (o->type == REDIS_HASH) {
10788 hashIterator *hi;
10789 robj *obj;
10790
10791 hi = hashInitIterator(o);
10792 while (hashNext(hi) != REDIS_ERR) {
10793 unsigned char eledigest[20];
10794
10795 memset(eledigest,0,20);
10796 obj = hashCurrent(hi,REDIS_HASH_KEY);
10797 mixObjectDigest(eledigest,obj);
10798 decrRefCount(obj);
10799 obj = hashCurrent(hi,REDIS_HASH_VALUE);
10800 mixObjectDigest(eledigest,obj);
10801 decrRefCount(obj);
10802 xorDigest(digest,eledigest,20);
10803 }
10804 hashReleaseIterator(hi);
10805 } else {
10806 redisPanic("Unknown object type");
10807 }
10808 /* If the key has an expire, add it to the mix */
10809 if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
10810 /* We can finally xor the key-val digest to the final digest */
10811 xorDigest(final,digest,20);
10812 }
10813 dictReleaseIterator(di);
10814 }
10815 }
10816
10817 static void debugCommand(redisClient *c) {
10818 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
10819 *((char*)-1) = 'x';
10820 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
10821 if (rdbSave(server.dbfilename) != REDIS_OK) {
10822 addReply(c,shared.err);
10823 return;
10824 }
10825 emptyDb();
10826 if (rdbLoad(server.dbfilename) != REDIS_OK) {
10827 addReply(c,shared.err);
10828 return;
10829 }
10830 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
10831 addReply(c,shared.ok);
10832 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
10833 emptyDb();
10834 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
10835 addReply(c,shared.err);
10836 return;
10837 }
10838 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
10839 addReply(c,shared.ok);
10840 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
10841 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
10842 robj *key, *val;
10843
10844 if (!de) {
10845 addReply(c,shared.nokeyerr);
10846 return;
10847 }
10848 key = dictGetEntryKey(de);
10849 val = dictGetEntryVal(de);
10850 if (!server.vm_enabled || (val->storage == REDIS_VM_MEMORY ||
10851 val->storage == REDIS_VM_SWAPPING)) {
10852 char *strenc;
10853 char buf[128];
10854
10855 if (val->encoding < (sizeof(strencoding)/sizeof(char*))) {
10856 strenc = strencoding[val->encoding];
10857 } else {
10858 snprintf(buf,64,"unknown encoding %d\n", val->encoding);
10859 strenc = buf;
10860 }
10861 addReplySds(c,sdscatprintf(sdsempty(),
10862 "+Key at:%p refcount:%d, value at:%p refcount:%d "
10863 "encoding:%s serializedlength:%lld\r\n",
10864 (void*)key, key->refcount, (void*)val, val->refcount,
10865 strenc, (long long) rdbSavedObjectLen(val,NULL)));
10866 } else {
10867 vmpointer *vp = (vmpointer*) val;
10868 addReplySds(c,sdscatprintf(sdsempty(),
10869 "+Key at:%p refcount:%d, value swapped at: page %llu "
10870 "using %llu pages\r\n",
10871 (void*)key, key->refcount, (unsigned long long) vp->page,
10872 (unsigned long long) vp->usedpages));
10873 }
10874 } else if (!strcasecmp(c->argv[1]->ptr,"swapin") && c->argc == 3) {
10875 lookupKeyRead(c->db,c->argv[2]);
10876 addReply(c,shared.ok);
10877 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
10878 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
10879 robj *key, *val;
10880 vmpointer *vp;
10881
10882 if (!server.vm_enabled) {
10883 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
10884 return;
10885 }
10886 if (!de) {
10887 addReply(c,shared.nokeyerr);
10888 return;
10889 }
10890 key = dictGetEntryKey(de);
10891 val = dictGetEntryVal(de);
10892 /* Swap it */
10893 if (val->storage != REDIS_VM_MEMORY) {
10894 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
10895 } else if (val->refcount != 1) {
10896 addReplySds(c,sdsnew("-ERR Object is shared\r\n"));
10897 } else if ((vp = vmSwapObjectBlocking(val)) != NULL) {
10898 dictGetEntryVal(de) = vp;
10899 addReply(c,shared.ok);
10900 } else {
10901 addReply(c,shared.err);
10902 }
10903 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
10904 long keys, j;
10905 robj *key, *val;
10906 char buf[128];
10907
10908 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
10909 return;
10910 for (j = 0; j < keys; j++) {
10911 snprintf(buf,sizeof(buf),"key:%lu",j);
10912 key = createStringObject(buf,strlen(buf));
10913 if (lookupKeyRead(c->db,key) != NULL) {
10914 decrRefCount(key);
10915 continue;
10916 }
10917 snprintf(buf,sizeof(buf),"value:%lu",j);
10918 val = createStringObject(buf,strlen(buf));
10919 dictAdd(c->db->dict,key,val);
10920 }
10921 addReply(c,shared.ok);
10922 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
10923 unsigned char digest[20];
10924 sds d = sdsnew("+");
10925 int j;
10926
10927 computeDatasetDigest(digest);
10928 for (j = 0; j < 20; j++)
10929 d = sdscatprintf(d, "%02x",digest[j]);
10930
10931 d = sdscatlen(d,"\r\n",2);
10932 addReplySds(c,d);
10933 } else {
10934 addReplySds(c,sdsnew(
10935 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
10936 }
10937 }
10938
10939 static void _redisAssert(char *estr, char *file, int line) {
10940 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
10941 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
10942 #ifdef HAVE_BACKTRACE
10943 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
10944 *((char*)-1) = 'x';
10945 #endif
10946 }
10947
10948 static void _redisPanic(char *msg, char *file, int line) {
10949 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
10950 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
10951 #ifdef HAVE_BACKTRACE
10952 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
10953 *((char*)-1) = 'x';
10954 #endif
10955 }
10956
10957 /* =================================== Main! ================================ */
10958
10959 #ifdef __linux__
10960 int linuxOvercommitMemoryValue(void) {
10961 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
10962 char buf[64];
10963
10964 if (!fp) return -1;
10965 if (fgets(buf,64,fp) == NULL) {
10966 fclose(fp);
10967 return -1;
10968 }
10969 fclose(fp);
10970
10971 return atoi(buf);
10972 }
10973
10974 void linuxOvercommitMemoryWarning(void) {
10975 if (linuxOvercommitMemoryValue() == 0) {
10976 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.");
10977 }
10978 }
10979 #endif /* __linux__ */
10980
10981 static void daemonize(void) {
10982 int fd;
10983 FILE *fp;
10984
10985 if (fork() != 0) exit(0); /* parent exits */
10986 setsid(); /* create a new session */
10987
10988 /* Every output goes to /dev/null. If Redis is daemonized but
10989 * the 'logfile' is set to 'stdout' in the configuration file
10990 * it will not log at all. */
10991 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
10992 dup2(fd, STDIN_FILENO);
10993 dup2(fd, STDOUT_FILENO);
10994 dup2(fd, STDERR_FILENO);
10995 if (fd > STDERR_FILENO) close(fd);
10996 }
10997 /* Try to write the pid file */
10998 fp = fopen(server.pidfile,"w");
10999 if (fp) {
11000 fprintf(fp,"%d\n",getpid());
11001 fclose(fp);
11002 }
11003 }
11004
11005 static void version() {
11006 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
11007 REDIS_GIT_SHA1, atoi(REDIS_GIT_DIRTY) > 0);
11008 exit(0);
11009 }
11010
11011 static void usage() {
11012 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
11013 fprintf(stderr," ./redis-server - (read config from stdin)\n");
11014 exit(1);
11015 }
11016
11017 int main(int argc, char **argv) {
11018 time_t start;
11019
11020 initServerConfig();
11021 sortCommandTable();
11022 if (argc == 2) {
11023 if (strcmp(argv[1], "-v") == 0 ||
11024 strcmp(argv[1], "--version") == 0) version();
11025 if (strcmp(argv[1], "--help") == 0) usage();
11026 resetServerSaveParams();
11027 loadServerConfig(argv[1]);
11028 } else if ((argc > 2)) {
11029 usage();
11030 } else {
11031 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'");
11032 }
11033 if (server.daemonize) daemonize();
11034 initServer();
11035 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
11036 #ifdef __linux__
11037 linuxOvercommitMemoryWarning();
11038 #endif
11039 start = time(NULL);
11040 if (server.appendonly) {
11041 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
11042 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
11043 } else {
11044 if (rdbLoad(server.dbfilename) == REDIS_OK)
11045 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
11046 }
11047 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
11048 aeSetBeforeSleepProc(server.el,beforeSleep);
11049 aeMain(server.el);
11050 aeDeleteEventLoop(server.el);
11051 return 0;
11052 }
11053
11054 /* ============================= Backtrace support ========================= */
11055
11056 #ifdef HAVE_BACKTRACE
11057 static char *findFuncName(void *pointer, unsigned long *offset);
11058
11059 static void *getMcontextEip(ucontext_t *uc) {
11060 #if defined(__FreeBSD__)
11061 return (void*) uc->uc_mcontext.mc_eip;
11062 #elif defined(__dietlibc__)
11063 return (void*) uc->uc_mcontext.eip;
11064 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
11065 #if __x86_64__
11066 return (void*) uc->uc_mcontext->__ss.__rip;
11067 #else
11068 return (void*) uc->uc_mcontext->__ss.__eip;
11069 #endif
11070 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
11071 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
11072 return (void*) uc->uc_mcontext->__ss.__rip;
11073 #else
11074 return (void*) uc->uc_mcontext->__ss.__eip;
11075 #endif
11076 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
11077 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
11078 #elif defined(__ia64__) /* Linux IA64 */
11079 return (void*) uc->uc_mcontext.sc_ip;
11080 #else
11081 return NULL;
11082 #endif
11083 }
11084
11085 static void segvHandler(int sig, siginfo_t *info, void *secret) {
11086 void *trace[100];
11087 char **messages = NULL;
11088 int i, trace_size = 0;
11089 unsigned long offset=0;
11090 ucontext_t *uc = (ucontext_t*) secret;
11091 sds infostring;
11092 REDIS_NOTUSED(info);
11093
11094 redisLog(REDIS_WARNING,
11095 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
11096 infostring = genRedisInfoString();
11097 redisLog(REDIS_WARNING, "%s",infostring);
11098 /* It's not safe to sdsfree() the returned string under memory
11099 * corruption conditions. Let it leak as we are going to abort */
11100
11101 trace_size = backtrace(trace, 100);
11102 /* overwrite sigaction with caller's address */
11103 if (getMcontextEip(uc) != NULL) {
11104 trace[1] = getMcontextEip(uc);
11105 }
11106 messages = backtrace_symbols(trace, trace_size);
11107
11108 for (i=1; i<trace_size; ++i) {
11109 char *fn = findFuncName(trace[i], &offset), *p;
11110
11111 p = strchr(messages[i],'+');
11112 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
11113 redisLog(REDIS_WARNING,"%s", messages[i]);
11114 } else {
11115 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
11116 }
11117 }
11118 /* free(messages); Don't call free() with possibly corrupted memory. */
11119 _exit(0);
11120 }
11121
11122 static void sigtermHandler(int sig) {
11123 REDIS_NOTUSED(sig);
11124
11125 redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
11126 server.shutdown_asap = 1;
11127 }
11128
11129 static void setupSigSegvAction(void) {
11130 struct sigaction act;
11131
11132 sigemptyset (&act.sa_mask);
11133 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
11134 * is used. Otherwise, sa_handler is used */
11135 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
11136 act.sa_sigaction = segvHandler;
11137 sigaction (SIGSEGV, &act, NULL);
11138 sigaction (SIGBUS, &act, NULL);
11139 sigaction (SIGFPE, &act, NULL);
11140 sigaction (SIGILL, &act, NULL);
11141 sigaction (SIGBUS, &act, NULL);
11142
11143 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
11144 act.sa_handler = sigtermHandler;
11145 sigaction (SIGTERM, &act, NULL);
11146 return;
11147 }
11148
11149 #include "staticsymbols.h"
11150 /* This function try to convert a pointer into a function name. It's used in
11151 * oreder to provide a backtrace under segmentation fault that's able to
11152 * display functions declared as static (otherwise the backtrace is useless). */
11153 static char *findFuncName(void *pointer, unsigned long *offset){
11154 int i, ret = -1;
11155 unsigned long off, minoff = 0;
11156
11157 /* Try to match against the Symbol with the smallest offset */
11158 for (i=0; symsTable[i].pointer; i++) {
11159 unsigned long lp = (unsigned long) pointer;
11160
11161 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
11162 off=lp-symsTable[i].pointer;
11163 if (ret < 0 || off < minoff) {
11164 minoff=off;
11165 ret=i;
11166 }
11167 }
11168 }
11169 if (ret == -1) return NULL;
11170 *offset = minoff;
11171 return symsTable[ret].name;
11172 }
11173 #else /* HAVE_BACKTRACE */
11174 static void setupSigSegvAction(void) {
11175 }
11176 #endif /* HAVE_BACKTRACE */
11177
11178
11179
11180 /* The End */
11181
11182
11183