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