]> git.saurik.com Git - redis.git/blob - redis.c
with --help states that you can use - as config file name to feed config via stdin
[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 "1.3.7"
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 #define __USE_POSIX199309
41 #define __USE_UNIX98
42 #include <signal.h>
43
44 #ifdef HAVE_BACKTRACE
45 #include <execinfo.h>
46 #include <ucontext.h>
47 #endif /* HAVE_BACKTRACE */
48
49 #include <sys/wait.h>
50 #include <errno.h>
51 #include <assert.h>
52 #include <ctype.h>
53 #include <stdarg.h>
54 #include <inttypes.h>
55 #include <arpa/inet.h>
56 #include <sys/stat.h>
57 #include <fcntl.h>
58 #include <sys/time.h>
59 #include <sys/resource.h>
60 #include <sys/uio.h>
61 #include <limits.h>
62 #include <math.h>
63 #include <pthread.h>
64
65 #if defined(__sun)
66 #include "solarisfixes.h"
67 #endif
68
69 #include "redis.h"
70 #include "ae.h" /* Event driven programming library */
71 #include "sds.h" /* Dynamic safe strings */
72 #include "anet.h" /* Networking the easy way */
73 #include "dict.h" /* Hash tables */
74 #include "adlist.h" /* Linked lists */
75 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
76 #include "lzf.h" /* LZF compression library */
77 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
78 #include "zipmap.h"
79
80 /* Error codes */
81 #define REDIS_OK 0
82 #define REDIS_ERR -1
83
84 /* Static server configuration */
85 #define REDIS_SERVERPORT 6379 /* TCP port */
86 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
87 #define REDIS_IOBUF_LEN 1024
88 #define REDIS_LOADBUF_LEN 1024
89 #define REDIS_STATIC_ARGS 4
90 #define REDIS_DEFAULT_DBNUM 16
91 #define REDIS_CONFIGLINE_MAX 1024
92 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
93 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
94 #define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* try to expire 10 keys/loop */
95 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
96 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
97
98 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
99 #define REDIS_WRITEV_THRESHOLD 3
100 /* Max number of iovecs used for each writev call */
101 #define REDIS_WRITEV_IOVEC_COUNT 256
102
103 /* Hash table parameters */
104 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
105
106 /* Command flags */
107 #define REDIS_CMD_BULK 1 /* Bulk write command */
108 #define REDIS_CMD_INLINE 2 /* Inline command */
109 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
110 this flags will return an error when the 'maxmemory' option is set in the
111 config file and the server is using more than maxmemory bytes of memory.
112 In short this commands are denied on low memory conditions. */
113 #define REDIS_CMD_DENYOOM 4
114
115 /* Object types */
116 #define REDIS_STRING 0
117 #define REDIS_LIST 1
118 #define REDIS_SET 2
119 #define REDIS_ZSET 3
120 #define REDIS_HASH 4
121
122 /* Objects encoding. Some kind of objects like Strings and Hashes can be
123 * internally represented in multiple ways. The 'encoding' field of the object
124 * is set to one of this fields for this object. */
125 #define REDIS_ENCODING_RAW 0 /* Raw representation */
126 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
127 #define REDIS_ENCODING_ZIPMAP 2 /* Encoded as zipmap */
128 #define REDIS_ENCODING_HT 3 /* Encoded as an hash table */
129
130 static char* strencoding[] = {
131 "raw", "int", "zipmap", "hashtable"
132 };
133
134 /* Object types only used for dumping to disk */
135 #define REDIS_EXPIRETIME 253
136 #define REDIS_SELECTDB 254
137 #define REDIS_EOF 255
138
139 /* Defines related to the dump file format. To store 32 bits lengths for short
140 * keys requires a lot of space, so we check the most significant 2 bits of
141 * the first byte to interpreter the length:
142 *
143 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
144 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
145 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
146 * 11|000000 this means: specially encoded object will follow. The six bits
147 * number specify the kind of object that follows.
148 * See the REDIS_RDB_ENC_* defines.
149 *
150 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
151 * values, will fit inside. */
152 #define REDIS_RDB_6BITLEN 0
153 #define REDIS_RDB_14BITLEN 1
154 #define REDIS_RDB_32BITLEN 2
155 #define REDIS_RDB_ENCVAL 3
156 #define REDIS_RDB_LENERR UINT_MAX
157
158 /* When a length of a string object stored on disk has the first two bits
159 * set, the remaining two bits specify a special encoding for the object
160 * accordingly to the following defines: */
161 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
162 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
163 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
164 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
165
166 /* Virtual memory object->where field. */
167 #define REDIS_VM_MEMORY 0 /* The object is on memory */
168 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
169 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
170 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
171
172 /* Virtual memory static configuration stuff.
173 * Check vmFindContiguousPages() to know more about this magic numbers. */
174 #define REDIS_VM_MAX_NEAR_PAGES 65536
175 #define REDIS_VM_MAX_RANDOM_JUMP 4096
176 #define REDIS_VM_MAX_THREADS 32
177 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
178 /* The following is the *percentage* of completed I/O jobs to process when the
179 * handelr is called. While Virtual Memory I/O operations are performed by
180 * threads, this operations must be processed by the main thread when completed
181 * in order to take effect. */
182 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
183
184 /* Client flags */
185 #define REDIS_SLAVE 1 /* This client is a slave server */
186 #define REDIS_MASTER 2 /* This client is a master server */
187 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
188 #define REDIS_MULTI 8 /* This client is in a MULTI context */
189 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
190 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
191
192 /* Slave replication state - slave side */
193 #define REDIS_REPL_NONE 0 /* No active replication */
194 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
195 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
196
197 /* Slave replication state - from the point of view of master
198 * Note that in SEND_BULK and ONLINE state the slave receives new updates
199 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
200 * to start the next background saving in order to send updates to it. */
201 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
202 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
203 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
204 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
205
206 /* List related stuff */
207 #define REDIS_HEAD 0
208 #define REDIS_TAIL 1
209
210 /* Sort operations */
211 #define REDIS_SORT_GET 0
212 #define REDIS_SORT_ASC 1
213 #define REDIS_SORT_DESC 2
214 #define REDIS_SORTKEY_MAX 1024
215
216 /* Log levels */
217 #define REDIS_DEBUG 0
218 #define REDIS_VERBOSE 1
219 #define REDIS_NOTICE 2
220 #define REDIS_WARNING 3
221
222 /* Anti-warning macro... */
223 #define REDIS_NOTUSED(V) ((void) V)
224
225 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
226 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
227
228 /* Append only defines */
229 #define APPENDFSYNC_NO 0
230 #define APPENDFSYNC_ALWAYS 1
231 #define APPENDFSYNC_EVERYSEC 2
232
233 /* Hashes related defaults */
234 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
235 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
236
237 /* We can print the stacktrace, so our assert is defined this way: */
238 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
239 static void _redisAssert(char *estr, char *file, int line);
240
241 /*================================= Data types ============================== */
242
243 /* A redis object, that is a type able to hold a string / list / set */
244
245 /* The VM object structure */
246 struct redisObjectVM {
247 off_t page; /* the page at witch the object is stored on disk */
248 off_t usedpages; /* number of pages used on disk */
249 time_t atime; /* Last access time */
250 } vm;
251
252 /* The actual Redis Object */
253 typedef struct redisObject {
254 void *ptr;
255 unsigned char type;
256 unsigned char encoding;
257 unsigned char storage; /* If this object is a key, where is the value?
258 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
259 unsigned char vtype; /* If this object is a key, and value is swapped out,
260 * this is the type of the swapped out object. */
261 int refcount;
262 /* VM fields, this are only allocated if VM is active, otherwise the
263 * object allocation function will just allocate
264 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
265 * Redis without VM active will not have any overhead. */
266 struct redisObjectVM vm;
267 } robj;
268
269 /* Macro used to initalize a Redis object allocated on the stack.
270 * Note that this macro is taken near the structure definition to make sure
271 * we'll update it when the structure is changed, to avoid bugs like
272 * bug #85 introduced exactly in this way. */
273 #define initStaticStringObject(_var,_ptr) do { \
274 _var.refcount = 1; \
275 _var.type = REDIS_STRING; \
276 _var.encoding = REDIS_ENCODING_RAW; \
277 _var.ptr = _ptr; \
278 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
279 } while(0);
280
281 typedef struct redisDb {
282 dict *dict; /* The keyspace for this DB */
283 dict *expires; /* Timeout of keys with a timeout set */
284 dict *blockingkeys; /* Keys with clients waiting for data (BLPOP) */
285 dict *io_keys; /* Keys with clients waiting for VM I/O */
286 int id;
287 } redisDb;
288
289 /* Client MULTI/EXEC state */
290 typedef struct multiCmd {
291 robj **argv;
292 int argc;
293 struct redisCommand *cmd;
294 } multiCmd;
295
296 typedef struct multiState {
297 multiCmd *commands; /* Array of MULTI commands */
298 int count; /* Total number of MULTI commands */
299 } multiState;
300
301 /* With multiplexing we need to take per-clinet state.
302 * Clients are taken in a liked list. */
303 typedef struct redisClient {
304 int fd;
305 redisDb *db;
306 int dictid;
307 sds querybuf;
308 robj **argv, **mbargv;
309 int argc, mbargc;
310 int bulklen; /* bulk read len. -1 if not in bulk read mode */
311 int multibulk; /* multi bulk command format active */
312 list *reply;
313 int sentlen;
314 time_t lastinteraction; /* time of the last interaction, used for timeout */
315 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
316 int slaveseldb; /* slave selected db, if this client is a slave */
317 int authenticated; /* when requirepass is non-NULL */
318 int replstate; /* replication state if this is a slave */
319 int repldbfd; /* replication DB file descriptor */
320 long repldboff; /* replication DB file offset */
321 off_t repldbsize; /* replication DB file size */
322 multiState mstate; /* MULTI/EXEC state */
323 robj **blockingkeys; /* The key we are waiting to terminate a blocking
324 * operation such as BLPOP. Otherwise NULL. */
325 int blockingkeysnum; /* Number of blocking keys */
326 time_t blockingto; /* Blocking operation timeout. If UNIX current time
327 * is >= blockingto then the operation timed out. */
328 list *io_keys; /* Keys this client is waiting to be loaded from the
329 * swap file in order to continue. */
330 } redisClient;
331
332 struct saveparam {
333 time_t seconds;
334 int changes;
335 };
336
337 /* Global server state structure */
338 struct redisServer {
339 int port;
340 int fd;
341 redisDb *db;
342 dict *sharingpool; /* Poll used for object sharing */
343 unsigned int sharingpoolsize;
344 long long dirty; /* changes to DB from the last save */
345 list *clients;
346 list *slaves, *monitors;
347 char neterr[ANET_ERR_LEN];
348 aeEventLoop *el;
349 int cronloops; /* number of times the cron function run */
350 list *objfreelist; /* A list of freed objects to avoid malloc() */
351 time_t lastsave; /* Unix time of last save succeeede */
352 /* Fields used only for stats */
353 time_t stat_starttime; /* server start time */
354 long long stat_numcommands; /* number of processed commands */
355 long long stat_numconnections; /* number of connections received */
356 long long stat_expiredkeys; /* number of expired keys */
357 /* Configuration */
358 int verbosity;
359 int glueoutputbuf;
360 int maxidletime;
361 int dbnum;
362 int daemonize;
363 int appendonly;
364 int appendfsync;
365 time_t lastfsync;
366 int appendfd;
367 int appendseldb;
368 char *pidfile;
369 pid_t bgsavechildpid;
370 pid_t bgrewritechildpid;
371 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
372 struct saveparam *saveparams;
373 int saveparamslen;
374 char *logfile;
375 char *bindaddr;
376 char *dbfilename;
377 char *appendfilename;
378 char *requirepass;
379 int shareobjects;
380 int rdbcompression;
381 /* Replication related */
382 int isslave;
383 char *masterauth;
384 char *masterhost;
385 int masterport;
386 redisClient *master; /* client that is master for this slave */
387 int replstate;
388 unsigned int maxclients;
389 unsigned long long maxmemory;
390 unsigned int blpop_blocked_clients;
391 unsigned int vm_blocked_clients;
392 /* Sort parameters - qsort_r() is only available under BSD so we
393 * have to take this state global, in order to pass it to sortCompare() */
394 int sort_desc;
395 int sort_alpha;
396 int sort_bypattern;
397 /* Virtual memory configuration */
398 int vm_enabled;
399 char *vm_swap_file;
400 off_t vm_page_size;
401 off_t vm_pages;
402 unsigned long long vm_max_memory;
403 /* Hashes config */
404 size_t hash_max_zipmap_entries;
405 size_t hash_max_zipmap_value;
406 /* Virtual memory state */
407 FILE *vm_fp;
408 int vm_fd;
409 off_t vm_next_page; /* Next probably empty page */
410 off_t vm_near_pages; /* Number of pages allocated sequentially */
411 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
412 time_t unixtime; /* Unix time sampled every second. */
413 /* Virtual memory I/O threads stuff */
414 /* An I/O thread process an element taken from the io_jobs queue and
415 * put the result of the operation in the io_done list. While the
416 * job is being processed, it's put on io_processing queue. */
417 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
418 list *io_processing; /* List of VM I/O jobs being processed */
419 list *io_processed; /* List of VM I/O jobs already processed */
420 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
421 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
422 pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
423 pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
424 pthread_attr_t io_threads_attr; /* attributes for threads creation */
425 int io_active_threads; /* Number of running I/O threads */
426 int vm_max_threads; /* Max number of I/O threads running at the same time */
427 /* Our main thread is blocked on the event loop, locking for sockets ready
428 * to be read or written, so when a threaded I/O operation is ready to be
429 * processed by the main thread, the I/O thread will use a unix pipe to
430 * awake the main thread. The followings are the two pipe FDs. */
431 int io_ready_pipe_read;
432 int io_ready_pipe_write;
433 /* Virtual memory stats */
434 unsigned long long vm_stats_used_pages;
435 unsigned long long vm_stats_swapped_objects;
436 unsigned long long vm_stats_swapouts;
437 unsigned long long vm_stats_swapins;
438 FILE *devnull;
439 };
440
441 typedef void redisCommandProc(redisClient *c);
442 struct redisCommand {
443 char *name;
444 redisCommandProc *proc;
445 int arity;
446 int flags;
447 /* Use a function to determine which keys need to be loaded
448 * in the background prior to executing this command. Takes precedence
449 * over vm_firstkey and others, ignored when NULL */
450 redisCommandProc *vm_preload_proc;
451 /* What keys should be loaded in background when calling this command? */
452 int vm_firstkey; /* The first argument that's a key (0 = no keys) */
453 int vm_lastkey; /* THe last argument that's a key */
454 int vm_keystep; /* The step between first and last key */
455 };
456
457 struct redisFunctionSym {
458 char *name;
459 unsigned long pointer;
460 };
461
462 typedef struct _redisSortObject {
463 robj *obj;
464 union {
465 double score;
466 robj *cmpobj;
467 } u;
468 } redisSortObject;
469
470 typedef struct _redisSortOperation {
471 int type;
472 robj *pattern;
473 } redisSortOperation;
474
475 /* ZSETs use a specialized version of Skiplists */
476
477 typedef struct zskiplistNode {
478 struct zskiplistNode **forward;
479 struct zskiplistNode *backward;
480 unsigned int *span;
481 double score;
482 robj *obj;
483 } zskiplistNode;
484
485 typedef struct zskiplist {
486 struct zskiplistNode *header, *tail;
487 unsigned long length;
488 int level;
489 } zskiplist;
490
491 typedef struct zset {
492 dict *dict;
493 zskiplist *zsl;
494 } zset;
495
496 /* Our shared "common" objects */
497
498 struct sharedObjectsStruct {
499 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
500 *colon, *nullbulk, *nullmultibulk, *queued,
501 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
502 *outofrangeerr, *plus,
503 *select0, *select1, *select2, *select3, *select4,
504 *select5, *select6, *select7, *select8, *select9;
505 } shared;
506
507 /* Global vars that are actally used as constants. The following double
508 * values are used for double on-disk serialization, and are initialized
509 * at runtime to avoid strange compiler optimizations. */
510
511 static double R_Zero, R_PosInf, R_NegInf, R_Nan;
512
513 /* VM threaded I/O request message */
514 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
515 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
516 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
517 typedef struct iojob {
518 int type; /* Request type, REDIS_IOJOB_* */
519 redisDb *db;/* Redis database */
520 robj *key; /* This I/O request is about swapping this key */
521 robj *val; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
522 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
523 off_t page; /* Swap page where to read/write the object */
524 off_t pages; /* Swap pages needed to safe object. PREPARE_SWAP return val */
525 int canceled; /* True if this command was canceled by blocking side of VM */
526 pthread_t thread; /* ID of the thread processing this entry */
527 } iojob;
528
529 /*================================ Prototypes =============================== */
530
531 static void freeStringObject(robj *o);
532 static void freeListObject(robj *o);
533 static void freeSetObject(robj *o);
534 static void decrRefCount(void *o);
535 static robj *createObject(int type, void *ptr);
536 static void freeClient(redisClient *c);
537 static int rdbLoad(char *filename);
538 static void addReply(redisClient *c, robj *obj);
539 static void addReplySds(redisClient *c, sds s);
540 static void incrRefCount(robj *o);
541 static int rdbSaveBackground(char *filename);
542 static robj *createStringObject(char *ptr, size_t len);
543 static robj *dupStringObject(robj *o);
544 static void replicationFeedSlaves(list *slaves, struct redisCommand *cmd, int dictid, robj **argv, int argc);
545 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
546 static int syncWithMaster(void);
547 static robj *tryObjectSharing(robj *o);
548 static int tryObjectEncoding(robj *o);
549 static robj *getDecodedObject(robj *o);
550 static int removeExpire(redisDb *db, robj *key);
551 static int expireIfNeeded(redisDb *db, robj *key);
552 static int deleteIfVolatile(redisDb *db, robj *key);
553 static int deleteIfSwapped(redisDb *db, robj *key);
554 static int deleteKey(redisDb *db, robj *key);
555 static time_t getExpire(redisDb *db, robj *key);
556 static int setExpire(redisDb *db, robj *key, time_t when);
557 static void updateSlavesWaitingBgsave(int bgsaveerr);
558 static void freeMemoryIfNeeded(void);
559 static int processCommand(redisClient *c);
560 static void setupSigSegvAction(void);
561 static void rdbRemoveTempFile(pid_t childpid);
562 static void aofRemoveTempFile(pid_t childpid);
563 static size_t stringObjectLen(robj *o);
564 static void processInputBuffer(redisClient *c);
565 static zskiplist *zslCreate(void);
566 static void zslFree(zskiplist *zsl);
567 static void zslInsert(zskiplist *zsl, double score, robj *obj);
568 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
569 static void initClientMultiState(redisClient *c);
570 static void freeClientMultiState(redisClient *c);
571 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
572 static void unblockClientWaitingData(redisClient *c);
573 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
574 static void vmInit(void);
575 static void vmMarkPagesFree(off_t page, off_t count);
576 static robj *vmLoadObject(robj *key);
577 static robj *vmPreviewObject(robj *key);
578 static int vmSwapOneObjectBlocking(void);
579 static int vmSwapOneObjectThreaded(void);
580 static int vmCanSwapOut(void);
581 static int tryFreeOneObjectFromFreelist(void);
582 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
583 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
584 static void vmCancelThreadedIOJob(robj *o);
585 static void lockThreadedIO(void);
586 static void unlockThreadedIO(void);
587 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
588 static void freeIOJob(iojob *j);
589 static void queueIOJob(iojob *j);
590 static int vmWriteObjectOnSwap(robj *o, off_t page);
591 static robj *vmReadObjectFromSwap(off_t page, int type);
592 static void waitEmptyIOJobsQueue(void);
593 static void vmReopenSwapFile(void);
594 static int vmFreePage(off_t page);
595 static void zunionInterBlockClientOnSwappedKeys(redisClient *c);
596 static int blockClientOnSwappedKeys(struct redisCommand *cmd, redisClient *c);
597 static int dontWaitForSwappedKey(redisClient *c, robj *key);
598 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
599 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
600 static struct redisCommand *lookupCommand(char *name);
601 static void call(redisClient *c, struct redisCommand *cmd);
602 static void resetClient(redisClient *c);
603 static void convertToRealHash(robj *o);
604
605 static void authCommand(redisClient *c);
606 static void pingCommand(redisClient *c);
607 static void echoCommand(redisClient *c);
608 static void setCommand(redisClient *c);
609 static void setnxCommand(redisClient *c);
610 static void getCommand(redisClient *c);
611 static void delCommand(redisClient *c);
612 static void existsCommand(redisClient *c);
613 static void incrCommand(redisClient *c);
614 static void decrCommand(redisClient *c);
615 static void incrbyCommand(redisClient *c);
616 static void decrbyCommand(redisClient *c);
617 static void selectCommand(redisClient *c);
618 static void randomkeyCommand(redisClient *c);
619 static void keysCommand(redisClient *c);
620 static void dbsizeCommand(redisClient *c);
621 static void lastsaveCommand(redisClient *c);
622 static void saveCommand(redisClient *c);
623 static void bgsaveCommand(redisClient *c);
624 static void bgrewriteaofCommand(redisClient *c);
625 static void shutdownCommand(redisClient *c);
626 static void moveCommand(redisClient *c);
627 static void renameCommand(redisClient *c);
628 static void renamenxCommand(redisClient *c);
629 static void lpushCommand(redisClient *c);
630 static void rpushCommand(redisClient *c);
631 static void lpopCommand(redisClient *c);
632 static void rpopCommand(redisClient *c);
633 static void llenCommand(redisClient *c);
634 static void lindexCommand(redisClient *c);
635 static void lrangeCommand(redisClient *c);
636 static void ltrimCommand(redisClient *c);
637 static void typeCommand(redisClient *c);
638 static void lsetCommand(redisClient *c);
639 static void saddCommand(redisClient *c);
640 static void sremCommand(redisClient *c);
641 static void smoveCommand(redisClient *c);
642 static void sismemberCommand(redisClient *c);
643 static void scardCommand(redisClient *c);
644 static void spopCommand(redisClient *c);
645 static void srandmemberCommand(redisClient *c);
646 static void sinterCommand(redisClient *c);
647 static void sinterstoreCommand(redisClient *c);
648 static void sunionCommand(redisClient *c);
649 static void sunionstoreCommand(redisClient *c);
650 static void sdiffCommand(redisClient *c);
651 static void sdiffstoreCommand(redisClient *c);
652 static void syncCommand(redisClient *c);
653 static void flushdbCommand(redisClient *c);
654 static void flushallCommand(redisClient *c);
655 static void sortCommand(redisClient *c);
656 static void lremCommand(redisClient *c);
657 static void rpoplpushcommand(redisClient *c);
658 static void infoCommand(redisClient *c);
659 static void mgetCommand(redisClient *c);
660 static void monitorCommand(redisClient *c);
661 static void expireCommand(redisClient *c);
662 static void expireatCommand(redisClient *c);
663 static void getsetCommand(redisClient *c);
664 static void ttlCommand(redisClient *c);
665 static void slaveofCommand(redisClient *c);
666 static void debugCommand(redisClient *c);
667 static void msetCommand(redisClient *c);
668 static void msetnxCommand(redisClient *c);
669 static void zaddCommand(redisClient *c);
670 static void zincrbyCommand(redisClient *c);
671 static void zrangeCommand(redisClient *c);
672 static void zrangebyscoreCommand(redisClient *c);
673 static void zcountCommand(redisClient *c);
674 static void zrevrangeCommand(redisClient *c);
675 static void zcardCommand(redisClient *c);
676 static void zremCommand(redisClient *c);
677 static void zscoreCommand(redisClient *c);
678 static void zremrangebyscoreCommand(redisClient *c);
679 static void multiCommand(redisClient *c);
680 static void execCommand(redisClient *c);
681 static void discardCommand(redisClient *c);
682 static void blpopCommand(redisClient *c);
683 static void brpopCommand(redisClient *c);
684 static void appendCommand(redisClient *c);
685 static void substrCommand(redisClient *c);
686 static void zrankCommand(redisClient *c);
687 static void zrevrankCommand(redisClient *c);
688 static void hsetCommand(redisClient *c);
689 static void hgetCommand(redisClient *c);
690 static void hdelCommand(redisClient *c);
691 static void hlenCommand(redisClient *c);
692 static void zremrangebyrankCommand(redisClient *c);
693 static void zunionCommand(redisClient *c);
694 static void zinterCommand(redisClient *c);
695 static void hkeysCommand(redisClient *c);
696 static void hvalsCommand(redisClient *c);
697 static void hgetallCommand(redisClient *c);
698 static void hexistsCommand(redisClient *c);
699
700 /*================================= Globals ================================= */
701
702 /* Global vars */
703 static struct redisServer server; /* server global state */
704 static struct redisCommand cmdTable[] = {
705 {"get",getCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
706 {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
707 {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
708 {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
709 {"substr",substrCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
710 {"del",delCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
711 {"exists",existsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
712 {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
713 {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
714 {"mget",mgetCommand,-2,REDIS_CMD_INLINE,NULL,1,-1,1},
715 {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
716 {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
717 {"rpop",rpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
718 {"lpop",lpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
719 {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
720 {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
721 {"llen",llenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
722 {"lindex",lindexCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
723 {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
724 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
725 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
726 {"lrem",lremCommand,4,REDIS_CMD_BULK,NULL,1,1,1},
727 {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,2,1},
728 {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
729 {"srem",sremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
730 {"smove",smoveCommand,4,REDIS_CMD_BULK,NULL,1,2,1},
731 {"sismember",sismemberCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
732 {"scard",scardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
733 {"spop",spopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
734 {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
735 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
736 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
737 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
738 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
739 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
740 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
741 {"smembers",sinterCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
742 {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
743 {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
744 {"zrem",zremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
745 {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
746 {"zremrangebyrank",zremrangebyrankCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
747 {"zunion",zunionCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
748 {"zinter",zinterCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
749 {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
750 {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
751 {"zcount",zcountCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
752 {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
753 {"zcard",zcardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
754 {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
755 {"zrank",zrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
756 {"zrevrank",zrevrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
757 {"hset",hsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
758 {"hget",hgetCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
759 {"hdel",hdelCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
760 {"hlen",hlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
761 {"hkeys",hkeysCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
762 {"hvals",hvalsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
763 {"hgetall",hgetallCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
764 {"hexists",hexistsCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
765 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
766 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
767 {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
768 {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
769 {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
770 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
771 {"select",selectCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
772 {"move",moveCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
773 {"rename",renameCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
774 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
775 {"expire",expireCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
776 {"expireat",expireatCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
777 {"keys",keysCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
778 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
779 {"auth",authCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
780 {"ping",pingCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
781 {"echo",echoCommand,2,REDIS_CMD_BULK,NULL,0,0,0},
782 {"save",saveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
783 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
784 {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
785 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
786 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
787 {"type",typeCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
788 {"multi",multiCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
789 {"exec",execCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
790 {"discard",discardCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
791 {"sync",syncCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
792 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
793 {"flushall",flushallCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
794 {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
795 {"info",infoCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
796 {"monitor",monitorCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
797 {"ttl",ttlCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
798 {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
799 {"debug",debugCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
800 {NULL,NULL,0,0,NULL,0,0,0}
801 };
802
803 static void usage();
804
805 /*============================ Utility functions ============================ */
806
807 /* Glob-style pattern matching. */
808 int stringmatchlen(const char *pattern, int patternLen,
809 const char *string, int stringLen, int nocase)
810 {
811 while(patternLen) {
812 switch(pattern[0]) {
813 case '*':
814 while (pattern[1] == '*') {
815 pattern++;
816 patternLen--;
817 }
818 if (patternLen == 1)
819 return 1; /* match */
820 while(stringLen) {
821 if (stringmatchlen(pattern+1, patternLen-1,
822 string, stringLen, nocase))
823 return 1; /* match */
824 string++;
825 stringLen--;
826 }
827 return 0; /* no match */
828 break;
829 case '?':
830 if (stringLen == 0)
831 return 0; /* no match */
832 string++;
833 stringLen--;
834 break;
835 case '[':
836 {
837 int not, match;
838
839 pattern++;
840 patternLen--;
841 not = pattern[0] == '^';
842 if (not) {
843 pattern++;
844 patternLen--;
845 }
846 match = 0;
847 while(1) {
848 if (pattern[0] == '\\') {
849 pattern++;
850 patternLen--;
851 if (pattern[0] == string[0])
852 match = 1;
853 } else if (pattern[0] == ']') {
854 break;
855 } else if (patternLen == 0) {
856 pattern--;
857 patternLen++;
858 break;
859 } else if (pattern[1] == '-' && patternLen >= 3) {
860 int start = pattern[0];
861 int end = pattern[2];
862 int c = string[0];
863 if (start > end) {
864 int t = start;
865 start = end;
866 end = t;
867 }
868 if (nocase) {
869 start = tolower(start);
870 end = tolower(end);
871 c = tolower(c);
872 }
873 pattern += 2;
874 patternLen -= 2;
875 if (c >= start && c <= end)
876 match = 1;
877 } else {
878 if (!nocase) {
879 if (pattern[0] == string[0])
880 match = 1;
881 } else {
882 if (tolower((int)pattern[0]) == tolower((int)string[0]))
883 match = 1;
884 }
885 }
886 pattern++;
887 patternLen--;
888 }
889 if (not)
890 match = !match;
891 if (!match)
892 return 0; /* no match */
893 string++;
894 stringLen--;
895 break;
896 }
897 case '\\':
898 if (patternLen >= 2) {
899 pattern++;
900 patternLen--;
901 }
902 /* fall through */
903 default:
904 if (!nocase) {
905 if (pattern[0] != string[0])
906 return 0; /* no match */
907 } else {
908 if (tolower((int)pattern[0]) != tolower((int)string[0]))
909 return 0; /* no match */
910 }
911 string++;
912 stringLen--;
913 break;
914 }
915 pattern++;
916 patternLen--;
917 if (stringLen == 0) {
918 while(*pattern == '*') {
919 pattern++;
920 patternLen--;
921 }
922 break;
923 }
924 }
925 if (patternLen == 0 && stringLen == 0)
926 return 1;
927 return 0;
928 }
929
930 static void redisLog(int level, const char *fmt, ...) {
931 va_list ap;
932 FILE *fp;
933
934 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
935 if (!fp) return;
936
937 va_start(ap, fmt);
938 if (level >= server.verbosity) {
939 char *c = ".-*#";
940 char buf[64];
941 time_t now;
942
943 now = time(NULL);
944 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
945 fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
946 vfprintf(fp, fmt, ap);
947 fprintf(fp,"\n");
948 fflush(fp);
949 }
950 va_end(ap);
951
952 if (server.logfile) fclose(fp);
953 }
954
955 /*====================== Hash table type implementation ==================== */
956
957 /* This is an hash table type that uses the SDS dynamic strings libary as
958 * keys and radis objects as values (objects can hold SDS strings,
959 * lists, sets). */
960
961 static void dictVanillaFree(void *privdata, void *val)
962 {
963 DICT_NOTUSED(privdata);
964 zfree(val);
965 }
966
967 static void dictListDestructor(void *privdata, void *val)
968 {
969 DICT_NOTUSED(privdata);
970 listRelease((list*)val);
971 }
972
973 static int sdsDictKeyCompare(void *privdata, const void *key1,
974 const void *key2)
975 {
976 int l1,l2;
977 DICT_NOTUSED(privdata);
978
979 l1 = sdslen((sds)key1);
980 l2 = sdslen((sds)key2);
981 if (l1 != l2) return 0;
982 return memcmp(key1, key2, l1) == 0;
983 }
984
985 static void dictRedisObjectDestructor(void *privdata, void *val)
986 {
987 DICT_NOTUSED(privdata);
988
989 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
990 decrRefCount(val);
991 }
992
993 static int dictObjKeyCompare(void *privdata, const void *key1,
994 const void *key2)
995 {
996 const robj *o1 = key1, *o2 = key2;
997 return sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
998 }
999
1000 static unsigned int dictObjHash(const void *key) {
1001 const robj *o = key;
1002 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1003 }
1004
1005 static int dictEncObjKeyCompare(void *privdata, const void *key1,
1006 const void *key2)
1007 {
1008 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
1009 int cmp;
1010
1011 if (o1->encoding == REDIS_ENCODING_INT &&
1012 o2->encoding == REDIS_ENCODING_INT &&
1013 o1->ptr == o2->ptr) return 1;
1014
1015 o1 = getDecodedObject(o1);
1016 o2 = getDecodedObject(o2);
1017 cmp = sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1018 decrRefCount(o1);
1019 decrRefCount(o2);
1020 return cmp;
1021 }
1022
1023 static unsigned int dictEncObjHash(const void *key) {
1024 robj *o = (robj*) key;
1025
1026 if (o->encoding == REDIS_ENCODING_RAW) {
1027 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1028 } else {
1029 if (o->encoding == REDIS_ENCODING_INT) {
1030 char buf[32];
1031 int len;
1032
1033 len = snprintf(buf,32,"%ld",(long)o->ptr);
1034 return dictGenHashFunction((unsigned char*)buf, len);
1035 } else {
1036 unsigned int hash;
1037
1038 o = getDecodedObject(o);
1039 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1040 decrRefCount(o);
1041 return hash;
1042 }
1043 }
1044 }
1045
1046 /* Sets type and expires */
1047 static dictType setDictType = {
1048 dictEncObjHash, /* hash function */
1049 NULL, /* key dup */
1050 NULL, /* val dup */
1051 dictEncObjKeyCompare, /* key compare */
1052 dictRedisObjectDestructor, /* key destructor */
1053 NULL /* val destructor */
1054 };
1055
1056 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1057 static dictType zsetDictType = {
1058 dictEncObjHash, /* hash function */
1059 NULL, /* key dup */
1060 NULL, /* val dup */
1061 dictEncObjKeyCompare, /* key compare */
1062 dictRedisObjectDestructor, /* key destructor */
1063 dictVanillaFree /* val destructor of malloc(sizeof(double)) */
1064 };
1065
1066 /* Db->dict */
1067 static dictType dbDictType = {
1068 dictObjHash, /* hash function */
1069 NULL, /* key dup */
1070 NULL, /* val dup */
1071 dictObjKeyCompare, /* key compare */
1072 dictRedisObjectDestructor, /* key destructor */
1073 dictRedisObjectDestructor /* val destructor */
1074 };
1075
1076 /* Db->expires */
1077 static dictType keyptrDictType = {
1078 dictObjHash, /* hash function */
1079 NULL, /* key dup */
1080 NULL, /* val dup */
1081 dictObjKeyCompare, /* key compare */
1082 dictRedisObjectDestructor, /* key destructor */
1083 NULL /* val destructor */
1084 };
1085
1086 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1087 static dictType hashDictType = {
1088 dictEncObjHash, /* hash function */
1089 NULL, /* key dup */
1090 NULL, /* val dup */
1091 dictEncObjKeyCompare, /* key compare */
1092 dictRedisObjectDestructor, /* key destructor */
1093 dictRedisObjectDestructor /* val destructor */
1094 };
1095
1096 /* Keylist hash table type has unencoded redis objects as keys and
1097 * lists as values. It's used for blocking operations (BLPOP) and to
1098 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1099 static dictType keylistDictType = {
1100 dictObjHash, /* hash function */
1101 NULL, /* key dup */
1102 NULL, /* val dup */
1103 dictObjKeyCompare, /* key compare */
1104 dictRedisObjectDestructor, /* key destructor */
1105 dictListDestructor /* val destructor */
1106 };
1107
1108 static void version();
1109
1110 /* ========================= Random utility functions ======================= */
1111
1112 /* Redis generally does not try to recover from out of memory conditions
1113 * when allocating objects or strings, it is not clear if it will be possible
1114 * to report this condition to the client since the networking layer itself
1115 * is based on heap allocation for send buffers, so we simply abort.
1116 * At least the code will be simpler to read... */
1117 static void oom(const char *msg) {
1118 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
1119 sleep(1);
1120 abort();
1121 }
1122
1123 /* ====================== Redis server networking stuff ===================== */
1124 static void closeTimedoutClients(void) {
1125 redisClient *c;
1126 listNode *ln;
1127 time_t now = time(NULL);
1128 listIter li;
1129
1130 listRewind(server.clients,&li);
1131 while ((ln = listNext(&li)) != NULL) {
1132 c = listNodeValue(ln);
1133 if (server.maxidletime &&
1134 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
1135 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
1136 (now - c->lastinteraction > server.maxidletime))
1137 {
1138 redisLog(REDIS_VERBOSE,"Closing idle client");
1139 freeClient(c);
1140 } else if (c->flags & REDIS_BLOCKED) {
1141 if (c->blockingto != 0 && c->blockingto < now) {
1142 addReply(c,shared.nullmultibulk);
1143 unblockClientWaitingData(c);
1144 }
1145 }
1146 }
1147 }
1148
1149 static int htNeedsResize(dict *dict) {
1150 long long size, used;
1151
1152 size = dictSlots(dict);
1153 used = dictSize(dict);
1154 return (size && used && size > DICT_HT_INITIAL_SIZE &&
1155 (used*100/size < REDIS_HT_MINFILL));
1156 }
1157
1158 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1159 * we resize the hash table to save memory */
1160 static void tryResizeHashTables(void) {
1161 int j;
1162
1163 for (j = 0; j < server.dbnum; j++) {
1164 if (htNeedsResize(server.db[j].dict)) {
1165 redisLog(REDIS_VERBOSE,"The hash table %d is too sparse, resize it...",j);
1166 dictResize(server.db[j].dict);
1167 redisLog(REDIS_VERBOSE,"Hash table %d resized.",j);
1168 }
1169 if (htNeedsResize(server.db[j].expires))
1170 dictResize(server.db[j].expires);
1171 }
1172 }
1173
1174 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1175 void backgroundSaveDoneHandler(int statloc) {
1176 int exitcode = WEXITSTATUS(statloc);
1177 int bysignal = WIFSIGNALED(statloc);
1178
1179 if (!bysignal && exitcode == 0) {
1180 redisLog(REDIS_NOTICE,
1181 "Background saving terminated with success");
1182 server.dirty = 0;
1183 server.lastsave = time(NULL);
1184 } else if (!bysignal && exitcode != 0) {
1185 redisLog(REDIS_WARNING, "Background saving error");
1186 } else {
1187 redisLog(REDIS_WARNING,
1188 "Background saving terminated by signal");
1189 rdbRemoveTempFile(server.bgsavechildpid);
1190 }
1191 server.bgsavechildpid = -1;
1192 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1193 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1194 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1195 }
1196
1197 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1198 * Handle this. */
1199 void backgroundRewriteDoneHandler(int statloc) {
1200 int exitcode = WEXITSTATUS(statloc);
1201 int bysignal = WIFSIGNALED(statloc);
1202
1203 if (!bysignal && exitcode == 0) {
1204 int fd;
1205 char tmpfile[256];
1206
1207 redisLog(REDIS_NOTICE,
1208 "Background append only file rewriting terminated with success");
1209 /* Now it's time to flush the differences accumulated by the parent */
1210 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
1211 fd = open(tmpfile,O_WRONLY|O_APPEND);
1212 if (fd == -1) {
1213 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
1214 goto cleanup;
1215 }
1216 /* Flush our data... */
1217 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
1218 (signed) sdslen(server.bgrewritebuf)) {
1219 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));
1220 close(fd);
1221 goto cleanup;
1222 }
1223 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
1224 /* Now our work is to rename the temp file into the stable file. And
1225 * switch the file descriptor used by the server for append only. */
1226 if (rename(tmpfile,server.appendfilename) == -1) {
1227 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
1228 close(fd);
1229 goto cleanup;
1230 }
1231 /* Mission completed... almost */
1232 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
1233 if (server.appendfd != -1) {
1234 /* If append only is actually enabled... */
1235 close(server.appendfd);
1236 server.appendfd = fd;
1237 fsync(fd);
1238 server.appendseldb = -1; /* Make sure it will issue SELECT */
1239 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
1240 } else {
1241 /* If append only is disabled we just generate a dump in this
1242 * format. Why not? */
1243 close(fd);
1244 }
1245 } else if (!bysignal && exitcode != 0) {
1246 redisLog(REDIS_WARNING, "Background append only file rewriting error");
1247 } else {
1248 redisLog(REDIS_WARNING,
1249 "Background append only file rewriting terminated by signal");
1250 }
1251 cleanup:
1252 sdsfree(server.bgrewritebuf);
1253 server.bgrewritebuf = sdsempty();
1254 aofRemoveTempFile(server.bgrewritechildpid);
1255 server.bgrewritechildpid = -1;
1256 }
1257
1258 static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
1259 int j, loops = server.cronloops++;
1260 REDIS_NOTUSED(eventLoop);
1261 REDIS_NOTUSED(id);
1262 REDIS_NOTUSED(clientData);
1263
1264 /* We take a cached value of the unix time in the global state because
1265 * with virtual memory and aging there is to store the current time
1266 * in objects at every object access, and accuracy is not needed.
1267 * To access a global var is faster than calling time(NULL) */
1268 server.unixtime = time(NULL);
1269
1270 /* Show some info about non-empty databases */
1271 for (j = 0; j < server.dbnum; j++) {
1272 long long size, used, vkeys;
1273
1274 size = dictSlots(server.db[j].dict);
1275 used = dictSize(server.db[j].dict);
1276 vkeys = dictSize(server.db[j].expires);
1277 if (!(loops % 50) && (used || vkeys)) {
1278 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
1279 /* dictPrintStats(server.dict); */
1280 }
1281 }
1282
1283 /* We don't want to resize the hash tables while a bacground saving
1284 * is in progress: the saving child is created using fork() that is
1285 * implemented with a copy-on-write semantic in most modern systems, so
1286 * if we resize the HT while there is the saving child at work actually
1287 * a lot of memory movements in the parent will cause a lot of pages
1288 * copied. */
1289 if (server.bgsavechildpid == -1 && !(loops % 10)) tryResizeHashTables();
1290
1291 /* Show information about connected clients */
1292 if (!(loops % 50)) {
1293 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1294 listLength(server.clients)-listLength(server.slaves),
1295 listLength(server.slaves),
1296 zmalloc_used_memory(),
1297 dictSize(server.sharingpool));
1298 }
1299
1300 /* Close connections of timedout clients */
1301 if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients)
1302 closeTimedoutClients();
1303
1304 /* Check if a background saving or AOF rewrite in progress terminated */
1305 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
1306 int statloc;
1307 pid_t pid;
1308
1309 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
1310 if (pid == server.bgsavechildpid) {
1311 backgroundSaveDoneHandler(statloc);
1312 } else {
1313 backgroundRewriteDoneHandler(statloc);
1314 }
1315 }
1316 } else {
1317 /* If there is not a background saving in progress check if
1318 * we have to save now */
1319 time_t now = time(NULL);
1320 for (j = 0; j < server.saveparamslen; j++) {
1321 struct saveparam *sp = server.saveparams+j;
1322
1323 if (server.dirty >= sp->changes &&
1324 now-server.lastsave > sp->seconds) {
1325 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
1326 sp->changes, sp->seconds);
1327 rdbSaveBackground(server.dbfilename);
1328 break;
1329 }
1330 }
1331 }
1332
1333 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1334 * will use few CPU cycles if there are few expiring keys, otherwise
1335 * it will get more aggressive to avoid that too much memory is used by
1336 * keys that can be removed from the keyspace. */
1337 for (j = 0; j < server.dbnum; j++) {
1338 int expired;
1339 redisDb *db = server.db+j;
1340
1341 /* Continue to expire if at the end of the cycle more than 25%
1342 * of the keys were expired. */
1343 do {
1344 long num = dictSize(db->expires);
1345 time_t now = time(NULL);
1346
1347 expired = 0;
1348 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
1349 num = REDIS_EXPIRELOOKUPS_PER_CRON;
1350 while (num--) {
1351 dictEntry *de;
1352 time_t t;
1353
1354 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
1355 t = (time_t) dictGetEntryVal(de);
1356 if (now > t) {
1357 deleteKey(db,dictGetEntryKey(de));
1358 expired++;
1359 server.stat_expiredkeys++;
1360 }
1361 }
1362 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
1363 }
1364
1365 /* Swap a few keys on disk if we are over the memory limit and VM
1366 * is enbled. Try to free objects from the free list first. */
1367 if (vmCanSwapOut()) {
1368 while (server.vm_enabled && zmalloc_used_memory() >
1369 server.vm_max_memory)
1370 {
1371 int retval;
1372
1373 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
1374 retval = (server.vm_max_threads == 0) ?
1375 vmSwapOneObjectBlocking() :
1376 vmSwapOneObjectThreaded();
1377 if (retval == REDIS_ERR && !(loops % 300) &&
1378 zmalloc_used_memory() >
1379 (server.vm_max_memory+server.vm_max_memory/10))
1380 {
1381 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1382 }
1383 /* Note that when using threade I/O we free just one object,
1384 * because anyway when the I/O thread in charge to swap this
1385 * object out will finish, the handler of completed jobs
1386 * will try to swap more objects if we are still out of memory. */
1387 if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
1388 }
1389 }
1390
1391 /* Check if we should connect to a MASTER */
1392 if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) {
1393 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
1394 if (syncWithMaster() == REDIS_OK) {
1395 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
1396 }
1397 }
1398 return 100;
1399 }
1400
1401 /* This function gets called every time Redis is entering the
1402 * main loop of the event driven library, that is, before to sleep
1403 * for ready file descriptors. */
1404 static void beforeSleep(struct aeEventLoop *eventLoop) {
1405 REDIS_NOTUSED(eventLoop);
1406
1407 if (server.vm_enabled && listLength(server.io_ready_clients)) {
1408 listIter li;
1409 listNode *ln;
1410
1411 listRewind(server.io_ready_clients,&li);
1412 while((ln = listNext(&li))) {
1413 redisClient *c = ln->value;
1414 struct redisCommand *cmd;
1415
1416 /* Resume the client. */
1417 listDelNode(server.io_ready_clients,ln);
1418 c->flags &= (~REDIS_IO_WAIT);
1419 server.vm_blocked_clients--;
1420 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1421 readQueryFromClient, c);
1422 cmd = lookupCommand(c->argv[0]->ptr);
1423 assert(cmd != NULL);
1424 call(c,cmd);
1425 resetClient(c);
1426 /* There may be more data to process in the input buffer. */
1427 if (c->querybuf && sdslen(c->querybuf) > 0)
1428 processInputBuffer(c);
1429 }
1430 }
1431 }
1432
1433 static void createSharedObjects(void) {
1434 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
1435 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
1436 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
1437 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
1438 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
1439 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
1440 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
1441 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
1442 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
1443 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
1444 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
1445 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
1446 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1447 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
1448 "-ERR no such key\r\n"));
1449 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
1450 "-ERR syntax error\r\n"));
1451 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
1452 "-ERR source and destination objects are the same\r\n"));
1453 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
1454 "-ERR index out of range\r\n"));
1455 shared.space = createObject(REDIS_STRING,sdsnew(" "));
1456 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
1457 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
1458 shared.select0 = createStringObject("select 0\r\n",10);
1459 shared.select1 = createStringObject("select 1\r\n",10);
1460 shared.select2 = createStringObject("select 2\r\n",10);
1461 shared.select3 = createStringObject("select 3\r\n",10);
1462 shared.select4 = createStringObject("select 4\r\n",10);
1463 shared.select5 = createStringObject("select 5\r\n",10);
1464 shared.select6 = createStringObject("select 6\r\n",10);
1465 shared.select7 = createStringObject("select 7\r\n",10);
1466 shared.select8 = createStringObject("select 8\r\n",10);
1467 shared.select9 = createStringObject("select 9\r\n",10);
1468 }
1469
1470 static void appendServerSaveParams(time_t seconds, int changes) {
1471 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
1472 server.saveparams[server.saveparamslen].seconds = seconds;
1473 server.saveparams[server.saveparamslen].changes = changes;
1474 server.saveparamslen++;
1475 }
1476
1477 static void resetServerSaveParams() {
1478 zfree(server.saveparams);
1479 server.saveparams = NULL;
1480 server.saveparamslen = 0;
1481 }
1482
1483 static void initServerConfig() {
1484 server.dbnum = REDIS_DEFAULT_DBNUM;
1485 server.port = REDIS_SERVERPORT;
1486 server.verbosity = REDIS_VERBOSE;
1487 server.maxidletime = REDIS_MAXIDLETIME;
1488 server.saveparams = NULL;
1489 server.logfile = NULL; /* NULL = log on standard output */
1490 server.bindaddr = NULL;
1491 server.glueoutputbuf = 1;
1492 server.daemonize = 0;
1493 server.appendonly = 0;
1494 server.appendfsync = APPENDFSYNC_ALWAYS;
1495 server.lastfsync = time(NULL);
1496 server.appendfd = -1;
1497 server.appendseldb = -1; /* Make sure the first time will not match */
1498 server.pidfile = "/var/run/redis.pid";
1499 server.dbfilename = "dump.rdb";
1500 server.appendfilename = "appendonly.aof";
1501 server.requirepass = NULL;
1502 server.shareobjects = 0;
1503 server.rdbcompression = 1;
1504 server.sharingpoolsize = 1024;
1505 server.maxclients = 0;
1506 server.blpop_blocked_clients = 0;
1507 server.maxmemory = 0;
1508 server.vm_enabled = 0;
1509 server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
1510 server.vm_page_size = 256; /* 256 bytes per page */
1511 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
1512 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
1513 server.vm_max_threads = 4;
1514 server.vm_blocked_clients = 0;
1515 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
1516 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
1517
1518 resetServerSaveParams();
1519
1520 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1521 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1522 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1523 /* Replication related */
1524 server.isslave = 0;
1525 server.masterauth = NULL;
1526 server.masterhost = NULL;
1527 server.masterport = 6379;
1528 server.master = NULL;
1529 server.replstate = REDIS_REPL_NONE;
1530
1531 /* Double constants initialization */
1532 R_Zero = 0.0;
1533 R_PosInf = 1.0/R_Zero;
1534 R_NegInf = -1.0/R_Zero;
1535 R_Nan = R_Zero/R_Zero;
1536 }
1537
1538 static void initServer() {
1539 int j;
1540
1541 signal(SIGHUP, SIG_IGN);
1542 signal(SIGPIPE, SIG_IGN);
1543 setupSigSegvAction();
1544
1545 server.devnull = fopen("/dev/null","w");
1546 if (server.devnull == NULL) {
1547 redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr);
1548 exit(1);
1549 }
1550 server.clients = listCreate();
1551 server.slaves = listCreate();
1552 server.monitors = listCreate();
1553 server.objfreelist = listCreate();
1554 createSharedObjects();
1555 server.el = aeCreateEventLoop();
1556 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
1557 server.sharingpool = dictCreate(&setDictType,NULL);
1558 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
1559 if (server.fd == -1) {
1560 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
1561 exit(1);
1562 }
1563 for (j = 0; j < server.dbnum; j++) {
1564 server.db[j].dict = dictCreate(&dbDictType,NULL);
1565 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
1566 server.db[j].blockingkeys = dictCreate(&keylistDictType,NULL);
1567 if (server.vm_enabled)
1568 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
1569 server.db[j].id = j;
1570 }
1571 server.cronloops = 0;
1572 server.bgsavechildpid = -1;
1573 server.bgrewritechildpid = -1;
1574 server.bgrewritebuf = sdsempty();
1575 server.lastsave = time(NULL);
1576 server.dirty = 0;
1577 server.stat_numcommands = 0;
1578 server.stat_numconnections = 0;
1579 server.stat_expiredkeys = 0;
1580 server.stat_starttime = time(NULL);
1581 server.unixtime = time(NULL);
1582 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
1583 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
1584 acceptHandler, NULL) == AE_ERR) oom("creating file event");
1585
1586 if (server.appendonly) {
1587 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
1588 if (server.appendfd == -1) {
1589 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1590 strerror(errno));
1591 exit(1);
1592 }
1593 }
1594
1595 if (server.vm_enabled) vmInit();
1596 }
1597
1598 /* Empty the whole database */
1599 static long long emptyDb() {
1600 int j;
1601 long long removed = 0;
1602
1603 for (j = 0; j < server.dbnum; j++) {
1604 removed += dictSize(server.db[j].dict);
1605 dictEmpty(server.db[j].dict);
1606 dictEmpty(server.db[j].expires);
1607 }
1608 return removed;
1609 }
1610
1611 static int yesnotoi(char *s) {
1612 if (!strcasecmp(s,"yes")) return 1;
1613 else if (!strcasecmp(s,"no")) return 0;
1614 else return -1;
1615 }
1616
1617 /* I agree, this is a very rudimental way to load a configuration...
1618 will improve later if the config gets more complex */
1619 static void loadServerConfig(char *filename) {
1620 FILE *fp;
1621 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
1622 int linenum = 0;
1623 sds line = NULL;
1624 char *errormsg = "Fatal error, can't open config file '%s'";
1625 char *errorbuf = zmalloc(sizeof(char)*(strlen(errormsg)+strlen(filename)));
1626 sprintf(errorbuf, errormsg, filename);
1627
1628 if (filename[0] == '-' && filename[1] == '\0')
1629 fp = stdin;
1630 else {
1631 if ((fp = fopen(filename,"r")) == NULL) {
1632 redisLog(REDIS_WARNING, errorbuf);
1633 exit(1);
1634 }
1635 }
1636
1637 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1638 sds *argv;
1639 int argc, j;
1640
1641 linenum++;
1642 line = sdsnew(buf);
1643 line = sdstrim(line," \t\r\n");
1644
1645 /* Skip comments and blank lines*/
1646 if (line[0] == '#' || line[0] == '\0') {
1647 sdsfree(line);
1648 continue;
1649 }
1650
1651 /* Split into arguments */
1652 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
1653 sdstolower(argv[0]);
1654
1655 /* Execute config directives */
1656 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
1657 server.maxidletime = atoi(argv[1]);
1658 if (server.maxidletime < 0) {
1659 err = "Invalid timeout value"; goto loaderr;
1660 }
1661 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
1662 server.port = atoi(argv[1]);
1663 if (server.port < 1 || server.port > 65535) {
1664 err = "Invalid port"; goto loaderr;
1665 }
1666 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
1667 server.bindaddr = zstrdup(argv[1]);
1668 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
1669 int seconds = atoi(argv[1]);
1670 int changes = atoi(argv[2]);
1671 if (seconds < 1 || changes < 0) {
1672 err = "Invalid save parameters"; goto loaderr;
1673 }
1674 appendServerSaveParams(seconds,changes);
1675 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
1676 if (chdir(argv[1]) == -1) {
1677 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
1678 argv[1], strerror(errno));
1679 exit(1);
1680 }
1681 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
1682 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
1683 else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
1684 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
1685 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
1686 else {
1687 err = "Invalid log level. Must be one of debug, notice, warning";
1688 goto loaderr;
1689 }
1690 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
1691 FILE *logfp;
1692
1693 server.logfile = zstrdup(argv[1]);
1694 if (!strcasecmp(server.logfile,"stdout")) {
1695 zfree(server.logfile);
1696 server.logfile = NULL;
1697 }
1698 if (server.logfile) {
1699 /* Test if we are able to open the file. The server will not
1700 * be able to abort just for this problem later... */
1701 logfp = fopen(server.logfile,"a");
1702 if (logfp == NULL) {
1703 err = sdscatprintf(sdsempty(),
1704 "Can't open the log file: %s", strerror(errno));
1705 goto loaderr;
1706 }
1707 fclose(logfp);
1708 }
1709 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
1710 server.dbnum = atoi(argv[1]);
1711 if (server.dbnum < 1) {
1712 err = "Invalid number of databases"; goto loaderr;
1713 }
1714 } else if (!strcasecmp(argv[0],"include") && argc == 2) {
1715 loadServerConfig(argv[1]);
1716 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
1717 server.maxclients = atoi(argv[1]);
1718 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
1719 server.maxmemory = strtoll(argv[1], NULL, 10);
1720 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
1721 server.masterhost = sdsnew(argv[1]);
1722 server.masterport = atoi(argv[2]);
1723 server.replstate = REDIS_REPL_CONNECT;
1724 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
1725 server.masterauth = zstrdup(argv[1]);
1726 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
1727 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
1728 err = "argument must be 'yes' or 'no'"; goto loaderr;
1729 }
1730 } else if (!strcasecmp(argv[0],"shareobjects") && argc == 2) {
1731 if ((server.shareobjects = yesnotoi(argv[1])) == -1) {
1732 err = "argument must be 'yes' or 'no'"; goto loaderr;
1733 }
1734 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
1735 if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
1736 err = "argument must be 'yes' or 'no'"; goto loaderr;
1737 }
1738 } else if (!strcasecmp(argv[0],"shareobjectspoolsize") && argc == 2) {
1739 server.sharingpoolsize = atoi(argv[1]);
1740 if (server.sharingpoolsize < 1) {
1741 err = "invalid object sharing pool size"; goto loaderr;
1742 }
1743 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
1744 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
1745 err = "argument must be 'yes' or 'no'"; goto loaderr;
1746 }
1747 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
1748 if ((server.appendonly = yesnotoi(argv[1])) == -1) {
1749 err = "argument must be 'yes' or 'no'"; goto loaderr;
1750 }
1751 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
1752 if (!strcasecmp(argv[1],"no")) {
1753 server.appendfsync = APPENDFSYNC_NO;
1754 } else if (!strcasecmp(argv[1],"always")) {
1755 server.appendfsync = APPENDFSYNC_ALWAYS;
1756 } else if (!strcasecmp(argv[1],"everysec")) {
1757 server.appendfsync = APPENDFSYNC_EVERYSEC;
1758 } else {
1759 err = "argument must be 'no', 'always' or 'everysec'";
1760 goto loaderr;
1761 }
1762 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
1763 server.requirepass = zstrdup(argv[1]);
1764 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
1765 server.pidfile = zstrdup(argv[1]);
1766 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
1767 server.dbfilename = zstrdup(argv[1]);
1768 } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
1769 if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
1770 err = "argument must be 'yes' or 'no'"; goto loaderr;
1771 }
1772 } else if (!strcasecmp(argv[0],"vm-swap-file") && argc == 2) {
1773 zfree(server.vm_swap_file);
1774 server.vm_swap_file = zstrdup(argv[1]);
1775 } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
1776 server.vm_max_memory = strtoll(argv[1], NULL, 10);
1777 } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
1778 server.vm_page_size = strtoll(argv[1], NULL, 10);
1779 } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
1780 server.vm_pages = strtoll(argv[1], NULL, 10);
1781 } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
1782 server.vm_max_threads = strtoll(argv[1], NULL, 10);
1783 } else if (!strcasecmp(argv[0],"hash-max-zipmap-entries") && argc == 2){
1784 server.hash_max_zipmap_entries = strtol(argv[1], NULL, 10);
1785 } else if (!strcasecmp(argv[0],"hash-max-zipmap-value") && argc == 2){
1786 server.hash_max_zipmap_value = strtol(argv[1], NULL, 10);
1787 } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
1788 server.vm_max_threads = strtoll(argv[1], NULL, 10);
1789 } else {
1790 err = "Bad directive or wrong number of arguments"; goto loaderr;
1791 }
1792 for (j = 0; j < argc; j++)
1793 sdsfree(argv[j]);
1794 zfree(argv);
1795 sdsfree(line);
1796 }
1797 if (fp != stdin) fclose(fp);
1798 return;
1799
1800 loaderr:
1801 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
1802 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
1803 fprintf(stderr, ">>> '%s'\n", line);
1804 fprintf(stderr, "%s\n", err);
1805 exit(1);
1806 }
1807
1808 static void freeClientArgv(redisClient *c) {
1809 int j;
1810
1811 for (j = 0; j < c->argc; j++)
1812 decrRefCount(c->argv[j]);
1813 for (j = 0; j < c->mbargc; j++)
1814 decrRefCount(c->mbargv[j]);
1815 c->argc = 0;
1816 c->mbargc = 0;
1817 }
1818
1819 static void freeClient(redisClient *c) {
1820 listNode *ln;
1821
1822 /* Note that if the client we are freeing is blocked into a blocking
1823 * call, we have to set querybuf to NULL *before* to call
1824 * unblockClientWaitingData() to avoid processInputBuffer() will get
1825 * called. Also it is important to remove the file events after
1826 * this, because this call adds the READABLE event. */
1827 sdsfree(c->querybuf);
1828 c->querybuf = NULL;
1829 if (c->flags & REDIS_BLOCKED)
1830 unblockClientWaitingData(c);
1831
1832 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
1833 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
1834 listRelease(c->reply);
1835 freeClientArgv(c);
1836 close(c->fd);
1837 /* Remove from the list of clients */
1838 ln = listSearchKey(server.clients,c);
1839 redisAssert(ln != NULL);
1840 listDelNode(server.clients,ln);
1841 /* Remove from the list of clients waiting for swapped keys */
1842 if (c->flags & REDIS_IO_WAIT && listLength(c->io_keys) == 0) {
1843 ln = listSearchKey(server.io_ready_clients,c);
1844 if (ln) {
1845 listDelNode(server.io_ready_clients,ln);
1846 server.vm_blocked_clients--;
1847 }
1848 }
1849 while (server.vm_enabled && listLength(c->io_keys)) {
1850 ln = listFirst(c->io_keys);
1851 dontWaitForSwappedKey(c,ln->value);
1852 }
1853 listRelease(c->io_keys);
1854 /* Other cleanup */
1855 if (c->flags & REDIS_SLAVE) {
1856 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
1857 close(c->repldbfd);
1858 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
1859 ln = listSearchKey(l,c);
1860 redisAssert(ln != NULL);
1861 listDelNode(l,ln);
1862 }
1863 if (c->flags & REDIS_MASTER) {
1864 server.master = NULL;
1865 server.replstate = REDIS_REPL_CONNECT;
1866 }
1867 zfree(c->argv);
1868 zfree(c->mbargv);
1869 freeClientMultiState(c);
1870 zfree(c);
1871 }
1872
1873 #define GLUEREPLY_UP_TO (1024)
1874 static void glueReplyBuffersIfNeeded(redisClient *c) {
1875 int copylen = 0;
1876 char buf[GLUEREPLY_UP_TO];
1877 listNode *ln;
1878 listIter li;
1879 robj *o;
1880
1881 listRewind(c->reply,&li);
1882 while((ln = listNext(&li))) {
1883 int objlen;
1884
1885 o = ln->value;
1886 objlen = sdslen(o->ptr);
1887 if (copylen + objlen <= GLUEREPLY_UP_TO) {
1888 memcpy(buf+copylen,o->ptr,objlen);
1889 copylen += objlen;
1890 listDelNode(c->reply,ln);
1891 } else {
1892 if (copylen == 0) return;
1893 break;
1894 }
1895 }
1896 /* Now the output buffer is empty, add the new single element */
1897 o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
1898 listAddNodeHead(c->reply,o);
1899 }
1900
1901 static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
1902 redisClient *c = privdata;
1903 int nwritten = 0, totwritten = 0, objlen;
1904 robj *o;
1905 REDIS_NOTUSED(el);
1906 REDIS_NOTUSED(mask);
1907
1908 /* Use writev() if we have enough buffers to send */
1909 if (!server.glueoutputbuf &&
1910 listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
1911 !(c->flags & REDIS_MASTER))
1912 {
1913 sendReplyToClientWritev(el, fd, privdata, mask);
1914 return;
1915 }
1916
1917 while(listLength(c->reply)) {
1918 if (server.glueoutputbuf && listLength(c->reply) > 1)
1919 glueReplyBuffersIfNeeded(c);
1920
1921 o = listNodeValue(listFirst(c->reply));
1922 objlen = sdslen(o->ptr);
1923
1924 if (objlen == 0) {
1925 listDelNode(c->reply,listFirst(c->reply));
1926 continue;
1927 }
1928
1929 if (c->flags & REDIS_MASTER) {
1930 /* Don't reply to a master */
1931 nwritten = objlen - c->sentlen;
1932 } else {
1933 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
1934 if (nwritten <= 0) break;
1935 }
1936 c->sentlen += nwritten;
1937 totwritten += nwritten;
1938 /* If we fully sent the object on head go to the next one */
1939 if (c->sentlen == objlen) {
1940 listDelNode(c->reply,listFirst(c->reply));
1941 c->sentlen = 0;
1942 }
1943 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1944 * bytes, in a single threaded server it's a good idea to serve
1945 * other clients as well, even if a very large request comes from
1946 * super fast link that is always able to accept data (in real world
1947 * scenario think about 'KEYS *' against the loopback interfae) */
1948 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
1949 }
1950 if (nwritten == -1) {
1951 if (errno == EAGAIN) {
1952 nwritten = 0;
1953 } else {
1954 redisLog(REDIS_VERBOSE,
1955 "Error writing to client: %s", strerror(errno));
1956 freeClient(c);
1957 return;
1958 }
1959 }
1960 if (totwritten > 0) c->lastinteraction = time(NULL);
1961 if (listLength(c->reply) == 0) {
1962 c->sentlen = 0;
1963 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
1964 }
1965 }
1966
1967 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
1968 {
1969 redisClient *c = privdata;
1970 int nwritten = 0, totwritten = 0, objlen, willwrite;
1971 robj *o;
1972 struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
1973 int offset, ion = 0;
1974 REDIS_NOTUSED(el);
1975 REDIS_NOTUSED(mask);
1976
1977 listNode *node;
1978 while (listLength(c->reply)) {
1979 offset = c->sentlen;
1980 ion = 0;
1981 willwrite = 0;
1982
1983 /* fill-in the iov[] array */
1984 for(node = listFirst(c->reply); node; node = listNextNode(node)) {
1985 o = listNodeValue(node);
1986 objlen = sdslen(o->ptr);
1987
1988 if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
1989 break;
1990
1991 if(ion == REDIS_WRITEV_IOVEC_COUNT)
1992 break; /* no more iovecs */
1993
1994 iov[ion].iov_base = ((char*)o->ptr) + offset;
1995 iov[ion].iov_len = objlen - offset;
1996 willwrite += objlen - offset;
1997 offset = 0; /* just for the first item */
1998 ion++;
1999 }
2000
2001 if(willwrite == 0)
2002 break;
2003
2004 /* write all collected blocks at once */
2005 if((nwritten = writev(fd, iov, ion)) < 0) {
2006 if (errno != EAGAIN) {
2007 redisLog(REDIS_VERBOSE,
2008 "Error writing to client: %s", strerror(errno));
2009 freeClient(c);
2010 return;
2011 }
2012 break;
2013 }
2014
2015 totwritten += nwritten;
2016 offset = c->sentlen;
2017
2018 /* remove written robjs from c->reply */
2019 while (nwritten && listLength(c->reply)) {
2020 o = listNodeValue(listFirst(c->reply));
2021 objlen = sdslen(o->ptr);
2022
2023 if(nwritten >= objlen - offset) {
2024 listDelNode(c->reply, listFirst(c->reply));
2025 nwritten -= objlen - offset;
2026 c->sentlen = 0;
2027 } else {
2028 /* partial write */
2029 c->sentlen += nwritten;
2030 break;
2031 }
2032 offset = 0;
2033 }
2034 }
2035
2036 if (totwritten > 0)
2037 c->lastinteraction = time(NULL);
2038
2039 if (listLength(c->reply) == 0) {
2040 c->sentlen = 0;
2041 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2042 }
2043 }
2044
2045 static struct redisCommand *lookupCommand(char *name) {
2046 int j = 0;
2047 while(cmdTable[j].name != NULL) {
2048 if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];
2049 j++;
2050 }
2051 return NULL;
2052 }
2053
2054 /* resetClient prepare the client to process the next command */
2055 static void resetClient(redisClient *c) {
2056 freeClientArgv(c);
2057 c->bulklen = -1;
2058 c->multibulk = 0;
2059 }
2060
2061 /* Call() is the core of Redis execution of a command */
2062 static void call(redisClient *c, struct redisCommand *cmd) {
2063 long long dirty;
2064
2065 dirty = server.dirty;
2066 cmd->proc(c);
2067 if (server.appendonly && server.dirty-dirty)
2068 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
2069 if (server.dirty-dirty && listLength(server.slaves))
2070 replicationFeedSlaves(server.slaves,cmd,c->db->id,c->argv,c->argc);
2071 if (listLength(server.monitors))
2072 replicationFeedSlaves(server.monitors,cmd,c->db->id,c->argv,c->argc);
2073 server.stat_numcommands++;
2074 }
2075
2076 /* If this function gets called we already read a whole
2077 * command, argments are in the client argv/argc fields.
2078 * processCommand() execute the command or prepare the
2079 * server for a bulk read from the client.
2080 *
2081 * If 1 is returned the client is still alive and valid and
2082 * and other operations can be performed by the caller. Otherwise
2083 * if 0 is returned the client was destroied (i.e. after QUIT). */
2084 static int processCommand(redisClient *c) {
2085 struct redisCommand *cmd;
2086
2087 /* Free some memory if needed (maxmemory setting) */
2088 if (server.maxmemory) freeMemoryIfNeeded();
2089
2090 /* Handle the multi bulk command type. This is an alternative protocol
2091 * supported by Redis in order to receive commands that are composed of
2092 * multiple binary-safe "bulk" arguments. The latency of processing is
2093 * a bit higher but this allows things like multi-sets, so if this
2094 * protocol is used only for MSET and similar commands this is a big win. */
2095 if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
2096 c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
2097 if (c->multibulk <= 0) {
2098 resetClient(c);
2099 return 1;
2100 } else {
2101 decrRefCount(c->argv[c->argc-1]);
2102 c->argc--;
2103 return 1;
2104 }
2105 } else if (c->multibulk) {
2106 if (c->bulklen == -1) {
2107 if (((char*)c->argv[0]->ptr)[0] != '$') {
2108 addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
2109 resetClient(c);
2110 return 1;
2111 } else {
2112 int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
2113 decrRefCount(c->argv[0]);
2114 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2115 c->argc--;
2116 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2117 resetClient(c);
2118 return 1;
2119 }
2120 c->argc--;
2121 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2122 return 1;
2123 }
2124 } else {
2125 c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
2126 c->mbargv[c->mbargc] = c->argv[0];
2127 c->mbargc++;
2128 c->argc--;
2129 c->multibulk--;
2130 if (c->multibulk == 0) {
2131 robj **auxargv;
2132 int auxargc;
2133
2134 /* Here we need to swap the multi-bulk argc/argv with the
2135 * normal argc/argv of the client structure. */
2136 auxargv = c->argv;
2137 c->argv = c->mbargv;
2138 c->mbargv = auxargv;
2139
2140 auxargc = c->argc;
2141 c->argc = c->mbargc;
2142 c->mbargc = auxargc;
2143
2144 /* We need to set bulklen to something different than -1
2145 * in order for the code below to process the command without
2146 * to try to read the last argument of a bulk command as
2147 * a special argument. */
2148 c->bulklen = 0;
2149 /* continue below and process the command */
2150 } else {
2151 c->bulklen = -1;
2152 return 1;
2153 }
2154 }
2155 }
2156 /* -- end of multi bulk commands processing -- */
2157
2158 /* The QUIT command is handled as a special case. Normal command
2159 * procs are unable to close the client connection safely */
2160 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
2161 freeClient(c);
2162 return 0;
2163 }
2164
2165 /* Now lookup the command and check ASAP about trivial error conditions
2166 * such wrong arity, bad command name and so forth. */
2167 cmd = lookupCommand(c->argv[0]->ptr);
2168 if (!cmd) {
2169 addReplySds(c,
2170 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2171 (char*)c->argv[0]->ptr));
2172 resetClient(c);
2173 return 1;
2174 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
2175 (c->argc < -cmd->arity)) {
2176 addReplySds(c,
2177 sdscatprintf(sdsempty(),
2178 "-ERR wrong number of arguments for '%s' command\r\n",
2179 cmd->name));
2180 resetClient(c);
2181 return 1;
2182 } else if (server.maxmemory && cmd->flags & REDIS_CMD_DENYOOM && zmalloc_used_memory() > server.maxmemory) {
2183 addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2184 resetClient(c);
2185 return 1;
2186 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
2187 /* This is a bulk command, we have to read the last argument yet. */
2188 int bulklen = atoi(c->argv[c->argc-1]->ptr);
2189
2190 decrRefCount(c->argv[c->argc-1]);
2191 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2192 c->argc--;
2193 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2194 resetClient(c);
2195 return 1;
2196 }
2197 c->argc--;
2198 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2199 /* It is possible that the bulk read is already in the
2200 * buffer. Check this condition and handle it accordingly.
2201 * This is just a fast path, alternative to call processInputBuffer().
2202 * It's a good idea since the code is small and this condition
2203 * happens most of the times. */
2204 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
2205 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2206 c->argc++;
2207 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2208 } else {
2209 /* Otherwise return... there is to read the last argument
2210 * from the socket. */
2211 return 1;
2212 }
2213 }
2214 /* Let's try to share objects on the command arguments vector */
2215 if (server.shareobjects) {
2216 int j;
2217 for(j = 1; j < c->argc; j++)
2218 c->argv[j] = tryObjectSharing(c->argv[j]);
2219 }
2220 /* Let's try to encode the bulk object to save space. */
2221 if (cmd->flags & REDIS_CMD_BULK)
2222 tryObjectEncoding(c->argv[c->argc-1]);
2223
2224 /* Check if the user is authenticated */
2225 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
2226 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
2227 resetClient(c);
2228 return 1;
2229 }
2230
2231 /* Exec the command */
2232 if (c->flags & REDIS_MULTI && cmd->proc != execCommand && cmd->proc != discardCommand) {
2233 queueMultiCommand(c,cmd);
2234 addReply(c,shared.queued);
2235 } else {
2236 if (server.vm_enabled && server.vm_max_threads > 0 &&
2237 blockClientOnSwappedKeys(cmd,c)) return 1;
2238 call(c,cmd);
2239 }
2240
2241 /* Prepare the client for the next command */
2242 resetClient(c);
2243 return 1;
2244 }
2245
2246 static void replicationFeedSlaves(list *slaves, struct redisCommand *cmd, int dictid, robj **argv, int argc) {
2247 listNode *ln;
2248 listIter li;
2249 int outc = 0, j;
2250 robj **outv;
2251 /* (args*2)+1 is enough room for args, spaces, newlines */
2252 robj *static_outv[REDIS_STATIC_ARGS*2+1];
2253
2254 if (argc <= REDIS_STATIC_ARGS) {
2255 outv = static_outv;
2256 } else {
2257 outv = zmalloc(sizeof(robj*)*(argc*2+1));
2258 }
2259
2260 for (j = 0; j < argc; j++) {
2261 if (j != 0) outv[outc++] = shared.space;
2262 if ((cmd->flags & REDIS_CMD_BULK) && j == argc-1) {
2263 robj *lenobj;
2264
2265 lenobj = createObject(REDIS_STRING,
2266 sdscatprintf(sdsempty(),"%lu\r\n",
2267 (unsigned long) stringObjectLen(argv[j])));
2268 lenobj->refcount = 0;
2269 outv[outc++] = lenobj;
2270 }
2271 outv[outc++] = argv[j];
2272 }
2273 outv[outc++] = shared.crlf;
2274
2275 /* Increment all the refcounts at start and decrement at end in order to
2276 * be sure to free objects if there is no slave in a replication state
2277 * able to be feed with commands */
2278 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
2279 listRewind(slaves,&li);
2280 while((ln = listNext(&li))) {
2281 redisClient *slave = ln->value;
2282
2283 /* Don't feed slaves that are still waiting for BGSAVE to start */
2284 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
2285
2286 /* Feed all the other slaves, MONITORs and so on */
2287 if (slave->slaveseldb != dictid) {
2288 robj *selectcmd;
2289
2290 switch(dictid) {
2291 case 0: selectcmd = shared.select0; break;
2292 case 1: selectcmd = shared.select1; break;
2293 case 2: selectcmd = shared.select2; break;
2294 case 3: selectcmd = shared.select3; break;
2295 case 4: selectcmd = shared.select4; break;
2296 case 5: selectcmd = shared.select5; break;
2297 case 6: selectcmd = shared.select6; break;
2298 case 7: selectcmd = shared.select7; break;
2299 case 8: selectcmd = shared.select8; break;
2300 case 9: selectcmd = shared.select9; break;
2301 default:
2302 selectcmd = createObject(REDIS_STRING,
2303 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
2304 selectcmd->refcount = 0;
2305 break;
2306 }
2307 addReply(slave,selectcmd);
2308 slave->slaveseldb = dictid;
2309 }
2310 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
2311 }
2312 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
2313 if (outv != static_outv) zfree(outv);
2314 }
2315
2316 static void processInputBuffer(redisClient *c) {
2317 again:
2318 /* Before to process the input buffer, make sure the client is not
2319 * waitig for a blocking operation such as BLPOP. Note that the first
2320 * iteration the client is never blocked, otherwise the processInputBuffer
2321 * would not be called at all, but after the execution of the first commands
2322 * in the input buffer the client may be blocked, and the "goto again"
2323 * will try to reiterate. The following line will make it return asap. */
2324 if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
2325 if (c->bulklen == -1) {
2326 /* Read the first line of the query */
2327 char *p = strchr(c->querybuf,'\n');
2328 size_t querylen;
2329
2330 if (p) {
2331 sds query, *argv;
2332 int argc, j;
2333
2334 query = c->querybuf;
2335 c->querybuf = sdsempty();
2336 querylen = 1+(p-(query));
2337 if (sdslen(query) > querylen) {
2338 /* leave data after the first line of the query in the buffer */
2339 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
2340 }
2341 *p = '\0'; /* remove "\n" */
2342 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
2343 sdsupdatelen(query);
2344
2345 /* Now we can split the query in arguments */
2346 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
2347 sdsfree(query);
2348
2349 if (c->argv) zfree(c->argv);
2350 c->argv = zmalloc(sizeof(robj*)*argc);
2351
2352 for (j = 0; j < argc; j++) {
2353 if (sdslen(argv[j])) {
2354 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
2355 c->argc++;
2356 } else {
2357 sdsfree(argv[j]);
2358 }
2359 }
2360 zfree(argv);
2361 if (c->argc) {
2362 /* Execute the command. If the client is still valid
2363 * after processCommand() return and there is something
2364 * on the query buffer try to process the next command. */
2365 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2366 } else {
2367 /* Nothing to process, argc == 0. Just process the query
2368 * buffer if it's not empty or return to the caller */
2369 if (sdslen(c->querybuf)) goto again;
2370 }
2371 return;
2372 } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
2373 redisLog(REDIS_VERBOSE, "Client protocol error");
2374 freeClient(c);
2375 return;
2376 }
2377 } else {
2378 /* Bulk read handling. Note that if we are at this point
2379 the client already sent a command terminated with a newline,
2380 we are reading the bulk data that is actually the last
2381 argument of the command. */
2382 int qbl = sdslen(c->querybuf);
2383
2384 if (c->bulklen <= qbl) {
2385 /* Copy everything but the final CRLF as final argument */
2386 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2387 c->argc++;
2388 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2389 /* Process the command. If the client is still valid after
2390 * the processing and there is more data in the buffer
2391 * try to parse it. */
2392 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2393 return;
2394 }
2395 }
2396 }
2397
2398 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2399 redisClient *c = (redisClient*) privdata;
2400 char buf[REDIS_IOBUF_LEN];
2401 int nread;
2402 REDIS_NOTUSED(el);
2403 REDIS_NOTUSED(mask);
2404
2405 nread = read(fd, buf, REDIS_IOBUF_LEN);
2406 if (nread == -1) {
2407 if (errno == EAGAIN) {
2408 nread = 0;
2409 } else {
2410 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
2411 freeClient(c);
2412 return;
2413 }
2414 } else if (nread == 0) {
2415 redisLog(REDIS_VERBOSE, "Client closed connection");
2416 freeClient(c);
2417 return;
2418 }
2419 if (nread) {
2420 c->querybuf = sdscatlen(c->querybuf, buf, nread);
2421 c->lastinteraction = time(NULL);
2422 } else {
2423 return;
2424 }
2425 if (!(c->flags & REDIS_BLOCKED))
2426 processInputBuffer(c);
2427 }
2428
2429 static int selectDb(redisClient *c, int id) {
2430 if (id < 0 || id >= server.dbnum)
2431 return REDIS_ERR;
2432 c->db = &server.db[id];
2433 return REDIS_OK;
2434 }
2435
2436 static void *dupClientReplyValue(void *o) {
2437 incrRefCount((robj*)o);
2438 return o;
2439 }
2440
2441 static redisClient *createClient(int fd) {
2442 redisClient *c = zmalloc(sizeof(*c));
2443
2444 anetNonBlock(NULL,fd);
2445 anetTcpNoDelay(NULL,fd);
2446 if (!c) return NULL;
2447 selectDb(c,0);
2448 c->fd = fd;
2449 c->querybuf = sdsempty();
2450 c->argc = 0;
2451 c->argv = NULL;
2452 c->bulklen = -1;
2453 c->multibulk = 0;
2454 c->mbargc = 0;
2455 c->mbargv = NULL;
2456 c->sentlen = 0;
2457 c->flags = 0;
2458 c->lastinteraction = time(NULL);
2459 c->authenticated = 0;
2460 c->replstate = REDIS_REPL_NONE;
2461 c->reply = listCreate();
2462 listSetFreeMethod(c->reply,decrRefCount);
2463 listSetDupMethod(c->reply,dupClientReplyValue);
2464 c->blockingkeys = NULL;
2465 c->blockingkeysnum = 0;
2466 c->io_keys = listCreate();
2467 listSetFreeMethod(c->io_keys,decrRefCount);
2468 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
2469 readQueryFromClient, c) == AE_ERR) {
2470 freeClient(c);
2471 return NULL;
2472 }
2473 listAddNodeTail(server.clients,c);
2474 initClientMultiState(c);
2475 return c;
2476 }
2477
2478 static void addReply(redisClient *c, robj *obj) {
2479 if (listLength(c->reply) == 0 &&
2480 (c->replstate == REDIS_REPL_NONE ||
2481 c->replstate == REDIS_REPL_ONLINE) &&
2482 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
2483 sendReplyToClient, c) == AE_ERR) return;
2484
2485 if (server.vm_enabled && obj->storage != REDIS_VM_MEMORY) {
2486 obj = dupStringObject(obj);
2487 obj->refcount = 0; /* getDecodedObject() will increment the refcount */
2488 }
2489 listAddNodeTail(c->reply,getDecodedObject(obj));
2490 }
2491
2492 static void addReplySds(redisClient *c, sds s) {
2493 robj *o = createObject(REDIS_STRING,s);
2494 addReply(c,o);
2495 decrRefCount(o);
2496 }
2497
2498 static void addReplyDouble(redisClient *c, double d) {
2499 char buf[128];
2500
2501 snprintf(buf,sizeof(buf),"%.17g",d);
2502 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2503 (unsigned long) strlen(buf),buf));
2504 }
2505
2506 static void addReplyLong(redisClient *c, long l) {
2507 char buf[128];
2508 size_t len;
2509
2510 if (l == 0) {
2511 addReply(c,shared.czero);
2512 return;
2513 } else if (l == 1) {
2514 addReply(c,shared.cone);
2515 return;
2516 }
2517 len = snprintf(buf,sizeof(buf),":%ld\r\n",l);
2518 addReplySds(c,sdsnewlen(buf,len));
2519 }
2520
2521 static void addReplyUlong(redisClient *c, unsigned long ul) {
2522 char buf[128];
2523 size_t len;
2524
2525 if (ul == 0) {
2526 addReply(c,shared.czero);
2527 return;
2528 } else if (ul == 1) {
2529 addReply(c,shared.cone);
2530 return;
2531 }
2532 len = snprintf(buf,sizeof(buf),":%lu\r\n",ul);
2533 addReplySds(c,sdsnewlen(buf,len));
2534 }
2535
2536 static void addReplyBulkLen(redisClient *c, robj *obj) {
2537 size_t len;
2538
2539 if (obj->encoding == REDIS_ENCODING_RAW) {
2540 len = sdslen(obj->ptr);
2541 } else {
2542 long n = (long)obj->ptr;
2543
2544 /* Compute how many bytes will take this integer as a radix 10 string */
2545 len = 1;
2546 if (n < 0) {
2547 len++;
2548 n = -n;
2549 }
2550 while((n = n/10) != 0) {
2551 len++;
2552 }
2553 }
2554 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len));
2555 }
2556
2557 static void addReplyBulk(redisClient *c, robj *obj) {
2558 addReplyBulkLen(c,obj);
2559 addReply(c,obj);
2560 addReply(c,shared.crlf);
2561 }
2562
2563 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2564 int cport, cfd;
2565 char cip[128];
2566 redisClient *c;
2567 REDIS_NOTUSED(el);
2568 REDIS_NOTUSED(mask);
2569 REDIS_NOTUSED(privdata);
2570
2571 cfd = anetAccept(server.neterr, fd, cip, &cport);
2572 if (cfd == AE_ERR) {
2573 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
2574 return;
2575 }
2576 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
2577 if ((c = createClient(cfd)) == NULL) {
2578 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2579 close(cfd); /* May be already closed, just ingore errors */
2580 return;
2581 }
2582 /* If maxclient directive is set and this is one client more... close the
2583 * connection. Note that we create the client instead to check before
2584 * for this condition, since now the socket is already set in nonblocking
2585 * mode and we can send an error for free using the Kernel I/O */
2586 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2587 char *err = "-ERR max number of clients reached\r\n";
2588
2589 /* That's a best effort error message, don't check write errors */
2590 if (write(c->fd,err,strlen(err)) == -1) {
2591 /* Nothing to do, Just to avoid the warning... */
2592 }
2593 freeClient(c);
2594 return;
2595 }
2596 server.stat_numconnections++;
2597 }
2598
2599 /* ======================= Redis objects implementation ===================== */
2600
2601 static robj *createObject(int type, void *ptr) {
2602 robj *o;
2603
2604 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
2605 if (listLength(server.objfreelist)) {
2606 listNode *head = listFirst(server.objfreelist);
2607 o = listNodeValue(head);
2608 listDelNode(server.objfreelist,head);
2609 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
2610 } else {
2611 if (server.vm_enabled) {
2612 pthread_mutex_unlock(&server.obj_freelist_mutex);
2613 o = zmalloc(sizeof(*o));
2614 } else {
2615 o = zmalloc(sizeof(*o)-sizeof(struct redisObjectVM));
2616 }
2617 }
2618 o->type = type;
2619 o->encoding = REDIS_ENCODING_RAW;
2620 o->ptr = ptr;
2621 o->refcount = 1;
2622 if (server.vm_enabled) {
2623 /* Note that this code may run in the context of an I/O thread
2624 * and accessing to server.unixtime in theory is an error
2625 * (no locks). But in practice this is safe, and even if we read
2626 * garbage Redis will not fail, as it's just a statistical info */
2627 o->vm.atime = server.unixtime;
2628 o->storage = REDIS_VM_MEMORY;
2629 }
2630 return o;
2631 }
2632
2633 static robj *createStringObject(char *ptr, size_t len) {
2634 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
2635 }
2636
2637 static robj *dupStringObject(robj *o) {
2638 assert(o->encoding == REDIS_ENCODING_RAW);
2639 return createStringObject(o->ptr,sdslen(o->ptr));
2640 }
2641
2642 static robj *createListObject(void) {
2643 list *l = listCreate();
2644
2645 listSetFreeMethod(l,decrRefCount);
2646 return createObject(REDIS_LIST,l);
2647 }
2648
2649 static robj *createSetObject(void) {
2650 dict *d = dictCreate(&setDictType,NULL);
2651 return createObject(REDIS_SET,d);
2652 }
2653
2654 static robj *createHashObject(void) {
2655 /* All the Hashes start as zipmaps. Will be automatically converted
2656 * into hash tables if there are enough elements or big elements
2657 * inside. */
2658 unsigned char *zm = zipmapNew();
2659 robj *o = createObject(REDIS_HASH,zm);
2660 o->encoding = REDIS_ENCODING_ZIPMAP;
2661 return o;
2662 }
2663
2664 static robj *createZsetObject(void) {
2665 zset *zs = zmalloc(sizeof(*zs));
2666
2667 zs->dict = dictCreate(&zsetDictType,NULL);
2668 zs->zsl = zslCreate();
2669 return createObject(REDIS_ZSET,zs);
2670 }
2671
2672 static void freeStringObject(robj *o) {
2673 if (o->encoding == REDIS_ENCODING_RAW) {
2674 sdsfree(o->ptr);
2675 }
2676 }
2677
2678 static void freeListObject(robj *o) {
2679 listRelease((list*) o->ptr);
2680 }
2681
2682 static void freeSetObject(robj *o) {
2683 dictRelease((dict*) o->ptr);
2684 }
2685
2686 static void freeZsetObject(robj *o) {
2687 zset *zs = o->ptr;
2688
2689 dictRelease(zs->dict);
2690 zslFree(zs->zsl);
2691 zfree(zs);
2692 }
2693
2694 static void freeHashObject(robj *o) {
2695 switch (o->encoding) {
2696 case REDIS_ENCODING_HT:
2697 dictRelease((dict*) o->ptr);
2698 break;
2699 case REDIS_ENCODING_ZIPMAP:
2700 zfree(o->ptr);
2701 break;
2702 default:
2703 redisAssert(0);
2704 break;
2705 }
2706 }
2707
2708 static void incrRefCount(robj *o) {
2709 redisAssert(!server.vm_enabled || o->storage == REDIS_VM_MEMORY);
2710 o->refcount++;
2711 }
2712
2713 static void decrRefCount(void *obj) {
2714 robj *o = obj;
2715
2716 /* Object is a key of a swapped out value, or in the process of being
2717 * loaded. */
2718 if (server.vm_enabled &&
2719 (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
2720 {
2721 if (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING) {
2722 redisAssert(o->refcount == 1);
2723 }
2724 if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(obj);
2725 redisAssert(o->type == REDIS_STRING);
2726 freeStringObject(o);
2727 vmMarkPagesFree(o->vm.page,o->vm.usedpages);
2728 pthread_mutex_lock(&server.obj_freelist_mutex);
2729 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
2730 !listAddNodeHead(server.objfreelist,o))
2731 zfree(o);
2732 pthread_mutex_unlock(&server.obj_freelist_mutex);
2733 server.vm_stats_swapped_objects--;
2734 return;
2735 }
2736 /* Object is in memory, or in the process of being swapped out. */
2737 if (--(o->refcount) == 0) {
2738 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
2739 vmCancelThreadedIOJob(obj);
2740 switch(o->type) {
2741 case REDIS_STRING: freeStringObject(o); break;
2742 case REDIS_LIST: freeListObject(o); break;
2743 case REDIS_SET: freeSetObject(o); break;
2744 case REDIS_ZSET: freeZsetObject(o); break;
2745 case REDIS_HASH: freeHashObject(o); break;
2746 default: redisAssert(0); break;
2747 }
2748 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
2749 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
2750 !listAddNodeHead(server.objfreelist,o))
2751 zfree(o);
2752 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
2753 }
2754 }
2755
2756 static robj *lookupKey(redisDb *db, robj *key) {
2757 dictEntry *de = dictFind(db->dict,key);
2758 if (de) {
2759 robj *key = dictGetEntryKey(de);
2760 robj *val = dictGetEntryVal(de);
2761
2762 if (server.vm_enabled) {
2763 if (key->storage == REDIS_VM_MEMORY ||
2764 key->storage == REDIS_VM_SWAPPING)
2765 {
2766 /* If we were swapping the object out, stop it, this key
2767 * was requested. */
2768 if (key->storage == REDIS_VM_SWAPPING)
2769 vmCancelThreadedIOJob(key);
2770 /* Update the access time of the key for the aging algorithm. */
2771 key->vm.atime = server.unixtime;
2772 } else {
2773 int notify = (key->storage == REDIS_VM_LOADING);
2774
2775 /* Our value was swapped on disk. Bring it at home. */
2776 redisAssert(val == NULL);
2777 val = vmLoadObject(key);
2778 dictGetEntryVal(de) = val;
2779
2780 /* Clients blocked by the VM subsystem may be waiting for
2781 * this key... */
2782 if (notify) handleClientsBlockedOnSwappedKey(db,key);
2783 }
2784 }
2785 return val;
2786 } else {
2787 return NULL;
2788 }
2789 }
2790
2791 static robj *lookupKeyRead(redisDb *db, robj *key) {
2792 expireIfNeeded(db,key);
2793 return lookupKey(db,key);
2794 }
2795
2796 static robj *lookupKeyWrite(redisDb *db, robj *key) {
2797 deleteIfVolatile(db,key);
2798 return lookupKey(db,key);
2799 }
2800
2801 static robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
2802 robj *o = lookupKeyRead(c->db, key);
2803 if (!o) addReply(c,reply);
2804 return o;
2805 }
2806
2807 static robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
2808 robj *o = lookupKeyWrite(c->db, key);
2809 if (!o) addReply(c,reply);
2810 return o;
2811 }
2812
2813 static int checkType(redisClient *c, robj *o, int type) {
2814 if (o->type != type) {
2815 addReply(c,shared.wrongtypeerr);
2816 return 1;
2817 }
2818 return 0;
2819 }
2820
2821 static int deleteKey(redisDb *db, robj *key) {
2822 int retval;
2823
2824 /* We need to protect key from destruction: after the first dictDelete()
2825 * it may happen that 'key' is no longer valid if we don't increment
2826 * it's count. This may happen when we get the object reference directly
2827 * from the hash table with dictRandomKey() or dict iterators */
2828 incrRefCount(key);
2829 if (dictSize(db->expires)) dictDelete(db->expires,key);
2830 retval = dictDelete(db->dict,key);
2831 decrRefCount(key);
2832
2833 return retval == DICT_OK;
2834 }
2835
2836 /* Try to share an object against the shared objects pool */
2837 static robj *tryObjectSharing(robj *o) {
2838 struct dictEntry *de;
2839 unsigned long c;
2840
2841 if (o == NULL || server.shareobjects == 0) return o;
2842
2843 redisAssert(o->type == REDIS_STRING);
2844 de = dictFind(server.sharingpool,o);
2845 if (de) {
2846 robj *shared = dictGetEntryKey(de);
2847
2848 c = ((unsigned long) dictGetEntryVal(de))+1;
2849 dictGetEntryVal(de) = (void*) c;
2850 incrRefCount(shared);
2851 decrRefCount(o);
2852 return shared;
2853 } else {
2854 /* Here we are using a stream algorihtm: Every time an object is
2855 * shared we increment its count, everytime there is a miss we
2856 * recrement the counter of a random object. If this object reaches
2857 * zero we remove the object and put the current object instead. */
2858 if (dictSize(server.sharingpool) >=
2859 server.sharingpoolsize) {
2860 de = dictGetRandomKey(server.sharingpool);
2861 redisAssert(de != NULL);
2862 c = ((unsigned long) dictGetEntryVal(de))-1;
2863 dictGetEntryVal(de) = (void*) c;
2864 if (c == 0) {
2865 dictDelete(server.sharingpool,de->key);
2866 }
2867 } else {
2868 c = 0; /* If the pool is empty we want to add this object */
2869 }
2870 if (c == 0) {
2871 int retval;
2872
2873 retval = dictAdd(server.sharingpool,o,(void*)1);
2874 redisAssert(retval == DICT_OK);
2875 incrRefCount(o);
2876 }
2877 return o;
2878 }
2879 }
2880
2881 /* Check if the nul-terminated string 's' can be represented by a long
2882 * (that is, is a number that fits into long without any other space or
2883 * character before or after the digits).
2884 *
2885 * If so, the function returns REDIS_OK and *longval is set to the value
2886 * of the number. Otherwise REDIS_ERR is returned */
2887 static int isStringRepresentableAsLong(sds s, long *longval) {
2888 char buf[32], *endptr;
2889 long value;
2890 int slen;
2891
2892 value = strtol(s, &endptr, 10);
2893 if (endptr[0] != '\0') return REDIS_ERR;
2894 slen = snprintf(buf,32,"%ld",value);
2895
2896 /* If the number converted back into a string is not identical
2897 * then it's not possible to encode the string as integer */
2898 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
2899 if (longval) *longval = value;
2900 return REDIS_OK;
2901 }
2902
2903 /* Try to encode a string object in order to save space */
2904 static int tryObjectEncoding(robj *o) {
2905 long value;
2906 sds s = o->ptr;
2907
2908 if (o->encoding != REDIS_ENCODING_RAW)
2909 return REDIS_ERR; /* Already encoded */
2910
2911 /* It's not save to encode shared objects: shared objects can be shared
2912 * everywhere in the "object space" of Redis. Encoded objects can only
2913 * appear as "values" (and not, for instance, as keys) */
2914 if (o->refcount > 1) return REDIS_ERR;
2915
2916 /* Currently we try to encode only strings */
2917 redisAssert(o->type == REDIS_STRING);
2918
2919 /* Check if we can represent this string as a long integer */
2920 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return REDIS_ERR;
2921
2922 /* Ok, this object can be encoded */
2923 o->encoding = REDIS_ENCODING_INT;
2924 sdsfree(o->ptr);
2925 o->ptr = (void*) value;
2926 return REDIS_OK;
2927 }
2928
2929 /* Get a decoded version of an encoded object (returned as a new object).
2930 * If the object is already raw-encoded just increment the ref count. */
2931 static robj *getDecodedObject(robj *o) {
2932 robj *dec;
2933
2934 if (o->encoding == REDIS_ENCODING_RAW) {
2935 incrRefCount(o);
2936 return o;
2937 }
2938 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
2939 char buf[32];
2940
2941 snprintf(buf,32,"%ld",(long)o->ptr);
2942 dec = createStringObject(buf,strlen(buf));
2943 return dec;
2944 } else {
2945 redisAssert(1 != 1);
2946 }
2947 }
2948
2949 /* Compare two string objects via strcmp() or alike.
2950 * Note that the objects may be integer-encoded. In such a case we
2951 * use snprintf() to get a string representation of the numbers on the stack
2952 * and compare the strings, it's much faster than calling getDecodedObject().
2953 *
2954 * Important note: if objects are not integer encoded, but binary-safe strings,
2955 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2956 * binary safe. */
2957 static int compareStringObjects(robj *a, robj *b) {
2958 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
2959 char bufa[128], bufb[128], *astr, *bstr;
2960 int bothsds = 1;
2961
2962 if (a == b) return 0;
2963 if (a->encoding != REDIS_ENCODING_RAW) {
2964 snprintf(bufa,sizeof(bufa),"%ld",(long) a->ptr);
2965 astr = bufa;
2966 bothsds = 0;
2967 } else {
2968 astr = a->ptr;
2969 }
2970 if (b->encoding != REDIS_ENCODING_RAW) {
2971 snprintf(bufb,sizeof(bufb),"%ld",(long) b->ptr);
2972 bstr = bufb;
2973 bothsds = 0;
2974 } else {
2975 bstr = b->ptr;
2976 }
2977 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
2978 }
2979
2980 static size_t stringObjectLen(robj *o) {
2981 redisAssert(o->type == REDIS_STRING);
2982 if (o->encoding == REDIS_ENCODING_RAW) {
2983 return sdslen(o->ptr);
2984 } else {
2985 char buf[32];
2986
2987 return snprintf(buf,32,"%ld",(long)o->ptr);
2988 }
2989 }
2990
2991 /*============================ RDB saving/loading =========================== */
2992
2993 static int rdbSaveType(FILE *fp, unsigned char type) {
2994 if (fwrite(&type,1,1,fp) == 0) return -1;
2995 return 0;
2996 }
2997
2998 static int rdbSaveTime(FILE *fp, time_t t) {
2999 int32_t t32 = (int32_t) t;
3000 if (fwrite(&t32,4,1,fp) == 0) return -1;
3001 return 0;
3002 }
3003
3004 /* check rdbLoadLen() comments for more info */
3005 static int rdbSaveLen(FILE *fp, uint32_t len) {
3006 unsigned char buf[2];
3007
3008 if (len < (1<<6)) {
3009 /* Save a 6 bit len */
3010 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
3011 if (fwrite(buf,1,1,fp) == 0) return -1;
3012 } else if (len < (1<<14)) {
3013 /* Save a 14 bit len */
3014 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
3015 buf[1] = len&0xFF;
3016 if (fwrite(buf,2,1,fp) == 0) return -1;
3017 } else {
3018 /* Save a 32 bit len */
3019 buf[0] = (REDIS_RDB_32BITLEN<<6);
3020 if (fwrite(buf,1,1,fp) == 0) return -1;
3021 len = htonl(len);
3022 if (fwrite(&len,4,1,fp) == 0) return -1;
3023 }
3024 return 0;
3025 }
3026
3027 /* String objects in the form "2391" "-100" without any space and with a
3028 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3029 * encoded as integers to save space */
3030 static int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
3031 long long value;
3032 char *endptr, buf[32];
3033
3034 /* Check if it's possible to encode this value as a number */
3035 value = strtoll(s, &endptr, 10);
3036 if (endptr[0] != '\0') return 0;
3037 snprintf(buf,32,"%lld",value);
3038
3039 /* If the number converted back into a string is not identical
3040 * then it's not possible to encode the string as integer */
3041 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
3042
3043 /* Finally check if it fits in our ranges */
3044 if (value >= -(1<<7) && value <= (1<<7)-1) {
3045 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
3046 enc[1] = value&0xFF;
3047 return 2;
3048 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
3049 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
3050 enc[1] = value&0xFF;
3051 enc[2] = (value>>8)&0xFF;
3052 return 3;
3053 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
3054 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
3055 enc[1] = value&0xFF;
3056 enc[2] = (value>>8)&0xFF;
3057 enc[3] = (value>>16)&0xFF;
3058 enc[4] = (value>>24)&0xFF;
3059 return 5;
3060 } else {
3061 return 0;
3062 }
3063 }
3064
3065 static int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
3066 size_t comprlen, outlen;
3067 unsigned char byte;
3068 void *out;
3069
3070 /* We require at least four bytes compression for this to be worth it */
3071 if (len <= 4) return 0;
3072 outlen = len-4;
3073 if ((out = zmalloc(outlen+1)) == NULL) return 0;
3074 comprlen = lzf_compress(s, len, out, outlen);
3075 if (comprlen == 0) {
3076 zfree(out);
3077 return 0;
3078 }
3079 /* Data compressed! Let's save it on disk */
3080 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
3081 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
3082 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
3083 if (rdbSaveLen(fp,len) == -1) goto writeerr;
3084 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
3085 zfree(out);
3086 return comprlen;
3087
3088 writeerr:
3089 zfree(out);
3090 return -1;
3091 }
3092
3093 /* Save a string objet as [len][data] on disk. If the object is a string
3094 * representation of an integer value we try to safe it in a special form */
3095 static int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
3096 int enclen;
3097
3098 /* Try integer encoding */
3099 if (len <= 11) {
3100 unsigned char buf[5];
3101 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
3102 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3103 return 0;
3104 }
3105 }
3106
3107 /* Try LZF compression - under 20 bytes it's unable to compress even
3108 * aaaaaaaaaaaaaaaaaa so skip it */
3109 if (server.rdbcompression && len > 20) {
3110 int retval;
3111
3112 retval = rdbSaveLzfStringObject(fp,s,len);
3113 if (retval == -1) return -1;
3114 if (retval > 0) return 0;
3115 /* retval == 0 means data can't be compressed, save the old way */
3116 }
3117
3118 /* Store verbatim */
3119 if (rdbSaveLen(fp,len) == -1) return -1;
3120 if (len && fwrite(s,len,1,fp) == 0) return -1;
3121 return 0;
3122 }
3123
3124 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3125 static int rdbSaveStringObject(FILE *fp, robj *obj) {
3126 int retval;
3127
3128 /* Avoid incr/decr ref count business when possible.
3129 * This plays well with copy-on-write given that we are probably
3130 * in a child process (BGSAVE). Also this makes sure key objects
3131 * of swapped objects are not incRefCount-ed (an assert does not allow
3132 * this in order to avoid bugs) */
3133 if (obj->encoding != REDIS_ENCODING_RAW) {
3134 obj = getDecodedObject(obj);
3135 retval = rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
3136 decrRefCount(obj);
3137 } else {
3138 retval = rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
3139 }
3140 return retval;
3141 }
3142
3143 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3144 * 8 bit integer specifing the length of the representation.
3145 * This 8 bit integer has special values in order to specify the following
3146 * conditions:
3147 * 253: not a number
3148 * 254: + inf
3149 * 255: - inf
3150 */
3151 static int rdbSaveDoubleValue(FILE *fp, double val) {
3152 unsigned char buf[128];
3153 int len;
3154
3155 if (isnan(val)) {
3156 buf[0] = 253;
3157 len = 1;
3158 } else if (!isfinite(val)) {
3159 len = 1;
3160 buf[0] = (val < 0) ? 255 : 254;
3161 } else {
3162 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
3163 buf[0] = strlen((char*)buf+1);
3164 len = buf[0]+1;
3165 }
3166 if (fwrite(buf,len,1,fp) == 0) return -1;
3167 return 0;
3168 }
3169
3170 /* Save a Redis object. */
3171 static int rdbSaveObject(FILE *fp, robj *o) {
3172 if (o->type == REDIS_STRING) {
3173 /* Save a string value */
3174 if (rdbSaveStringObject(fp,o) == -1) return -1;
3175 } else if (o->type == REDIS_LIST) {
3176 /* Save a list value */
3177 list *list = o->ptr;
3178 listIter li;
3179 listNode *ln;
3180
3181 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
3182 listRewind(list,&li);
3183 while((ln = listNext(&li))) {
3184 robj *eleobj = listNodeValue(ln);
3185
3186 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3187 }
3188 } else if (o->type == REDIS_SET) {
3189 /* Save a set value */
3190 dict *set = o->ptr;
3191 dictIterator *di = dictGetIterator(set);
3192 dictEntry *de;
3193
3194 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
3195 while((de = dictNext(di)) != NULL) {
3196 robj *eleobj = dictGetEntryKey(de);
3197
3198 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3199 }
3200 dictReleaseIterator(di);
3201 } else if (o->type == REDIS_ZSET) {
3202 /* Save a set value */
3203 zset *zs = o->ptr;
3204 dictIterator *di = dictGetIterator(zs->dict);
3205 dictEntry *de;
3206
3207 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
3208 while((de = dictNext(di)) != NULL) {
3209 robj *eleobj = dictGetEntryKey(de);
3210 double *score = dictGetEntryVal(de);
3211
3212 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3213 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
3214 }
3215 dictReleaseIterator(di);
3216 } else if (o->type == REDIS_HASH) {
3217 /* Save a hash value */
3218 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3219 unsigned char *p = zipmapRewind(o->ptr);
3220 unsigned int count = zipmapLen(o->ptr);
3221 unsigned char *key, *val;
3222 unsigned int klen, vlen;
3223
3224 if (rdbSaveLen(fp,count) == -1) return -1;
3225 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
3226 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
3227 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
3228 }
3229 } else {
3230 dictIterator *di = dictGetIterator(o->ptr);
3231 dictEntry *de;
3232
3233 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
3234 while((de = dictNext(di)) != NULL) {
3235 robj *key = dictGetEntryKey(de);
3236 robj *val = dictGetEntryVal(de);
3237
3238 if (rdbSaveStringObject(fp,key) == -1) return -1;
3239 if (rdbSaveStringObject(fp,val) == -1) return -1;
3240 }
3241 dictReleaseIterator(di);
3242 }
3243 } else {
3244 redisAssert(0);
3245 }
3246 return 0;
3247 }
3248
3249 /* Return the length the object will have on disk if saved with
3250 * the rdbSaveObject() function. Currently we use a trick to get
3251 * this length with very little changes to the code. In the future
3252 * we could switch to a faster solution. */
3253 static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
3254 if (fp == NULL) fp = server.devnull;
3255 rewind(fp);
3256 assert(rdbSaveObject(fp,o) != 1);
3257 return ftello(fp);
3258 }
3259
3260 /* Return the number of pages required to save this object in the swap file */
3261 static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
3262 off_t bytes = rdbSavedObjectLen(o,fp);
3263
3264 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
3265 }
3266
3267 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3268 static int rdbSave(char *filename) {
3269 dictIterator *di = NULL;
3270 dictEntry *de;
3271 FILE *fp;
3272 char tmpfile[256];
3273 int j;
3274 time_t now = time(NULL);
3275
3276 /* Wait for I/O therads to terminate, just in case this is a
3277 * foreground-saving, to avoid seeking the swap file descriptor at the
3278 * same time. */
3279 if (server.vm_enabled)
3280 waitEmptyIOJobsQueue();
3281
3282 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
3283 fp = fopen(tmpfile,"w");
3284 if (!fp) {
3285 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
3286 return REDIS_ERR;
3287 }
3288 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
3289 for (j = 0; j < server.dbnum; j++) {
3290 redisDb *db = server.db+j;
3291 dict *d = db->dict;
3292 if (dictSize(d) == 0) continue;
3293 di = dictGetIterator(d);
3294 if (!di) {
3295 fclose(fp);
3296 return REDIS_ERR;
3297 }
3298
3299 /* Write the SELECT DB opcode */
3300 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
3301 if (rdbSaveLen(fp,j) == -1) goto werr;
3302
3303 /* Iterate this DB writing every entry */
3304 while((de = dictNext(di)) != NULL) {
3305 robj *key = dictGetEntryKey(de);
3306 robj *o = dictGetEntryVal(de);
3307 time_t expiretime = getExpire(db,key);
3308
3309 /* Save the expire time */
3310 if (expiretime != -1) {
3311 /* If this key is already expired skip it */
3312 if (expiretime < now) continue;
3313 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
3314 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
3315 }
3316 /* Save the key and associated value. This requires special
3317 * handling if the value is swapped out. */
3318 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
3319 key->storage == REDIS_VM_SWAPPING) {
3320 /* Save type, key, value */
3321 if (rdbSaveType(fp,o->type) == -1) goto werr;
3322 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3323 if (rdbSaveObject(fp,o) == -1) goto werr;
3324 } else {
3325 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3326 robj *po;
3327 /* Get a preview of the object in memory */
3328 po = vmPreviewObject(key);
3329 /* Save type, key, value */
3330 if (rdbSaveType(fp,key->vtype) == -1) goto werr;
3331 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3332 if (rdbSaveObject(fp,po) == -1) goto werr;
3333 /* Remove the loaded object from memory */
3334 decrRefCount(po);
3335 }
3336 }
3337 dictReleaseIterator(di);
3338 }
3339 /* EOF opcode */
3340 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
3341
3342 /* Make sure data will not remain on the OS's output buffers */
3343 fflush(fp);
3344 fsync(fileno(fp));
3345 fclose(fp);
3346
3347 /* Use RENAME to make sure the DB file is changed atomically only
3348 * if the generate DB file is ok. */
3349 if (rename(tmpfile,filename) == -1) {
3350 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
3351 unlink(tmpfile);
3352 return REDIS_ERR;
3353 }
3354 redisLog(REDIS_NOTICE,"DB saved on disk");
3355 server.dirty = 0;
3356 server.lastsave = time(NULL);
3357 return REDIS_OK;
3358
3359 werr:
3360 fclose(fp);
3361 unlink(tmpfile);
3362 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
3363 if (di) dictReleaseIterator(di);
3364 return REDIS_ERR;
3365 }
3366
3367 static int rdbSaveBackground(char *filename) {
3368 pid_t childpid;
3369
3370 if (server.bgsavechildpid != -1) return REDIS_ERR;
3371 if (server.vm_enabled) waitEmptyIOJobsQueue();
3372 if ((childpid = fork()) == 0) {
3373 /* Child */
3374 if (server.vm_enabled) vmReopenSwapFile();
3375 close(server.fd);
3376 if (rdbSave(filename) == REDIS_OK) {
3377 _exit(0);
3378 } else {
3379 _exit(1);
3380 }
3381 } else {
3382 /* Parent */
3383 if (childpid == -1) {
3384 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
3385 strerror(errno));
3386 return REDIS_ERR;
3387 }
3388 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
3389 server.bgsavechildpid = childpid;
3390 return REDIS_OK;
3391 }
3392 return REDIS_OK; /* unreached */
3393 }
3394
3395 static void rdbRemoveTempFile(pid_t childpid) {
3396 char tmpfile[256];
3397
3398 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
3399 unlink(tmpfile);
3400 }
3401
3402 static int rdbLoadType(FILE *fp) {
3403 unsigned char type;
3404 if (fread(&type,1,1,fp) == 0) return -1;
3405 return type;
3406 }
3407
3408 static time_t rdbLoadTime(FILE *fp) {
3409 int32_t t32;
3410 if (fread(&t32,4,1,fp) == 0) return -1;
3411 return (time_t) t32;
3412 }
3413
3414 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3415 * of this file for a description of how this are stored on disk.
3416 *
3417 * isencoded is set to 1 if the readed length is not actually a length but
3418 * an "encoding type", check the above comments for more info */
3419 static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
3420 unsigned char buf[2];
3421 uint32_t len;
3422 int type;
3423
3424 if (isencoded) *isencoded = 0;
3425 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
3426 type = (buf[0]&0xC0)>>6;
3427 if (type == REDIS_RDB_6BITLEN) {
3428 /* Read a 6 bit len */
3429 return buf[0]&0x3F;
3430 } else if (type == REDIS_RDB_ENCVAL) {
3431 /* Read a 6 bit len encoding type */
3432 if (isencoded) *isencoded = 1;
3433 return buf[0]&0x3F;
3434 } else if (type == REDIS_RDB_14BITLEN) {
3435 /* Read a 14 bit len */
3436 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
3437 return ((buf[0]&0x3F)<<8)|buf[1];
3438 } else {
3439 /* Read a 32 bit len */
3440 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
3441 return ntohl(len);
3442 }
3443 }
3444
3445 static robj *rdbLoadIntegerObject(FILE *fp, int enctype) {
3446 unsigned char enc[4];
3447 long long val;
3448
3449 if (enctype == REDIS_RDB_ENC_INT8) {
3450 if (fread(enc,1,1,fp) == 0) return NULL;
3451 val = (signed char)enc[0];
3452 } else if (enctype == REDIS_RDB_ENC_INT16) {
3453 uint16_t v;
3454 if (fread(enc,2,1,fp) == 0) return NULL;
3455 v = enc[0]|(enc[1]<<8);
3456 val = (int16_t)v;
3457 } else if (enctype == REDIS_RDB_ENC_INT32) {
3458 uint32_t v;
3459 if (fread(enc,4,1,fp) == 0) return NULL;
3460 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
3461 val = (int32_t)v;
3462 } else {
3463 val = 0; /* anti-warning */
3464 redisAssert(0);
3465 }
3466 return createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",val));
3467 }
3468
3469 static robj *rdbLoadLzfStringObject(FILE*fp) {
3470 unsigned int len, clen;
3471 unsigned char *c = NULL;
3472 sds val = NULL;
3473
3474 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3475 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3476 if ((c = zmalloc(clen)) == NULL) goto err;
3477 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
3478 if (fread(c,clen,1,fp) == 0) goto err;
3479 if (lzf_decompress(c,clen,val,len) == 0) goto err;
3480 zfree(c);
3481 return createObject(REDIS_STRING,val);
3482 err:
3483 zfree(c);
3484 sdsfree(val);
3485 return NULL;
3486 }
3487
3488 static robj *rdbLoadStringObject(FILE*fp) {
3489 int isencoded;
3490 uint32_t len;
3491 sds val;
3492
3493 len = rdbLoadLen(fp,&isencoded);
3494 if (isencoded) {
3495 switch(len) {
3496 case REDIS_RDB_ENC_INT8:
3497 case REDIS_RDB_ENC_INT16:
3498 case REDIS_RDB_ENC_INT32:
3499 return tryObjectSharing(rdbLoadIntegerObject(fp,len));
3500 case REDIS_RDB_ENC_LZF:
3501 return tryObjectSharing(rdbLoadLzfStringObject(fp));
3502 default:
3503 redisAssert(0);
3504 }
3505 }
3506
3507 if (len == REDIS_RDB_LENERR) return NULL;
3508 val = sdsnewlen(NULL,len);
3509 if (len && fread(val,len,1,fp) == 0) {
3510 sdsfree(val);
3511 return NULL;
3512 }
3513 return tryObjectSharing(createObject(REDIS_STRING,val));
3514 }
3515
3516 /* For information about double serialization check rdbSaveDoubleValue() */
3517 static int rdbLoadDoubleValue(FILE *fp, double *val) {
3518 char buf[128];
3519 unsigned char len;
3520
3521 if (fread(&len,1,1,fp) == 0) return -1;
3522 switch(len) {
3523 case 255: *val = R_NegInf; return 0;
3524 case 254: *val = R_PosInf; return 0;
3525 case 253: *val = R_Nan; return 0;
3526 default:
3527 if (fread(buf,len,1,fp) == 0) return -1;
3528 buf[len] = '\0';
3529 sscanf(buf, "%lg", val);
3530 return 0;
3531 }
3532 }
3533
3534 /* Load a Redis object of the specified type from the specified file.
3535 * On success a newly allocated object is returned, otherwise NULL. */
3536 static robj *rdbLoadObject(int type, FILE *fp) {
3537 robj *o;
3538
3539 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
3540 if (type == REDIS_STRING) {
3541 /* Read string value */
3542 if ((o = rdbLoadStringObject(fp)) == NULL) return NULL;
3543 tryObjectEncoding(o);
3544 } else if (type == REDIS_LIST || type == REDIS_SET) {
3545 /* Read list/set value */
3546 uint32_t listlen;
3547
3548 if ((listlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3549 o = (type == REDIS_LIST) ? createListObject() : createSetObject();
3550 /* It's faster to expand the dict to the right size asap in order
3551 * to avoid rehashing */
3552 if (type == REDIS_SET && listlen > DICT_HT_INITIAL_SIZE)
3553 dictExpand(o->ptr,listlen);
3554 /* Load every single element of the list/set */
3555 while(listlen--) {
3556 robj *ele;
3557
3558 if ((ele = rdbLoadStringObject(fp)) == NULL) return NULL;
3559 tryObjectEncoding(ele);
3560 if (type == REDIS_LIST) {
3561 listAddNodeTail((list*)o->ptr,ele);
3562 } else {
3563 dictAdd((dict*)o->ptr,ele,NULL);
3564 }
3565 }
3566 } else if (type == REDIS_ZSET) {
3567 /* Read list/set value */
3568 size_t zsetlen;
3569 zset *zs;
3570
3571 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3572 o = createZsetObject();
3573 zs = o->ptr;
3574 /* Load every single element of the list/set */
3575 while(zsetlen--) {
3576 robj *ele;
3577 double *score = zmalloc(sizeof(double));
3578
3579 if ((ele = rdbLoadStringObject(fp)) == NULL) return NULL;
3580 tryObjectEncoding(ele);
3581 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
3582 dictAdd(zs->dict,ele,score);
3583 zslInsert(zs->zsl,*score,ele);
3584 incrRefCount(ele); /* added to skiplist */
3585 }
3586 } else if (type == REDIS_HASH) {
3587 size_t hashlen;
3588
3589 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3590 o = createHashObject();
3591 /* Too many entries? Use an hash table. */
3592 if (hashlen > server.hash_max_zipmap_entries)
3593 convertToRealHash(o);
3594 /* Load every key/value, then set it into the zipmap or hash
3595 * table, as needed. */
3596 while(hashlen--) {
3597 robj *key, *val;
3598
3599 if ((key = rdbLoadStringObject(fp)) == NULL) return NULL;
3600 if ((val = rdbLoadStringObject(fp)) == NULL) return NULL;
3601 /* If we are using a zipmap and there are too big values
3602 * the object is converted to real hash table encoding. */
3603 if (o->encoding != REDIS_ENCODING_HT &&
3604 (sdslen(key->ptr) > server.hash_max_zipmap_value ||
3605 sdslen(val->ptr) > server.hash_max_zipmap_value))
3606 {
3607 convertToRealHash(o);
3608 }
3609
3610 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3611 unsigned char *zm = o->ptr;
3612
3613 zm = zipmapSet(zm,key->ptr,sdslen(key->ptr),
3614 val->ptr,sdslen(val->ptr),NULL);
3615 o->ptr = zm;
3616 decrRefCount(key);
3617 decrRefCount(val);
3618 } else {
3619 tryObjectEncoding(key);
3620 tryObjectEncoding(val);
3621 dictAdd((dict*)o->ptr,key,val);
3622 }
3623 }
3624 } else {
3625 redisAssert(0);
3626 }
3627 return o;
3628 }
3629
3630 static int rdbLoad(char *filename) {
3631 FILE *fp;
3632 robj *keyobj = NULL;
3633 uint32_t dbid;
3634 int type, retval, rdbver;
3635 dict *d = server.db[0].dict;
3636 redisDb *db = server.db+0;
3637 char buf[1024];
3638 time_t expiretime = -1, now = time(NULL);
3639 long long loadedkeys = 0;
3640
3641 fp = fopen(filename,"r");
3642 if (!fp) return REDIS_ERR;
3643 if (fread(buf,9,1,fp) == 0) goto eoferr;
3644 buf[9] = '\0';
3645 if (memcmp(buf,"REDIS",5) != 0) {
3646 fclose(fp);
3647 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
3648 return REDIS_ERR;
3649 }
3650 rdbver = atoi(buf+5);
3651 if (rdbver != 1) {
3652 fclose(fp);
3653 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
3654 return REDIS_ERR;
3655 }
3656 while(1) {
3657 robj *o;
3658
3659 /* Read type. */
3660 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
3661 if (type == REDIS_EXPIRETIME) {
3662 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
3663 /* We read the time so we need to read the object type again */
3664 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
3665 }
3666 if (type == REDIS_EOF) break;
3667 /* Handle SELECT DB opcode as a special case */
3668 if (type == REDIS_SELECTDB) {
3669 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
3670 goto eoferr;
3671 if (dbid >= (unsigned)server.dbnum) {
3672 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
3673 exit(1);
3674 }
3675 db = server.db+dbid;
3676 d = db->dict;
3677 continue;
3678 }
3679 /* Read key */
3680 if ((keyobj = rdbLoadStringObject(fp)) == NULL) goto eoferr;
3681 /* Read value */
3682 if ((o = rdbLoadObject(type,fp)) == NULL) goto eoferr;
3683 /* Add the new object in the hash table */
3684 retval = dictAdd(d,keyobj,o);
3685 if (retval == DICT_ERR) {
3686 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj->ptr);
3687 exit(1);
3688 }
3689 /* Set the expire time if needed */
3690 if (expiretime != -1) {
3691 setExpire(db,keyobj,expiretime);
3692 /* Delete this key if already expired */
3693 if (expiretime < now) deleteKey(db,keyobj);
3694 expiretime = -1;
3695 }
3696 keyobj = o = NULL;
3697 /* Handle swapping while loading big datasets when VM is on */
3698 loadedkeys++;
3699 if (server.vm_enabled && (loadedkeys % 5000) == 0) {
3700 while (zmalloc_used_memory() > server.vm_max_memory) {
3701 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
3702 }
3703 }
3704 }
3705 fclose(fp);
3706 return REDIS_OK;
3707
3708 eoferr: /* unexpected end of file is handled here with a fatal exit */
3709 if (keyobj) decrRefCount(keyobj);
3710 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3711 exit(1);
3712 return REDIS_ERR; /* Just to avoid warning */
3713 }
3714
3715 /*================================== Commands =============================== */
3716
3717 static void authCommand(redisClient *c) {
3718 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
3719 c->authenticated = 1;
3720 addReply(c,shared.ok);
3721 } else {
3722 c->authenticated = 0;
3723 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3724 }
3725 }
3726
3727 static void pingCommand(redisClient *c) {
3728 addReply(c,shared.pong);
3729 }
3730
3731 static void echoCommand(redisClient *c) {
3732 addReplyBulk(c,c->argv[1]);
3733 }
3734
3735 /*=================================== Strings =============================== */
3736
3737 static void setGenericCommand(redisClient *c, int nx) {
3738 int retval;
3739
3740 if (nx) deleteIfVolatile(c->db,c->argv[1]);
3741 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
3742 if (retval == DICT_ERR) {
3743 if (!nx) {
3744 /* If the key is about a swapped value, we want a new key object
3745 * to overwrite the old. So we delete the old key in the database.
3746 * This will also make sure that swap pages about the old object
3747 * will be marked as free. */
3748 if (server.vm_enabled && deleteIfSwapped(c->db,c->argv[1]))
3749 incrRefCount(c->argv[1]);
3750 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
3751 incrRefCount(c->argv[2]);
3752 } else {
3753 addReply(c,shared.czero);
3754 return;
3755 }
3756 } else {
3757 incrRefCount(c->argv[1]);
3758 incrRefCount(c->argv[2]);
3759 }
3760 server.dirty++;
3761 removeExpire(c->db,c->argv[1]);
3762 addReply(c, nx ? shared.cone : shared.ok);
3763 }
3764
3765 static void setCommand(redisClient *c) {
3766 setGenericCommand(c,0);
3767 }
3768
3769 static void setnxCommand(redisClient *c) {
3770 setGenericCommand(c,1);
3771 }
3772
3773 static int getGenericCommand(redisClient *c) {
3774 robj *o;
3775
3776 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
3777 return REDIS_OK;
3778
3779 if (o->type != REDIS_STRING) {
3780 addReply(c,shared.wrongtypeerr);
3781 return REDIS_ERR;
3782 } else {
3783 addReplyBulk(c,o);
3784 return REDIS_OK;
3785 }
3786 }
3787
3788 static void getCommand(redisClient *c) {
3789 getGenericCommand(c);
3790 }
3791
3792 static void getsetCommand(redisClient *c) {
3793 if (getGenericCommand(c) == REDIS_ERR) return;
3794 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
3795 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
3796 } else {
3797 incrRefCount(c->argv[1]);
3798 }
3799 incrRefCount(c->argv[2]);
3800 server.dirty++;
3801 removeExpire(c->db,c->argv[1]);
3802 }
3803
3804 static void mgetCommand(redisClient *c) {
3805 int j;
3806
3807 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
3808 for (j = 1; j < c->argc; j++) {
3809 robj *o = lookupKeyRead(c->db,c->argv[j]);
3810 if (o == NULL) {
3811 addReply(c,shared.nullbulk);
3812 } else {
3813 if (o->type != REDIS_STRING) {
3814 addReply(c,shared.nullbulk);
3815 } else {
3816 addReplyBulk(c,o);
3817 }
3818 }
3819 }
3820 }
3821
3822 static void msetGenericCommand(redisClient *c, int nx) {
3823 int j, busykeys = 0;
3824
3825 if ((c->argc % 2) == 0) {
3826 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3827 return;
3828 }
3829 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3830 * set nothing at all if at least one already key exists. */
3831 if (nx) {
3832 for (j = 1; j < c->argc; j += 2) {
3833 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
3834 busykeys++;
3835 }
3836 }
3837 }
3838 if (busykeys) {
3839 addReply(c, shared.czero);
3840 return;
3841 }
3842
3843 for (j = 1; j < c->argc; j += 2) {
3844 int retval;
3845
3846 tryObjectEncoding(c->argv[j+1]);
3847 retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
3848 if (retval == DICT_ERR) {
3849 dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
3850 incrRefCount(c->argv[j+1]);
3851 } else {
3852 incrRefCount(c->argv[j]);
3853 incrRefCount(c->argv[j+1]);
3854 }
3855 removeExpire(c->db,c->argv[j]);
3856 }
3857 server.dirty += (c->argc-1)/2;
3858 addReply(c, nx ? shared.cone : shared.ok);
3859 }
3860
3861 static void msetCommand(redisClient *c) {
3862 msetGenericCommand(c,0);
3863 }
3864
3865 static void msetnxCommand(redisClient *c) {
3866 msetGenericCommand(c,1);
3867 }
3868
3869 static void incrDecrCommand(redisClient *c, long long incr) {
3870 long long value;
3871 int retval;
3872 robj *o;
3873
3874 o = lookupKeyWrite(c->db,c->argv[1]);
3875 if (o == NULL) {
3876 value = 0;
3877 } else {
3878 if (o->type != REDIS_STRING) {
3879 value = 0;
3880 } else {
3881 char *eptr;
3882
3883 if (o->encoding == REDIS_ENCODING_RAW)
3884 value = strtoll(o->ptr, &eptr, 10);
3885 else if (o->encoding == REDIS_ENCODING_INT)
3886 value = (long)o->ptr;
3887 else
3888 redisAssert(1 != 1);
3889 }
3890 }
3891
3892 value += incr;
3893 o = createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",value));
3894 tryObjectEncoding(o);
3895 retval = dictAdd(c->db->dict,c->argv[1],o);
3896 if (retval == DICT_ERR) {
3897 dictReplace(c->db->dict,c->argv[1],o);
3898 removeExpire(c->db,c->argv[1]);
3899 } else {
3900 incrRefCount(c->argv[1]);
3901 }
3902 server.dirty++;
3903 addReply(c,shared.colon);
3904 addReply(c,o);
3905 addReply(c,shared.crlf);
3906 }
3907
3908 static void incrCommand(redisClient *c) {
3909 incrDecrCommand(c,1);
3910 }
3911
3912 static void decrCommand(redisClient *c) {
3913 incrDecrCommand(c,-1);
3914 }
3915
3916 static void incrbyCommand(redisClient *c) {
3917 long long incr = strtoll(c->argv[2]->ptr, NULL, 10);
3918 incrDecrCommand(c,incr);
3919 }
3920
3921 static void decrbyCommand(redisClient *c) {
3922 long long incr = strtoll(c->argv[2]->ptr, NULL, 10);
3923 incrDecrCommand(c,-incr);
3924 }
3925
3926 static void appendCommand(redisClient *c) {
3927 int retval;
3928 size_t totlen;
3929 robj *o;
3930
3931 o = lookupKeyWrite(c->db,c->argv[1]);
3932 if (o == NULL) {
3933 /* Create the key */
3934 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
3935 incrRefCount(c->argv[1]);
3936 incrRefCount(c->argv[2]);
3937 totlen = stringObjectLen(c->argv[2]);
3938 } else {
3939 dictEntry *de;
3940
3941 de = dictFind(c->db->dict,c->argv[1]);
3942 assert(de != NULL);
3943
3944 o = dictGetEntryVal(de);
3945 if (o->type != REDIS_STRING) {
3946 addReply(c,shared.wrongtypeerr);
3947 return;
3948 }
3949 /* If the object is specially encoded or shared we have to make
3950 * a copy */
3951 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
3952 robj *decoded = getDecodedObject(o);
3953
3954 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
3955 decrRefCount(decoded);
3956 dictReplace(c->db->dict,c->argv[1],o);
3957 }
3958 /* APPEND! */
3959 if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
3960 o->ptr = sdscatlen(o->ptr,
3961 c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
3962 } else {
3963 o->ptr = sdscatprintf(o->ptr, "%ld",
3964 (unsigned long) c->argv[2]->ptr);
3965 }
3966 totlen = sdslen(o->ptr);
3967 }
3968 server.dirty++;
3969 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
3970 }
3971
3972 static void substrCommand(redisClient *c) {
3973 robj *o;
3974 long start = atoi(c->argv[2]->ptr);
3975 long end = atoi(c->argv[3]->ptr);
3976 size_t rangelen, strlen;
3977 sds range;
3978
3979 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
3980 checkType(c,o,REDIS_STRING)) return;
3981
3982 o = getDecodedObject(o);
3983 strlen = sdslen(o->ptr);
3984
3985 /* convert negative indexes */
3986 if (start < 0) start = strlen+start;
3987 if (end < 0) end = strlen+end;
3988 if (start < 0) start = 0;
3989 if (end < 0) end = 0;
3990
3991 /* indexes sanity checks */
3992 if (start > end || (size_t)start >= strlen) {
3993 /* Out of range start or start > end result in null reply */
3994 addReply(c,shared.nullbulk);
3995 decrRefCount(o);
3996 return;
3997 }
3998 if ((size_t)end >= strlen) end = strlen-1;
3999 rangelen = (end-start)+1;
4000
4001 /* Return the result */
4002 addReplySds(c,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen));
4003 range = sdsnewlen((char*)o->ptr+start,rangelen);
4004 addReplySds(c,range);
4005 addReply(c,shared.crlf);
4006 decrRefCount(o);
4007 }
4008
4009 /* ========================= Type agnostic commands ========================= */
4010
4011 static void delCommand(redisClient *c) {
4012 int deleted = 0, j;
4013
4014 for (j = 1; j < c->argc; j++) {
4015 if (deleteKey(c->db,c->argv[j])) {
4016 server.dirty++;
4017 deleted++;
4018 }
4019 }
4020 addReplyLong(c,deleted);
4021 }
4022
4023 static void existsCommand(redisClient *c) {
4024 addReply(c,lookupKeyRead(c->db,c->argv[1]) ? shared.cone : shared.czero);
4025 }
4026
4027 static void selectCommand(redisClient *c) {
4028 int id = atoi(c->argv[1]->ptr);
4029
4030 if (selectDb(c,id) == REDIS_ERR) {
4031 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
4032 } else {
4033 addReply(c,shared.ok);
4034 }
4035 }
4036
4037 static void randomkeyCommand(redisClient *c) {
4038 dictEntry *de;
4039
4040 while(1) {
4041 de = dictGetRandomKey(c->db->dict);
4042 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
4043 }
4044 if (de == NULL) {
4045 addReply(c,shared.plus);
4046 addReply(c,shared.crlf);
4047 } else {
4048 addReply(c,shared.plus);
4049 addReply(c,dictGetEntryKey(de));
4050 addReply(c,shared.crlf);
4051 }
4052 }
4053
4054 static void keysCommand(redisClient *c) {
4055 dictIterator *di;
4056 dictEntry *de;
4057 sds pattern = c->argv[1]->ptr;
4058 int plen = sdslen(pattern);
4059 unsigned long numkeys = 0;
4060 robj *lenobj = createObject(REDIS_STRING,NULL);
4061
4062 di = dictGetIterator(c->db->dict);
4063 addReply(c,lenobj);
4064 decrRefCount(lenobj);
4065 while((de = dictNext(di)) != NULL) {
4066 robj *keyobj = dictGetEntryKey(de);
4067
4068 sds key = keyobj->ptr;
4069 if ((pattern[0] == '*' && pattern[1] == '\0') ||
4070 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
4071 if (expireIfNeeded(c->db,keyobj) == 0) {
4072 addReplyBulk(c,keyobj);
4073 numkeys++;
4074 }
4075 }
4076 }
4077 dictReleaseIterator(di);
4078 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
4079 }
4080
4081 static void dbsizeCommand(redisClient *c) {
4082 addReplySds(c,
4083 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
4084 }
4085
4086 static void lastsaveCommand(redisClient *c) {
4087 addReplySds(c,
4088 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
4089 }
4090
4091 static void typeCommand(redisClient *c) {
4092 robj *o;
4093 char *type;
4094
4095 o = lookupKeyRead(c->db,c->argv[1]);
4096 if (o == NULL) {
4097 type = "+none";
4098 } else {
4099 switch(o->type) {
4100 case REDIS_STRING: type = "+string"; break;
4101 case REDIS_LIST: type = "+list"; break;
4102 case REDIS_SET: type = "+set"; break;
4103 case REDIS_ZSET: type = "+zset"; break;
4104 case REDIS_HASH: type = "+hash"; break;
4105 default: type = "+unknown"; break;
4106 }
4107 }
4108 addReplySds(c,sdsnew(type));
4109 addReply(c,shared.crlf);
4110 }
4111
4112 static void saveCommand(redisClient *c) {
4113 if (server.bgsavechildpid != -1) {
4114 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
4115 return;
4116 }
4117 if (rdbSave(server.dbfilename) == REDIS_OK) {
4118 addReply(c,shared.ok);
4119 } else {
4120 addReply(c,shared.err);
4121 }
4122 }
4123
4124 static void bgsaveCommand(redisClient *c) {
4125 if (server.bgsavechildpid != -1) {
4126 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
4127 return;
4128 }
4129 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
4130 char *status = "+Background saving started\r\n";
4131 addReplySds(c,sdsnew(status));
4132 } else {
4133 addReply(c,shared.err);
4134 }
4135 }
4136
4137 static void shutdownCommand(redisClient *c) {
4138 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
4139 /* Kill the saving child if there is a background saving in progress.
4140 We want to avoid race conditions, for instance our saving child may
4141 overwrite the synchronous saving did by SHUTDOWN. */
4142 if (server.bgsavechildpid != -1) {
4143 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
4144 kill(server.bgsavechildpid,SIGKILL);
4145 rdbRemoveTempFile(server.bgsavechildpid);
4146 }
4147 if (server.appendonly) {
4148 /* Append only file: fsync() the AOF and exit */
4149 fsync(server.appendfd);
4150 if (server.vm_enabled) unlink(server.vm_swap_file);
4151 exit(0);
4152 } else {
4153 /* Snapshotting. Perform a SYNC SAVE and exit */
4154 if (rdbSave(server.dbfilename) == REDIS_OK) {
4155 if (server.daemonize)
4156 unlink(server.pidfile);
4157 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
4158 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
4159 if (server.vm_enabled) unlink(server.vm_swap_file);
4160 exit(0);
4161 } else {
4162 /* Ooops.. error saving! The best we can do is to continue
4163 * operating. Note that if there was a background saving process,
4164 * in the next cron() Redis will be notified that the background
4165 * saving aborted, handling special stuff like slaves pending for
4166 * synchronization... */
4167 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
4168 addReplySds(c,
4169 sdsnew("-ERR can't quit, problems saving the DB\r\n"));
4170 }
4171 }
4172 }
4173
4174 static void renameGenericCommand(redisClient *c, int nx) {
4175 robj *o;
4176
4177 /* To use the same key as src and dst is probably an error */
4178 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
4179 addReply(c,shared.sameobjecterr);
4180 return;
4181 }
4182
4183 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
4184 return;
4185
4186 incrRefCount(o);
4187 deleteIfVolatile(c->db,c->argv[2]);
4188 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
4189 if (nx) {
4190 decrRefCount(o);
4191 addReply(c,shared.czero);
4192 return;
4193 }
4194 dictReplace(c->db->dict,c->argv[2],o);
4195 } else {
4196 incrRefCount(c->argv[2]);
4197 }
4198 deleteKey(c->db,c->argv[1]);
4199 server.dirty++;
4200 addReply(c,nx ? shared.cone : shared.ok);
4201 }
4202
4203 static void renameCommand(redisClient *c) {
4204 renameGenericCommand(c,0);
4205 }
4206
4207 static void renamenxCommand(redisClient *c) {
4208 renameGenericCommand(c,1);
4209 }
4210
4211 static void moveCommand(redisClient *c) {
4212 robj *o;
4213 redisDb *src, *dst;
4214 int srcid;
4215
4216 /* Obtain source and target DB pointers */
4217 src = c->db;
4218 srcid = c->db->id;
4219 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
4220 addReply(c,shared.outofrangeerr);
4221 return;
4222 }
4223 dst = c->db;
4224 selectDb(c,srcid); /* Back to the source DB */
4225
4226 /* If the user is moving using as target the same
4227 * DB as the source DB it is probably an error. */
4228 if (src == dst) {
4229 addReply(c,shared.sameobjecterr);
4230 return;
4231 }
4232
4233 /* Check if the element exists and get a reference */
4234 o = lookupKeyWrite(c->db,c->argv[1]);
4235 if (!o) {
4236 addReply(c,shared.czero);
4237 return;
4238 }
4239
4240 /* Try to add the element to the target DB */
4241 deleteIfVolatile(dst,c->argv[1]);
4242 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
4243 addReply(c,shared.czero);
4244 return;
4245 }
4246 incrRefCount(c->argv[1]);
4247 incrRefCount(o);
4248
4249 /* OK! key moved, free the entry in the source DB */
4250 deleteKey(src,c->argv[1]);
4251 server.dirty++;
4252 addReply(c,shared.cone);
4253 }
4254
4255 /* =================================== Lists ================================ */
4256 static void pushGenericCommand(redisClient *c, int where) {
4257 robj *lobj;
4258 list *list;
4259
4260 lobj = lookupKeyWrite(c->db,c->argv[1]);
4261 if (lobj == NULL) {
4262 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
4263 addReply(c,shared.cone);
4264 return;
4265 }
4266 lobj = createListObject();
4267 list = lobj->ptr;
4268 if (where == REDIS_HEAD) {
4269 listAddNodeHead(list,c->argv[2]);
4270 } else {
4271 listAddNodeTail(list,c->argv[2]);
4272 }
4273 dictAdd(c->db->dict,c->argv[1],lobj);
4274 incrRefCount(c->argv[1]);
4275 incrRefCount(c->argv[2]);
4276 } else {
4277 if (lobj->type != REDIS_LIST) {
4278 addReply(c,shared.wrongtypeerr);
4279 return;
4280 }
4281 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
4282 addReply(c,shared.cone);
4283 return;
4284 }
4285 list = lobj->ptr;
4286 if (where == REDIS_HEAD) {
4287 listAddNodeHead(list,c->argv[2]);
4288 } else {
4289 listAddNodeTail(list,c->argv[2]);
4290 }
4291 incrRefCount(c->argv[2]);
4292 }
4293 server.dirty++;
4294 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",listLength(list)));
4295 }
4296
4297 static void lpushCommand(redisClient *c) {
4298 pushGenericCommand(c,REDIS_HEAD);
4299 }
4300
4301 static void rpushCommand(redisClient *c) {
4302 pushGenericCommand(c,REDIS_TAIL);
4303 }
4304
4305 static void llenCommand(redisClient *c) {
4306 robj *o;
4307 list *l;
4308
4309 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
4310 checkType(c,o,REDIS_LIST)) return;
4311
4312 l = o->ptr;
4313 addReplyUlong(c,listLength(l));
4314 }
4315
4316 static void lindexCommand(redisClient *c) {
4317 robj *o;
4318 int index = atoi(c->argv[2]->ptr);
4319 list *list;
4320 listNode *ln;
4321
4322 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4323 checkType(c,o,REDIS_LIST)) return;
4324 list = o->ptr;
4325
4326 ln = listIndex(list, index);
4327 if (ln == NULL) {
4328 addReply(c,shared.nullbulk);
4329 } else {
4330 robj *ele = listNodeValue(ln);
4331 addReplyBulk(c,ele);
4332 }
4333 }
4334
4335 static void lsetCommand(redisClient *c) {
4336 robj *o;
4337 int index = atoi(c->argv[2]->ptr);
4338 list *list;
4339 listNode *ln;
4340
4341 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL ||
4342 checkType(c,o,REDIS_LIST)) return;
4343 list = o->ptr;
4344
4345 ln = listIndex(list, index);
4346 if (ln == NULL) {
4347 addReply(c,shared.outofrangeerr);
4348 } else {
4349 robj *ele = listNodeValue(ln);
4350
4351 decrRefCount(ele);
4352 listNodeValue(ln) = c->argv[3];
4353 incrRefCount(c->argv[3]);
4354 addReply(c,shared.ok);
4355 server.dirty++;
4356 }
4357 }
4358
4359 static void popGenericCommand(redisClient *c, int where) {
4360 robj *o;
4361 list *list;
4362 listNode *ln;
4363
4364 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4365 checkType(c,o,REDIS_LIST)) return;
4366 list = o->ptr;
4367
4368 if (where == REDIS_HEAD)
4369 ln = listFirst(list);
4370 else
4371 ln = listLast(list);
4372
4373 if (ln == NULL) {
4374 addReply(c,shared.nullbulk);
4375 } else {
4376 robj *ele = listNodeValue(ln);
4377 addReplyBulk(c,ele);
4378 listDelNode(list,ln);
4379 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
4380 server.dirty++;
4381 }
4382 }
4383
4384 static void lpopCommand(redisClient *c) {
4385 popGenericCommand(c,REDIS_HEAD);
4386 }
4387
4388 static void rpopCommand(redisClient *c) {
4389 popGenericCommand(c,REDIS_TAIL);
4390 }
4391
4392 static void lrangeCommand(redisClient *c) {
4393 robj *o;
4394 int start = atoi(c->argv[2]->ptr);
4395 int end = atoi(c->argv[3]->ptr);
4396 int llen;
4397 int rangelen, j;
4398 list *list;
4399 listNode *ln;
4400 robj *ele;
4401
4402 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullmultibulk)) == NULL ||
4403 checkType(c,o,REDIS_LIST)) return;
4404 list = o->ptr;
4405 llen = listLength(list);
4406
4407 /* convert negative indexes */
4408 if (start < 0) start = llen+start;
4409 if (end < 0) end = llen+end;
4410 if (start < 0) start = 0;
4411 if (end < 0) end = 0;
4412
4413 /* indexes sanity checks */
4414 if (start > end || start >= llen) {
4415 /* Out of range start or start > end result in empty list */
4416 addReply(c,shared.emptymultibulk);
4417 return;
4418 }
4419 if (end >= llen) end = llen-1;
4420 rangelen = (end-start)+1;
4421
4422 /* Return the result in form of a multi-bulk reply */
4423 ln = listIndex(list, start);
4424 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
4425 for (j = 0; j < rangelen; j++) {
4426 ele = listNodeValue(ln);
4427 addReplyBulk(c,ele);
4428 ln = ln->next;
4429 }
4430 }
4431
4432 static void ltrimCommand(redisClient *c) {
4433 robj *o;
4434 int start = atoi(c->argv[2]->ptr);
4435 int end = atoi(c->argv[3]->ptr);
4436 int llen;
4437 int j, ltrim, rtrim;
4438 list *list;
4439 listNode *ln;
4440
4441 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
4442 checkType(c,o,REDIS_LIST)) return;
4443 list = o->ptr;
4444 llen = listLength(list);
4445
4446 /* convert negative indexes */
4447 if (start < 0) start = llen+start;
4448 if (end < 0) end = llen+end;
4449 if (start < 0) start = 0;
4450 if (end < 0) end = 0;
4451
4452 /* indexes sanity checks */
4453 if (start > end || start >= llen) {
4454 /* Out of range start or start > end result in empty list */
4455 ltrim = llen;
4456 rtrim = 0;
4457 } else {
4458 if (end >= llen) end = llen-1;
4459 ltrim = start;
4460 rtrim = llen-end-1;
4461 }
4462
4463 /* Remove list elements to perform the trim */
4464 for (j = 0; j < ltrim; j++) {
4465 ln = listFirst(list);
4466 listDelNode(list,ln);
4467 }
4468 for (j = 0; j < rtrim; j++) {
4469 ln = listLast(list);
4470 listDelNode(list,ln);
4471 }
4472 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
4473 server.dirty++;
4474 addReply(c,shared.ok);
4475 }
4476
4477 static void lremCommand(redisClient *c) {
4478 robj *o;
4479 list *list;
4480 listNode *ln, *next;
4481 int toremove = atoi(c->argv[2]->ptr);
4482 int removed = 0;
4483 int fromtail = 0;
4484
4485 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
4486 checkType(c,o,REDIS_LIST)) return;
4487 list = o->ptr;
4488
4489 if (toremove < 0) {
4490 toremove = -toremove;
4491 fromtail = 1;
4492 }
4493 ln = fromtail ? list->tail : list->head;
4494 while (ln) {
4495 robj *ele = listNodeValue(ln);
4496
4497 next = fromtail ? ln->prev : ln->next;
4498 if (compareStringObjects(ele,c->argv[3]) == 0) {
4499 listDelNode(list,ln);
4500 server.dirty++;
4501 removed++;
4502 if (toremove && removed == toremove) break;
4503 }
4504 ln = next;
4505 }
4506 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
4507 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
4508 }
4509
4510 /* This is the semantic of this command:
4511 * RPOPLPUSH srclist dstlist:
4512 * IF LLEN(srclist) > 0
4513 * element = RPOP srclist
4514 * LPUSH dstlist element
4515 * RETURN element
4516 * ELSE
4517 * RETURN nil
4518 * END
4519 * END
4520 *
4521 * The idea is to be able to get an element from a list in a reliable way
4522 * since the element is not just returned but pushed against another list
4523 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4524 */
4525 static void rpoplpushcommand(redisClient *c) {
4526 robj *sobj;
4527 list *srclist;
4528 listNode *ln;
4529
4530 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4531 checkType(c,sobj,REDIS_LIST)) return;
4532 srclist = sobj->ptr;
4533 ln = listLast(srclist);
4534
4535 if (ln == NULL) {
4536 addReply(c,shared.nullbulk);
4537 } else {
4538 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
4539 robj *ele = listNodeValue(ln);
4540 list *dstlist;
4541
4542 if (dobj && dobj->type != REDIS_LIST) {
4543 addReply(c,shared.wrongtypeerr);
4544 return;
4545 }
4546
4547 /* Add the element to the target list (unless it's directly
4548 * passed to some BLPOP-ing client */
4549 if (!handleClientsWaitingListPush(c,c->argv[2],ele)) {
4550 if (dobj == NULL) {
4551 /* Create the list if the key does not exist */
4552 dobj = createListObject();
4553 dictAdd(c->db->dict,c->argv[2],dobj);
4554 incrRefCount(c->argv[2]);
4555 }
4556 dstlist = dobj->ptr;
4557 listAddNodeHead(dstlist,ele);
4558 incrRefCount(ele);
4559 }
4560
4561 /* Send the element to the client as reply as well */
4562 addReplyBulk(c,ele);
4563
4564 /* Finally remove the element from the source list */
4565 listDelNode(srclist,ln);
4566 if (listLength(srclist) == 0) deleteKey(c->db,c->argv[1]);
4567 server.dirty++;
4568 }
4569 }
4570
4571 /* ==================================== Sets ================================ */
4572
4573 static void saddCommand(redisClient *c) {
4574 robj *set;
4575
4576 set = lookupKeyWrite(c->db,c->argv[1]);
4577 if (set == NULL) {
4578 set = createSetObject();
4579 dictAdd(c->db->dict,c->argv[1],set);
4580 incrRefCount(c->argv[1]);
4581 } else {
4582 if (set->type != REDIS_SET) {
4583 addReply(c,shared.wrongtypeerr);
4584 return;
4585 }
4586 }
4587 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
4588 incrRefCount(c->argv[2]);
4589 server.dirty++;
4590 addReply(c,shared.cone);
4591 } else {
4592 addReply(c,shared.czero);
4593 }
4594 }
4595
4596 static void sremCommand(redisClient *c) {
4597 robj *set;
4598
4599 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
4600 checkType(c,set,REDIS_SET)) return;
4601
4602 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
4603 server.dirty++;
4604 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
4605 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
4606 addReply(c,shared.cone);
4607 } else {
4608 addReply(c,shared.czero);
4609 }
4610 }
4611
4612 static void smoveCommand(redisClient *c) {
4613 robj *srcset, *dstset;
4614
4615 srcset = lookupKeyWrite(c->db,c->argv[1]);
4616 dstset = lookupKeyWrite(c->db,c->argv[2]);
4617
4618 /* If the source key does not exist return 0, if it's of the wrong type
4619 * raise an error */
4620 if (srcset == NULL || srcset->type != REDIS_SET) {
4621 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
4622 return;
4623 }
4624 /* Error if the destination key is not a set as well */
4625 if (dstset && dstset->type != REDIS_SET) {
4626 addReply(c,shared.wrongtypeerr);
4627 return;
4628 }
4629 /* Remove the element from the source set */
4630 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
4631 /* Key not found in the src set! return zero */
4632 addReply(c,shared.czero);
4633 return;
4634 }
4635 if (dictSize((dict*)srcset->ptr) == 0 && srcset != dstset)
4636 deleteKey(c->db,c->argv[1]);
4637 server.dirty++;
4638 /* Add the element to the destination set */
4639 if (!dstset) {
4640 dstset = createSetObject();
4641 dictAdd(c->db->dict,c->argv[2],dstset);
4642 incrRefCount(c->argv[2]);
4643 }
4644 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
4645 incrRefCount(c->argv[3]);
4646 addReply(c,shared.cone);
4647 }
4648
4649 static void sismemberCommand(redisClient *c) {
4650 robj *set;
4651
4652 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
4653 checkType(c,set,REDIS_SET)) return;
4654
4655 if (dictFind(set->ptr,c->argv[2]))
4656 addReply(c,shared.cone);
4657 else
4658 addReply(c,shared.czero);
4659 }
4660
4661 static void scardCommand(redisClient *c) {
4662 robj *o;
4663 dict *s;
4664
4665 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
4666 checkType(c,o,REDIS_SET)) return;
4667
4668 s = o->ptr;
4669 addReplyUlong(c,dictSize(s));
4670 }
4671
4672 static void spopCommand(redisClient *c) {
4673 robj *set;
4674 dictEntry *de;
4675
4676 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4677 checkType(c,set,REDIS_SET)) return;
4678
4679 de = dictGetRandomKey(set->ptr);
4680 if (de == NULL) {
4681 addReply(c,shared.nullbulk);
4682 } else {
4683 robj *ele = dictGetEntryKey(de);
4684
4685 addReplyBulk(c,ele);
4686 dictDelete(set->ptr,ele);
4687 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
4688 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
4689 server.dirty++;
4690 }
4691 }
4692
4693 static void srandmemberCommand(redisClient *c) {
4694 robj *set;
4695 dictEntry *de;
4696
4697 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4698 checkType(c,set,REDIS_SET)) return;
4699
4700 de = dictGetRandomKey(set->ptr);
4701 if (de == NULL) {
4702 addReply(c,shared.nullbulk);
4703 } else {
4704 robj *ele = dictGetEntryKey(de);
4705
4706 addReplyBulk(c,ele);
4707 }
4708 }
4709
4710 static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
4711 dict **d1 = (void*) s1, **d2 = (void*) s2;
4712
4713 return dictSize(*d1)-dictSize(*d2);
4714 }
4715
4716 static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
4717 dict **dv = zmalloc(sizeof(dict*)*setsnum);
4718 dictIterator *di;
4719 dictEntry *de;
4720 robj *lenobj = NULL, *dstset = NULL;
4721 unsigned long j, cardinality = 0;
4722
4723 for (j = 0; j < setsnum; j++) {
4724 robj *setobj;
4725
4726 setobj = dstkey ?
4727 lookupKeyWrite(c->db,setskeys[j]) :
4728 lookupKeyRead(c->db,setskeys[j]);
4729 if (!setobj) {
4730 zfree(dv);
4731 if (dstkey) {
4732 if (deleteKey(c->db,dstkey))
4733 server.dirty++;
4734 addReply(c,shared.czero);
4735 } else {
4736 addReply(c,shared.nullmultibulk);
4737 }
4738 return;
4739 }
4740 if (setobj->type != REDIS_SET) {
4741 zfree(dv);
4742 addReply(c,shared.wrongtypeerr);
4743 return;
4744 }
4745 dv[j] = setobj->ptr;
4746 }
4747 /* Sort sets from the smallest to largest, this will improve our
4748 * algorithm's performace */
4749 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
4750
4751 /* The first thing we should output is the total number of elements...
4752 * since this is a multi-bulk write, but at this stage we don't know
4753 * the intersection set size, so we use a trick, append an empty object
4754 * to the output list and save the pointer to later modify it with the
4755 * right length */
4756 if (!dstkey) {
4757 lenobj = createObject(REDIS_STRING,NULL);
4758 addReply(c,lenobj);
4759 decrRefCount(lenobj);
4760 } else {
4761 /* If we have a target key where to store the resulting set
4762 * create this key with an empty set inside */
4763 dstset = createSetObject();
4764 }
4765
4766 /* Iterate all the elements of the first (smallest) set, and test
4767 * the element against all the other sets, if at least one set does
4768 * not include the element it is discarded */
4769 di = dictGetIterator(dv[0]);
4770
4771 while((de = dictNext(di)) != NULL) {
4772 robj *ele;
4773
4774 for (j = 1; j < setsnum; j++)
4775 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
4776 if (j != setsnum)
4777 continue; /* at least one set does not contain the member */
4778 ele = dictGetEntryKey(de);
4779 if (!dstkey) {
4780 addReplyBulk(c,ele);
4781 cardinality++;
4782 } else {
4783 dictAdd(dstset->ptr,ele,NULL);
4784 incrRefCount(ele);
4785 }
4786 }
4787 dictReleaseIterator(di);
4788
4789 if (dstkey) {
4790 /* Store the resulting set into the target, if the intersection
4791 * is not an empty set. */
4792 deleteKey(c->db,dstkey);
4793 if (dictSize((dict*)dstset->ptr) > 0) {
4794 dictAdd(c->db->dict,dstkey,dstset);
4795 incrRefCount(dstkey);
4796 addReplyLong(c,dictSize((dict*)dstset->ptr));
4797 } else {
4798 decrRefCount(dstset);
4799 addReply(c,shared.czero);
4800 }
4801 server.dirty++;
4802 } else {
4803 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
4804 }
4805 zfree(dv);
4806 }
4807
4808 static void sinterCommand(redisClient *c) {
4809 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
4810 }
4811
4812 static void sinterstoreCommand(redisClient *c) {
4813 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
4814 }
4815
4816 #define REDIS_OP_UNION 0
4817 #define REDIS_OP_DIFF 1
4818 #define REDIS_OP_INTER 2
4819
4820 static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
4821 dict **dv = zmalloc(sizeof(dict*)*setsnum);
4822 dictIterator *di;
4823 dictEntry *de;
4824 robj *dstset = NULL;
4825 int j, cardinality = 0;
4826
4827 for (j = 0; j < setsnum; j++) {
4828 robj *setobj;
4829
4830 setobj = dstkey ?
4831 lookupKeyWrite(c->db,setskeys[j]) :
4832 lookupKeyRead(c->db,setskeys[j]);
4833 if (!setobj) {
4834 dv[j] = NULL;
4835 continue;
4836 }
4837 if (setobj->type != REDIS_SET) {
4838 zfree(dv);
4839 addReply(c,shared.wrongtypeerr);
4840 return;
4841 }
4842 dv[j] = setobj->ptr;
4843 }
4844
4845 /* We need a temp set object to store our union. If the dstkey
4846 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4847 * this set object will be the resulting object to set into the target key*/
4848 dstset = createSetObject();
4849
4850 /* Iterate all the elements of all the sets, add every element a single
4851 * time to the result set */
4852 for (j = 0; j < setsnum; j++) {
4853 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
4854 if (!dv[j]) continue; /* non existing keys are like empty sets */
4855
4856 di = dictGetIterator(dv[j]);
4857
4858 while((de = dictNext(di)) != NULL) {
4859 robj *ele;
4860
4861 /* dictAdd will not add the same element multiple times */
4862 ele = dictGetEntryKey(de);
4863 if (op == REDIS_OP_UNION || j == 0) {
4864 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
4865 incrRefCount(ele);
4866 cardinality++;
4867 }
4868 } else if (op == REDIS_OP_DIFF) {
4869 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
4870 cardinality--;
4871 }
4872 }
4873 }
4874 dictReleaseIterator(di);
4875
4876 /* result set is empty? Exit asap. */
4877 if (op == REDIS_OP_DIFF && cardinality == 0) break;
4878 }
4879
4880 /* Output the content of the resulting set, if not in STORE mode */
4881 if (!dstkey) {
4882 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
4883 di = dictGetIterator(dstset->ptr);
4884 while((de = dictNext(di)) != NULL) {
4885 robj *ele;
4886
4887 ele = dictGetEntryKey(de);
4888 addReplyBulk(c,ele);
4889 }
4890 dictReleaseIterator(di);
4891 decrRefCount(dstset);
4892 } else {
4893 /* If we have a target key where to store the resulting set
4894 * create this key with the result set inside */
4895 deleteKey(c->db,dstkey);
4896 if (dictSize((dict*)dstset->ptr) > 0) {
4897 dictAdd(c->db->dict,dstkey,dstset);
4898 incrRefCount(dstkey);
4899 addReplyLong(c,dictSize((dict*)dstset->ptr));
4900 } else {
4901 decrRefCount(dstset);
4902 addReply(c,shared.czero);
4903 }
4904 server.dirty++;
4905 }
4906 zfree(dv);
4907 }
4908
4909 static void sunionCommand(redisClient *c) {
4910 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
4911 }
4912
4913 static void sunionstoreCommand(redisClient *c) {
4914 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
4915 }
4916
4917 static void sdiffCommand(redisClient *c) {
4918 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
4919 }
4920
4921 static void sdiffstoreCommand(redisClient *c) {
4922 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
4923 }
4924
4925 /* ==================================== ZSets =============================== */
4926
4927 /* ZSETs are ordered sets using two data structures to hold the same elements
4928 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4929 * data structure.
4930 *
4931 * The elements are added to an hash table mapping Redis objects to scores.
4932 * At the same time the elements are added to a skip list mapping scores
4933 * to Redis objects (so objects are sorted by scores in this "view"). */
4934
4935 /* This skiplist implementation is almost a C translation of the original
4936 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4937 * Alternative to Balanced Trees", modified in three ways:
4938 * a) this implementation allows for repeated values.
4939 * b) the comparison is not just by key (our 'score') but by satellite data.
4940 * c) there is a back pointer, so it's a doubly linked list with the back
4941 * pointers being only at "level 1". This allows to traverse the list
4942 * from tail to head, useful for ZREVRANGE. */
4943
4944 static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
4945 zskiplistNode *zn = zmalloc(sizeof(*zn));
4946
4947 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
4948 if (level > 0)
4949 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
4950 zn->score = score;
4951 zn->obj = obj;
4952 return zn;
4953 }
4954
4955 static zskiplist *zslCreate(void) {
4956 int j;
4957 zskiplist *zsl;
4958
4959 zsl = zmalloc(sizeof(*zsl));
4960 zsl->level = 1;
4961 zsl->length = 0;
4962 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
4963 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
4964 zsl->header->forward[j] = NULL;
4965
4966 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
4967 if (j < ZSKIPLIST_MAXLEVEL-1)
4968 zsl->header->span[j] = 0;
4969 }
4970 zsl->header->backward = NULL;
4971 zsl->tail = NULL;
4972 return zsl;
4973 }
4974
4975 static void zslFreeNode(zskiplistNode *node) {
4976 decrRefCount(node->obj);
4977 zfree(node->forward);
4978 zfree(node->span);
4979 zfree(node);
4980 }
4981
4982 static void zslFree(zskiplist *zsl) {
4983 zskiplistNode *node = zsl->header->forward[0], *next;
4984
4985 zfree(zsl->header->forward);
4986 zfree(zsl->header->span);
4987 zfree(zsl->header);
4988 while(node) {
4989 next = node->forward[0];
4990 zslFreeNode(node);
4991 node = next;
4992 }
4993 zfree(zsl);
4994 }
4995
4996 static int zslRandomLevel(void) {
4997 int level = 1;
4998 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
4999 level += 1;
5000 return level;
5001 }
5002
5003 static void zslInsert(zskiplist *zsl, double score, robj *obj) {
5004 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5005 unsigned int rank[ZSKIPLIST_MAXLEVEL];
5006 int i, level;
5007
5008 x = zsl->header;
5009 for (i = zsl->level-1; i >= 0; i--) {
5010 /* store rank that is crossed to reach the insert position */
5011 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
5012
5013 while (x->forward[i] &&
5014 (x->forward[i]->score < score ||
5015 (x->forward[i]->score == score &&
5016 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
5017 rank[i] += i > 0 ? x->span[i-1] : 1;
5018 x = x->forward[i];
5019 }
5020 update[i] = x;
5021 }
5022 /* we assume the key is not already inside, since we allow duplicated
5023 * scores, and the re-insertion of score and redis object should never
5024 * happpen since the caller of zslInsert() should test in the hash table
5025 * if the element is already inside or not. */
5026 level = zslRandomLevel();
5027 if (level > zsl->level) {
5028 for (i = zsl->level; i < level; i++) {
5029 rank[i] = 0;
5030 update[i] = zsl->header;
5031 update[i]->span[i-1] = zsl->length;
5032 }
5033 zsl->level = level;
5034 }
5035 x = zslCreateNode(level,score,obj);
5036 for (i = 0; i < level; i++) {
5037 x->forward[i] = update[i]->forward[i];
5038 update[i]->forward[i] = x;
5039
5040 /* update span covered by update[i] as x is inserted here */
5041 if (i > 0) {
5042 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
5043 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
5044 }
5045 }
5046
5047 /* increment span for untouched levels */
5048 for (i = level; i < zsl->level; i++) {
5049 update[i]->span[i-1]++;
5050 }
5051
5052 x->backward = (update[0] == zsl->header) ? NULL : update[0];
5053 if (x->forward[0])
5054 x->forward[0]->backward = x;
5055 else
5056 zsl->tail = x;
5057 zsl->length++;
5058 }
5059
5060 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5061 void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
5062 int i;
5063 for (i = 0; i < zsl->level; i++) {
5064 if (update[i]->forward[i] == x) {
5065 if (i > 0) {
5066 update[i]->span[i-1] += x->span[i-1] - 1;
5067 }
5068 update[i]->forward[i] = x->forward[i];
5069 } else {
5070 /* invariant: i > 0, because update[0]->forward[0]
5071 * is always equal to x */
5072 update[i]->span[i-1] -= 1;
5073 }
5074 }
5075 if (x->forward[0]) {
5076 x->forward[0]->backward = x->backward;
5077 } else {
5078 zsl->tail = x->backward;
5079 }
5080 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
5081 zsl->level--;
5082 zsl->length--;
5083 }
5084
5085 /* Delete an element with matching score/object from the skiplist. */
5086 static int zslDelete(zskiplist *zsl, double score, robj *obj) {
5087 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5088 int i;
5089
5090 x = zsl->header;
5091 for (i = zsl->level-1; i >= 0; i--) {
5092 while (x->forward[i] &&
5093 (x->forward[i]->score < score ||
5094 (x->forward[i]->score == score &&
5095 compareStringObjects(x->forward[i]->obj,obj) < 0)))
5096 x = x->forward[i];
5097 update[i] = x;
5098 }
5099 /* We may have multiple elements with the same score, what we need
5100 * is to find the element with both the right score and object. */
5101 x = x->forward[0];
5102 if (x && score == x->score && compareStringObjects(x->obj,obj) == 0) {
5103 zslDeleteNode(zsl, x, update);
5104 zslFreeNode(x);
5105 return 1;
5106 } else {
5107 return 0; /* not found */
5108 }
5109 return 0; /* not found */
5110 }
5111
5112 /* Delete all the elements with score between min and max from the skiplist.
5113 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5114 * Note that this function takes the reference to the hash table view of the
5115 * sorted set, in order to remove the elements from the hash table too. */
5116 static unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
5117 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5118 unsigned long removed = 0;
5119 int i;
5120
5121 x = zsl->header;
5122 for (i = zsl->level-1; i >= 0; i--) {
5123 while (x->forward[i] && x->forward[i]->score < min)
5124 x = x->forward[i];
5125 update[i] = x;
5126 }
5127 /* We may have multiple elements with the same score, what we need
5128 * is to find the element with both the right score and object. */
5129 x = x->forward[0];
5130 while (x && x->score <= max) {
5131 zskiplistNode *next = x->forward[0];
5132 zslDeleteNode(zsl, x, update);
5133 dictDelete(dict,x->obj);
5134 zslFreeNode(x);
5135 removed++;
5136 x = next;
5137 }
5138 return removed; /* not found */
5139 }
5140
5141 /* Delete all the elements with rank between start and end from the skiplist.
5142 * Start and end are inclusive. Note that start and end need to be 1-based */
5143 static unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
5144 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5145 unsigned long traversed = 0, removed = 0;
5146 int i;
5147
5148 x = zsl->header;
5149 for (i = zsl->level-1; i >= 0; i--) {
5150 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
5151 traversed += i > 0 ? x->span[i-1] : 1;
5152 x = x->forward[i];
5153 }
5154 update[i] = x;
5155 }
5156
5157 traversed++;
5158 x = x->forward[0];
5159 while (x && traversed <= end) {
5160 zskiplistNode *next = x->forward[0];
5161 zslDeleteNode(zsl, x, update);
5162 dictDelete(dict,x->obj);
5163 zslFreeNode(x);
5164 removed++;
5165 traversed++;
5166 x = next;
5167 }
5168 return removed;
5169 }
5170
5171 /* Find the first node having a score equal or greater than the specified one.
5172 * Returns NULL if there is no match. */
5173 static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
5174 zskiplistNode *x;
5175 int i;
5176
5177 x = zsl->header;
5178 for (i = zsl->level-1; i >= 0; i--) {
5179 while (x->forward[i] && x->forward[i]->score < score)
5180 x = x->forward[i];
5181 }
5182 /* We may have multiple elements with the same score, what we need
5183 * is to find the element with both the right score and object. */
5184 return x->forward[0];
5185 }
5186
5187 /* Find the rank for an element by both score and key.
5188 * Returns 0 when the element cannot be found, rank otherwise.
5189 * Note that the rank is 1-based due to the span of zsl->header to the
5190 * first element. */
5191 static unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
5192 zskiplistNode *x;
5193 unsigned long rank = 0;
5194 int i;
5195
5196 x = zsl->header;
5197 for (i = zsl->level-1; i >= 0; i--) {
5198 while (x->forward[i] &&
5199 (x->forward[i]->score < score ||
5200 (x->forward[i]->score == score &&
5201 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
5202 rank += i > 0 ? x->span[i-1] : 1;
5203 x = x->forward[i];
5204 }
5205
5206 /* x might be equal to zsl->header, so test if obj is non-NULL */
5207 if (x->obj && compareStringObjects(x->obj,o) == 0) {
5208 return rank;
5209 }
5210 }
5211 return 0;
5212 }
5213
5214 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5215 zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
5216 zskiplistNode *x;
5217 unsigned long traversed = 0;
5218 int i;
5219
5220 x = zsl->header;
5221 for (i = zsl->level-1; i >= 0; i--) {
5222 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
5223 {
5224 traversed += i > 0 ? x->span[i-1] : 1;
5225 x = x->forward[i];
5226 }
5227 if (traversed == rank) {
5228 return x;
5229 }
5230 }
5231 return NULL;
5232 }
5233
5234 /* The actual Z-commands implementations */
5235
5236 /* This generic command implements both ZADD and ZINCRBY.
5237 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5238 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5239 static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
5240 robj *zsetobj;
5241 zset *zs;
5242 double *score;
5243
5244 zsetobj = lookupKeyWrite(c->db,key);
5245 if (zsetobj == NULL) {
5246 zsetobj = createZsetObject();
5247 dictAdd(c->db->dict,key,zsetobj);
5248 incrRefCount(key);
5249 } else {
5250 if (zsetobj->type != REDIS_ZSET) {
5251 addReply(c,shared.wrongtypeerr);
5252 return;
5253 }
5254 }
5255 zs = zsetobj->ptr;
5256
5257 /* Ok now since we implement both ZADD and ZINCRBY here the code
5258 * needs to handle the two different conditions. It's all about setting
5259 * '*score', that is, the new score to set, to the right value. */
5260 score = zmalloc(sizeof(double));
5261 if (doincrement) {
5262 dictEntry *de;
5263
5264 /* Read the old score. If the element was not present starts from 0 */
5265 de = dictFind(zs->dict,ele);
5266 if (de) {
5267 double *oldscore = dictGetEntryVal(de);
5268 *score = *oldscore + scoreval;
5269 } else {
5270 *score = scoreval;
5271 }
5272 } else {
5273 *score = scoreval;
5274 }
5275
5276 /* What follows is a simple remove and re-insert operation that is common
5277 * to both ZADD and ZINCRBY... */
5278 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
5279 /* case 1: New element */
5280 incrRefCount(ele); /* added to hash */
5281 zslInsert(zs->zsl,*score,ele);
5282 incrRefCount(ele); /* added to skiplist */
5283 server.dirty++;
5284 if (doincrement)
5285 addReplyDouble(c,*score);
5286 else
5287 addReply(c,shared.cone);
5288 } else {
5289 dictEntry *de;
5290 double *oldscore;
5291
5292 /* case 2: Score update operation */
5293 de = dictFind(zs->dict,ele);
5294 redisAssert(de != NULL);
5295 oldscore = dictGetEntryVal(de);
5296 if (*score != *oldscore) {
5297 int deleted;
5298
5299 /* Remove and insert the element in the skip list with new score */
5300 deleted = zslDelete(zs->zsl,*oldscore,ele);
5301 redisAssert(deleted != 0);
5302 zslInsert(zs->zsl,*score,ele);
5303 incrRefCount(ele);
5304 /* Update the score in the hash table */
5305 dictReplace(zs->dict,ele,score);
5306 server.dirty++;
5307 } else {
5308 zfree(score);
5309 }
5310 if (doincrement)
5311 addReplyDouble(c,*score);
5312 else
5313 addReply(c,shared.czero);
5314 }
5315 }
5316
5317 static void zaddCommand(redisClient *c) {
5318 double scoreval;
5319
5320 scoreval = strtod(c->argv[2]->ptr,NULL);
5321 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
5322 }
5323
5324 static void zincrbyCommand(redisClient *c) {
5325 double scoreval;
5326
5327 scoreval = strtod(c->argv[2]->ptr,NULL);
5328 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
5329 }
5330
5331 static void zremCommand(redisClient *c) {
5332 robj *zsetobj;
5333 zset *zs;
5334 dictEntry *de;
5335 double *oldscore;
5336 int deleted;
5337
5338 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5339 checkType(c,zsetobj,REDIS_ZSET)) return;
5340
5341 zs = zsetobj->ptr;
5342 de = dictFind(zs->dict,c->argv[2]);
5343 if (de == NULL) {
5344 addReply(c,shared.czero);
5345 return;
5346 }
5347 /* Delete from the skiplist */
5348 oldscore = dictGetEntryVal(de);
5349 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
5350 redisAssert(deleted != 0);
5351
5352 /* Delete from the hash table */
5353 dictDelete(zs->dict,c->argv[2]);
5354 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
5355 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
5356 server.dirty++;
5357 addReply(c,shared.cone);
5358 }
5359
5360 static void zremrangebyscoreCommand(redisClient *c) {
5361 double min = strtod(c->argv[2]->ptr,NULL);
5362 double max = strtod(c->argv[3]->ptr,NULL);
5363 long deleted;
5364 robj *zsetobj;
5365 zset *zs;
5366
5367 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5368 checkType(c,zsetobj,REDIS_ZSET)) return;
5369
5370 zs = zsetobj->ptr;
5371 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
5372 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
5373 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
5374 server.dirty += deleted;
5375 addReplyLong(c,deleted);
5376 }
5377
5378 static void zremrangebyrankCommand(redisClient *c) {
5379 int start = atoi(c->argv[2]->ptr);
5380 int end = atoi(c->argv[3]->ptr);
5381 int llen;
5382 long deleted;
5383 robj *zsetobj;
5384 zset *zs;
5385
5386 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5387 checkType(c,zsetobj,REDIS_ZSET)) return;
5388 zs = zsetobj->ptr;
5389 llen = zs->zsl->length;
5390
5391 /* convert negative indexes */
5392 if (start < 0) start = llen+start;
5393 if (end < 0) end = llen+end;
5394 if (start < 0) start = 0;
5395 if (end < 0) end = 0;
5396
5397 /* indexes sanity checks */
5398 if (start > end || start >= llen) {
5399 addReply(c,shared.czero);
5400 return;
5401 }
5402 if (end >= llen) end = llen-1;
5403
5404 /* increment start and end because zsl*Rank functions
5405 * use 1-based rank */
5406 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
5407 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
5408 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
5409 server.dirty += deleted;
5410 addReplyLong(c, deleted);
5411 }
5412
5413 typedef struct {
5414 dict *dict;
5415 double weight;
5416 } zsetopsrc;
5417
5418 static int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
5419 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
5420 unsigned long size1, size2;
5421 size1 = d1->dict ? dictSize(d1->dict) : 0;
5422 size2 = d2->dict ? dictSize(d2->dict) : 0;
5423 return size1 - size2;
5424 }
5425
5426 #define REDIS_AGGR_SUM 1
5427 #define REDIS_AGGR_MIN 2
5428 #define REDIS_AGGR_MAX 3
5429
5430 inline static void zunionInterAggregate(double *target, double val, int aggregate) {
5431 if (aggregate == REDIS_AGGR_SUM) {
5432 *target = *target + val;
5433 } else if (aggregate == REDIS_AGGR_MIN) {
5434 *target = val < *target ? val : *target;
5435 } else if (aggregate == REDIS_AGGR_MAX) {
5436 *target = val > *target ? val : *target;
5437 } else {
5438 /* safety net */
5439 redisAssert(0 != 0);
5440 }
5441 }
5442
5443 static void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
5444 int i, j, zsetnum;
5445 int aggregate = REDIS_AGGR_SUM;
5446 zsetopsrc *src;
5447 robj *dstobj;
5448 zset *dstzset;
5449 dictIterator *di;
5450 dictEntry *de;
5451
5452 /* expect zsetnum input keys to be given */
5453 zsetnum = atoi(c->argv[2]->ptr);
5454 if (zsetnum < 1) {
5455 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNION/ZINTER\r\n"));
5456 return;
5457 }
5458
5459 /* test if the expected number of keys would overflow */
5460 if (3+zsetnum > c->argc) {
5461 addReply(c,shared.syntaxerr);
5462 return;
5463 }
5464
5465 /* read keys to be used for input */
5466 src = zmalloc(sizeof(zsetopsrc) * zsetnum);
5467 for (i = 0, j = 3; i < zsetnum; i++, j++) {
5468 robj *zsetobj = lookupKeyWrite(c->db,c->argv[j]);
5469 if (!zsetobj) {
5470 src[i].dict = NULL;
5471 } else {
5472 if (zsetobj->type != REDIS_ZSET) {
5473 zfree(src);
5474 addReply(c,shared.wrongtypeerr);
5475 return;
5476 }
5477 src[i].dict = ((zset*)zsetobj->ptr)->dict;
5478 }
5479
5480 /* default all weights to 1 */
5481 src[i].weight = 1.0;
5482 }
5483
5484 /* parse optional extra arguments */
5485 if (j < c->argc) {
5486 int remaining = c->argc - j;
5487
5488 while (remaining) {
5489 if (remaining >= (zsetnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
5490 j++; remaining--;
5491 for (i = 0; i < zsetnum; i++, j++, remaining--) {
5492 src[i].weight = strtod(c->argv[j]->ptr, NULL);
5493 }
5494 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
5495 j++; remaining--;
5496 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
5497 aggregate = REDIS_AGGR_SUM;
5498 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
5499 aggregate = REDIS_AGGR_MIN;
5500 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
5501 aggregate = REDIS_AGGR_MAX;
5502 } else {
5503 zfree(src);
5504 addReply(c,shared.syntaxerr);
5505 return;
5506 }
5507 j++; remaining--;
5508 } else {
5509 zfree(src);
5510 addReply(c,shared.syntaxerr);
5511 return;
5512 }
5513 }
5514 }
5515
5516 /* sort sets from the smallest to largest, this will improve our
5517 * algorithm's performance */
5518 qsort(src,zsetnum,sizeof(zsetopsrc), qsortCompareZsetopsrcByCardinality);
5519
5520 dstobj = createZsetObject();
5521 dstzset = dstobj->ptr;
5522
5523 if (op == REDIS_OP_INTER) {
5524 /* skip going over all entries if the smallest zset is NULL or empty */
5525 if (src[0].dict && dictSize(src[0].dict) > 0) {
5526 /* precondition: as src[0].dict is non-empty and the zsets are ordered
5527 * from small to large, all src[i > 0].dict are non-empty too */
5528 di = dictGetIterator(src[0].dict);
5529 while((de = dictNext(di)) != NULL) {
5530 double *score = zmalloc(sizeof(double)), value;
5531 *score = src[0].weight * (*(double*)dictGetEntryVal(de));
5532
5533 for (j = 1; j < zsetnum; j++) {
5534 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
5535 if (other) {
5536 value = src[j].weight * (*(double*)dictGetEntryVal(other));
5537 zunionInterAggregate(score, value, aggregate);
5538 } else {
5539 break;
5540 }
5541 }
5542
5543 /* skip entry when not present in every source dict */
5544 if (j != zsetnum) {
5545 zfree(score);
5546 } else {
5547 robj *o = dictGetEntryKey(de);
5548 dictAdd(dstzset->dict,o,score);
5549 incrRefCount(o); /* added to dictionary */
5550 zslInsert(dstzset->zsl,*score,o);
5551 incrRefCount(o); /* added to skiplist */
5552 }
5553 }
5554 dictReleaseIterator(di);
5555 }
5556 } else if (op == REDIS_OP_UNION) {
5557 for (i = 0; i < zsetnum; i++) {
5558 if (!src[i].dict) continue;
5559
5560 di = dictGetIterator(src[i].dict);
5561 while((de = dictNext(di)) != NULL) {
5562 /* skip key when already processed */
5563 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
5564
5565 double *score = zmalloc(sizeof(double)), value;
5566 *score = src[i].weight * (*(double*)dictGetEntryVal(de));
5567
5568 /* because the zsets are sorted by size, its only possible
5569 * for sets at larger indices to hold this entry */
5570 for (j = (i+1); j < zsetnum; j++) {
5571 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
5572 if (other) {
5573 value = src[j].weight * (*(double*)dictGetEntryVal(other));
5574 zunionInterAggregate(score, value, aggregate);
5575 }
5576 }
5577
5578 robj *o = dictGetEntryKey(de);
5579 dictAdd(dstzset->dict,o,score);
5580 incrRefCount(o); /* added to dictionary */
5581 zslInsert(dstzset->zsl,*score,o);
5582 incrRefCount(o); /* added to skiplist */
5583 }
5584 dictReleaseIterator(di);
5585 }
5586 } else {
5587 /* unknown operator */
5588 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
5589 }
5590
5591 deleteKey(c->db,dstkey);
5592 if (dstzset->zsl->length) {
5593 dictAdd(c->db->dict,dstkey,dstobj);
5594 incrRefCount(dstkey);
5595 addReplyLong(c, dstzset->zsl->length);
5596 server.dirty++;
5597 } else {
5598 decrRefCount(dstzset);
5599 addReply(c, shared.czero);
5600 }
5601 zfree(src);
5602 }
5603
5604 static void zunionCommand(redisClient *c) {
5605 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
5606 }
5607
5608 static void zinterCommand(redisClient *c) {
5609 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
5610 }
5611
5612 static void zrangeGenericCommand(redisClient *c, int reverse) {
5613 robj *o;
5614 int start = atoi(c->argv[2]->ptr);
5615 int end = atoi(c->argv[3]->ptr);
5616 int withscores = 0;
5617 int llen;
5618 int rangelen, j;
5619 zset *zsetobj;
5620 zskiplist *zsl;
5621 zskiplistNode *ln;
5622 robj *ele;
5623
5624 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
5625 withscores = 1;
5626 } else if (c->argc >= 5) {
5627 addReply(c,shared.syntaxerr);
5628 return;
5629 }
5630
5631 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullmultibulk)) == NULL ||
5632 checkType(c,o,REDIS_ZSET)) return;
5633 zsetobj = o->ptr;
5634 zsl = zsetobj->zsl;
5635 llen = zsl->length;
5636
5637 /* convert negative indexes */
5638 if (start < 0) start = llen+start;
5639 if (end < 0) end = llen+end;
5640 if (start < 0) start = 0;
5641 if (end < 0) end = 0;
5642
5643 /* indexes sanity checks */
5644 if (start > end || start >= llen) {
5645 /* Out of range start or start > end result in empty list */
5646 addReply(c,shared.emptymultibulk);
5647 return;
5648 }
5649 if (end >= llen) end = llen-1;
5650 rangelen = (end-start)+1;
5651
5652 /* check if starting point is trivial, before searching
5653 * the element in log(N) time */
5654 if (reverse) {
5655 ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start);
5656 } else {
5657 ln = start == 0 ?
5658 zsl->header->forward[0] : zslGetElementByRank(zsl, start+1);
5659 }
5660
5661 /* Return the result in form of a multi-bulk reply */
5662 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
5663 withscores ? (rangelen*2) : rangelen));
5664 for (j = 0; j < rangelen; j++) {
5665 ele = ln->obj;
5666 addReplyBulk(c,ele);
5667 if (withscores)
5668 addReplyDouble(c,ln->score);
5669 ln = reverse ? ln->backward : ln->forward[0];
5670 }
5671 }
5672
5673 static void zrangeCommand(redisClient *c) {
5674 zrangeGenericCommand(c,0);
5675 }
5676
5677 static void zrevrangeCommand(redisClient *c) {
5678 zrangeGenericCommand(c,1);
5679 }
5680
5681 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
5682 * If justcount is non-zero, just the count is returned. */
5683 static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
5684 robj *o;
5685 double min, max;
5686 int minex = 0, maxex = 0; /* are min or max exclusive? */
5687 int offset = 0, limit = -1;
5688 int withscores = 0;
5689 int badsyntax = 0;
5690
5691 /* Parse the min-max interval. If one of the values is prefixed
5692 * by the "(" character, it's considered "open". For instance
5693 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
5694 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
5695 if (((char*)c->argv[2]->ptr)[0] == '(') {
5696 min = strtod((char*)c->argv[2]->ptr+1,NULL);
5697 minex = 1;
5698 } else {
5699 min = strtod(c->argv[2]->ptr,NULL);
5700 }
5701 if (((char*)c->argv[3]->ptr)[0] == '(') {
5702 max = strtod((char*)c->argv[3]->ptr+1,NULL);
5703 maxex = 1;
5704 } else {
5705 max = strtod(c->argv[3]->ptr,NULL);
5706 }
5707
5708 /* Parse "WITHSCORES": note that if the command was called with
5709 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
5710 * enter the following paths to parse WITHSCORES and LIMIT. */
5711 if (c->argc == 5 || c->argc == 8) {
5712 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
5713 withscores = 1;
5714 else
5715 badsyntax = 1;
5716 }
5717 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
5718 badsyntax = 1;
5719 if (badsyntax) {
5720 addReplySds(c,
5721 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5722 return;
5723 }
5724
5725 /* Parse "LIMIT" */
5726 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
5727 addReply(c,shared.syntaxerr);
5728 return;
5729 } else if (c->argc == (7 + withscores)) {
5730 offset = atoi(c->argv[5]->ptr);
5731 limit = atoi(c->argv[6]->ptr);
5732 if (offset < 0) offset = 0;
5733 }
5734
5735 /* Ok, lookup the key and get the range */
5736 o = lookupKeyRead(c->db,c->argv[1]);
5737 if (o == NULL) {
5738 addReply(c,justcount ? shared.czero : shared.nullmultibulk);
5739 } else {
5740 if (o->type != REDIS_ZSET) {
5741 addReply(c,shared.wrongtypeerr);
5742 } else {
5743 zset *zsetobj = o->ptr;
5744 zskiplist *zsl = zsetobj->zsl;
5745 zskiplistNode *ln;
5746 robj *ele, *lenobj = NULL;
5747 unsigned long rangelen = 0;
5748
5749 /* Get the first node with the score >= min, or with
5750 * score > min if 'minex' is true. */
5751 ln = zslFirstWithScore(zsl,min);
5752 while (minex && ln && ln->score == min) ln = ln->forward[0];
5753
5754 if (ln == NULL) {
5755 /* No element matching the speciifed interval */
5756 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
5757 return;
5758 }
5759
5760 /* We don't know in advance how many matching elements there
5761 * are in the list, so we push this object that will represent
5762 * the multi-bulk length in the output buffer, and will "fix"
5763 * it later */
5764 if (!justcount) {
5765 lenobj = createObject(REDIS_STRING,NULL);
5766 addReply(c,lenobj);
5767 decrRefCount(lenobj);
5768 }
5769
5770 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
5771 if (offset) {
5772 offset--;
5773 ln = ln->forward[0];
5774 continue;
5775 }
5776 if (limit == 0) break;
5777 if (!justcount) {
5778 ele = ln->obj;
5779 addReplyBulk(c,ele);
5780 if (withscores)
5781 addReplyDouble(c,ln->score);
5782 }
5783 ln = ln->forward[0];
5784 rangelen++;
5785 if (limit > 0) limit--;
5786 }
5787 if (justcount) {
5788 addReplyLong(c,(long)rangelen);
5789 } else {
5790 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
5791 withscores ? (rangelen*2) : rangelen);
5792 }
5793 }
5794 }
5795 }
5796
5797 static void zrangebyscoreCommand(redisClient *c) {
5798 genericZrangebyscoreCommand(c,0);
5799 }
5800
5801 static void zcountCommand(redisClient *c) {
5802 genericZrangebyscoreCommand(c,1);
5803 }
5804
5805 static void zcardCommand(redisClient *c) {
5806 robj *o;
5807 zset *zs;
5808
5809 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5810 checkType(c,o,REDIS_ZSET)) return;
5811
5812 zs = o->ptr;
5813 addReplyUlong(c,zs->zsl->length);
5814 }
5815
5816 static void zscoreCommand(redisClient *c) {
5817 robj *o;
5818 zset *zs;
5819 dictEntry *de;
5820
5821 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5822 checkType(c,o,REDIS_ZSET)) return;
5823
5824 zs = o->ptr;
5825 de = dictFind(zs->dict,c->argv[2]);
5826 if (!de) {
5827 addReply(c,shared.nullbulk);
5828 } else {
5829 double *score = dictGetEntryVal(de);
5830
5831 addReplyDouble(c,*score);
5832 }
5833 }
5834
5835 static void zrankGenericCommand(redisClient *c, int reverse) {
5836 robj *o;
5837 zset *zs;
5838 zskiplist *zsl;
5839 dictEntry *de;
5840 unsigned long rank;
5841 double *score;
5842
5843 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5844 checkType(c,o,REDIS_ZSET)) return;
5845
5846 zs = o->ptr;
5847 zsl = zs->zsl;
5848 de = dictFind(zs->dict,c->argv[2]);
5849 if (!de) {
5850 addReply(c,shared.nullbulk);
5851 return;
5852 }
5853
5854 score = dictGetEntryVal(de);
5855 rank = zslGetRank(zsl, *score, c->argv[2]);
5856 if (rank) {
5857 if (reverse) {
5858 addReplyLong(c, zsl->length - rank);
5859 } else {
5860 addReplyLong(c, rank-1);
5861 }
5862 } else {
5863 addReply(c,shared.nullbulk);
5864 }
5865 }
5866
5867 static void zrankCommand(redisClient *c) {
5868 zrankGenericCommand(c, 0);
5869 }
5870
5871 static void zrevrankCommand(redisClient *c) {
5872 zrankGenericCommand(c, 1);
5873 }
5874
5875 /* =================================== Hashes =============================== */
5876 static void hsetCommand(redisClient *c) {
5877 int update = 0;
5878 robj *o = lookupKeyWrite(c->db,c->argv[1]);
5879
5880 if (o == NULL) {
5881 o = createHashObject();
5882 dictAdd(c->db->dict,c->argv[1],o);
5883 incrRefCount(c->argv[1]);
5884 } else {
5885 if (o->type != REDIS_HASH) {
5886 addReply(c,shared.wrongtypeerr);
5887 return;
5888 }
5889 }
5890 /* We want to convert the zipmap into an hash table right now if the
5891 * entry to be added is too big. Note that we check if the object
5892 * is integer encoded before to try fetching the length in the test below.
5893 * This is because integers are small, but currently stringObjectLen()
5894 * performs a slow conversion: not worth it. */
5895 if (o->encoding == REDIS_ENCODING_ZIPMAP &&
5896 ((c->argv[2]->encoding == REDIS_ENCODING_RAW &&
5897 sdslen(c->argv[2]->ptr) > server.hash_max_zipmap_value) ||
5898 (c->argv[3]->encoding == REDIS_ENCODING_RAW &&
5899 sdslen(c->argv[3]->ptr) > server.hash_max_zipmap_value)))
5900 {
5901 convertToRealHash(o);
5902 }
5903
5904 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
5905 unsigned char *zm = o->ptr;
5906 robj *valobj = getDecodedObject(c->argv[3]);
5907
5908 zm = zipmapSet(zm,c->argv[2]->ptr,sdslen(c->argv[2]->ptr),
5909 valobj->ptr,sdslen(valobj->ptr),&update);
5910 decrRefCount(valobj);
5911 o->ptr = zm;
5912
5913 /* And here there is the second check for hash conversion...
5914 * we want to do it only if the operation was not just an update as
5915 * zipmapLen() is O(N). */
5916 if (!update && zipmapLen(zm) > server.hash_max_zipmap_entries)
5917 convertToRealHash(o);
5918 } else {
5919 tryObjectEncoding(c->argv[2]);
5920 /* note that c->argv[3] is already encoded, as the latest arg
5921 * of a bulk command is always integer encoded if possible. */
5922 if (dictReplace(o->ptr,c->argv[2],c->argv[3])) {
5923 incrRefCount(c->argv[2]);
5924 } else {
5925 update = 1;
5926 }
5927 incrRefCount(c->argv[3]);
5928 }
5929 server.dirty++;
5930 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",update == 0));
5931 }
5932
5933 static void hgetCommand(redisClient *c) {
5934 robj *o;
5935
5936 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5937 checkType(c,o,REDIS_HASH)) return;
5938
5939 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
5940 unsigned char *zm = o->ptr;
5941 unsigned char *val;
5942 unsigned int vlen;
5943 robj *field;
5944
5945 field = getDecodedObject(c->argv[2]);
5946 if (zipmapGet(zm,field->ptr,sdslen(field->ptr), &val,&vlen)) {
5947 addReplySds(c,sdscatprintf(sdsempty(),"$%u\r\n", vlen));
5948 addReplySds(c,sdsnewlen(val,vlen));
5949 addReply(c,shared.crlf);
5950 decrRefCount(field);
5951 return;
5952 } else {
5953 addReply(c,shared.nullbulk);
5954 decrRefCount(field);
5955 return;
5956 }
5957 } else {
5958 struct dictEntry *de;
5959
5960 de = dictFind(o->ptr,c->argv[2]);
5961 if (de == NULL) {
5962 addReply(c,shared.nullbulk);
5963 } else {
5964 robj *e = dictGetEntryVal(de);
5965
5966 addReplyBulk(c,e);
5967 }
5968 }
5969 }
5970
5971 static void hdelCommand(redisClient *c) {
5972 robj *o;
5973 int deleted = 0;
5974
5975 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5976 checkType(c,o,REDIS_HASH)) return;
5977
5978 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
5979 robj *field = getDecodedObject(c->argv[2]);
5980
5981 o->ptr = zipmapDel((unsigned char*) o->ptr,
5982 (unsigned char*) field->ptr,
5983 sdslen(field->ptr), &deleted);
5984 decrRefCount(field);
5985 if (zipmapLen((unsigned char*) o->ptr) == 0)
5986 deleteKey(c->db,c->argv[1]);
5987 } else {
5988 deleted = dictDelete((dict*)o->ptr,c->argv[2]) == DICT_OK;
5989 if (htNeedsResize(o->ptr)) dictResize(o->ptr);
5990 if (dictSize((dict*)o->ptr) == 0) deleteKey(c->db,c->argv[1]);
5991 }
5992 if (deleted) server.dirty++;
5993 addReply(c,deleted ? shared.cone : shared.czero);
5994 }
5995
5996 static void hlenCommand(redisClient *c) {
5997 robj *o;
5998 unsigned long len;
5999
6000 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6001 checkType(c,o,REDIS_HASH)) return;
6002
6003 len = (o->encoding == REDIS_ENCODING_ZIPMAP) ?
6004 zipmapLen((unsigned char*)o->ptr) : dictSize((dict*)o->ptr);
6005 addReplyUlong(c,len);
6006 }
6007
6008 #define REDIS_GETALL_KEYS 1
6009 #define REDIS_GETALL_VALS 2
6010 static void genericHgetallCommand(redisClient *c, int flags) {
6011 robj *o, *lenobj;
6012 unsigned long count = 0;
6013
6014 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullmultibulk)) == NULL
6015 || checkType(c,o,REDIS_HASH)) return;
6016
6017 lenobj = createObject(REDIS_STRING,NULL);
6018 addReply(c,lenobj);
6019 decrRefCount(lenobj);
6020
6021 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6022 unsigned char *p = zipmapRewind(o->ptr);
6023 unsigned char *field, *val;
6024 unsigned int flen, vlen;
6025
6026 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
6027 robj *aux;
6028
6029 if (flags & REDIS_GETALL_KEYS) {
6030 aux = createStringObject((char*)field,flen);
6031 addReplyBulk(c,aux);
6032 decrRefCount(aux);
6033 count++;
6034 }
6035 if (flags & REDIS_GETALL_VALS) {
6036 aux = createStringObject((char*)val,vlen);
6037 addReplyBulk(c,aux);
6038 decrRefCount(aux);
6039 count++;
6040 }
6041 }
6042 } else {
6043 dictIterator *di = dictGetIterator(o->ptr);
6044 dictEntry *de;
6045
6046 while((de = dictNext(di)) != NULL) {
6047 robj *fieldobj = dictGetEntryKey(de);
6048 robj *valobj = dictGetEntryVal(de);
6049
6050 if (flags & REDIS_GETALL_KEYS) {
6051 addReplyBulk(c,fieldobj);
6052 count++;
6053 }
6054 if (flags & REDIS_GETALL_VALS) {
6055 addReplyBulk(c,valobj);
6056 count++;
6057 }
6058 }
6059 dictReleaseIterator(di);
6060 }
6061 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",count);
6062 }
6063
6064 static void hkeysCommand(redisClient *c) {
6065 genericHgetallCommand(c,REDIS_GETALL_KEYS);
6066 }
6067
6068 static void hvalsCommand(redisClient *c) {
6069 genericHgetallCommand(c,REDIS_GETALL_VALS);
6070 }
6071
6072 static void hgetallCommand(redisClient *c) {
6073 genericHgetallCommand(c,REDIS_GETALL_KEYS|REDIS_GETALL_VALS);
6074 }
6075
6076 static void hexistsCommand(redisClient *c) {
6077 robj *o;
6078 int exists = 0;
6079
6080 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6081 checkType(c,o,REDIS_HASH)) return;
6082
6083 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6084 robj *field;
6085 unsigned char *zm = o->ptr;
6086
6087 field = getDecodedObject(c->argv[2]);
6088 exists = zipmapExists(zm,field->ptr,sdslen(field->ptr));
6089 decrRefCount(field);
6090 } else {
6091 exists = dictFind(o->ptr,c->argv[2]) != NULL;
6092 }
6093 addReply(c,exists ? shared.cone : shared.czero);
6094 }
6095
6096 static void convertToRealHash(robj *o) {
6097 unsigned char *key, *val, *p, *zm = o->ptr;
6098 unsigned int klen, vlen;
6099 dict *dict = dictCreate(&hashDictType,NULL);
6100
6101 assert(o->type == REDIS_HASH && o->encoding != REDIS_ENCODING_HT);
6102 p = zipmapRewind(zm);
6103 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
6104 robj *keyobj, *valobj;
6105
6106 keyobj = createStringObject((char*)key,klen);
6107 valobj = createStringObject((char*)val,vlen);
6108 tryObjectEncoding(keyobj);
6109 tryObjectEncoding(valobj);
6110 dictAdd(dict,keyobj,valobj);
6111 }
6112 o->encoding = REDIS_ENCODING_HT;
6113 o->ptr = dict;
6114 zfree(zm);
6115 }
6116
6117 /* ========================= Non type-specific commands ==================== */
6118
6119 static void flushdbCommand(redisClient *c) {
6120 server.dirty += dictSize(c->db->dict);
6121 dictEmpty(c->db->dict);
6122 dictEmpty(c->db->expires);
6123 addReply(c,shared.ok);
6124 }
6125
6126 static void flushallCommand(redisClient *c) {
6127 server.dirty += emptyDb();
6128 addReply(c,shared.ok);
6129 rdbSave(server.dbfilename);
6130 server.dirty++;
6131 }
6132
6133 static redisSortOperation *createSortOperation(int type, robj *pattern) {
6134 redisSortOperation *so = zmalloc(sizeof(*so));
6135 so->type = type;
6136 so->pattern = pattern;
6137 return so;
6138 }
6139
6140 /* Return the value associated to the key with a name obtained
6141 * substituting the first occurence of '*' in 'pattern' with 'subst' */
6142 static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
6143 char *p;
6144 sds spat, ssub;
6145 robj keyobj;
6146 int prefixlen, sublen, postfixlen;
6147 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6148 struct {
6149 long len;
6150 long free;
6151 char buf[REDIS_SORTKEY_MAX+1];
6152 } keyname;
6153
6154 /* If the pattern is "#" return the substitution object itself in order
6155 * to implement the "SORT ... GET #" feature. */
6156 spat = pattern->ptr;
6157 if (spat[0] == '#' && spat[1] == '\0') {
6158 return subst;
6159 }
6160
6161 /* The substitution object may be specially encoded. If so we create
6162 * a decoded object on the fly. Otherwise getDecodedObject will just
6163 * increment the ref count, that we'll decrement later. */
6164 subst = getDecodedObject(subst);
6165
6166 ssub = subst->ptr;
6167 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
6168 p = strchr(spat,'*');
6169 if (!p) {
6170 decrRefCount(subst);
6171 return NULL;
6172 }
6173
6174 prefixlen = p-spat;
6175 sublen = sdslen(ssub);
6176 postfixlen = sdslen(spat)-(prefixlen+1);
6177 memcpy(keyname.buf,spat,prefixlen);
6178 memcpy(keyname.buf+prefixlen,ssub,sublen);
6179 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
6180 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
6181 keyname.len = prefixlen+sublen+postfixlen;
6182
6183 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2))
6184 decrRefCount(subst);
6185
6186 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
6187 return lookupKeyRead(db,&keyobj);
6188 }
6189
6190 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6191 * the additional parameter is not standard but a BSD-specific we have to
6192 * pass sorting parameters via the global 'server' structure */
6193 static int sortCompare(const void *s1, const void *s2) {
6194 const redisSortObject *so1 = s1, *so2 = s2;
6195 int cmp;
6196
6197 if (!server.sort_alpha) {
6198 /* Numeric sorting. Here it's trivial as we precomputed scores */
6199 if (so1->u.score > so2->u.score) {
6200 cmp = 1;
6201 } else if (so1->u.score < so2->u.score) {
6202 cmp = -1;
6203 } else {
6204 cmp = 0;
6205 }
6206 } else {
6207 /* Alphanumeric sorting */
6208 if (server.sort_bypattern) {
6209 if (!so1->u.cmpobj || !so2->u.cmpobj) {
6210 /* At least one compare object is NULL */
6211 if (so1->u.cmpobj == so2->u.cmpobj)
6212 cmp = 0;
6213 else if (so1->u.cmpobj == NULL)
6214 cmp = -1;
6215 else
6216 cmp = 1;
6217 } else {
6218 /* We have both the objects, use strcoll */
6219 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
6220 }
6221 } else {
6222 /* Compare elements directly */
6223 robj *dec1, *dec2;
6224
6225 dec1 = getDecodedObject(so1->obj);
6226 dec2 = getDecodedObject(so2->obj);
6227 cmp = strcoll(dec1->ptr,dec2->ptr);
6228 decrRefCount(dec1);
6229 decrRefCount(dec2);
6230 }
6231 }
6232 return server.sort_desc ? -cmp : cmp;
6233 }
6234
6235 /* The SORT command is the most complex command in Redis. Warning: this code
6236 * is optimized for speed and a bit less for readability */
6237 static void sortCommand(redisClient *c) {
6238 list *operations;
6239 int outputlen = 0;
6240 int desc = 0, alpha = 0;
6241 int limit_start = 0, limit_count = -1, start, end;
6242 int j, dontsort = 0, vectorlen;
6243 int getop = 0; /* GET operation counter */
6244 robj *sortval, *sortby = NULL, *storekey = NULL;
6245 redisSortObject *vector; /* Resulting vector to sort */
6246
6247 /* Lookup the key to sort. It must be of the right types */
6248 sortval = lookupKeyRead(c->db,c->argv[1]);
6249 if (sortval == NULL) {
6250 addReply(c,shared.nullmultibulk);
6251 return;
6252 }
6253 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
6254 sortval->type != REDIS_ZSET)
6255 {
6256 addReply(c,shared.wrongtypeerr);
6257 return;
6258 }
6259
6260 /* Create a list of operations to perform for every sorted element.
6261 * Operations can be GET/DEL/INCR/DECR */
6262 operations = listCreate();
6263 listSetFreeMethod(operations,zfree);
6264 j = 2;
6265
6266 /* Now we need to protect sortval incrementing its count, in the future
6267 * SORT may have options able to overwrite/delete keys during the sorting
6268 * and the sorted key itself may get destroied */
6269 incrRefCount(sortval);
6270
6271 /* The SORT command has an SQL-alike syntax, parse it */
6272 while(j < c->argc) {
6273 int leftargs = c->argc-j-1;
6274 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
6275 desc = 0;
6276 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
6277 desc = 1;
6278 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
6279 alpha = 1;
6280 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
6281 limit_start = atoi(c->argv[j+1]->ptr);
6282 limit_count = atoi(c->argv[j+2]->ptr);
6283 j+=2;
6284 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
6285 storekey = c->argv[j+1];
6286 j++;
6287 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
6288 sortby = c->argv[j+1];
6289 /* If the BY pattern does not contain '*', i.e. it is constant,
6290 * we don't need to sort nor to lookup the weight keys. */
6291 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
6292 j++;
6293 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
6294 listAddNodeTail(operations,createSortOperation(
6295 REDIS_SORT_GET,c->argv[j+1]));
6296 getop++;
6297 j++;
6298 } else {
6299 decrRefCount(sortval);
6300 listRelease(operations);
6301 addReply(c,shared.syntaxerr);
6302 return;
6303 }
6304 j++;
6305 }
6306
6307 /* Load the sorting vector with all the objects to sort */
6308 switch(sortval->type) {
6309 case REDIS_LIST: vectorlen = listLength((list*)sortval->ptr); break;
6310 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
6311 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
6312 default: vectorlen = 0; redisAssert(0); /* Avoid GCC warning */
6313 }
6314 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
6315 j = 0;
6316
6317 if (sortval->type == REDIS_LIST) {
6318 list *list = sortval->ptr;
6319 listNode *ln;
6320 listIter li;
6321
6322 listRewind(list,&li);
6323 while((ln = listNext(&li))) {
6324 robj *ele = ln->value;
6325 vector[j].obj = ele;
6326 vector[j].u.score = 0;
6327 vector[j].u.cmpobj = NULL;
6328 j++;
6329 }
6330 } else {
6331 dict *set;
6332 dictIterator *di;
6333 dictEntry *setele;
6334
6335 if (sortval->type == REDIS_SET) {
6336 set = sortval->ptr;
6337 } else {
6338 zset *zs = sortval->ptr;
6339 set = zs->dict;
6340 }
6341
6342 di = dictGetIterator(set);
6343 while((setele = dictNext(di)) != NULL) {
6344 vector[j].obj = dictGetEntryKey(setele);
6345 vector[j].u.score = 0;
6346 vector[j].u.cmpobj = NULL;
6347 j++;
6348 }
6349 dictReleaseIterator(di);
6350 }
6351 redisAssert(j == vectorlen);
6352
6353 /* Now it's time to load the right scores in the sorting vector */
6354 if (dontsort == 0) {
6355 for (j = 0; j < vectorlen; j++) {
6356 if (sortby) {
6357 robj *byval;
6358
6359 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
6360 if (!byval || byval->type != REDIS_STRING) continue;
6361 if (alpha) {
6362 vector[j].u.cmpobj = getDecodedObject(byval);
6363 } else {
6364 if (byval->encoding == REDIS_ENCODING_RAW) {
6365 vector[j].u.score = strtod(byval->ptr,NULL);
6366 } else {
6367 /* Don't need to decode the object if it's
6368 * integer-encoded (the only encoding supported) so
6369 * far. We can just cast it */
6370 if (byval->encoding == REDIS_ENCODING_INT) {
6371 vector[j].u.score = (long)byval->ptr;
6372 } else
6373 redisAssert(1 != 1);
6374 }
6375 }
6376 } else {
6377 if (!alpha) {
6378 if (vector[j].obj->encoding == REDIS_ENCODING_RAW)
6379 vector[j].u.score = strtod(vector[j].obj->ptr,NULL);
6380 else {
6381 if (vector[j].obj->encoding == REDIS_ENCODING_INT)
6382 vector[j].u.score = (long) vector[j].obj->ptr;
6383 else
6384 redisAssert(1 != 1);
6385 }
6386 }
6387 }
6388 }
6389 }
6390
6391 /* We are ready to sort the vector... perform a bit of sanity check
6392 * on the LIMIT option too. We'll use a partial version of quicksort. */
6393 start = (limit_start < 0) ? 0 : limit_start;
6394 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
6395 if (start >= vectorlen) {
6396 start = vectorlen-1;
6397 end = vectorlen-2;
6398 }
6399 if (end >= vectorlen) end = vectorlen-1;
6400
6401 if (dontsort == 0) {
6402 server.sort_desc = desc;
6403 server.sort_alpha = alpha;
6404 server.sort_bypattern = sortby ? 1 : 0;
6405 if (sortby && (start != 0 || end != vectorlen-1))
6406 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
6407 else
6408 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
6409 }
6410
6411 /* Send command output to the output buffer, performing the specified
6412 * GET/DEL/INCR/DECR operations if any. */
6413 outputlen = getop ? getop*(end-start+1) : end-start+1;
6414 if (storekey == NULL) {
6415 /* STORE option not specified, sent the sorting result to client */
6416 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
6417 for (j = start; j <= end; j++) {
6418 listNode *ln;
6419 listIter li;
6420
6421 if (!getop) addReplyBulk(c,vector[j].obj);
6422 listRewind(operations,&li);
6423 while((ln = listNext(&li))) {
6424 redisSortOperation *sop = ln->value;
6425 robj *val = lookupKeyByPattern(c->db,sop->pattern,
6426 vector[j].obj);
6427
6428 if (sop->type == REDIS_SORT_GET) {
6429 if (!val || val->type != REDIS_STRING) {
6430 addReply(c,shared.nullbulk);
6431 } else {
6432 addReplyBulk(c,val);
6433 }
6434 } else {
6435 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
6436 }
6437 }
6438 }
6439 } else {
6440 robj *listObject = createListObject();
6441 list *listPtr = (list*) listObject->ptr;
6442
6443 /* STORE option specified, set the sorting result as a List object */
6444 for (j = start; j <= end; j++) {
6445 listNode *ln;
6446 listIter li;
6447
6448 if (!getop) {
6449 listAddNodeTail(listPtr,vector[j].obj);
6450 incrRefCount(vector[j].obj);
6451 }
6452 listRewind(operations,&li);
6453 while((ln = listNext(&li))) {
6454 redisSortOperation *sop = ln->value;
6455 robj *val = lookupKeyByPattern(c->db,sop->pattern,
6456 vector[j].obj);
6457
6458 if (sop->type == REDIS_SORT_GET) {
6459 if (!val || val->type != REDIS_STRING) {
6460 listAddNodeTail(listPtr,createStringObject("",0));
6461 } else {
6462 listAddNodeTail(listPtr,val);
6463 incrRefCount(val);
6464 }
6465 } else {
6466 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
6467 }
6468 }
6469 }
6470 if (dictReplace(c->db->dict,storekey,listObject)) {
6471 incrRefCount(storekey);
6472 }
6473 /* Note: we add 1 because the DB is dirty anyway since even if the
6474 * SORT result is empty a new key is set and maybe the old content
6475 * replaced. */
6476 server.dirty += 1+outputlen;
6477 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
6478 }
6479
6480 /* Cleanup */
6481 decrRefCount(sortval);
6482 listRelease(operations);
6483 for (j = 0; j < vectorlen; j++) {
6484 if (sortby && alpha && vector[j].u.cmpobj)
6485 decrRefCount(vector[j].u.cmpobj);
6486 }
6487 zfree(vector);
6488 }
6489
6490 /* Convert an amount of bytes into a human readable string in the form
6491 * of 100B, 2G, 100M, 4K, and so forth. */
6492 static void bytesToHuman(char *s, unsigned long long n) {
6493 double d;
6494
6495 if (n < 1024) {
6496 /* Bytes */
6497 sprintf(s,"%lluB",n);
6498 return;
6499 } else if (n < (1024*1024)) {
6500 d = (double)n/(1024);
6501 sprintf(s,"%.2fK",d);
6502 } else if (n < (1024LL*1024*1024)) {
6503 d = (double)n/(1024*1024);
6504 sprintf(s,"%.2fM",d);
6505 } else if (n < (1024LL*1024*1024*1024)) {
6506 d = (double)n/(1024LL*1024*1024);
6507 sprintf(s,"%.2fG",d);
6508 }
6509 }
6510
6511 /* Create the string returned by the INFO command. This is decoupled
6512 * by the INFO command itself as we need to report the same information
6513 * on memory corruption problems. */
6514 static sds genRedisInfoString(void) {
6515 sds info;
6516 time_t uptime = time(NULL)-server.stat_starttime;
6517 int j;
6518 char hmem[64];
6519
6520 bytesToHuman(hmem,zmalloc_used_memory());
6521 info = sdscatprintf(sdsempty(),
6522 "redis_version:%s\r\n"
6523 "arch_bits:%s\r\n"
6524 "multiplexing_api:%s\r\n"
6525 "process_id:%ld\r\n"
6526 "uptime_in_seconds:%ld\r\n"
6527 "uptime_in_days:%ld\r\n"
6528 "connected_clients:%d\r\n"
6529 "connected_slaves:%d\r\n"
6530 "blocked_clients:%d\r\n"
6531 "used_memory:%zu\r\n"
6532 "used_memory_human:%s\r\n"
6533 "changes_since_last_save:%lld\r\n"
6534 "bgsave_in_progress:%d\r\n"
6535 "last_save_time:%ld\r\n"
6536 "bgrewriteaof_in_progress:%d\r\n"
6537 "total_connections_received:%lld\r\n"
6538 "total_commands_processed:%lld\r\n"
6539 "expired_keys:%lld\r\n"
6540 "hash_max_zipmap_entries:%ld\r\n"
6541 "hash_max_zipmap_value:%ld\r\n"
6542 "vm_enabled:%d\r\n"
6543 "role:%s\r\n"
6544 ,REDIS_VERSION,
6545 (sizeof(long) == 8) ? "64" : "32",
6546 aeGetApiName(),
6547 (long) getpid(),
6548 uptime,
6549 uptime/(3600*24),
6550 listLength(server.clients)-listLength(server.slaves),
6551 listLength(server.slaves),
6552 server.blpop_blocked_clients,
6553 zmalloc_used_memory(),
6554 hmem,
6555 server.dirty,
6556 server.bgsavechildpid != -1,
6557 server.lastsave,
6558 server.bgrewritechildpid != -1,
6559 server.stat_numconnections,
6560 server.stat_numcommands,
6561 server.stat_expiredkeys,
6562 server.hash_max_zipmap_entries,
6563 server.hash_max_zipmap_value,
6564 server.vm_enabled != 0,
6565 server.masterhost == NULL ? "master" : "slave"
6566 );
6567 if (server.masterhost) {
6568 info = sdscatprintf(info,
6569 "master_host:%s\r\n"
6570 "master_port:%d\r\n"
6571 "master_link_status:%s\r\n"
6572 "master_last_io_seconds_ago:%d\r\n"
6573 ,server.masterhost,
6574 server.masterport,
6575 (server.replstate == REDIS_REPL_CONNECTED) ?
6576 "up" : "down",
6577 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
6578 );
6579 }
6580 if (server.vm_enabled) {
6581 lockThreadedIO();
6582 info = sdscatprintf(info,
6583 "vm_conf_max_memory:%llu\r\n"
6584 "vm_conf_page_size:%llu\r\n"
6585 "vm_conf_pages:%llu\r\n"
6586 "vm_stats_used_pages:%llu\r\n"
6587 "vm_stats_swapped_objects:%llu\r\n"
6588 "vm_stats_swappin_count:%llu\r\n"
6589 "vm_stats_swappout_count:%llu\r\n"
6590 "vm_stats_io_newjobs_len:%lu\r\n"
6591 "vm_stats_io_processing_len:%lu\r\n"
6592 "vm_stats_io_processed_len:%lu\r\n"
6593 "vm_stats_io_active_threads:%lu\r\n"
6594 "vm_stats_blocked_clients:%lu\r\n"
6595 ,(unsigned long long) server.vm_max_memory,
6596 (unsigned long long) server.vm_page_size,
6597 (unsigned long long) server.vm_pages,
6598 (unsigned long long) server.vm_stats_used_pages,
6599 (unsigned long long) server.vm_stats_swapped_objects,
6600 (unsigned long long) server.vm_stats_swapins,
6601 (unsigned long long) server.vm_stats_swapouts,
6602 (unsigned long) listLength(server.io_newjobs),
6603 (unsigned long) listLength(server.io_processing),
6604 (unsigned long) listLength(server.io_processed),
6605 (unsigned long) server.io_active_threads,
6606 (unsigned long) server.vm_blocked_clients
6607 );
6608 unlockThreadedIO();
6609 }
6610 for (j = 0; j < server.dbnum; j++) {
6611 long long keys, vkeys;
6612
6613 keys = dictSize(server.db[j].dict);
6614 vkeys = dictSize(server.db[j].expires);
6615 if (keys || vkeys) {
6616 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
6617 j, keys, vkeys);
6618 }
6619 }
6620 return info;
6621 }
6622
6623 static void infoCommand(redisClient *c) {
6624 sds info = genRedisInfoString();
6625 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
6626 (unsigned long)sdslen(info)));
6627 addReplySds(c,info);
6628 addReply(c,shared.crlf);
6629 }
6630
6631 static void monitorCommand(redisClient *c) {
6632 /* ignore MONITOR if aleady slave or in monitor mode */
6633 if (c->flags & REDIS_SLAVE) return;
6634
6635 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
6636 c->slaveseldb = 0;
6637 listAddNodeTail(server.monitors,c);
6638 addReply(c,shared.ok);
6639 }
6640
6641 /* ================================= Expire ================================= */
6642 static int removeExpire(redisDb *db, robj *key) {
6643 if (dictDelete(db->expires,key) == DICT_OK) {
6644 return 1;
6645 } else {
6646 return 0;
6647 }
6648 }
6649
6650 static int setExpire(redisDb *db, robj *key, time_t when) {
6651 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
6652 return 0;
6653 } else {
6654 incrRefCount(key);
6655 return 1;
6656 }
6657 }
6658
6659 /* Return the expire time of the specified key, or -1 if no expire
6660 * is associated with this key (i.e. the key is non volatile) */
6661 static time_t getExpire(redisDb *db, robj *key) {
6662 dictEntry *de;
6663
6664 /* No expire? return ASAP */
6665 if (dictSize(db->expires) == 0 ||
6666 (de = dictFind(db->expires,key)) == NULL) return -1;
6667
6668 return (time_t) dictGetEntryVal(de);
6669 }
6670
6671 static int expireIfNeeded(redisDb *db, robj *key) {
6672 time_t when;
6673 dictEntry *de;
6674
6675 /* No expire? return ASAP */
6676 if (dictSize(db->expires) == 0 ||
6677 (de = dictFind(db->expires,key)) == NULL) return 0;
6678
6679 /* Lookup the expire */
6680 when = (time_t) dictGetEntryVal(de);
6681 if (time(NULL) <= when) return 0;
6682
6683 /* Delete the key */
6684 dictDelete(db->expires,key);
6685 server.stat_expiredkeys++;
6686 return dictDelete(db->dict,key) == DICT_OK;
6687 }
6688
6689 static int deleteIfVolatile(redisDb *db, robj *key) {
6690 dictEntry *de;
6691
6692 /* No expire? return ASAP */
6693 if (dictSize(db->expires) == 0 ||
6694 (de = dictFind(db->expires,key)) == NULL) return 0;
6695
6696 /* Delete the key */
6697 server.dirty++;
6698 server.stat_expiredkeys++;
6699 dictDelete(db->expires,key);
6700 return dictDelete(db->dict,key) == DICT_OK;
6701 }
6702
6703 static void expireGenericCommand(redisClient *c, robj *key, time_t seconds) {
6704 dictEntry *de;
6705
6706 de = dictFind(c->db->dict,key);
6707 if (de == NULL) {
6708 addReply(c,shared.czero);
6709 return;
6710 }
6711 if (seconds < 0) {
6712 if (deleteKey(c->db,key)) server.dirty++;
6713 addReply(c, shared.cone);
6714 return;
6715 } else {
6716 time_t when = time(NULL)+seconds;
6717 if (setExpire(c->db,key,when)) {
6718 addReply(c,shared.cone);
6719 server.dirty++;
6720 } else {
6721 addReply(c,shared.czero);
6722 }
6723 return;
6724 }
6725 }
6726
6727 static void expireCommand(redisClient *c) {
6728 expireGenericCommand(c,c->argv[1],strtol(c->argv[2]->ptr,NULL,10));
6729 }
6730
6731 static void expireatCommand(redisClient *c) {
6732 expireGenericCommand(c,c->argv[1],strtol(c->argv[2]->ptr,NULL,10)-time(NULL));
6733 }
6734
6735 static void ttlCommand(redisClient *c) {
6736 time_t expire;
6737 int ttl = -1;
6738
6739 expire = getExpire(c->db,c->argv[1]);
6740 if (expire != -1) {
6741 ttl = (int) (expire-time(NULL));
6742 if (ttl < 0) ttl = -1;
6743 }
6744 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
6745 }
6746
6747 /* ================================ MULTI/EXEC ============================== */
6748
6749 /* Client state initialization for MULTI/EXEC */
6750 static void initClientMultiState(redisClient *c) {
6751 c->mstate.commands = NULL;
6752 c->mstate.count = 0;
6753 }
6754
6755 /* Release all the resources associated with MULTI/EXEC state */
6756 static void freeClientMultiState(redisClient *c) {
6757 int j;
6758
6759 for (j = 0; j < c->mstate.count; j++) {
6760 int i;
6761 multiCmd *mc = c->mstate.commands+j;
6762
6763 for (i = 0; i < mc->argc; i++)
6764 decrRefCount(mc->argv[i]);
6765 zfree(mc->argv);
6766 }
6767 zfree(c->mstate.commands);
6768 }
6769
6770 /* Add a new command into the MULTI commands queue */
6771 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
6772 multiCmd *mc;
6773 int j;
6774
6775 c->mstate.commands = zrealloc(c->mstate.commands,
6776 sizeof(multiCmd)*(c->mstate.count+1));
6777 mc = c->mstate.commands+c->mstate.count;
6778 mc->cmd = cmd;
6779 mc->argc = c->argc;
6780 mc->argv = zmalloc(sizeof(robj*)*c->argc);
6781 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
6782 for (j = 0; j < c->argc; j++)
6783 incrRefCount(mc->argv[j]);
6784 c->mstate.count++;
6785 }
6786
6787 static void multiCommand(redisClient *c) {
6788 c->flags |= REDIS_MULTI;
6789 addReply(c,shared.ok);
6790 }
6791
6792 static void discardCommand(redisClient *c) {
6793 if (!(c->flags & REDIS_MULTI)) {
6794 addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
6795 return;
6796 }
6797
6798 freeClientMultiState(c);
6799 initClientMultiState(c);
6800 c->flags &= (~REDIS_MULTI);
6801 addReply(c,shared.ok);
6802 }
6803
6804 static void execCommand(redisClient *c) {
6805 int j;
6806 robj **orig_argv;
6807 int orig_argc;
6808
6809 if (!(c->flags & REDIS_MULTI)) {
6810 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
6811 return;
6812 }
6813
6814 orig_argv = c->argv;
6815 orig_argc = c->argc;
6816 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
6817 for (j = 0; j < c->mstate.count; j++) {
6818 c->argc = c->mstate.commands[j].argc;
6819 c->argv = c->mstate.commands[j].argv;
6820 call(c,c->mstate.commands[j].cmd);
6821 }
6822 c->argv = orig_argv;
6823 c->argc = orig_argc;
6824 freeClientMultiState(c);
6825 initClientMultiState(c);
6826 c->flags &= (~REDIS_MULTI);
6827 }
6828
6829 /* =========================== Blocking Operations ========================= */
6830
6831 /* Currently Redis blocking operations support is limited to list POP ops,
6832 * so the current implementation is not fully generic, but it is also not
6833 * completely specific so it will not require a rewrite to support new
6834 * kind of blocking operations in the future.
6835 *
6836 * Still it's important to note that list blocking operations can be already
6837 * used as a notification mechanism in order to implement other blocking
6838 * operations at application level, so there must be a very strong evidence
6839 * of usefulness and generality before new blocking operations are implemented.
6840 *
6841 * This is how the current blocking POP works, we use BLPOP as example:
6842 * - If the user calls BLPOP and the key exists and contains a non empty list
6843 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
6844 * if there is not to block.
6845 * - If instead BLPOP is called and the key does not exists or the list is
6846 * empty we need to block. In order to do so we remove the notification for
6847 * new data to read in the client socket (so that we'll not serve new
6848 * requests if the blocking request is not served). Also we put the client
6849 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
6850 * blocking for this keys.
6851 * - If a PUSH operation against a key with blocked clients waiting is
6852 * performed, we serve the first in the list: basically instead to push
6853 * the new element inside the list we return it to the (first / oldest)
6854 * blocking client, unblock the client, and remove it form the list.
6855 *
6856 * The above comment and the source code should be enough in order to understand
6857 * the implementation and modify / fix it later.
6858 */
6859
6860 /* Set a client in blocking mode for the specified key, with the specified
6861 * timeout */
6862 static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
6863 dictEntry *de;
6864 list *l;
6865 int j;
6866
6867 c->blockingkeys = zmalloc(sizeof(robj*)*numkeys);
6868 c->blockingkeysnum = numkeys;
6869 c->blockingto = timeout;
6870 for (j = 0; j < numkeys; j++) {
6871 /* Add the key in the client structure, to map clients -> keys */
6872 c->blockingkeys[j] = keys[j];
6873 incrRefCount(keys[j]);
6874
6875 /* And in the other "side", to map keys -> clients */
6876 de = dictFind(c->db->blockingkeys,keys[j]);
6877 if (de == NULL) {
6878 int retval;
6879
6880 /* For every key we take a list of clients blocked for it */
6881 l = listCreate();
6882 retval = dictAdd(c->db->blockingkeys,keys[j],l);
6883 incrRefCount(keys[j]);
6884 assert(retval == DICT_OK);
6885 } else {
6886 l = dictGetEntryVal(de);
6887 }
6888 listAddNodeTail(l,c);
6889 }
6890 /* Mark the client as a blocked client */
6891 c->flags |= REDIS_BLOCKED;
6892 server.blpop_blocked_clients++;
6893 }
6894
6895 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
6896 static void unblockClientWaitingData(redisClient *c) {
6897 dictEntry *de;
6898 list *l;
6899 int j;
6900
6901 assert(c->blockingkeys != NULL);
6902 /* The client may wait for multiple keys, so unblock it for every key. */
6903 for (j = 0; j < c->blockingkeysnum; j++) {
6904 /* Remove this client from the list of clients waiting for this key. */
6905 de = dictFind(c->db->blockingkeys,c->blockingkeys[j]);
6906 assert(de != NULL);
6907 l = dictGetEntryVal(de);
6908 listDelNode(l,listSearchKey(l,c));
6909 /* If the list is empty we need to remove it to avoid wasting memory */
6910 if (listLength(l) == 0)
6911 dictDelete(c->db->blockingkeys,c->blockingkeys[j]);
6912 decrRefCount(c->blockingkeys[j]);
6913 }
6914 /* Cleanup the client structure */
6915 zfree(c->blockingkeys);
6916 c->blockingkeys = NULL;
6917 c->flags &= (~REDIS_BLOCKED);
6918 server.blpop_blocked_clients--;
6919 /* We want to process data if there is some command waiting
6920 * in the input buffer. Note that this is safe even if
6921 * unblockClientWaitingData() gets called from freeClient() because
6922 * freeClient() will be smart enough to call this function
6923 * *after* c->querybuf was set to NULL. */
6924 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
6925 }
6926
6927 /* This should be called from any function PUSHing into lists.
6928 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
6929 * 'ele' is the element pushed.
6930 *
6931 * If the function returns 0 there was no client waiting for a list push
6932 * against this key.
6933 *
6934 * If the function returns 1 there was a client waiting for a list push
6935 * against this key, the element was passed to this client thus it's not
6936 * needed to actually add it to the list and the caller should return asap. */
6937 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
6938 struct dictEntry *de;
6939 redisClient *receiver;
6940 list *l;
6941 listNode *ln;
6942
6943 de = dictFind(c->db->blockingkeys,key);
6944 if (de == NULL) return 0;
6945 l = dictGetEntryVal(de);
6946 ln = listFirst(l);
6947 assert(ln != NULL);
6948 receiver = ln->value;
6949
6950 addReplySds(receiver,sdsnew("*2\r\n"));
6951 addReplyBulk(receiver,key);
6952 addReplyBulk(receiver,ele);
6953 unblockClientWaitingData(receiver);
6954 return 1;
6955 }
6956
6957 /* Blocking RPOP/LPOP */
6958 static void blockingPopGenericCommand(redisClient *c, int where) {
6959 robj *o;
6960 time_t timeout;
6961 int j;
6962
6963 for (j = 1; j < c->argc-1; j++) {
6964 o = lookupKeyWrite(c->db,c->argv[j]);
6965 if (o != NULL) {
6966 if (o->type != REDIS_LIST) {
6967 addReply(c,shared.wrongtypeerr);
6968 return;
6969 } else {
6970 list *list = o->ptr;
6971 if (listLength(list) != 0) {
6972 /* If the list contains elements fall back to the usual
6973 * non-blocking POP operation */
6974 robj *argv[2], **orig_argv;
6975 int orig_argc;
6976
6977 /* We need to alter the command arguments before to call
6978 * popGenericCommand() as the command takes a single key. */
6979 orig_argv = c->argv;
6980 orig_argc = c->argc;
6981 argv[1] = c->argv[j];
6982 c->argv = argv;
6983 c->argc = 2;
6984
6985 /* Also the return value is different, we need to output
6986 * the multi bulk reply header and the key name. The
6987 * "real" command will add the last element (the value)
6988 * for us. If this souds like an hack to you it's just
6989 * because it is... */
6990 addReplySds(c,sdsnew("*2\r\n"));
6991 addReplyBulk(c,argv[1]);
6992 popGenericCommand(c,where);
6993
6994 /* Fix the client structure with the original stuff */
6995 c->argv = orig_argv;
6996 c->argc = orig_argc;
6997 return;
6998 }
6999 }
7000 }
7001 }
7002 /* If the list is empty or the key does not exists we must block */
7003 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
7004 if (timeout > 0) timeout += time(NULL);
7005 blockForKeys(c,c->argv+1,c->argc-2,timeout);
7006 }
7007
7008 static void blpopCommand(redisClient *c) {
7009 blockingPopGenericCommand(c,REDIS_HEAD);
7010 }
7011
7012 static void brpopCommand(redisClient *c) {
7013 blockingPopGenericCommand(c,REDIS_TAIL);
7014 }
7015
7016 /* =============================== Replication ============================= */
7017
7018 static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
7019 ssize_t nwritten, ret = size;
7020 time_t start = time(NULL);
7021
7022 timeout++;
7023 while(size) {
7024 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
7025 nwritten = write(fd,ptr,size);
7026 if (nwritten == -1) return -1;
7027 ptr += nwritten;
7028 size -= nwritten;
7029 }
7030 if ((time(NULL)-start) > timeout) {
7031 errno = ETIMEDOUT;
7032 return -1;
7033 }
7034 }
7035 return ret;
7036 }
7037
7038 static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
7039 ssize_t nread, totread = 0;
7040 time_t start = time(NULL);
7041
7042 timeout++;
7043 while(size) {
7044 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
7045 nread = read(fd,ptr,size);
7046 if (nread == -1) return -1;
7047 ptr += nread;
7048 size -= nread;
7049 totread += nread;
7050 }
7051 if ((time(NULL)-start) > timeout) {
7052 errno = ETIMEDOUT;
7053 return -1;
7054 }
7055 }
7056 return totread;
7057 }
7058
7059 static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
7060 ssize_t nread = 0;
7061
7062 size--;
7063 while(size) {
7064 char c;
7065
7066 if (syncRead(fd,&c,1,timeout) == -1) return -1;
7067 if (c == '\n') {
7068 *ptr = '\0';
7069 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
7070 return nread;
7071 } else {
7072 *ptr++ = c;
7073 *ptr = '\0';
7074 nread++;
7075 }
7076 }
7077 return nread;
7078 }
7079
7080 static void syncCommand(redisClient *c) {
7081 /* ignore SYNC if aleady slave or in monitor mode */
7082 if (c->flags & REDIS_SLAVE) return;
7083
7084 /* SYNC can't be issued when the server has pending data to send to
7085 * the client about already issued commands. We need a fresh reply
7086 * buffer registering the differences between the BGSAVE and the current
7087 * dataset, so that we can copy to other slaves if needed. */
7088 if (listLength(c->reply) != 0) {
7089 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7090 return;
7091 }
7092
7093 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
7094 /* Here we need to check if there is a background saving operation
7095 * in progress, or if it is required to start one */
7096 if (server.bgsavechildpid != -1) {
7097 /* Ok a background save is in progress. Let's check if it is a good
7098 * one for replication, i.e. if there is another slave that is
7099 * registering differences since the server forked to save */
7100 redisClient *slave;
7101 listNode *ln;
7102 listIter li;
7103
7104 listRewind(server.slaves,&li);
7105 while((ln = listNext(&li))) {
7106 slave = ln->value;
7107 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
7108 }
7109 if (ln) {
7110 /* Perfect, the server is already registering differences for
7111 * another slave. Set the right state, and copy the buffer. */
7112 listRelease(c->reply);
7113 c->reply = listDup(slave->reply);
7114 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7115 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
7116 } else {
7117 /* No way, we need to wait for the next BGSAVE in order to
7118 * register differences */
7119 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
7120 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
7121 }
7122 } else {
7123 /* Ok we don't have a BGSAVE in progress, let's start one */
7124 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
7125 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
7126 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
7127 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
7128 return;
7129 }
7130 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7131 }
7132 c->repldbfd = -1;
7133 c->flags |= REDIS_SLAVE;
7134 c->slaveseldb = 0;
7135 listAddNodeTail(server.slaves,c);
7136 return;
7137 }
7138
7139 static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
7140 redisClient *slave = privdata;
7141 REDIS_NOTUSED(el);
7142 REDIS_NOTUSED(mask);
7143 char buf[REDIS_IOBUF_LEN];
7144 ssize_t nwritten, buflen;
7145
7146 if (slave->repldboff == 0) {
7147 /* Write the bulk write count before to transfer the DB. In theory here
7148 * we don't know how much room there is in the output buffer of the
7149 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7150 * operations) will never be smaller than the few bytes we need. */
7151 sds bulkcount;
7152
7153 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7154 slave->repldbsize);
7155 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
7156 {
7157 sdsfree(bulkcount);
7158 freeClient(slave);
7159 return;
7160 }
7161 sdsfree(bulkcount);
7162 }
7163 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
7164 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
7165 if (buflen <= 0) {
7166 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
7167 (buflen == 0) ? "premature EOF" : strerror(errno));
7168 freeClient(slave);
7169 return;
7170 }
7171 if ((nwritten = write(fd,buf,buflen)) == -1) {
7172 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
7173 strerror(errno));
7174 freeClient(slave);
7175 return;
7176 }
7177 slave->repldboff += nwritten;
7178 if (slave->repldboff == slave->repldbsize) {
7179 close(slave->repldbfd);
7180 slave->repldbfd = -1;
7181 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
7182 slave->replstate = REDIS_REPL_ONLINE;
7183 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
7184 sendReplyToClient, slave) == AE_ERR) {
7185 freeClient(slave);
7186 return;
7187 }
7188 addReplySds(slave,sdsempty());
7189 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
7190 }
7191 }
7192
7193 /* This function is called at the end of every backgrond saving.
7194 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
7195 * otherwise REDIS_ERR is passed to the function.
7196 *
7197 * The goal of this function is to handle slaves waiting for a successful
7198 * background saving in order to perform non-blocking synchronization. */
7199 static void updateSlavesWaitingBgsave(int bgsaveerr) {
7200 listNode *ln;
7201 int startbgsave = 0;
7202 listIter li;
7203
7204 listRewind(server.slaves,&li);
7205 while((ln = listNext(&li))) {
7206 redisClient *slave = ln->value;
7207
7208 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
7209 startbgsave = 1;
7210 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7211 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
7212 struct redis_stat buf;
7213
7214 if (bgsaveerr != REDIS_OK) {
7215 freeClient(slave);
7216 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
7217 continue;
7218 }
7219 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
7220 redis_fstat(slave->repldbfd,&buf) == -1) {
7221 freeClient(slave);
7222 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
7223 continue;
7224 }
7225 slave->repldboff = 0;
7226 slave->repldbsize = buf.st_size;
7227 slave->replstate = REDIS_REPL_SEND_BULK;
7228 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
7229 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
7230 freeClient(slave);
7231 continue;
7232 }
7233 }
7234 }
7235 if (startbgsave) {
7236 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
7237 listIter li;
7238
7239 listRewind(server.slaves,&li);
7240 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
7241 while((ln = listNext(&li))) {
7242 redisClient *slave = ln->value;
7243
7244 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
7245 freeClient(slave);
7246 }
7247 }
7248 }
7249 }
7250
7251 static int syncWithMaster(void) {
7252 char buf[1024], tmpfile[256], authcmd[1024];
7253 long dumpsize;
7254 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
7255 int dfd, maxtries = 5;
7256
7257 if (fd == -1) {
7258 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
7259 strerror(errno));
7260 return REDIS_ERR;
7261 }
7262
7263 /* AUTH with the master if required. */
7264 if(server.masterauth) {
7265 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
7266 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
7267 close(fd);
7268 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
7269 strerror(errno));
7270 return REDIS_ERR;
7271 }
7272 /* Read the AUTH result. */
7273 if (syncReadLine(fd,buf,1024,3600) == -1) {
7274 close(fd);
7275 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
7276 strerror(errno));
7277 return REDIS_ERR;
7278 }
7279 if (buf[0] != '+') {
7280 close(fd);
7281 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
7282 return REDIS_ERR;
7283 }
7284 }
7285
7286 /* Issue the SYNC command */
7287 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
7288 close(fd);
7289 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
7290 strerror(errno));
7291 return REDIS_ERR;
7292 }
7293 /* Read the bulk write count */
7294 if (syncReadLine(fd,buf,1024,3600) == -1) {
7295 close(fd);
7296 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
7297 strerror(errno));
7298 return REDIS_ERR;
7299 }
7300 if (buf[0] != '$') {
7301 close(fd);
7302 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
7303 return REDIS_ERR;
7304 }
7305 dumpsize = strtol(buf+1,NULL,10);
7306 redisLog(REDIS_NOTICE,"Receiving %ld bytes data dump from MASTER",dumpsize);
7307 /* Read the bulk write data on a temp file */
7308 while(maxtries--) {
7309 snprintf(tmpfile,256,
7310 "temp-%d.%ld.rdb",(int)time(NULL),(long int)getpid());
7311 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
7312 if (dfd != -1) break;
7313 sleep(1);
7314 }
7315 if (dfd == -1) {
7316 close(fd);
7317 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
7318 return REDIS_ERR;
7319 }
7320 while(dumpsize) {
7321 int nread, nwritten;
7322
7323 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
7324 if (nread == -1) {
7325 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
7326 strerror(errno));
7327 close(fd);
7328 close(dfd);
7329 return REDIS_ERR;
7330 }
7331 nwritten = write(dfd,buf,nread);
7332 if (nwritten == -1) {
7333 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
7334 close(fd);
7335 close(dfd);
7336 return REDIS_ERR;
7337 }
7338 dumpsize -= nread;
7339 }
7340 close(dfd);
7341 if (rename(tmpfile,server.dbfilename) == -1) {
7342 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
7343 unlink(tmpfile);
7344 close(fd);
7345 return REDIS_ERR;
7346 }
7347 emptyDb();
7348 if (rdbLoad(server.dbfilename) != REDIS_OK) {
7349 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
7350 close(fd);
7351 return REDIS_ERR;
7352 }
7353 server.master = createClient(fd);
7354 server.master->flags |= REDIS_MASTER;
7355 server.master->authenticated = 1;
7356 server.replstate = REDIS_REPL_CONNECTED;
7357 return REDIS_OK;
7358 }
7359
7360 static void slaveofCommand(redisClient *c) {
7361 if (!strcasecmp(c->argv[1]->ptr,"no") &&
7362 !strcasecmp(c->argv[2]->ptr,"one")) {
7363 if (server.masterhost) {
7364 sdsfree(server.masterhost);
7365 server.masterhost = NULL;
7366 if (server.master) freeClient(server.master);
7367 server.replstate = REDIS_REPL_NONE;
7368 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
7369 }
7370 } else {
7371 sdsfree(server.masterhost);
7372 server.masterhost = sdsdup(c->argv[1]->ptr);
7373 server.masterport = atoi(c->argv[2]->ptr);
7374 if (server.master) freeClient(server.master);
7375 server.replstate = REDIS_REPL_CONNECT;
7376 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
7377 server.masterhost, server.masterport);
7378 }
7379 addReply(c,shared.ok);
7380 }
7381
7382 /* ============================ Maxmemory directive ======================== */
7383
7384 /* Try to free one object form the pre-allocated objects free list.
7385 * This is useful under low mem conditions as by default we take 1 million
7386 * free objects allocated. On success REDIS_OK is returned, otherwise
7387 * REDIS_ERR. */
7388 static int tryFreeOneObjectFromFreelist(void) {
7389 robj *o;
7390
7391 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
7392 if (listLength(server.objfreelist)) {
7393 listNode *head = listFirst(server.objfreelist);
7394 o = listNodeValue(head);
7395 listDelNode(server.objfreelist,head);
7396 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
7397 zfree(o);
7398 return REDIS_OK;
7399 } else {
7400 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
7401 return REDIS_ERR;
7402 }
7403 }
7404
7405 /* This function gets called when 'maxmemory' is set on the config file to limit
7406 * the max memory used by the server, and we are out of memory.
7407 * This function will try to, in order:
7408 *
7409 * - Free objects from the free list
7410 * - Try to remove keys with an EXPIRE set
7411 *
7412 * It is not possible to free enough memory to reach used-memory < maxmemory
7413 * the server will start refusing commands that will enlarge even more the
7414 * memory usage.
7415 */
7416 static void freeMemoryIfNeeded(void) {
7417 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
7418 int j, k, freed = 0;
7419
7420 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
7421 for (j = 0; j < server.dbnum; j++) {
7422 int minttl = -1;
7423 robj *minkey = NULL;
7424 struct dictEntry *de;
7425
7426 if (dictSize(server.db[j].expires)) {
7427 freed = 1;
7428 /* From a sample of three keys drop the one nearest to
7429 * the natural expire */
7430 for (k = 0; k < 3; k++) {
7431 time_t t;
7432
7433 de = dictGetRandomKey(server.db[j].expires);
7434 t = (time_t) dictGetEntryVal(de);
7435 if (minttl == -1 || t < minttl) {
7436 minkey = dictGetEntryKey(de);
7437 minttl = t;
7438 }
7439 }
7440 deleteKey(server.db+j,minkey);
7441 }
7442 }
7443 if (!freed) return; /* nothing to free... */
7444 }
7445 }
7446
7447 /* ============================== Append Only file ========================== */
7448
7449 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
7450 sds buf = sdsempty();
7451 int j;
7452 ssize_t nwritten;
7453 time_t now;
7454 robj *tmpargv[3];
7455
7456 /* The DB this command was targetting is not the same as the last command
7457 * we appendend. To issue a SELECT command is needed. */
7458 if (dictid != server.appendseldb) {
7459 char seldb[64];
7460
7461 snprintf(seldb,sizeof(seldb),"%d",dictid);
7462 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
7463 (unsigned long)strlen(seldb),seldb);
7464 server.appendseldb = dictid;
7465 }
7466
7467 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
7468 * EXPIREs into EXPIREATs calls */
7469 if (cmd->proc == expireCommand) {
7470 long when;
7471
7472 tmpargv[0] = createStringObject("EXPIREAT",8);
7473 tmpargv[1] = argv[1];
7474 incrRefCount(argv[1]);
7475 when = time(NULL)+strtol(argv[2]->ptr,NULL,10);
7476 tmpargv[2] = createObject(REDIS_STRING,
7477 sdscatprintf(sdsempty(),"%ld",when));
7478 argv = tmpargv;
7479 }
7480
7481 /* Append the actual command */
7482 buf = sdscatprintf(buf,"*%d\r\n",argc);
7483 for (j = 0; j < argc; j++) {
7484 robj *o = argv[j];
7485
7486 o = getDecodedObject(o);
7487 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
7488 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
7489 buf = sdscatlen(buf,"\r\n",2);
7490 decrRefCount(o);
7491 }
7492
7493 /* Free the objects from the modified argv for EXPIREAT */
7494 if (cmd->proc == expireCommand) {
7495 for (j = 0; j < 3; j++)
7496 decrRefCount(argv[j]);
7497 }
7498
7499 /* We want to perform a single write. This should be guaranteed atomic
7500 * at least if the filesystem we are writing is a real physical one.
7501 * While this will save us against the server being killed I don't think
7502 * there is much to do about the whole server stopping for power problems
7503 * or alike */
7504 nwritten = write(server.appendfd,buf,sdslen(buf));
7505 if (nwritten != (signed)sdslen(buf)) {
7506 /* Ooops, we are in troubles. The best thing to do for now is
7507 * to simply exit instead to give the illusion that everything is
7508 * working as expected. */
7509 if (nwritten == -1) {
7510 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
7511 } else {
7512 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
7513 }
7514 exit(1);
7515 }
7516 /* If a background append only file rewriting is in progress we want to
7517 * accumulate the differences between the child DB and the current one
7518 * in a buffer, so that when the child process will do its work we
7519 * can append the differences to the new append only file. */
7520 if (server.bgrewritechildpid != -1)
7521 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
7522
7523 sdsfree(buf);
7524 now = time(NULL);
7525 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
7526 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
7527 now-server.lastfsync > 1))
7528 {
7529 fsync(server.appendfd); /* Let's try to get this data on the disk */
7530 server.lastfsync = now;
7531 }
7532 }
7533
7534 /* In Redis commands are always executed in the context of a client, so in
7535 * order to load the append only file we need to create a fake client. */
7536 static struct redisClient *createFakeClient(void) {
7537 struct redisClient *c = zmalloc(sizeof(*c));
7538
7539 selectDb(c,0);
7540 c->fd = -1;
7541 c->querybuf = sdsempty();
7542 c->argc = 0;
7543 c->argv = NULL;
7544 c->flags = 0;
7545 /* We set the fake client as a slave waiting for the synchronization
7546 * so that Redis will not try to send replies to this client. */
7547 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
7548 c->reply = listCreate();
7549 listSetFreeMethod(c->reply,decrRefCount);
7550 listSetDupMethod(c->reply,dupClientReplyValue);
7551 return c;
7552 }
7553
7554 static void freeFakeClient(struct redisClient *c) {
7555 sdsfree(c->querybuf);
7556 listRelease(c->reply);
7557 zfree(c);
7558 }
7559
7560 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
7561 * error (the append only file is zero-length) REDIS_ERR is returned. On
7562 * fatal error an error message is logged and the program exists. */
7563 int loadAppendOnlyFile(char *filename) {
7564 struct redisClient *fakeClient;
7565 FILE *fp = fopen(filename,"r");
7566 struct redis_stat sb;
7567 unsigned long long loadedkeys = 0;
7568
7569 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
7570 return REDIS_ERR;
7571
7572 if (fp == NULL) {
7573 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
7574 exit(1);
7575 }
7576
7577 fakeClient = createFakeClient();
7578 while(1) {
7579 int argc, j;
7580 unsigned long len;
7581 robj **argv;
7582 char buf[128];
7583 sds argsds;
7584 struct redisCommand *cmd;
7585
7586 if (fgets(buf,sizeof(buf),fp) == NULL) {
7587 if (feof(fp))
7588 break;
7589 else
7590 goto readerr;
7591 }
7592 if (buf[0] != '*') goto fmterr;
7593 argc = atoi(buf+1);
7594 argv = zmalloc(sizeof(robj*)*argc);
7595 for (j = 0; j < argc; j++) {
7596 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
7597 if (buf[0] != '$') goto fmterr;
7598 len = strtol(buf+1,NULL,10);
7599 argsds = sdsnewlen(NULL,len);
7600 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
7601 argv[j] = createObject(REDIS_STRING,argsds);
7602 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
7603 }
7604
7605 /* Command lookup */
7606 cmd = lookupCommand(argv[0]->ptr);
7607 if (!cmd) {
7608 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
7609 exit(1);
7610 }
7611 /* Try object sharing and encoding */
7612 if (server.shareobjects) {
7613 int j;
7614 for(j = 1; j < argc; j++)
7615 argv[j] = tryObjectSharing(argv[j]);
7616 }
7617 if (cmd->flags & REDIS_CMD_BULK)
7618 tryObjectEncoding(argv[argc-1]);
7619 /* Run the command in the context of a fake client */
7620 fakeClient->argc = argc;
7621 fakeClient->argv = argv;
7622 cmd->proc(fakeClient);
7623 /* Discard the reply objects list from the fake client */
7624 while(listLength(fakeClient->reply))
7625 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
7626 /* Clean up, ready for the next command */
7627 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
7628 zfree(argv);
7629 /* Handle swapping while loading big datasets when VM is on */
7630 loadedkeys++;
7631 if (server.vm_enabled && (loadedkeys % 5000) == 0) {
7632 while (zmalloc_used_memory() > server.vm_max_memory) {
7633 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
7634 }
7635 }
7636 }
7637 fclose(fp);
7638 freeFakeClient(fakeClient);
7639 return REDIS_OK;
7640
7641 readerr:
7642 if (feof(fp)) {
7643 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
7644 } else {
7645 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
7646 }
7647 exit(1);
7648 fmterr:
7649 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
7650 exit(1);
7651 }
7652
7653 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
7654 static int fwriteBulkObject(FILE *fp, robj *obj) {
7655 char buf[128];
7656 int decrrc = 0;
7657
7658 /* Avoid the incr/decr ref count business if possible to help
7659 * copy-on-write (we are often in a child process when this function
7660 * is called).
7661 * Also makes sure that key objects don't get incrRefCount-ed when VM
7662 * is enabled */
7663 if (obj->encoding != REDIS_ENCODING_RAW) {
7664 obj = getDecodedObject(obj);
7665 decrrc = 1;
7666 }
7667 snprintf(buf,sizeof(buf),"$%ld\r\n",(long)sdslen(obj->ptr));
7668 if (fwrite(buf,strlen(buf),1,fp) == 0) goto err;
7669 if (sdslen(obj->ptr) && fwrite(obj->ptr,sdslen(obj->ptr),1,fp) == 0)
7670 goto err;
7671 if (fwrite("\r\n",2,1,fp) == 0) goto err;
7672 if (decrrc) decrRefCount(obj);
7673 return 1;
7674 err:
7675 if (decrrc) decrRefCount(obj);
7676 return 0;
7677 }
7678
7679 /* Write binary-safe string into a file in the bulkformat
7680 * $<count>\r\n<payload>\r\n */
7681 static int fwriteBulkString(FILE *fp, char *s, unsigned long len) {
7682 char buf[128];
7683
7684 snprintf(buf,sizeof(buf),"$%ld\r\n",(unsigned long)len);
7685 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
7686 if (len && fwrite(s,len,1,fp) == 0) return 0;
7687 if (fwrite("\r\n",2,1,fp) == 0) return 0;
7688 return 1;
7689 }
7690
7691 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
7692 static int fwriteBulkDouble(FILE *fp, double d) {
7693 char buf[128], dbuf[128];
7694
7695 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
7696 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
7697 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
7698 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
7699 return 1;
7700 }
7701
7702 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
7703 static int fwriteBulkLong(FILE *fp, long l) {
7704 char buf[128], lbuf[128];
7705
7706 snprintf(lbuf,sizeof(lbuf),"%ld\r\n",l);
7707 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(lbuf)-2);
7708 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
7709 if (fwrite(lbuf,strlen(lbuf),1,fp) == 0) return 0;
7710 return 1;
7711 }
7712
7713 /* Write a sequence of commands able to fully rebuild the dataset into
7714 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
7715 static int rewriteAppendOnlyFile(char *filename) {
7716 dictIterator *di = NULL;
7717 dictEntry *de;
7718 FILE *fp;
7719 char tmpfile[256];
7720 int j;
7721 time_t now = time(NULL);
7722
7723 /* Note that we have to use a different temp name here compared to the
7724 * one used by rewriteAppendOnlyFileBackground() function. */
7725 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
7726 fp = fopen(tmpfile,"w");
7727 if (!fp) {
7728 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
7729 return REDIS_ERR;
7730 }
7731 for (j = 0; j < server.dbnum; j++) {
7732 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
7733 redisDb *db = server.db+j;
7734 dict *d = db->dict;
7735 if (dictSize(d) == 0) continue;
7736 di = dictGetIterator(d);
7737 if (!di) {
7738 fclose(fp);
7739 return REDIS_ERR;
7740 }
7741
7742 /* SELECT the new DB */
7743 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
7744 if (fwriteBulkLong(fp,j) == 0) goto werr;
7745
7746 /* Iterate this DB writing every entry */
7747 while((de = dictNext(di)) != NULL) {
7748 robj *key, *o;
7749 time_t expiretime;
7750 int swapped;
7751
7752 key = dictGetEntryKey(de);
7753 /* If the value for this key is swapped, load a preview in memory.
7754 * We use a "swapped" flag to remember if we need to free the
7755 * value object instead to just increment the ref count anyway
7756 * in order to avoid copy-on-write of pages if we are forked() */
7757 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
7758 key->storage == REDIS_VM_SWAPPING) {
7759 o = dictGetEntryVal(de);
7760 swapped = 0;
7761 } else {
7762 o = vmPreviewObject(key);
7763 swapped = 1;
7764 }
7765 expiretime = getExpire(db,key);
7766
7767 /* Save the key and associated value */
7768 if (o->type == REDIS_STRING) {
7769 /* Emit a SET command */
7770 char cmd[]="*3\r\n$3\r\nSET\r\n";
7771 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
7772 /* Key and value */
7773 if (fwriteBulkObject(fp,key) == 0) goto werr;
7774 if (fwriteBulkObject(fp,o) == 0) goto werr;
7775 } else if (o->type == REDIS_LIST) {
7776 /* Emit the RPUSHes needed to rebuild the list */
7777 list *list = o->ptr;
7778 listNode *ln;
7779 listIter li;
7780
7781 listRewind(list,&li);
7782 while((ln = listNext(&li))) {
7783 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
7784 robj *eleobj = listNodeValue(ln);
7785
7786 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
7787 if (fwriteBulkObject(fp,key) == 0) goto werr;
7788 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
7789 }
7790 } else if (o->type == REDIS_SET) {
7791 /* Emit the SADDs needed to rebuild the set */
7792 dict *set = o->ptr;
7793 dictIterator *di = dictGetIterator(set);
7794 dictEntry *de;
7795
7796 while((de = dictNext(di)) != NULL) {
7797 char cmd[]="*3\r\n$4\r\nSADD\r\n";
7798 robj *eleobj = dictGetEntryKey(de);
7799
7800 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
7801 if (fwriteBulkObject(fp,key) == 0) goto werr;
7802 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
7803 }
7804 dictReleaseIterator(di);
7805 } else if (o->type == REDIS_ZSET) {
7806 /* Emit the ZADDs needed to rebuild the sorted set */
7807 zset *zs = o->ptr;
7808 dictIterator *di = dictGetIterator(zs->dict);
7809 dictEntry *de;
7810
7811 while((de = dictNext(di)) != NULL) {
7812 char cmd[]="*4\r\n$4\r\nZADD\r\n";
7813 robj *eleobj = dictGetEntryKey(de);
7814 double *score = dictGetEntryVal(de);
7815
7816 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
7817 if (fwriteBulkObject(fp,key) == 0) goto werr;
7818 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
7819 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
7820 }
7821 dictReleaseIterator(di);
7822 } else if (o->type == REDIS_HASH) {
7823 char cmd[]="*4\r\n$4\r\nHSET\r\n";
7824
7825 /* Emit the HSETs needed to rebuild the hash */
7826 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
7827 unsigned char *p = zipmapRewind(o->ptr);
7828 unsigned char *field, *val;
7829 unsigned int flen, vlen;
7830
7831 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
7832 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
7833 if (fwriteBulkObject(fp,key) == 0) goto werr;
7834 if (fwriteBulkString(fp,(char*)field,flen) == -1)
7835 return -1;
7836 if (fwriteBulkString(fp,(char*)val,vlen) == -1)
7837 return -1;
7838 }
7839 } else {
7840 dictIterator *di = dictGetIterator(o->ptr);
7841 dictEntry *de;
7842
7843 while((de = dictNext(di)) != NULL) {
7844 robj *field = dictGetEntryKey(de);
7845 robj *val = dictGetEntryVal(de);
7846
7847 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
7848 if (fwriteBulkObject(fp,key) == 0) goto werr;
7849 if (fwriteBulkObject(fp,field) == -1) return -1;
7850 if (fwriteBulkObject(fp,val) == -1) return -1;
7851 }
7852 dictReleaseIterator(di);
7853 }
7854 } else {
7855 redisAssert(0);
7856 }
7857 /* Save the expire time */
7858 if (expiretime != -1) {
7859 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
7860 /* If this key is already expired skip it */
7861 if (expiretime < now) continue;
7862 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
7863 if (fwriteBulkObject(fp,key) == 0) goto werr;
7864 if (fwriteBulkLong(fp,expiretime) == 0) goto werr;
7865 }
7866 if (swapped) decrRefCount(o);
7867 }
7868 dictReleaseIterator(di);
7869 }
7870
7871 /* Make sure data will not remain on the OS's output buffers */
7872 fflush(fp);
7873 fsync(fileno(fp));
7874 fclose(fp);
7875
7876 /* Use RENAME to make sure the DB file is changed atomically only
7877 * if the generate DB file is ok. */
7878 if (rename(tmpfile,filename) == -1) {
7879 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
7880 unlink(tmpfile);
7881 return REDIS_ERR;
7882 }
7883 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
7884 return REDIS_OK;
7885
7886 werr:
7887 fclose(fp);
7888 unlink(tmpfile);
7889 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
7890 if (di) dictReleaseIterator(di);
7891 return REDIS_ERR;
7892 }
7893
7894 /* This is how rewriting of the append only file in background works:
7895 *
7896 * 1) The user calls BGREWRITEAOF
7897 * 2) Redis calls this function, that forks():
7898 * 2a) the child rewrite the append only file in a temp file.
7899 * 2b) the parent accumulates differences in server.bgrewritebuf.
7900 * 3) When the child finished '2a' exists.
7901 * 4) The parent will trap the exit code, if it's OK, will append the
7902 * data accumulated into server.bgrewritebuf into the temp file, and
7903 * finally will rename(2) the temp file in the actual file name.
7904 * The the new file is reopened as the new append only file. Profit!
7905 */
7906 static int rewriteAppendOnlyFileBackground(void) {
7907 pid_t childpid;
7908
7909 if (server.bgrewritechildpid != -1) return REDIS_ERR;
7910 if (server.vm_enabled) waitEmptyIOJobsQueue();
7911 if ((childpid = fork()) == 0) {
7912 /* Child */
7913 char tmpfile[256];
7914
7915 if (server.vm_enabled) vmReopenSwapFile();
7916 close(server.fd);
7917 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
7918 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
7919 _exit(0);
7920 } else {
7921 _exit(1);
7922 }
7923 } else {
7924 /* Parent */
7925 if (childpid == -1) {
7926 redisLog(REDIS_WARNING,
7927 "Can't rewrite append only file in background: fork: %s",
7928 strerror(errno));
7929 return REDIS_ERR;
7930 }
7931 redisLog(REDIS_NOTICE,
7932 "Background append only file rewriting started by pid %d",childpid);
7933 server.bgrewritechildpid = childpid;
7934 /* We set appendseldb to -1 in order to force the next call to the
7935 * feedAppendOnlyFile() to issue a SELECT command, so the differences
7936 * accumulated by the parent into server.bgrewritebuf will start
7937 * with a SELECT statement and it will be safe to merge. */
7938 server.appendseldb = -1;
7939 return REDIS_OK;
7940 }
7941 return REDIS_OK; /* unreached */
7942 }
7943
7944 static void bgrewriteaofCommand(redisClient *c) {
7945 if (server.bgrewritechildpid != -1) {
7946 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
7947 return;
7948 }
7949 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
7950 char *status = "+Background append only file rewriting started\r\n";
7951 addReplySds(c,sdsnew(status));
7952 } else {
7953 addReply(c,shared.err);
7954 }
7955 }
7956
7957 static void aofRemoveTempFile(pid_t childpid) {
7958 char tmpfile[256];
7959
7960 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
7961 unlink(tmpfile);
7962 }
7963
7964 /* Virtual Memory is composed mainly of two subsystems:
7965 * - Blocking Virutal Memory
7966 * - Threaded Virtual Memory I/O
7967 * The two parts are not fully decoupled, but functions are split among two
7968 * different sections of the source code (delimited by comments) in order to
7969 * make more clear what functionality is about the blocking VM and what about
7970 * the threaded (not blocking) VM.
7971 *
7972 * Redis VM design:
7973 *
7974 * Redis VM is a blocking VM (one that blocks reading swapped values from
7975 * disk into memory when a value swapped out is needed in memory) that is made
7976 * unblocking by trying to examine the command argument vector in order to
7977 * load in background values that will likely be needed in order to exec
7978 * the command. The command is executed only once all the relevant keys
7979 * are loaded into memory.
7980 *
7981 * This basically is almost as simple of a blocking VM, but almost as parallel
7982 * as a fully non-blocking VM.
7983 */
7984
7985 /* =================== Virtual Memory - Blocking Side ====================== */
7986
7987 /* substitute the first occurrence of '%p' with the process pid in the
7988 * swap file name. */
7989 static void expandVmSwapFilename(void) {
7990 char *p = strstr(server.vm_swap_file,"%p");
7991 sds new;
7992
7993 if (!p) return;
7994 new = sdsempty();
7995 *p = '\0';
7996 new = sdscat(new,server.vm_swap_file);
7997 new = sdscatprintf(new,"%ld",(long) getpid());
7998 new = sdscat(new,p+2);
7999 zfree(server.vm_swap_file);
8000 server.vm_swap_file = new;
8001 }
8002
8003 static void vmInit(void) {
8004 off_t totsize;
8005 int pipefds[2];
8006 size_t stacksize;
8007
8008 if (server.vm_max_threads != 0)
8009 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
8010
8011 expandVmSwapFilename();
8012 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
8013 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
8014 server.vm_fp = fopen(server.vm_swap_file,"w+b");
8015 }
8016 if (server.vm_fp == NULL) {
8017 redisLog(REDIS_WARNING,
8018 "Impossible to open the swap file: %s. Exiting.",
8019 strerror(errno));
8020 exit(1);
8021 }
8022 server.vm_fd = fileno(server.vm_fp);
8023 server.vm_next_page = 0;
8024 server.vm_near_pages = 0;
8025 server.vm_stats_used_pages = 0;
8026 server.vm_stats_swapped_objects = 0;
8027 server.vm_stats_swapouts = 0;
8028 server.vm_stats_swapins = 0;
8029 totsize = server.vm_pages*server.vm_page_size;
8030 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
8031 if (ftruncate(server.vm_fd,totsize) == -1) {
8032 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
8033 strerror(errno));
8034 exit(1);
8035 } else {
8036 redisLog(REDIS_NOTICE,"Swap file allocated with success");
8037 }
8038 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
8039 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
8040 (long long) (server.vm_pages+7)/8, server.vm_pages);
8041 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
8042
8043 /* Initialize threaded I/O (used by Virtual Memory) */
8044 server.io_newjobs = listCreate();
8045 server.io_processing = listCreate();
8046 server.io_processed = listCreate();
8047 server.io_ready_clients = listCreate();
8048 pthread_mutex_init(&server.io_mutex,NULL);
8049 pthread_mutex_init(&server.obj_freelist_mutex,NULL);
8050 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
8051 server.io_active_threads = 0;
8052 if (pipe(pipefds) == -1) {
8053 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
8054 ,strerror(errno));
8055 exit(1);
8056 }
8057 server.io_ready_pipe_read = pipefds[0];
8058 server.io_ready_pipe_write = pipefds[1];
8059 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
8060 /* LZF requires a lot of stack */
8061 pthread_attr_init(&server.io_threads_attr);
8062 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
8063 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
8064 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
8065 /* Listen for events in the threaded I/O pipe */
8066 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
8067 vmThreadedIOCompletedJob, NULL) == AE_ERR)
8068 oom("creating file event");
8069 }
8070
8071 /* Mark the page as used */
8072 static void vmMarkPageUsed(off_t page) {
8073 off_t byte = page/8;
8074 int bit = page&7;
8075 redisAssert(vmFreePage(page) == 1);
8076 server.vm_bitmap[byte] |= 1<<bit;
8077 }
8078
8079 /* Mark N contiguous pages as used, with 'page' being the first. */
8080 static void vmMarkPagesUsed(off_t page, off_t count) {
8081 off_t j;
8082
8083 for (j = 0; j < count; j++)
8084 vmMarkPageUsed(page+j);
8085 server.vm_stats_used_pages += count;
8086 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
8087 (long long)count, (long long)page);
8088 }
8089
8090 /* Mark the page as free */
8091 static void vmMarkPageFree(off_t page) {
8092 off_t byte = page/8;
8093 int bit = page&7;
8094 redisAssert(vmFreePage(page) == 0);
8095 server.vm_bitmap[byte] &= ~(1<<bit);
8096 }
8097
8098 /* Mark N contiguous pages as free, with 'page' being the first. */
8099 static void vmMarkPagesFree(off_t page, off_t count) {
8100 off_t j;
8101
8102 for (j = 0; j < count; j++)
8103 vmMarkPageFree(page+j);
8104 server.vm_stats_used_pages -= count;
8105 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
8106 (long long)count, (long long)page);
8107 }
8108
8109 /* Test if the page is free */
8110 static int vmFreePage(off_t page) {
8111 off_t byte = page/8;
8112 int bit = page&7;
8113 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
8114 }
8115
8116 /* Find N contiguous free pages storing the first page of the cluster in *first.
8117 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
8118 * REDIS_ERR is returned.
8119 *
8120 * This function uses a simple algorithm: we try to allocate
8121 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
8122 * again from the start of the swap file searching for free spaces.
8123 *
8124 * If it looks pretty clear that there are no free pages near our offset
8125 * we try to find less populated places doing a forward jump of
8126 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
8127 * without hurry, and then we jump again and so forth...
8128 *
8129 * This function can be improved using a free list to avoid to guess
8130 * too much, since we could collect data about freed pages.
8131 *
8132 * note: I implemented this function just after watching an episode of
8133 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
8134 */
8135 static int vmFindContiguousPages(off_t *first, off_t n) {
8136 off_t base, offset = 0, since_jump = 0, numfree = 0;
8137
8138 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
8139 server.vm_near_pages = 0;
8140 server.vm_next_page = 0;
8141 }
8142 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
8143 base = server.vm_next_page;
8144
8145 while(offset < server.vm_pages) {
8146 off_t this = base+offset;
8147
8148 /* If we overflow, restart from page zero */
8149 if (this >= server.vm_pages) {
8150 this -= server.vm_pages;
8151 if (this == 0) {
8152 /* Just overflowed, what we found on tail is no longer
8153 * interesting, as it's no longer contiguous. */
8154 numfree = 0;
8155 }
8156 }
8157 if (vmFreePage(this)) {
8158 /* This is a free page */
8159 numfree++;
8160 /* Already got N free pages? Return to the caller, with success */
8161 if (numfree == n) {
8162 *first = this-(n-1);
8163 server.vm_next_page = this+1;
8164 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
8165 return REDIS_OK;
8166 }
8167 } else {
8168 /* The current one is not a free page */
8169 numfree = 0;
8170 }
8171
8172 /* Fast-forward if the current page is not free and we already
8173 * searched enough near this place. */
8174 since_jump++;
8175 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
8176 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
8177 since_jump = 0;
8178 /* Note that even if we rewind after the jump, we are don't need
8179 * to make sure numfree is set to zero as we only jump *if* it
8180 * is set to zero. */
8181 } else {
8182 /* Otherwise just check the next page */
8183 offset++;
8184 }
8185 }
8186 return REDIS_ERR;
8187 }
8188
8189 /* Write the specified object at the specified page of the swap file */
8190 static int vmWriteObjectOnSwap(robj *o, off_t page) {
8191 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
8192 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
8193 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
8194 redisLog(REDIS_WARNING,
8195 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
8196 strerror(errno));
8197 return REDIS_ERR;
8198 }
8199 rdbSaveObject(server.vm_fp,o);
8200 fflush(server.vm_fp);
8201 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
8202 return REDIS_OK;
8203 }
8204
8205 /* Swap the 'val' object relative to 'key' into disk. Store all the information
8206 * needed to later retrieve the object into the key object.
8207 * If we can't find enough contiguous empty pages to swap the object on disk
8208 * REDIS_ERR is returned. */
8209 static int vmSwapObjectBlocking(robj *key, robj *val) {
8210 off_t pages = rdbSavedObjectPages(val,NULL);
8211 off_t page;
8212
8213 assert(key->storage == REDIS_VM_MEMORY);
8214 assert(key->refcount == 1);
8215 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return REDIS_ERR;
8216 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return REDIS_ERR;
8217 key->vm.page = page;
8218 key->vm.usedpages = pages;
8219 key->storage = REDIS_VM_SWAPPED;
8220 key->vtype = val->type;
8221 decrRefCount(val); /* Deallocate the object from memory. */
8222 vmMarkPagesUsed(page,pages);
8223 redisLog(REDIS_DEBUG,"VM: object %s swapped out at %lld (%lld pages)",
8224 (unsigned char*) key->ptr,
8225 (unsigned long long) page, (unsigned long long) pages);
8226 server.vm_stats_swapped_objects++;
8227 server.vm_stats_swapouts++;
8228 return REDIS_OK;
8229 }
8230
8231 static robj *vmReadObjectFromSwap(off_t page, int type) {
8232 robj *o;
8233
8234 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
8235 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
8236 redisLog(REDIS_WARNING,
8237 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
8238 strerror(errno));
8239 _exit(1);
8240 }
8241 o = rdbLoadObject(type,server.vm_fp);
8242 if (o == NULL) {
8243 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
8244 _exit(1);
8245 }
8246 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
8247 return o;
8248 }
8249
8250 /* Load the value object relative to the 'key' object from swap to memory.
8251 * The newly allocated object is returned.
8252 *
8253 * If preview is true the unserialized object is returned to the caller but
8254 * no changes are made to the key object, nor the pages are marked as freed */
8255 static robj *vmGenericLoadObject(robj *key, int preview) {
8256 robj *val;
8257
8258 redisAssert(key->storage == REDIS_VM_SWAPPED || key->storage == REDIS_VM_LOADING);
8259 val = vmReadObjectFromSwap(key->vm.page,key->vtype);
8260 if (!preview) {
8261 key->storage = REDIS_VM_MEMORY;
8262 key->vm.atime = server.unixtime;
8263 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
8264 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk",
8265 (unsigned char*) key->ptr);
8266 server.vm_stats_swapped_objects--;
8267 } else {
8268 redisLog(REDIS_DEBUG, "VM: object %s previewed from disk",
8269 (unsigned char*) key->ptr);
8270 }
8271 server.vm_stats_swapins++;
8272 return val;
8273 }
8274
8275 /* Plain object loading, from swap to memory */
8276 static robj *vmLoadObject(robj *key) {
8277 /* If we are loading the object in background, stop it, we
8278 * need to load this object synchronously ASAP. */
8279 if (key->storage == REDIS_VM_LOADING)
8280 vmCancelThreadedIOJob(key);
8281 return vmGenericLoadObject(key,0);
8282 }
8283
8284 /* Just load the value on disk, without to modify the key.
8285 * This is useful when we want to perform some operation on the value
8286 * without to really bring it from swap to memory, like while saving the
8287 * dataset or rewriting the append only log. */
8288 static robj *vmPreviewObject(robj *key) {
8289 return vmGenericLoadObject(key,1);
8290 }
8291
8292 /* How a good candidate is this object for swapping?
8293 * The better candidate it is, the greater the returned value.
8294 *
8295 * Currently we try to perform a fast estimation of the object size in
8296 * memory, and combine it with aging informations.
8297 *
8298 * Basically swappability = idle-time * log(estimated size)
8299 *
8300 * Bigger objects are preferred over smaller objects, but not
8301 * proportionally, this is why we use the logarithm. This algorithm is
8302 * just a first try and will probably be tuned later. */
8303 static double computeObjectSwappability(robj *o) {
8304 time_t age = server.unixtime - o->vm.atime;
8305 long asize = 0;
8306 list *l;
8307 dict *d;
8308 struct dictEntry *de;
8309 int z;
8310
8311 if (age <= 0) return 0;
8312 switch(o->type) {
8313 case REDIS_STRING:
8314 if (o->encoding != REDIS_ENCODING_RAW) {
8315 asize = sizeof(*o);
8316 } else {
8317 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
8318 }
8319 break;
8320 case REDIS_LIST:
8321 l = o->ptr;
8322 listNode *ln = listFirst(l);
8323
8324 asize = sizeof(list);
8325 if (ln) {
8326 robj *ele = ln->value;
8327 long elesize;
8328
8329 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
8330 (sizeof(*o)+sdslen(ele->ptr)) :
8331 sizeof(*o);
8332 asize += (sizeof(listNode)+elesize)*listLength(l);
8333 }
8334 break;
8335 case REDIS_SET:
8336 case REDIS_ZSET:
8337 z = (o->type == REDIS_ZSET);
8338 d = z ? ((zset*)o->ptr)->dict : o->ptr;
8339
8340 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
8341 if (z) asize += sizeof(zset)-sizeof(dict);
8342 if (dictSize(d)) {
8343 long elesize;
8344 robj *ele;
8345
8346 de = dictGetRandomKey(d);
8347 ele = dictGetEntryKey(de);
8348 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
8349 (sizeof(*o)+sdslen(ele->ptr)) :
8350 sizeof(*o);
8351 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
8352 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
8353 }
8354 break;
8355 case REDIS_HASH:
8356 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
8357 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
8358 unsigned int len = zipmapLen((unsigned char*)o->ptr);
8359 unsigned int klen, vlen;
8360 unsigned char *key, *val;
8361
8362 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
8363 klen = 0;
8364 vlen = 0;
8365 }
8366 asize = len*(klen+vlen+3);
8367 } else if (o->encoding == REDIS_ENCODING_HT) {
8368 d = o->ptr;
8369 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
8370 if (dictSize(d)) {
8371 long elesize;
8372 robj *ele;
8373
8374 de = dictGetRandomKey(d);
8375 ele = dictGetEntryKey(de);
8376 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
8377 (sizeof(*o)+sdslen(ele->ptr)) :
8378 sizeof(*o);
8379 ele = dictGetEntryVal(de);
8380 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
8381 (sizeof(*o)+sdslen(ele->ptr)) :
8382 sizeof(*o);
8383 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
8384 }
8385 }
8386 break;
8387 }
8388 return (double)age*log(1+asize);
8389 }
8390
8391 /* Try to swap an object that's a good candidate for swapping.
8392 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
8393 * to swap any object at all.
8394 *
8395 * If 'usethreaded' is true, Redis will try to swap the object in background
8396 * using I/O threads. */
8397 static int vmSwapOneObject(int usethreads) {
8398 int j, i;
8399 struct dictEntry *best = NULL;
8400 double best_swappability = 0;
8401 redisDb *best_db = NULL;
8402 robj *key, *val;
8403
8404 for (j = 0; j < server.dbnum; j++) {
8405 redisDb *db = server.db+j;
8406 /* Why maxtries is set to 100?
8407 * Because this way (usually) we'll find 1 object even if just 1% - 2%
8408 * are swappable objects */
8409 int maxtries = 100;
8410
8411 if (dictSize(db->dict) == 0) continue;
8412 for (i = 0; i < 5; i++) {
8413 dictEntry *de;
8414 double swappability;
8415
8416 if (maxtries) maxtries--;
8417 de = dictGetRandomKey(db->dict);
8418 key = dictGetEntryKey(de);
8419 val = dictGetEntryVal(de);
8420 /* Only swap objects that are currently in memory.
8421 *
8422 * Also don't swap shared objects if threaded VM is on, as we
8423 * try to ensure that the main thread does not touch the
8424 * object while the I/O thread is using it, but we can't
8425 * control other keys without adding additional mutex. */
8426 if (key->storage != REDIS_VM_MEMORY ||
8427 (server.vm_max_threads != 0 && val->refcount != 1)) {
8428 if (maxtries) i--; /* don't count this try */
8429 continue;
8430 }
8431 swappability = computeObjectSwappability(val);
8432 if (!best || swappability > best_swappability) {
8433 best = de;
8434 best_swappability = swappability;
8435 best_db = db;
8436 }
8437 }
8438 }
8439 if (best == NULL) return REDIS_ERR;
8440 key = dictGetEntryKey(best);
8441 val = dictGetEntryVal(best);
8442
8443 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
8444 key->ptr, best_swappability);
8445
8446 /* Unshare the key if needed */
8447 if (key->refcount > 1) {
8448 robj *newkey = dupStringObject(key);
8449 decrRefCount(key);
8450 key = dictGetEntryKey(best) = newkey;
8451 }
8452 /* Swap it */
8453 if (usethreads) {
8454 vmSwapObjectThreaded(key,val,best_db);
8455 return REDIS_OK;
8456 } else {
8457 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
8458 dictGetEntryVal(best) = NULL;
8459 return REDIS_OK;
8460 } else {
8461 return REDIS_ERR;
8462 }
8463 }
8464 }
8465
8466 static int vmSwapOneObjectBlocking() {
8467 return vmSwapOneObject(0);
8468 }
8469
8470 static int vmSwapOneObjectThreaded() {
8471 return vmSwapOneObject(1);
8472 }
8473
8474 /* Return true if it's safe to swap out objects in a given moment.
8475 * Basically we don't want to swap objects out while there is a BGSAVE
8476 * or a BGAEOREWRITE running in backgroud. */
8477 static int vmCanSwapOut(void) {
8478 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
8479 }
8480
8481 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
8482 * and was deleted. Otherwise 0 is returned. */
8483 static int deleteIfSwapped(redisDb *db, robj *key) {
8484 dictEntry *de;
8485 robj *foundkey;
8486
8487 if ((de = dictFind(db->dict,key)) == NULL) return 0;
8488 foundkey = dictGetEntryKey(de);
8489 if (foundkey->storage == REDIS_VM_MEMORY) return 0;
8490 deleteKey(db,key);
8491 return 1;
8492 }
8493
8494 /* =================== Virtual Memory - Threaded I/O ======================= */
8495
8496 static void freeIOJob(iojob *j) {
8497 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
8498 j->type == REDIS_IOJOB_DO_SWAP ||
8499 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
8500 decrRefCount(j->val);
8501 decrRefCount(j->key);
8502 zfree(j);
8503 }
8504
8505 /* Every time a thread finished a Job, it writes a byte into the write side
8506 * of an unix pipe in order to "awake" the main thread, and this function
8507 * is called. */
8508 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
8509 int mask)
8510 {
8511 char buf[1];
8512 int retval, processed = 0, toprocess = -1, trytoswap = 1;
8513 REDIS_NOTUSED(el);
8514 REDIS_NOTUSED(mask);
8515 REDIS_NOTUSED(privdata);
8516
8517 /* For every byte we read in the read side of the pipe, there is one
8518 * I/O job completed to process. */
8519 while((retval = read(fd,buf,1)) == 1) {
8520 iojob *j;
8521 listNode *ln;
8522 robj *key;
8523 struct dictEntry *de;
8524
8525 redisLog(REDIS_DEBUG,"Processing I/O completed job");
8526
8527 /* Get the processed element (the oldest one) */
8528 lockThreadedIO();
8529 assert(listLength(server.io_processed) != 0);
8530 if (toprocess == -1) {
8531 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
8532 if (toprocess <= 0) toprocess = 1;
8533 }
8534 ln = listFirst(server.io_processed);
8535 j = ln->value;
8536 listDelNode(server.io_processed,ln);
8537 unlockThreadedIO();
8538 /* If this job is marked as canceled, just ignore it */
8539 if (j->canceled) {
8540 freeIOJob(j);
8541 continue;
8542 }
8543 /* Post process it in the main thread, as there are things we
8544 * can do just here to avoid race conditions and/or invasive locks */
8545 redisLog(REDIS_DEBUG,"Job %p type: %d, key at %p (%s) refcount: %d\n", (void*) j, j->type, (void*)j->key, (char*)j->key->ptr, j->key->refcount);
8546 de = dictFind(j->db->dict,j->key);
8547 assert(de != NULL);
8548 key = dictGetEntryKey(de);
8549 if (j->type == REDIS_IOJOB_LOAD) {
8550 redisDb *db;
8551
8552 /* Key loaded, bring it at home */
8553 key->storage = REDIS_VM_MEMORY;
8554 key->vm.atime = server.unixtime;
8555 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
8556 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
8557 (unsigned char*) key->ptr);
8558 server.vm_stats_swapped_objects--;
8559 server.vm_stats_swapins++;
8560 dictGetEntryVal(de) = j->val;
8561 incrRefCount(j->val);
8562 db = j->db;
8563 freeIOJob(j);
8564 /* Handle clients waiting for this key to be loaded. */
8565 handleClientsBlockedOnSwappedKey(db,key);
8566 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
8567 /* Now we know the amount of pages required to swap this object.
8568 * Let's find some space for it, and queue this task again
8569 * rebranded as REDIS_IOJOB_DO_SWAP. */
8570 if (!vmCanSwapOut() ||
8571 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
8572 {
8573 /* Ooops... no space or we can't swap as there is
8574 * a fork()ed Redis trying to save stuff on disk. */
8575 freeIOJob(j);
8576 key->storage = REDIS_VM_MEMORY; /* undo operation */
8577 } else {
8578 /* Note that we need to mark this pages as used now,
8579 * if the job will be canceled, we'll mark them as freed
8580 * again. */
8581 vmMarkPagesUsed(j->page,j->pages);
8582 j->type = REDIS_IOJOB_DO_SWAP;
8583 lockThreadedIO();
8584 queueIOJob(j);
8585 unlockThreadedIO();
8586 }
8587 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
8588 robj *val;
8589
8590 /* Key swapped. We can finally free some memory. */
8591 if (key->storage != REDIS_VM_SWAPPING) {
8592 printf("key->storage: %d\n",key->storage);
8593 printf("key->name: %s\n",(char*)key->ptr);
8594 printf("key->refcount: %d\n",key->refcount);
8595 printf("val: %p\n",(void*)j->val);
8596 printf("val->type: %d\n",j->val->type);
8597 printf("val->ptr: %s\n",(char*)j->val->ptr);
8598 }
8599 redisAssert(key->storage == REDIS_VM_SWAPPING);
8600 val = dictGetEntryVal(de);
8601 key->vm.page = j->page;
8602 key->vm.usedpages = j->pages;
8603 key->storage = REDIS_VM_SWAPPED;
8604 key->vtype = j->val->type;
8605 decrRefCount(val); /* Deallocate the object from memory. */
8606 dictGetEntryVal(de) = NULL;
8607 redisLog(REDIS_DEBUG,
8608 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
8609 (unsigned char*) key->ptr,
8610 (unsigned long long) j->page, (unsigned long long) j->pages);
8611 server.vm_stats_swapped_objects++;
8612 server.vm_stats_swapouts++;
8613 freeIOJob(j);
8614 /* Put a few more swap requests in queue if we are still
8615 * out of memory */
8616 if (trytoswap && vmCanSwapOut() &&
8617 zmalloc_used_memory() > server.vm_max_memory)
8618 {
8619 int more = 1;
8620 while(more) {
8621 lockThreadedIO();
8622 more = listLength(server.io_newjobs) <
8623 (unsigned) server.vm_max_threads;
8624 unlockThreadedIO();
8625 /* Don't waste CPU time if swappable objects are rare. */
8626 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
8627 trytoswap = 0;
8628 break;
8629 }
8630 }
8631 }
8632 }
8633 processed++;
8634 if (processed == toprocess) return;
8635 }
8636 if (retval < 0 && errno != EAGAIN) {
8637 redisLog(REDIS_WARNING,
8638 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
8639 strerror(errno));
8640 }
8641 }
8642
8643 static void lockThreadedIO(void) {
8644 pthread_mutex_lock(&server.io_mutex);
8645 }
8646
8647 static void unlockThreadedIO(void) {
8648 pthread_mutex_unlock(&server.io_mutex);
8649 }
8650
8651 /* Remove the specified object from the threaded I/O queue if still not
8652 * processed, otherwise make sure to flag it as canceled. */
8653 static void vmCancelThreadedIOJob(robj *o) {
8654 list *lists[3] = {
8655 server.io_newjobs, /* 0 */
8656 server.io_processing, /* 1 */
8657 server.io_processed /* 2 */
8658 };
8659 int i;
8660
8661 assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
8662 again:
8663 lockThreadedIO();
8664 /* Search for a matching key in one of the queues */
8665 for (i = 0; i < 3; i++) {
8666 listNode *ln;
8667 listIter li;
8668
8669 listRewind(lists[i],&li);
8670 while ((ln = listNext(&li)) != NULL) {
8671 iojob *job = ln->value;
8672
8673 if (job->canceled) continue; /* Skip this, already canceled. */
8674 if (compareStringObjects(job->key,o) == 0) {
8675 redisLog(REDIS_DEBUG,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
8676 (void*)job, (char*)o->ptr, job->type, i);
8677 /* Mark the pages as free since the swap didn't happened
8678 * or happened but is now discarded. */
8679 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
8680 vmMarkPagesFree(job->page,job->pages);
8681 /* Cancel the job. It depends on the list the job is
8682 * living in. */
8683 switch(i) {
8684 case 0: /* io_newjobs */
8685 /* If the job was yet not processed the best thing to do
8686 * is to remove it from the queue at all */
8687 freeIOJob(job);
8688 listDelNode(lists[i],ln);
8689 break;
8690 case 1: /* io_processing */
8691 /* Oh Shi- the thread is messing with the Job:
8692 *
8693 * Probably it's accessing the object if this is a
8694 * PREPARE_SWAP or DO_SWAP job.
8695 * If it's a LOAD job it may be reading from disk and
8696 * if we don't wait for the job to terminate before to
8697 * cancel it, maybe in a few microseconds data can be
8698 * corrupted in this pages. So the short story is:
8699 *
8700 * Better to wait for the job to move into the
8701 * next queue (processed)... */
8702
8703 /* We try again and again until the job is completed. */
8704 unlockThreadedIO();
8705 /* But let's wait some time for the I/O thread
8706 * to finish with this job. After all this condition
8707 * should be very rare. */
8708 usleep(1);
8709 goto again;
8710 case 2: /* io_processed */
8711 /* The job was already processed, that's easy...
8712 * just mark it as canceled so that we'll ignore it
8713 * when processing completed jobs. */
8714 job->canceled = 1;
8715 break;
8716 }
8717 /* Finally we have to adjust the storage type of the object
8718 * in order to "UNDO" the operaiton. */
8719 if (o->storage == REDIS_VM_LOADING)
8720 o->storage = REDIS_VM_SWAPPED;
8721 else if (o->storage == REDIS_VM_SWAPPING)
8722 o->storage = REDIS_VM_MEMORY;
8723 unlockThreadedIO();
8724 return;
8725 }
8726 }
8727 }
8728 unlockThreadedIO();
8729 assert(1 != 1); /* We should never reach this */
8730 }
8731
8732 static void *IOThreadEntryPoint(void *arg) {
8733 iojob *j;
8734 listNode *ln;
8735 REDIS_NOTUSED(arg);
8736
8737 pthread_detach(pthread_self());
8738 while(1) {
8739 /* Get a new job to process */
8740 lockThreadedIO();
8741 if (listLength(server.io_newjobs) == 0) {
8742 /* No new jobs in queue, exit. */
8743 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
8744 (long) pthread_self());
8745 server.io_active_threads--;
8746 unlockThreadedIO();
8747 return NULL;
8748 }
8749 ln = listFirst(server.io_newjobs);
8750 j = ln->value;
8751 listDelNode(server.io_newjobs,ln);
8752 /* Add the job in the processing queue */
8753 j->thread = pthread_self();
8754 listAddNodeTail(server.io_processing,j);
8755 ln = listLast(server.io_processing); /* We use ln later to remove it */
8756 unlockThreadedIO();
8757 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
8758 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
8759
8760 /* Process the Job */
8761 if (j->type == REDIS_IOJOB_LOAD) {
8762 j->val = vmReadObjectFromSwap(j->page,j->key->vtype);
8763 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
8764 FILE *fp = fopen("/dev/null","w+");
8765 j->pages = rdbSavedObjectPages(j->val,fp);
8766 fclose(fp);
8767 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
8768 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
8769 j->canceled = 1;
8770 }
8771
8772 /* Done: insert the job into the processed queue */
8773 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
8774 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
8775 lockThreadedIO();
8776 listDelNode(server.io_processing,ln);
8777 listAddNodeTail(server.io_processed,j);
8778 unlockThreadedIO();
8779
8780 /* Signal the main thread there is new stuff to process */
8781 assert(write(server.io_ready_pipe_write,"x",1) == 1);
8782 }
8783 return NULL; /* never reached */
8784 }
8785
8786 static void spawnIOThread(void) {
8787 pthread_t thread;
8788 sigset_t mask, omask;
8789 int err;
8790
8791 sigemptyset(&mask);
8792 sigaddset(&mask,SIGCHLD);
8793 sigaddset(&mask,SIGHUP);
8794 sigaddset(&mask,SIGPIPE);
8795 pthread_sigmask(SIG_SETMASK, &mask, &omask);
8796 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
8797 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
8798 strerror(err));
8799 usleep(1000000);
8800 }
8801 pthread_sigmask(SIG_SETMASK, &omask, NULL);
8802 server.io_active_threads++;
8803 }
8804
8805 /* We need to wait for the last thread to exit before we are able to
8806 * fork() in order to BGSAVE or BGREWRITEAOF. */
8807 static void waitEmptyIOJobsQueue(void) {
8808 while(1) {
8809 int io_processed_len;
8810
8811 lockThreadedIO();
8812 if (listLength(server.io_newjobs) == 0 &&
8813 listLength(server.io_processing) == 0 &&
8814 server.io_active_threads == 0)
8815 {
8816 unlockThreadedIO();
8817 return;
8818 }
8819 /* While waiting for empty jobs queue condition we post-process some
8820 * finshed job, as I/O threads may be hanging trying to write against
8821 * the io_ready_pipe_write FD but there are so much pending jobs that
8822 * it's blocking. */
8823 io_processed_len = listLength(server.io_processed);
8824 unlockThreadedIO();
8825 if (io_processed_len) {
8826 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
8827 usleep(1000); /* 1 millisecond */
8828 } else {
8829 usleep(10000); /* 10 milliseconds */
8830 }
8831 }
8832 }
8833
8834 static void vmReopenSwapFile(void) {
8835 /* Note: we don't close the old one as we are in the child process
8836 * and don't want to mess at all with the original file object. */
8837 server.vm_fp = fopen(server.vm_swap_file,"r+b");
8838 if (server.vm_fp == NULL) {
8839 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
8840 server.vm_swap_file);
8841 _exit(1);
8842 }
8843 server.vm_fd = fileno(server.vm_fp);
8844 }
8845
8846 /* This function must be called while with threaded IO locked */
8847 static void queueIOJob(iojob *j) {
8848 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
8849 (void*)j, j->type, (char*)j->key->ptr);
8850 listAddNodeTail(server.io_newjobs,j);
8851 if (server.io_active_threads < server.vm_max_threads)
8852 spawnIOThread();
8853 }
8854
8855 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
8856 iojob *j;
8857
8858 assert(key->storage == REDIS_VM_MEMORY);
8859 assert(key->refcount == 1);
8860
8861 j = zmalloc(sizeof(*j));
8862 j->type = REDIS_IOJOB_PREPARE_SWAP;
8863 j->db = db;
8864 j->key = dupStringObject(key);
8865 j->val = val;
8866 incrRefCount(val);
8867 j->canceled = 0;
8868 j->thread = (pthread_t) -1;
8869 key->storage = REDIS_VM_SWAPPING;
8870
8871 lockThreadedIO();
8872 queueIOJob(j);
8873 unlockThreadedIO();
8874 return REDIS_OK;
8875 }
8876
8877 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
8878
8879 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
8880 * If there is not already a job loading the key, it is craeted.
8881 * The key is added to the io_keys list in the client structure, and also
8882 * in the hash table mapping swapped keys to waiting clients, that is,
8883 * server.io_waited_keys. */
8884 static int waitForSwappedKey(redisClient *c, robj *key) {
8885 struct dictEntry *de;
8886 robj *o;
8887 list *l;
8888
8889 /* If the key does not exist or is already in RAM we don't need to
8890 * block the client at all. */
8891 de = dictFind(c->db->dict,key);
8892 if (de == NULL) return 0;
8893 o = dictGetEntryKey(de);
8894 if (o->storage == REDIS_VM_MEMORY) {
8895 return 0;
8896 } else if (o->storage == REDIS_VM_SWAPPING) {
8897 /* We were swapping the key, undo it! */
8898 vmCancelThreadedIOJob(o);
8899 return 0;
8900 }
8901
8902 /* OK: the key is either swapped, or being loaded just now. */
8903
8904 /* Add the key to the list of keys this client is waiting for.
8905 * This maps clients to keys they are waiting for. */
8906 listAddNodeTail(c->io_keys,key);
8907 incrRefCount(key);
8908
8909 /* Add the client to the swapped keys => clients waiting map. */
8910 de = dictFind(c->db->io_keys,key);
8911 if (de == NULL) {
8912 int retval;
8913
8914 /* For every key we take a list of clients blocked for it */
8915 l = listCreate();
8916 retval = dictAdd(c->db->io_keys,key,l);
8917 incrRefCount(key);
8918 assert(retval == DICT_OK);
8919 } else {
8920 l = dictGetEntryVal(de);
8921 }
8922 listAddNodeTail(l,c);
8923
8924 /* Are we already loading the key from disk? If not create a job */
8925 if (o->storage == REDIS_VM_SWAPPED) {
8926 iojob *j;
8927
8928 o->storage = REDIS_VM_LOADING;
8929 j = zmalloc(sizeof(*j));
8930 j->type = REDIS_IOJOB_LOAD;
8931 j->db = c->db;
8932 j->key = dupStringObject(key);
8933 j->key->vtype = o->vtype;
8934 j->page = o->vm.page;
8935 j->val = NULL;
8936 j->canceled = 0;
8937 j->thread = (pthread_t) -1;
8938 lockThreadedIO();
8939 queueIOJob(j);
8940 unlockThreadedIO();
8941 }
8942 return 1;
8943 }
8944
8945 /* Preload keys needed for the ZUNION and ZINTER commands. */
8946 static void zunionInterBlockClientOnSwappedKeys(redisClient *c) {
8947 int i, num;
8948 num = atoi(c->argv[2]->ptr);
8949 for (i = 0; i < num; i++) {
8950 waitForSwappedKey(c,c->argv[3+i]);
8951 }
8952 }
8953
8954 /* Is this client attempting to run a command against swapped keys?
8955 * If so, block it ASAP, load the keys in background, then resume it.
8956 *
8957 * The important idea about this function is that it can fail! If keys will
8958 * still be swapped when the client is resumed, this key lookups will
8959 * just block loading keys from disk. In practical terms this should only
8960 * happen with SORT BY command or if there is a bug in this function.
8961 *
8962 * Return 1 if the client is marked as blocked, 0 if the client can
8963 * continue as the keys it is going to access appear to be in memory. */
8964 static int blockClientOnSwappedKeys(struct redisCommand *cmd, redisClient *c) {
8965 int j, last;
8966
8967 if (cmd->vm_preload_proc != NULL) {
8968 cmd->vm_preload_proc(c);
8969 } else {
8970 if (cmd->vm_firstkey == 0) return 0;
8971 last = cmd->vm_lastkey;
8972 if (last < 0) last = c->argc+last;
8973 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep)
8974 waitForSwappedKey(c,c->argv[j]);
8975 }
8976
8977 /* If the client was blocked for at least one key, mark it as blocked. */
8978 if (listLength(c->io_keys)) {
8979 c->flags |= REDIS_IO_WAIT;
8980 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
8981 server.vm_blocked_clients++;
8982 return 1;
8983 } else {
8984 return 0;
8985 }
8986 }
8987
8988 /* Remove the 'key' from the list of blocked keys for a given client.
8989 *
8990 * The function returns 1 when there are no longer blocking keys after
8991 * the current one was removed (and the client can be unblocked). */
8992 static int dontWaitForSwappedKey(redisClient *c, robj *key) {
8993 list *l;
8994 listNode *ln;
8995 listIter li;
8996 struct dictEntry *de;
8997
8998 /* Remove the key from the list of keys this client is waiting for. */
8999 listRewind(c->io_keys,&li);
9000 while ((ln = listNext(&li)) != NULL) {
9001 if (compareStringObjects(ln->value,key) == 0) {
9002 listDelNode(c->io_keys,ln);
9003 break;
9004 }
9005 }
9006 assert(ln != NULL);
9007
9008 /* Remove the client form the key => waiting clients map. */
9009 de = dictFind(c->db->io_keys,key);
9010 assert(de != NULL);
9011 l = dictGetEntryVal(de);
9012 ln = listSearchKey(l,c);
9013 assert(ln != NULL);
9014 listDelNode(l,ln);
9015 if (listLength(l) == 0)
9016 dictDelete(c->db->io_keys,key);
9017
9018 return listLength(c->io_keys) == 0;
9019 }
9020
9021 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
9022 struct dictEntry *de;
9023 list *l;
9024 listNode *ln;
9025 int len;
9026
9027 de = dictFind(db->io_keys,key);
9028 if (!de) return;
9029
9030 l = dictGetEntryVal(de);
9031 len = listLength(l);
9032 /* Note: we can't use something like while(listLength(l)) as the list
9033 * can be freed by the calling function when we remove the last element. */
9034 while (len--) {
9035 ln = listFirst(l);
9036 redisClient *c = ln->value;
9037
9038 if (dontWaitForSwappedKey(c,key)) {
9039 /* Put the client in the list of clients ready to go as we
9040 * loaded all the keys about it. */
9041 listAddNodeTail(server.io_ready_clients,c);
9042 }
9043 }
9044 }
9045
9046 /* ================================= Debugging ============================== */
9047
9048 static void debugCommand(redisClient *c) {
9049 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
9050 *((char*)-1) = 'x';
9051 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
9052 if (rdbSave(server.dbfilename) != REDIS_OK) {
9053 addReply(c,shared.err);
9054 return;
9055 }
9056 emptyDb();
9057 if (rdbLoad(server.dbfilename) != REDIS_OK) {
9058 addReply(c,shared.err);
9059 return;
9060 }
9061 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
9062 addReply(c,shared.ok);
9063 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
9064 emptyDb();
9065 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
9066 addReply(c,shared.err);
9067 return;
9068 }
9069 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
9070 addReply(c,shared.ok);
9071 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
9072 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
9073 robj *key, *val;
9074
9075 if (!de) {
9076 addReply(c,shared.nokeyerr);
9077 return;
9078 }
9079 key = dictGetEntryKey(de);
9080 val = dictGetEntryVal(de);
9081 if (!server.vm_enabled || (key->storage == REDIS_VM_MEMORY ||
9082 key->storage == REDIS_VM_SWAPPING)) {
9083 char *strenc;
9084 char buf[128];
9085
9086 if (val->encoding < (sizeof(strencoding)/sizeof(char*))) {
9087 strenc = strencoding[val->encoding];
9088 } else {
9089 snprintf(buf,64,"unknown encoding %d\n", val->encoding);
9090 strenc = buf;
9091 }
9092 addReplySds(c,sdscatprintf(sdsempty(),
9093 "+Key at:%p refcount:%d, value at:%p refcount:%d "
9094 "encoding:%s serializedlength:%lld\r\n",
9095 (void*)key, key->refcount, (void*)val, val->refcount,
9096 strenc, (long long) rdbSavedObjectLen(val,NULL)));
9097 } else {
9098 addReplySds(c,sdscatprintf(sdsempty(),
9099 "+Key at:%p refcount:%d, value swapped at: page %llu "
9100 "using %llu pages\r\n",
9101 (void*)key, key->refcount, (unsigned long long) key->vm.page,
9102 (unsigned long long) key->vm.usedpages));
9103 }
9104 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
9105 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
9106 robj *key, *val;
9107
9108 if (!server.vm_enabled) {
9109 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
9110 return;
9111 }
9112 if (!de) {
9113 addReply(c,shared.nokeyerr);
9114 return;
9115 }
9116 key = dictGetEntryKey(de);
9117 val = dictGetEntryVal(de);
9118 /* If the key is shared we want to create a copy */
9119 if (key->refcount > 1) {
9120 robj *newkey = dupStringObject(key);
9121 decrRefCount(key);
9122 key = dictGetEntryKey(de) = newkey;
9123 }
9124 /* Swap it */
9125 if (key->storage != REDIS_VM_MEMORY) {
9126 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
9127 } else if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
9128 dictGetEntryVal(de) = NULL;
9129 addReply(c,shared.ok);
9130 } else {
9131 addReply(c,shared.err);
9132 }
9133 } else {
9134 addReplySds(c,sdsnew(
9135 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
9136 }
9137 }
9138
9139 static void _redisAssert(char *estr, char *file, int line) {
9140 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
9141 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true\n",file,line,estr);
9142 #ifdef HAVE_BACKTRACE
9143 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
9144 *((char*)-1) = 'x';
9145 #endif
9146 }
9147
9148 /* =================================== Main! ================================ */
9149
9150 #ifdef __linux__
9151 int linuxOvercommitMemoryValue(void) {
9152 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
9153 char buf[64];
9154
9155 if (!fp) return -1;
9156 if (fgets(buf,64,fp) == NULL) {
9157 fclose(fp);
9158 return -1;
9159 }
9160 fclose(fp);
9161
9162 return atoi(buf);
9163 }
9164
9165 void linuxOvercommitMemoryWarning(void) {
9166 if (linuxOvercommitMemoryValue() == 0) {
9167 redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low condition memory. 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.");
9168 }
9169 }
9170 #endif /* __linux__ */
9171
9172 static void daemonize(void) {
9173 int fd;
9174 FILE *fp;
9175
9176 if (fork() != 0) exit(0); /* parent exits */
9177 setsid(); /* create a new session */
9178
9179 /* Every output goes to /dev/null. If Redis is daemonized but
9180 * the 'logfile' is set to 'stdout' in the configuration file
9181 * it will not log at all. */
9182 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
9183 dup2(fd, STDIN_FILENO);
9184 dup2(fd, STDOUT_FILENO);
9185 dup2(fd, STDERR_FILENO);
9186 if (fd > STDERR_FILENO) close(fd);
9187 }
9188 /* Try to write the pid file */
9189 fp = fopen(server.pidfile,"w");
9190 if (fp) {
9191 fprintf(fp,"%d\n",getpid());
9192 fclose(fp);
9193 }
9194 }
9195
9196 static void version() {
9197 printf("Redis server version %s\n", REDIS_VERSION);
9198 exit(0);
9199 }
9200
9201 static void usage() {
9202 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
9203 fprintf(stderr," ./redis-server - (read config from stdin)\n");
9204 exit(1);
9205 }
9206
9207 int main(int argc, char **argv) {
9208 time_t start;
9209
9210 initServerConfig();
9211 if (argc == 2) {
9212 if (strcmp(argv[1], "-v") == 0 ||
9213 strcmp(argv[1], "--version") == 0) version();
9214 if (strcmp(argv[1], "--help") == 0) usage();
9215 resetServerSaveParams();
9216 loadServerConfig(argv[1]);
9217 } else if ((argc > 2)) {
9218 usage();
9219 } else {
9220 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'");
9221 }
9222 if (server.daemonize) daemonize();
9223 initServer();
9224 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
9225 #ifdef __linux__
9226 linuxOvercommitMemoryWarning();
9227 #endif
9228 start = time(NULL);
9229 if (server.appendonly) {
9230 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
9231 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
9232 } else {
9233 if (rdbLoad(server.dbfilename) == REDIS_OK)
9234 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
9235 }
9236 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
9237 aeSetBeforeSleepProc(server.el,beforeSleep);
9238 aeMain(server.el);
9239 aeDeleteEventLoop(server.el);
9240 return 0;
9241 }
9242
9243 /* ============================= Backtrace support ========================= */
9244
9245 #ifdef HAVE_BACKTRACE
9246 static char *findFuncName(void *pointer, unsigned long *offset);
9247
9248 static void *getMcontextEip(ucontext_t *uc) {
9249 #if defined(__FreeBSD__)
9250 return (void*) uc->uc_mcontext.mc_eip;
9251 #elif defined(__dietlibc__)
9252 return (void*) uc->uc_mcontext.eip;
9253 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
9254 #if __x86_64__
9255 return (void*) uc->uc_mcontext->__ss.__rip;
9256 #else
9257 return (void*) uc->uc_mcontext->__ss.__eip;
9258 #endif
9259 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
9260 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
9261 return (void*) uc->uc_mcontext->__ss.__rip;
9262 #else
9263 return (void*) uc->uc_mcontext->__ss.__eip;
9264 #endif
9265 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
9266 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
9267 #elif defined(__ia64__) /* Linux IA64 */
9268 return (void*) uc->uc_mcontext.sc_ip;
9269 #else
9270 return NULL;
9271 #endif
9272 }
9273
9274 static void segvHandler(int sig, siginfo_t *info, void *secret) {
9275 void *trace[100];
9276 char **messages = NULL;
9277 int i, trace_size = 0;
9278 unsigned long offset=0;
9279 ucontext_t *uc = (ucontext_t*) secret;
9280 sds infostring;
9281 REDIS_NOTUSED(info);
9282
9283 redisLog(REDIS_WARNING,
9284 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
9285 infostring = genRedisInfoString();
9286 redisLog(REDIS_WARNING, "%s",infostring);
9287 /* It's not safe to sdsfree() the returned string under memory
9288 * corruption conditions. Let it leak as we are going to abort */
9289
9290 trace_size = backtrace(trace, 100);
9291 /* overwrite sigaction with caller's address */
9292 if (getMcontextEip(uc) != NULL) {
9293 trace[1] = getMcontextEip(uc);
9294 }
9295 messages = backtrace_symbols(trace, trace_size);
9296
9297 for (i=1; i<trace_size; ++i) {
9298 char *fn = findFuncName(trace[i], &offset), *p;
9299
9300 p = strchr(messages[i],'+');
9301 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
9302 redisLog(REDIS_WARNING,"%s", messages[i]);
9303 } else {
9304 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
9305 }
9306 }
9307 /* free(messages); Don't call free() with possibly corrupted memory. */
9308 _exit(0);
9309 }
9310
9311 static void setupSigSegvAction(void) {
9312 struct sigaction act;
9313
9314 sigemptyset (&act.sa_mask);
9315 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
9316 * is used. Otherwise, sa_handler is used */
9317 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
9318 act.sa_sigaction = segvHandler;
9319 sigaction (SIGSEGV, &act, NULL);
9320 sigaction (SIGBUS, &act, NULL);
9321 sigaction (SIGFPE, &act, NULL);
9322 sigaction (SIGILL, &act, NULL);
9323 sigaction (SIGBUS, &act, NULL);
9324 return;
9325 }
9326
9327 #include "staticsymbols.h"
9328 /* This function try to convert a pointer into a function name. It's used in
9329 * oreder to provide a backtrace under segmentation fault that's able to
9330 * display functions declared as static (otherwise the backtrace is useless). */
9331 static char *findFuncName(void *pointer, unsigned long *offset){
9332 int i, ret = -1;
9333 unsigned long off, minoff = 0;
9334
9335 /* Try to match against the Symbol with the smallest offset */
9336 for (i=0; symsTable[i].pointer; i++) {
9337 unsigned long lp = (unsigned long) pointer;
9338
9339 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
9340 off=lp-symsTable[i].pointer;
9341 if (ret < 0 || off < minoff) {
9342 minoff=off;
9343 ret=i;
9344 }
9345 }
9346 }
9347 if (ret == -1) return NULL;
9348 *offset = minoff;
9349 return symsTable[ret].name;
9350 }
9351 #else /* HAVE_BACKTRACE */
9352 static void setupSigSegvAction(void) {
9353 }
9354 #endif /* HAVE_BACKTRACE */
9355
9356
9357
9358 /* The End */
9359
9360
9361