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