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