]> git.saurik.com Git - redis.git/blob - redis.c
0e188f602f88a77dd77110fe71906d5a4c040fcc
[redis.git] / redis.c
1 /*
2 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
28 */
29
30 #define REDIS_VERSION "2.1.1"
31
32 #include "fmacros.h"
33 #include "config.h"
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39 #include <unistd.h>
40 #include <signal.h>
41
42 #ifdef HAVE_BACKTRACE
43 #include <execinfo.h>
44 #include <ucontext.h>
45 #endif /* HAVE_BACKTRACE */
46
47 #include <sys/wait.h>
48 #include <errno.h>
49 #include <assert.h>
50 #include <ctype.h>
51 #include <stdarg.h>
52 #include <inttypes.h>
53 #include <arpa/inet.h>
54 #include <sys/stat.h>
55 #include <fcntl.h>
56 #include <sys/time.h>
57 #include <sys/resource.h>
58 #include <sys/uio.h>
59 #include <limits.h>
60 #include <float.h>
61 #include <math.h>
62 #include <pthread.h>
63
64 #if defined(__sun)
65 #include "solarisfixes.h"
66 #endif
67
68 #include "redis.h"
69 #include "ae.h" /* Event driven programming library */
70 #include "sds.h" /* Dynamic safe strings */
71 #include "anet.h" /* Networking the easy way */
72 #include "dict.h" /* Hash tables */
73 #include "adlist.h" /* Linked lists */
74 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
75 #include "lzf.h" /* LZF compression library */
76 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
77 #include "zipmap.h" /* Compact dictionary-alike data structure */
78 #include "ziplist.h" /* Compact list data structure */
79 #include "sha1.h" /* SHA1 is used for DEBUG DIGEST */
80 #include "release.h" /* Release and/or git repository information */
81
82 /* Error codes */
83 #define REDIS_OK 0
84 #define REDIS_ERR -1
85
86 /* Static server configuration */
87 #define REDIS_SERVERPORT 6379 /* TCP port */
88 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
89 #define REDIS_IOBUF_LEN 1024
90 #define REDIS_LOADBUF_LEN 1024
91 #define REDIS_STATIC_ARGS 8
92 #define REDIS_DEFAULT_DBNUM 16
93 #define REDIS_CONFIGLINE_MAX 1024
94 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
95 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
96 #define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
97 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
98 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
99
100 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
101 #define REDIS_WRITEV_THRESHOLD 3
102 /* Max number of iovecs used for each writev call */
103 #define REDIS_WRITEV_IOVEC_COUNT 256
104
105 /* Hash table parameters */
106 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
107
108 /* Command flags */
109 #define REDIS_CMD_BULK 1 /* Bulk write command */
110 #define REDIS_CMD_INLINE 2 /* Inline command */
111 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
112 this flags will return an error when the 'maxmemory' option is set in the
113 config file and the server is using more than maxmemory bytes of memory.
114 In short this commands are denied on low memory conditions. */
115 #define REDIS_CMD_DENYOOM 4
116 #define REDIS_CMD_FORCE_REPLICATION 8 /* Force replication even if dirty is 0 */
117
118 /* Object types */
119 #define REDIS_STRING 0
120 #define REDIS_LIST 1
121 #define REDIS_SET 2
122 #define REDIS_ZSET 3
123 #define REDIS_HASH 4
124
125 /* Objects encoding. Some kind of objects like Strings and Hashes can be
126 * internally represented in multiple ways. The 'encoding' field of the object
127 * is set to one of this fields for this object. */
128 #define REDIS_ENCODING_RAW 0 /* Raw representation */
129 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
130 #define REDIS_ENCODING_HT 2 /* Encoded as hash table */
131 #define REDIS_ENCODING_ZIPMAP 3 /* Encoded as zipmap */
132 #define REDIS_ENCODING_LIST 4 /* Encoded as zipmap */
133 #define REDIS_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
134
135 static char* strencoding[] = {
136 "raw", "int", "zipmap", "hashtable"
137 };
138
139 /* Object types only used for dumping to disk */
140 #define REDIS_EXPIRETIME 253
141 #define REDIS_SELECTDB 254
142 #define REDIS_EOF 255
143
144 /* Defines related to the dump file format. To store 32 bits lengths for short
145 * keys requires a lot of space, so we check the most significant 2 bits of
146 * the first byte to interpreter the length:
147 *
148 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
149 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
150 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
151 * 11|000000 this means: specially encoded object will follow. The six bits
152 * number specify the kind of object that follows.
153 * See the REDIS_RDB_ENC_* defines.
154 *
155 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
156 * values, will fit inside. */
157 #define REDIS_RDB_6BITLEN 0
158 #define REDIS_RDB_14BITLEN 1
159 #define REDIS_RDB_32BITLEN 2
160 #define REDIS_RDB_ENCVAL 3
161 #define REDIS_RDB_LENERR UINT_MAX
162
163 /* When a length of a string object stored on disk has the first two bits
164 * set, the remaining two bits specify a special encoding for the object
165 * accordingly to the following defines: */
166 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
167 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
168 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
169 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
170
171 /* Virtual memory object->where field. */
172 #define REDIS_VM_MEMORY 0 /* The object is on memory */
173 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
174 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
175 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
176
177 /* Virtual memory static configuration stuff.
178 * Check vmFindContiguousPages() to know more about this magic numbers. */
179 #define REDIS_VM_MAX_NEAR_PAGES 65536
180 #define REDIS_VM_MAX_RANDOM_JUMP 4096
181 #define REDIS_VM_MAX_THREADS 32
182 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
183 /* The following is the *percentage* of completed I/O jobs to process when the
184 * handelr is called. While Virtual Memory I/O operations are performed by
185 * threads, this operations must be processed by the main thread when completed
186 * in order to take effect. */
187 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
188
189 /* Client flags */
190 #define REDIS_SLAVE 1 /* This client is a slave server */
191 #define REDIS_MASTER 2 /* This client is a master server */
192 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
193 #define REDIS_MULTI 8 /* This client is in a MULTI context */
194 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
195 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
196 #define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
197
198 /* Slave replication state - slave side */
199 #define REDIS_REPL_NONE 0 /* No active replication */
200 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
201 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
202
203 /* Slave replication state - from the point of view of master
204 * Note that in SEND_BULK and ONLINE state the slave receives new updates
205 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
206 * to start the next background saving in order to send updates to it. */
207 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
208 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
209 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
210 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
211
212 /* List related stuff */
213 #define REDIS_HEAD 0
214 #define REDIS_TAIL 1
215
216 /* Sort operations */
217 #define REDIS_SORT_GET 0
218 #define REDIS_SORT_ASC 1
219 #define REDIS_SORT_DESC 2
220 #define REDIS_SORTKEY_MAX 1024
221
222 /* Log levels */
223 #define REDIS_DEBUG 0
224 #define REDIS_VERBOSE 1
225 #define REDIS_NOTICE 2
226 #define REDIS_WARNING 3
227
228 /* Anti-warning macro... */
229 #define REDIS_NOTUSED(V) ((void) V)
230
231 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
232 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
233
234 /* Append only defines */
235 #define APPENDFSYNC_NO 0
236 #define APPENDFSYNC_ALWAYS 1
237 #define APPENDFSYNC_EVERYSEC 2
238
239 /* Hashes related defaults */
240 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
241 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
242
243 /* We can print the stacktrace, so our assert is defined this way: */
244 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
245 #define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
246 static void _redisAssert(char *estr, char *file, int line);
247 static void _redisPanic(char *msg, char *file, int line);
248
249 /*================================= Data types ============================== */
250
251 /* A redis object, that is a type able to hold a string / list / set */
252
253 /* The VM object structure */
254 struct redisObjectVM {
255 off_t page; /* the page at witch the object is stored on disk */
256 off_t usedpages; /* number of pages used on disk */
257 time_t atime; /* Last access time */
258 } vm;
259
260 /* The actual Redis Object */
261 typedef struct redisObject {
262 void *ptr;
263 unsigned char type;
264 unsigned char encoding;
265 unsigned char storage; /* If this object is a key, where is the value?
266 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
267 unsigned char vtype; /* If this object is a key, and value is swapped out,
268 * this is the type of the swapped out object. */
269 int refcount;
270 /* VM fields, this are only allocated if VM is active, otherwise the
271 * object allocation function will just allocate
272 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
273 * Redis without VM active will not have any overhead. */
274 struct redisObjectVM vm;
275 } robj;
276
277 /* Macro used to initalize a Redis object allocated on the stack.
278 * Note that this macro is taken near the structure definition to make sure
279 * we'll update it when the structure is changed, to avoid bugs like
280 * bug #85 introduced exactly in this way. */
281 #define initStaticStringObject(_var,_ptr) do { \
282 _var.refcount = 1; \
283 _var.type = REDIS_STRING; \
284 _var.encoding = REDIS_ENCODING_RAW; \
285 _var.ptr = _ptr; \
286 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
287 } while(0);
288
289 typedef struct redisDb {
290 dict *dict; /* The keyspace for this DB */
291 dict *expires; /* Timeout of keys with a timeout set */
292 dict *blocking_keys; /* Keys with clients waiting for data (BLPOP) */
293 dict *io_keys; /* Keys with clients waiting for VM I/O */
294 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
295 int id;
296 } redisDb;
297
298 /* Client MULTI/EXEC state */
299 typedef struct multiCmd {
300 robj **argv;
301 int argc;
302 struct redisCommand *cmd;
303 } multiCmd;
304
305 typedef struct multiState {
306 multiCmd *commands; /* Array of MULTI commands */
307 int count; /* Total number of MULTI commands */
308 } multiState;
309
310 /* With multiplexing we need to take per-clinet state.
311 * Clients are taken in a liked list. */
312 typedef struct redisClient {
313 int fd;
314 redisDb *db;
315 int dictid;
316 sds querybuf;
317 robj **argv, **mbargv;
318 int argc, mbargc;
319 int bulklen; /* bulk read len. -1 if not in bulk read mode */
320 int multibulk; /* multi bulk command format active */
321 list *reply;
322 int sentlen;
323 time_t lastinteraction; /* time of the last interaction, used for timeout */
324 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
325 int slaveseldb; /* slave selected db, if this client is a slave */
326 int authenticated; /* when requirepass is non-NULL */
327 int replstate; /* replication state if this is a slave */
328 int repldbfd; /* replication DB file descriptor */
329 long repldboff; /* replication DB file offset */
330 off_t repldbsize; /* replication DB file size */
331 multiState mstate; /* MULTI/EXEC state */
332 robj **blocking_keys; /* The key we are waiting to terminate a blocking
333 * operation such as BLPOP. Otherwise NULL. */
334 int blocking_keys_num; /* Number of blocking keys */
335 time_t blockingto; /* Blocking operation timeout. If UNIX current time
336 * is >= blockingto then the operation timed out. */
337 list *io_keys; /* Keys this client is waiting to be loaded from the
338 * swap file in order to continue. */
339 list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */
340 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
341 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
342 } redisClient;
343
344 struct saveparam {
345 time_t seconds;
346 int changes;
347 };
348
349 /* Global server state structure */
350 struct redisServer {
351 int port;
352 int fd;
353 redisDb *db;
354 long long dirty; /* changes to DB from the last save */
355 list *clients;
356 list *slaves, *monitors;
357 char neterr[ANET_ERR_LEN];
358 aeEventLoop *el;
359 int cronloops; /* number of times the cron function run */
360 list *objfreelist; /* A list of freed objects to avoid malloc() */
361 time_t lastsave; /* Unix time of last save succeeede */
362 /* Fields used only for stats */
363 time_t stat_starttime; /* server start time */
364 long long stat_numcommands; /* number of processed commands */
365 long long stat_numconnections; /* number of connections received */
366 long long stat_expiredkeys; /* number of expired keys */
367 /* Configuration */
368 int verbosity;
369 int glueoutputbuf;
370 int maxidletime;
371 int dbnum;
372 int daemonize;
373 int appendonly;
374 int appendfsync;
375 int shutdown_asap;
376 time_t lastfsync;
377 int appendfd;
378 int appendseldb;
379 char *pidfile;
380 pid_t bgsavechildpid;
381 pid_t bgrewritechildpid;
382 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
383 sds aofbuf; /* AOF buffer, written before entering the event loop */
384 struct saveparam *saveparams;
385 int saveparamslen;
386 char *logfile;
387 char *bindaddr;
388 char *dbfilename;
389 char *appendfilename;
390 char *requirepass;
391 int rdbcompression;
392 int activerehashing;
393 /* Replication related */
394 int isslave;
395 char *masterauth;
396 char *masterhost;
397 int masterport;
398 redisClient *master; /* client that is master for this slave */
399 int replstate;
400 unsigned int maxclients;
401 unsigned long long maxmemory;
402 unsigned int blpop_blocked_clients;
403 unsigned int vm_blocked_clients;
404 /* Sort parameters - qsort_r() is only available under BSD so we
405 * have to take this state global, in order to pass it to sortCompare() */
406 int sort_desc;
407 int sort_alpha;
408 int sort_bypattern;
409 /* Virtual memory configuration */
410 int vm_enabled;
411 char *vm_swap_file;
412 off_t vm_page_size;
413 off_t vm_pages;
414 unsigned long long vm_max_memory;
415 /* Hashes config */
416 size_t hash_max_zipmap_entries;
417 size_t hash_max_zipmap_value;
418 /* Virtual memory state */
419 FILE *vm_fp;
420 int vm_fd;
421 off_t vm_next_page; /* Next probably empty page */
422 off_t vm_near_pages; /* Number of pages allocated sequentially */
423 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
424 time_t unixtime; /* Unix time sampled every second. */
425 /* Virtual memory I/O threads stuff */
426 /* An I/O thread process an element taken from the io_jobs queue and
427 * put the result of the operation in the io_done list. While the
428 * job is being processed, it's put on io_processing queue. */
429 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
430 list *io_processing; /* List of VM I/O jobs being processed */
431 list *io_processed; /* List of VM I/O jobs already processed */
432 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
433 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
434 pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
435 pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
436 pthread_attr_t io_threads_attr; /* attributes for threads creation */
437 int io_active_threads; /* Number of running I/O threads */
438 int vm_max_threads; /* Max number of I/O threads running at the same time */
439 /* Our main thread is blocked on the event loop, locking for sockets ready
440 * to be read or written, so when a threaded I/O operation is ready to be
441 * processed by the main thread, the I/O thread will use a unix pipe to
442 * awake the main thread. The followings are the two pipe FDs. */
443 int io_ready_pipe_read;
444 int io_ready_pipe_write;
445 /* Virtual memory stats */
446 unsigned long long vm_stats_used_pages;
447 unsigned long long vm_stats_swapped_objects;
448 unsigned long long vm_stats_swapouts;
449 unsigned long long vm_stats_swapins;
450 /* Pubsub */
451 dict *pubsub_channels; /* Map channels to list of subscribed clients */
452 list *pubsub_patterns; /* A list of pubsub_patterns */
453 /* Misc */
454 FILE *devnull;
455 };
456
457 typedef struct pubsubPattern {
458 redisClient *client;
459 robj *pattern;
460 } pubsubPattern;
461
462 typedef void redisCommandProc(redisClient *c);
463 typedef void redisVmPreloadProc(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
464 struct redisCommand {
465 char *name;
466 redisCommandProc *proc;
467 int arity;
468 int flags;
469 /* Use a function to determine which keys need to be loaded
470 * in the background prior to executing this command. Takes precedence
471 * over vm_firstkey and others, ignored when NULL */
472 redisVmPreloadProc *vm_preload_proc;
473 /* What keys should be loaded in background when calling this command? */
474 int vm_firstkey; /* The first argument that's a key (0 = no keys) */
475 int vm_lastkey; /* THe last argument that's a key */
476 int vm_keystep; /* The step between first and last key */
477 };
478
479 struct redisFunctionSym {
480 char *name;
481 unsigned long pointer;
482 };
483
484 typedef struct _redisSortObject {
485 robj *obj;
486 union {
487 double score;
488 robj *cmpobj;
489 } u;
490 } redisSortObject;
491
492 typedef struct _redisSortOperation {
493 int type;
494 robj *pattern;
495 } redisSortOperation;
496
497 /* ZSETs use a specialized version of Skiplists */
498
499 typedef struct zskiplistNode {
500 struct zskiplistNode **forward;
501 struct zskiplistNode *backward;
502 unsigned int *span;
503 double score;
504 robj *obj;
505 } zskiplistNode;
506
507 typedef struct zskiplist {
508 struct zskiplistNode *header, *tail;
509 unsigned long length;
510 int level;
511 } zskiplist;
512
513 typedef struct zset {
514 dict *dict;
515 zskiplist *zsl;
516 } zset;
517
518 /* Our shared "common" objects */
519
520 #define REDIS_SHARED_INTEGERS 10000
521 struct sharedObjectsStruct {
522 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
523 *colon, *nullbulk, *nullmultibulk, *queued,
524 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
525 *outofrangeerr, *plus,
526 *select0, *select1, *select2, *select3, *select4,
527 *select5, *select6, *select7, *select8, *select9,
528 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk, *mbulk3,
529 *mbulk4, *psubscribebulk, *punsubscribebulk,
530 *integers[REDIS_SHARED_INTEGERS];
531 } shared;
532
533 /* Global vars that are actally used as constants. The following double
534 * values are used for double on-disk serialization, and are initialized
535 * at runtime to avoid strange compiler optimizations. */
536
537 static double R_Zero, R_PosInf, R_NegInf, R_Nan;
538
539 /* VM threaded I/O request message */
540 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
541 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
542 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
543 typedef struct iojob {
544 int type; /* Request type, REDIS_IOJOB_* */
545 redisDb *db;/* Redis database */
546 robj *key; /* This I/O request is about swapping this key */
547 robj *val; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
548 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
549 off_t page; /* Swap page where to read/write the object */
550 off_t pages; /* Swap pages needed to save object. PREPARE_SWAP return val */
551 int canceled; /* True if this command was canceled by blocking side of VM */
552 pthread_t thread; /* ID of the thread processing this entry */
553 } iojob;
554
555 /*================================ Prototypes =============================== */
556
557 static void freeStringObject(robj *o);
558 static void freeListObject(robj *o);
559 static void freeSetObject(robj *o);
560 static void decrRefCount(void *o);
561 static robj *createObject(int type, void *ptr);
562 static void freeClient(redisClient *c);
563 static int rdbLoad(char *filename);
564 static void addReply(redisClient *c, robj *obj);
565 static void addReplySds(redisClient *c, sds s);
566 static void incrRefCount(robj *o);
567 static int rdbSaveBackground(char *filename);
568 static robj *createStringObject(char *ptr, size_t len);
569 static robj *dupStringObject(robj *o);
570 static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
571 static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
572 static void flushAppendOnlyFile(void);
573 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
574 static int syncWithMaster(void);
575 static robj *tryObjectEncoding(robj *o);
576 static robj *getDecodedObject(robj *o);
577 static int removeExpire(redisDb *db, robj *key);
578 static int expireIfNeeded(redisDb *db, robj *key);
579 static int deleteIfVolatile(redisDb *db, robj *key);
580 static int deleteIfSwapped(redisDb *db, robj *key);
581 static int deleteKey(redisDb *db, robj *key);
582 static time_t getExpire(redisDb *db, robj *key);
583 static int setExpire(redisDb *db, robj *key, time_t when);
584 static void updateSlavesWaitingBgsave(int bgsaveerr);
585 static void freeMemoryIfNeeded(void);
586 static int processCommand(redisClient *c);
587 static void setupSigSegvAction(void);
588 static void rdbRemoveTempFile(pid_t childpid);
589 static void aofRemoveTempFile(pid_t childpid);
590 static size_t stringObjectLen(robj *o);
591 static void processInputBuffer(redisClient *c);
592 static zskiplist *zslCreate(void);
593 static void zslFree(zskiplist *zsl);
594 static void zslInsert(zskiplist *zsl, double score, robj *obj);
595 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
596 static void initClientMultiState(redisClient *c);
597 static void freeClientMultiState(redisClient *c);
598 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
599 static void unblockClientWaitingData(redisClient *c);
600 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
601 static void vmInit(void);
602 static void vmMarkPagesFree(off_t page, off_t count);
603 static robj *vmLoadObject(robj *key);
604 static robj *vmPreviewObject(robj *key);
605 static int vmSwapOneObjectBlocking(void);
606 static int vmSwapOneObjectThreaded(void);
607 static int vmCanSwapOut(void);
608 static int tryFreeOneObjectFromFreelist(void);
609 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
610 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
611 static void vmCancelThreadedIOJob(robj *o);
612 static void lockThreadedIO(void);
613 static void unlockThreadedIO(void);
614 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
615 static void freeIOJob(iojob *j);
616 static void queueIOJob(iojob *j);
617 static int vmWriteObjectOnSwap(robj *o, off_t page);
618 static robj *vmReadObjectFromSwap(off_t page, int type);
619 static void waitEmptyIOJobsQueue(void);
620 static void vmReopenSwapFile(void);
621 static int vmFreePage(off_t page);
622 static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
623 static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
624 static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd);
625 static int dontWaitForSwappedKey(redisClient *c, robj *key);
626 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
627 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
628 static struct redisCommand *lookupCommand(char *name);
629 static void call(redisClient *c, struct redisCommand *cmd);
630 static void resetClient(redisClient *c);
631 static void convertToRealHash(robj *o);
632 static int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
633 static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
634 static void freePubsubPattern(void *p);
635 static int listMatchPubsubPattern(void *a, void *b);
636 static int compareStringObjects(robj *a, robj *b);
637 static int equalStringObjects(robj *a, robj *b);
638 static void usage();
639 static int rewriteAppendOnlyFileBackground(void);
640 static int vmSwapObjectBlocking(robj *key, robj *val);
641 static int prepareForShutdown();
642 static void touchWatchedKey(redisDb *db, robj *key);
643 static void touchWatchedKeysOnFlush(int dbid);
644 static void unwatchAllKeys(redisClient *c);
645
646 static void authCommand(redisClient *c);
647 static void pingCommand(redisClient *c);
648 static void echoCommand(redisClient *c);
649 static void setCommand(redisClient *c);
650 static void setnxCommand(redisClient *c);
651 static void setexCommand(redisClient *c);
652 static void getCommand(redisClient *c);
653 static void delCommand(redisClient *c);
654 static void existsCommand(redisClient *c);
655 static void incrCommand(redisClient *c);
656 static void decrCommand(redisClient *c);
657 static void incrbyCommand(redisClient *c);
658 static void decrbyCommand(redisClient *c);
659 static void selectCommand(redisClient *c);
660 static void randomkeyCommand(redisClient *c);
661 static void keysCommand(redisClient *c);
662 static void dbsizeCommand(redisClient *c);
663 static void lastsaveCommand(redisClient *c);
664 static void saveCommand(redisClient *c);
665 static void bgsaveCommand(redisClient *c);
666 static void bgrewriteaofCommand(redisClient *c);
667 static void shutdownCommand(redisClient *c);
668 static void moveCommand(redisClient *c);
669 static void renameCommand(redisClient *c);
670 static void renamenxCommand(redisClient *c);
671 static void lpushCommand(redisClient *c);
672 static void rpushCommand(redisClient *c);
673 static void lpopCommand(redisClient *c);
674 static void rpopCommand(redisClient *c);
675 static void llenCommand(redisClient *c);
676 static void lindexCommand(redisClient *c);
677 static void lrangeCommand(redisClient *c);
678 static void ltrimCommand(redisClient *c);
679 static void typeCommand(redisClient *c);
680 static void lsetCommand(redisClient *c);
681 static void saddCommand(redisClient *c);
682 static void sremCommand(redisClient *c);
683 static void smoveCommand(redisClient *c);
684 static void sismemberCommand(redisClient *c);
685 static void scardCommand(redisClient *c);
686 static void spopCommand(redisClient *c);
687 static void srandmemberCommand(redisClient *c);
688 static void sinterCommand(redisClient *c);
689 static void sinterstoreCommand(redisClient *c);
690 static void sunionCommand(redisClient *c);
691 static void sunionstoreCommand(redisClient *c);
692 static void sdiffCommand(redisClient *c);
693 static void sdiffstoreCommand(redisClient *c);
694 static void syncCommand(redisClient *c);
695 static void flushdbCommand(redisClient *c);
696 static void flushallCommand(redisClient *c);
697 static void sortCommand(redisClient *c);
698 static void lremCommand(redisClient *c);
699 static void rpoplpushcommand(redisClient *c);
700 static void infoCommand(redisClient *c);
701 static void mgetCommand(redisClient *c);
702 static void monitorCommand(redisClient *c);
703 static void expireCommand(redisClient *c);
704 static void expireatCommand(redisClient *c);
705 static void getsetCommand(redisClient *c);
706 static void ttlCommand(redisClient *c);
707 static void slaveofCommand(redisClient *c);
708 static void debugCommand(redisClient *c);
709 static void msetCommand(redisClient *c);
710 static void msetnxCommand(redisClient *c);
711 static void zaddCommand(redisClient *c);
712 static void zincrbyCommand(redisClient *c);
713 static void zrangeCommand(redisClient *c);
714 static void zrangebyscoreCommand(redisClient *c);
715 static void zcountCommand(redisClient *c);
716 static void zrevrangeCommand(redisClient *c);
717 static void zcardCommand(redisClient *c);
718 static void zremCommand(redisClient *c);
719 static void zscoreCommand(redisClient *c);
720 static void zremrangebyscoreCommand(redisClient *c);
721 static void multiCommand(redisClient *c);
722 static void execCommand(redisClient *c);
723 static void discardCommand(redisClient *c);
724 static void blpopCommand(redisClient *c);
725 static void brpopCommand(redisClient *c);
726 static void appendCommand(redisClient *c);
727 static void substrCommand(redisClient *c);
728 static void zrankCommand(redisClient *c);
729 static void zrevrankCommand(redisClient *c);
730 static void hsetCommand(redisClient *c);
731 static void hsetnxCommand(redisClient *c);
732 static void hgetCommand(redisClient *c);
733 static void hmsetCommand(redisClient *c);
734 static void hmgetCommand(redisClient *c);
735 static void hdelCommand(redisClient *c);
736 static void hlenCommand(redisClient *c);
737 static void zremrangebyrankCommand(redisClient *c);
738 static void zunionstoreCommand(redisClient *c);
739 static void zinterstoreCommand(redisClient *c);
740 static void hkeysCommand(redisClient *c);
741 static void hvalsCommand(redisClient *c);
742 static void hgetallCommand(redisClient *c);
743 static void hexistsCommand(redisClient *c);
744 static void configCommand(redisClient *c);
745 static void hincrbyCommand(redisClient *c);
746 static void subscribeCommand(redisClient *c);
747 static void unsubscribeCommand(redisClient *c);
748 static void psubscribeCommand(redisClient *c);
749 static void punsubscribeCommand(redisClient *c);
750 static void publishCommand(redisClient *c);
751 static void watchCommand(redisClient *c);
752 static void unwatchCommand(redisClient *c);
753
754 /*================================= Globals ================================= */
755
756 /* Global vars */
757 static struct redisServer server; /* server global state */
758 static struct redisCommand *commandTable;
759 static struct redisCommand readonlyCommandTable[] = {
760 {"get",getCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
761 {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
762 {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
763 {"setex",setexCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
764 {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
765 {"substr",substrCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
766 {"del",delCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
767 {"exists",existsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
768 {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
769 {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
770 {"mget",mgetCommand,-2,REDIS_CMD_INLINE,NULL,1,-1,1},
771 {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
772 {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
773 {"rpop",rpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
774 {"lpop",lpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
775 {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
776 {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
777 {"llen",llenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
778 {"lindex",lindexCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
779 {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
780 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
781 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
782 {"lrem",lremCommand,4,REDIS_CMD_BULK,NULL,1,1,1},
783 {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,2,1},
784 {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
785 {"srem",sremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
786 {"smove",smoveCommand,4,REDIS_CMD_BULK,NULL,1,2,1},
787 {"sismember",sismemberCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
788 {"scard",scardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
789 {"spop",spopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
790 {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
791 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
792 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
793 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
794 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
795 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
796 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
797 {"smembers",sinterCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
798 {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
799 {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
800 {"zrem",zremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
801 {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
802 {"zremrangebyrank",zremrangebyrankCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
803 {"zunionstore",zunionstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
804 {"zinterstore",zinterstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
805 {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
806 {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
807 {"zcount",zcountCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
808 {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
809 {"zcard",zcardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
810 {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
811 {"zrank",zrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
812 {"zrevrank",zrevrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
813 {"hset",hsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
814 {"hsetnx",hsetnxCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
815 {"hget",hgetCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
816 {"hmset",hmsetCommand,-4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
817 {"hmget",hmgetCommand,-3,REDIS_CMD_BULK,NULL,1,1,1},
818 {"hincrby",hincrbyCommand,4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
819 {"hdel",hdelCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
820 {"hlen",hlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
821 {"hkeys",hkeysCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
822 {"hvals",hvalsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
823 {"hgetall",hgetallCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
824 {"hexists",hexistsCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
825 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
826 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
827 {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
828 {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
829 {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
830 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
831 {"select",selectCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
832 {"move",moveCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
833 {"rename",renameCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
834 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
835 {"expire",expireCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
836 {"expireat",expireatCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
837 {"keys",keysCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
838 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
839 {"auth",authCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
840 {"ping",pingCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
841 {"echo",echoCommand,2,REDIS_CMD_BULK,NULL,0,0,0},
842 {"save",saveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
843 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
844 {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
845 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
846 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
847 {"type",typeCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
848 {"multi",multiCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
849 {"exec",execCommand,1,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0},
850 {"discard",discardCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
851 {"sync",syncCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
852 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
853 {"flushall",flushallCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
854 {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
855 {"info",infoCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
856 {"monitor",monitorCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
857 {"ttl",ttlCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
858 {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
859 {"debug",debugCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
860 {"config",configCommand,-2,REDIS_CMD_BULK,NULL,0,0,0},
861 {"subscribe",subscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
862 {"unsubscribe",unsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
863 {"psubscribe",psubscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
864 {"punsubscribe",punsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
865 {"publish",publishCommand,3,REDIS_CMD_BULK|REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0},
866 {"watch",watchCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
867 {"unwatch",unwatchCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}
868 };
869
870 /*============================ Utility functions ============================ */
871
872 /* Glob-style pattern matching. */
873 static int stringmatchlen(const char *pattern, int patternLen,
874 const char *string, int stringLen, int nocase)
875 {
876 while(patternLen) {
877 switch(pattern[0]) {
878 case '*':
879 while (pattern[1] == '*') {
880 pattern++;
881 patternLen--;
882 }
883 if (patternLen == 1)
884 return 1; /* match */
885 while(stringLen) {
886 if (stringmatchlen(pattern+1, patternLen-1,
887 string, stringLen, nocase))
888 return 1; /* match */
889 string++;
890 stringLen--;
891 }
892 return 0; /* no match */
893 break;
894 case '?':
895 if (stringLen == 0)
896 return 0; /* no match */
897 string++;
898 stringLen--;
899 break;
900 case '[':
901 {
902 int not, match;
903
904 pattern++;
905 patternLen--;
906 not = pattern[0] == '^';
907 if (not) {
908 pattern++;
909 patternLen--;
910 }
911 match = 0;
912 while(1) {
913 if (pattern[0] == '\\') {
914 pattern++;
915 patternLen--;
916 if (pattern[0] == string[0])
917 match = 1;
918 } else if (pattern[0] == ']') {
919 break;
920 } else if (patternLen == 0) {
921 pattern--;
922 patternLen++;
923 break;
924 } else if (pattern[1] == '-' && patternLen >= 3) {
925 int start = pattern[0];
926 int end = pattern[2];
927 int c = string[0];
928 if (start > end) {
929 int t = start;
930 start = end;
931 end = t;
932 }
933 if (nocase) {
934 start = tolower(start);
935 end = tolower(end);
936 c = tolower(c);
937 }
938 pattern += 2;
939 patternLen -= 2;
940 if (c >= start && c <= end)
941 match = 1;
942 } else {
943 if (!nocase) {
944 if (pattern[0] == string[0])
945 match = 1;
946 } else {
947 if (tolower((int)pattern[0]) == tolower((int)string[0]))
948 match = 1;
949 }
950 }
951 pattern++;
952 patternLen--;
953 }
954 if (not)
955 match = !match;
956 if (!match)
957 return 0; /* no match */
958 string++;
959 stringLen--;
960 break;
961 }
962 case '\\':
963 if (patternLen >= 2) {
964 pattern++;
965 patternLen--;
966 }
967 /* fall through */
968 default:
969 if (!nocase) {
970 if (pattern[0] != string[0])
971 return 0; /* no match */
972 } else {
973 if (tolower((int)pattern[0]) != tolower((int)string[0]))
974 return 0; /* no match */
975 }
976 string++;
977 stringLen--;
978 break;
979 }
980 pattern++;
981 patternLen--;
982 if (stringLen == 0) {
983 while(*pattern == '*') {
984 pattern++;
985 patternLen--;
986 }
987 break;
988 }
989 }
990 if (patternLen == 0 && stringLen == 0)
991 return 1;
992 return 0;
993 }
994
995 static int stringmatch(const char *pattern, const char *string, int nocase) {
996 return stringmatchlen(pattern,strlen(pattern),string,strlen(string),nocase);
997 }
998
999 /* Convert a string representing an amount of memory into the number of
1000 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
1001 * (1024*1024*1024).
1002 *
1003 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
1004 * set to 0 */
1005 static long long memtoll(const char *p, int *err) {
1006 const char *u;
1007 char buf[128];
1008 long mul; /* unit multiplier */
1009 long long val;
1010 unsigned int digits;
1011
1012 if (err) *err = 0;
1013 /* Search the first non digit character. */
1014 u = p;
1015 if (*u == '-') u++;
1016 while(*u && isdigit(*u)) u++;
1017 if (*u == '\0' || !strcasecmp(u,"b")) {
1018 mul = 1;
1019 } else if (!strcasecmp(u,"k")) {
1020 mul = 1000;
1021 } else if (!strcasecmp(u,"kb")) {
1022 mul = 1024;
1023 } else if (!strcasecmp(u,"m")) {
1024 mul = 1000*1000;
1025 } else if (!strcasecmp(u,"mb")) {
1026 mul = 1024*1024;
1027 } else if (!strcasecmp(u,"g")) {
1028 mul = 1000L*1000*1000;
1029 } else if (!strcasecmp(u,"gb")) {
1030 mul = 1024L*1024*1024;
1031 } else {
1032 if (err) *err = 1;
1033 mul = 1;
1034 }
1035 digits = u-p;
1036 if (digits >= sizeof(buf)) {
1037 if (err) *err = 1;
1038 return LLONG_MAX;
1039 }
1040 memcpy(buf,p,digits);
1041 buf[digits] = '\0';
1042 val = strtoll(buf,NULL,10);
1043 return val*mul;
1044 }
1045
1046 /* Convert a long long into a string. Returns the number of
1047 * characters needed to represent the number, that can be shorter if passed
1048 * buffer length is not enough to store the whole number. */
1049 static int ll2string(char *s, size_t len, long long value) {
1050 char buf[32], *p;
1051 unsigned long long v;
1052 size_t l;
1053
1054 if (len == 0) return 0;
1055 v = (value < 0) ? -value : value;
1056 p = buf+31; /* point to the last character */
1057 do {
1058 *p-- = '0'+(v%10);
1059 v /= 10;
1060 } while(v);
1061 if (value < 0) *p-- = '-';
1062 p++;
1063 l = 32-(p-buf);
1064 if (l+1 > len) l = len-1; /* Make sure it fits, including the nul term */
1065 memcpy(s,p,l);
1066 s[l] = '\0';
1067 return l;
1068 }
1069
1070 static void redisLog(int level, const char *fmt, ...) {
1071 va_list ap;
1072 FILE *fp;
1073
1074 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
1075 if (!fp) return;
1076
1077 va_start(ap, fmt);
1078 if (level >= server.verbosity) {
1079 char *c = ".-*#";
1080 char buf[64];
1081 time_t now;
1082
1083 now = time(NULL);
1084 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
1085 fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
1086 vfprintf(fp, fmt, ap);
1087 fprintf(fp,"\n");
1088 fflush(fp);
1089 }
1090 va_end(ap);
1091
1092 if (server.logfile) fclose(fp);
1093 }
1094
1095 /*====================== Hash table type implementation ==================== */
1096
1097 /* This is an hash table type that uses the SDS dynamic strings libary as
1098 * keys and radis objects as values (objects can hold SDS strings,
1099 * lists, sets). */
1100
1101 static void dictVanillaFree(void *privdata, void *val)
1102 {
1103 DICT_NOTUSED(privdata);
1104 zfree(val);
1105 }
1106
1107 static void dictListDestructor(void *privdata, void *val)
1108 {
1109 DICT_NOTUSED(privdata);
1110 listRelease((list*)val);
1111 }
1112
1113 static int sdsDictKeyCompare(void *privdata, const void *key1,
1114 const void *key2)
1115 {
1116 int l1,l2;
1117 DICT_NOTUSED(privdata);
1118
1119 l1 = sdslen((sds)key1);
1120 l2 = sdslen((sds)key2);
1121 if (l1 != l2) return 0;
1122 return memcmp(key1, key2, l1) == 0;
1123 }
1124
1125 static void dictRedisObjectDestructor(void *privdata, void *val)
1126 {
1127 DICT_NOTUSED(privdata);
1128
1129 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
1130 decrRefCount(val);
1131 }
1132
1133 static int dictObjKeyCompare(void *privdata, const void *key1,
1134 const void *key2)
1135 {
1136 const robj *o1 = key1, *o2 = key2;
1137 return sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1138 }
1139
1140 static unsigned int dictObjHash(const void *key) {
1141 const robj *o = key;
1142 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1143 }
1144
1145 static int dictEncObjKeyCompare(void *privdata, const void *key1,
1146 const void *key2)
1147 {
1148 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
1149 int cmp;
1150
1151 if (o1->encoding == REDIS_ENCODING_INT &&
1152 o2->encoding == REDIS_ENCODING_INT)
1153 return o1->ptr == o2->ptr;
1154
1155 o1 = getDecodedObject(o1);
1156 o2 = getDecodedObject(o2);
1157 cmp = sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1158 decrRefCount(o1);
1159 decrRefCount(o2);
1160 return cmp;
1161 }
1162
1163 static unsigned int dictEncObjHash(const void *key) {
1164 robj *o = (robj*) key;
1165
1166 if (o->encoding == REDIS_ENCODING_RAW) {
1167 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1168 } else {
1169 if (o->encoding == REDIS_ENCODING_INT) {
1170 char buf[32];
1171 int len;
1172
1173 len = ll2string(buf,32,(long)o->ptr);
1174 return dictGenHashFunction((unsigned char*)buf, len);
1175 } else {
1176 unsigned int hash;
1177
1178 o = getDecodedObject(o);
1179 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1180 decrRefCount(o);
1181 return hash;
1182 }
1183 }
1184 }
1185
1186 /* Sets type and expires */
1187 static dictType setDictType = {
1188 dictEncObjHash, /* hash function */
1189 NULL, /* key dup */
1190 NULL, /* val dup */
1191 dictEncObjKeyCompare, /* key compare */
1192 dictRedisObjectDestructor, /* key destructor */
1193 NULL /* val destructor */
1194 };
1195
1196 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1197 static dictType zsetDictType = {
1198 dictEncObjHash, /* hash function */
1199 NULL, /* key dup */
1200 NULL, /* val dup */
1201 dictEncObjKeyCompare, /* key compare */
1202 dictRedisObjectDestructor, /* key destructor */
1203 dictVanillaFree /* val destructor of malloc(sizeof(double)) */
1204 };
1205
1206 /* Db->dict */
1207 static dictType dbDictType = {
1208 dictObjHash, /* hash function */
1209 NULL, /* key dup */
1210 NULL, /* val dup */
1211 dictObjKeyCompare, /* key compare */
1212 dictRedisObjectDestructor, /* key destructor */
1213 dictRedisObjectDestructor /* val destructor */
1214 };
1215
1216 /* Db->expires */
1217 static dictType keyptrDictType = {
1218 dictObjHash, /* hash function */
1219 NULL, /* key dup */
1220 NULL, /* val dup */
1221 dictObjKeyCompare, /* key compare */
1222 dictRedisObjectDestructor, /* key destructor */
1223 NULL /* val destructor */
1224 };
1225
1226 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1227 static dictType hashDictType = {
1228 dictEncObjHash, /* hash function */
1229 NULL, /* key dup */
1230 NULL, /* val dup */
1231 dictEncObjKeyCompare, /* key compare */
1232 dictRedisObjectDestructor, /* key destructor */
1233 dictRedisObjectDestructor /* val destructor */
1234 };
1235
1236 /* Keylist hash table type has unencoded redis objects as keys and
1237 * lists as values. It's used for blocking operations (BLPOP) and to
1238 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1239 static dictType keylistDictType = {
1240 dictObjHash, /* hash function */
1241 NULL, /* key dup */
1242 NULL, /* val dup */
1243 dictObjKeyCompare, /* key compare */
1244 dictRedisObjectDestructor, /* key destructor */
1245 dictListDestructor /* val destructor */
1246 };
1247
1248 static void version();
1249
1250 /* ========================= Random utility functions ======================= */
1251
1252 /* Redis generally does not try to recover from out of memory conditions
1253 * when allocating objects or strings, it is not clear if it will be possible
1254 * to report this condition to the client since the networking layer itself
1255 * is based on heap allocation for send buffers, so we simply abort.
1256 * At least the code will be simpler to read... */
1257 static void oom(const char *msg) {
1258 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
1259 sleep(1);
1260 abort();
1261 }
1262
1263 /* ====================== Redis server networking stuff ===================== */
1264 static void closeTimedoutClients(void) {
1265 redisClient *c;
1266 listNode *ln;
1267 time_t now = time(NULL);
1268 listIter li;
1269
1270 listRewind(server.clients,&li);
1271 while ((ln = listNext(&li)) != NULL) {
1272 c = listNodeValue(ln);
1273 if (server.maxidletime &&
1274 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
1275 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
1276 dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
1277 listLength(c->pubsub_patterns) == 0 &&
1278 (now - c->lastinteraction > server.maxidletime))
1279 {
1280 redisLog(REDIS_VERBOSE,"Closing idle client");
1281 freeClient(c);
1282 } else if (c->flags & REDIS_BLOCKED) {
1283 if (c->blockingto != 0 && c->blockingto < now) {
1284 addReply(c,shared.nullmultibulk);
1285 unblockClientWaitingData(c);
1286 }
1287 }
1288 }
1289 }
1290
1291 static int htNeedsResize(dict *dict) {
1292 long long size, used;
1293
1294 size = dictSlots(dict);
1295 used = dictSize(dict);
1296 return (size && used && size > DICT_HT_INITIAL_SIZE &&
1297 (used*100/size < REDIS_HT_MINFILL));
1298 }
1299
1300 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1301 * we resize the hash table to save memory */
1302 static void tryResizeHashTables(void) {
1303 int j;
1304
1305 for (j = 0; j < server.dbnum; j++) {
1306 if (htNeedsResize(server.db[j].dict))
1307 dictResize(server.db[j].dict);
1308 if (htNeedsResize(server.db[j].expires))
1309 dictResize(server.db[j].expires);
1310 }
1311 }
1312
1313 /* Our hash table implementation performs rehashing incrementally while
1314 * we write/read from the hash table. Still if the server is idle, the hash
1315 * table will use two tables for a long time. So we try to use 1 millisecond
1316 * of CPU time at every serverCron() loop in order to rehash some key. */
1317 static void incrementallyRehash(void) {
1318 int j;
1319
1320 for (j = 0; j < server.dbnum; j++) {
1321 if (dictIsRehashing(server.db[j].dict)) {
1322 dictRehashMilliseconds(server.db[j].dict,1);
1323 break; /* already used our millisecond for this loop... */
1324 }
1325 }
1326 }
1327
1328 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1329 void backgroundSaveDoneHandler(int statloc) {
1330 int exitcode = WEXITSTATUS(statloc);
1331 int bysignal = WIFSIGNALED(statloc);
1332
1333 if (!bysignal && exitcode == 0) {
1334 redisLog(REDIS_NOTICE,
1335 "Background saving terminated with success");
1336 server.dirty = 0;
1337 server.lastsave = time(NULL);
1338 } else if (!bysignal && exitcode != 0) {
1339 redisLog(REDIS_WARNING, "Background saving error");
1340 } else {
1341 redisLog(REDIS_WARNING,
1342 "Background saving terminated by signal %d", WTERMSIG(statloc));
1343 rdbRemoveTempFile(server.bgsavechildpid);
1344 }
1345 server.bgsavechildpid = -1;
1346 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1347 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1348 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1349 }
1350
1351 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1352 * Handle this. */
1353 void backgroundRewriteDoneHandler(int statloc) {
1354 int exitcode = WEXITSTATUS(statloc);
1355 int bysignal = WIFSIGNALED(statloc);
1356
1357 if (!bysignal && exitcode == 0) {
1358 int fd;
1359 char tmpfile[256];
1360
1361 redisLog(REDIS_NOTICE,
1362 "Background append only file rewriting terminated with success");
1363 /* Now it's time to flush the differences accumulated by the parent */
1364 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
1365 fd = open(tmpfile,O_WRONLY|O_APPEND);
1366 if (fd == -1) {
1367 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
1368 goto cleanup;
1369 }
1370 /* Flush our data... */
1371 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
1372 (signed) sdslen(server.bgrewritebuf)) {
1373 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));
1374 close(fd);
1375 goto cleanup;
1376 }
1377 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
1378 /* Now our work is to rename the temp file into the stable file. And
1379 * switch the file descriptor used by the server for append only. */
1380 if (rename(tmpfile,server.appendfilename) == -1) {
1381 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
1382 close(fd);
1383 goto cleanup;
1384 }
1385 /* Mission completed... almost */
1386 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
1387 if (server.appendfd != -1) {
1388 /* If append only is actually enabled... */
1389 close(server.appendfd);
1390 server.appendfd = fd;
1391 fsync(fd);
1392 server.appendseldb = -1; /* Make sure it will issue SELECT */
1393 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
1394 } else {
1395 /* If append only is disabled we just generate a dump in this
1396 * format. Why not? */
1397 close(fd);
1398 }
1399 } else if (!bysignal && exitcode != 0) {
1400 redisLog(REDIS_WARNING, "Background append only file rewriting error");
1401 } else {
1402 redisLog(REDIS_WARNING,
1403 "Background append only file rewriting terminated by signal %d",
1404 WTERMSIG(statloc));
1405 }
1406 cleanup:
1407 sdsfree(server.bgrewritebuf);
1408 server.bgrewritebuf = sdsempty();
1409 aofRemoveTempFile(server.bgrewritechildpid);
1410 server.bgrewritechildpid = -1;
1411 }
1412
1413 /* This function is called once a background process of some kind terminates,
1414 * as we want to avoid resizing the hash tables when there is a child in order
1415 * to play well with copy-on-write (otherwise when a resize happens lots of
1416 * memory pages are copied). The goal of this function is to update the ability
1417 * for dict.c to resize the hash tables accordingly to the fact we have o not
1418 * running childs. */
1419 static void updateDictResizePolicy(void) {
1420 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
1421 dictEnableResize();
1422 else
1423 dictDisableResize();
1424 }
1425
1426 static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
1427 int j, loops = server.cronloops++;
1428 REDIS_NOTUSED(eventLoop);
1429 REDIS_NOTUSED(id);
1430 REDIS_NOTUSED(clientData);
1431
1432 /* We take a cached value of the unix time in the global state because
1433 * with virtual memory and aging there is to store the current time
1434 * in objects at every object access, and accuracy is not needed.
1435 * To access a global var is faster than calling time(NULL) */
1436 server.unixtime = time(NULL);
1437
1438 /* We received a SIGTERM, shutting down here in a safe way, as it is
1439 * not ok doing so inside the signal handler. */
1440 if (server.shutdown_asap) {
1441 if (prepareForShutdown() == REDIS_OK) exit(0);
1442 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
1443 }
1444
1445 /* Show some info about non-empty databases */
1446 for (j = 0; j < server.dbnum; j++) {
1447 long long size, used, vkeys;
1448
1449 size = dictSlots(server.db[j].dict);
1450 used = dictSize(server.db[j].dict);
1451 vkeys = dictSize(server.db[j].expires);
1452 if (!(loops % 50) && (used || vkeys)) {
1453 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
1454 /* dictPrintStats(server.dict); */
1455 }
1456 }
1457
1458 /* We don't want to resize the hash tables while a bacground saving
1459 * is in progress: the saving child is created using fork() that is
1460 * implemented with a copy-on-write semantic in most modern systems, so
1461 * if we resize the HT while there is the saving child at work actually
1462 * a lot of memory movements in the parent will cause a lot of pages
1463 * copied. */
1464 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
1465 if (!(loops % 10)) tryResizeHashTables();
1466 if (server.activerehashing) incrementallyRehash();
1467 }
1468
1469 /* Show information about connected clients */
1470 if (!(loops % 50)) {
1471 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
1472 listLength(server.clients)-listLength(server.slaves),
1473 listLength(server.slaves),
1474 zmalloc_used_memory());
1475 }
1476
1477 /* Close connections of timedout clients */
1478 if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients)
1479 closeTimedoutClients();
1480
1481 /* Check if a background saving or AOF rewrite in progress terminated */
1482 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
1483 int statloc;
1484 pid_t pid;
1485
1486 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
1487 if (pid == server.bgsavechildpid) {
1488 backgroundSaveDoneHandler(statloc);
1489 } else {
1490 backgroundRewriteDoneHandler(statloc);
1491 }
1492 updateDictResizePolicy();
1493 }
1494 } else {
1495 /* If there is not a background saving in progress check if
1496 * we have to save now */
1497 time_t now = time(NULL);
1498 for (j = 0; j < server.saveparamslen; j++) {
1499 struct saveparam *sp = server.saveparams+j;
1500
1501 if (server.dirty >= sp->changes &&
1502 now-server.lastsave > sp->seconds) {
1503 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
1504 sp->changes, sp->seconds);
1505 rdbSaveBackground(server.dbfilename);
1506 break;
1507 }
1508 }
1509 }
1510
1511 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1512 * will use few CPU cycles if there are few expiring keys, otherwise
1513 * it will get more aggressive to avoid that too much memory is used by
1514 * keys that can be removed from the keyspace. */
1515 for (j = 0; j < server.dbnum; j++) {
1516 int expired;
1517 redisDb *db = server.db+j;
1518
1519 /* Continue to expire if at the end of the cycle more than 25%
1520 * of the keys were expired. */
1521 do {
1522 long num = dictSize(db->expires);
1523 time_t now = time(NULL);
1524
1525 expired = 0;
1526 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
1527 num = REDIS_EXPIRELOOKUPS_PER_CRON;
1528 while (num--) {
1529 dictEntry *de;
1530 time_t t;
1531
1532 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
1533 t = (time_t) dictGetEntryVal(de);
1534 if (now > t) {
1535 deleteKey(db,dictGetEntryKey(de));
1536 expired++;
1537 server.stat_expiredkeys++;
1538 }
1539 }
1540 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
1541 }
1542
1543 /* Swap a few keys on disk if we are over the memory limit and VM
1544 * is enbled. Try to free objects from the free list first. */
1545 if (vmCanSwapOut()) {
1546 while (server.vm_enabled && zmalloc_used_memory() >
1547 server.vm_max_memory)
1548 {
1549 int retval;
1550
1551 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
1552 retval = (server.vm_max_threads == 0) ?
1553 vmSwapOneObjectBlocking() :
1554 vmSwapOneObjectThreaded();
1555 if (retval == REDIS_ERR && !(loops % 300) &&
1556 zmalloc_used_memory() >
1557 (server.vm_max_memory+server.vm_max_memory/10))
1558 {
1559 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1560 }
1561 /* Note that when using threade I/O we free just one object,
1562 * because anyway when the I/O thread in charge to swap this
1563 * object out will finish, the handler of completed jobs
1564 * will try to swap more objects if we are still out of memory. */
1565 if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
1566 }
1567 }
1568
1569 /* Check if we should connect to a MASTER */
1570 if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) {
1571 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
1572 if (syncWithMaster() == REDIS_OK) {
1573 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
1574 if (server.appendonly) rewriteAppendOnlyFileBackground();
1575 }
1576 }
1577 return 100;
1578 }
1579
1580 /* This function gets called every time Redis is entering the
1581 * main loop of the event driven library, that is, before to sleep
1582 * for ready file descriptors. */
1583 static void beforeSleep(struct aeEventLoop *eventLoop) {
1584 REDIS_NOTUSED(eventLoop);
1585
1586 /* Awake clients that got all the swapped keys they requested */
1587 if (server.vm_enabled && listLength(server.io_ready_clients)) {
1588 listIter li;
1589 listNode *ln;
1590
1591 listRewind(server.io_ready_clients,&li);
1592 while((ln = listNext(&li))) {
1593 redisClient *c = ln->value;
1594 struct redisCommand *cmd;
1595
1596 /* Resume the client. */
1597 listDelNode(server.io_ready_clients,ln);
1598 c->flags &= (~REDIS_IO_WAIT);
1599 server.vm_blocked_clients--;
1600 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1601 readQueryFromClient, c);
1602 cmd = lookupCommand(c->argv[0]->ptr);
1603 assert(cmd != NULL);
1604 call(c,cmd);
1605 resetClient(c);
1606 /* There may be more data to process in the input buffer. */
1607 if (c->querybuf && sdslen(c->querybuf) > 0)
1608 processInputBuffer(c);
1609 }
1610 }
1611 /* Write the AOF buffer on disk */
1612 flushAppendOnlyFile();
1613 }
1614
1615 static void createSharedObjects(void) {
1616 int j;
1617
1618 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
1619 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
1620 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
1621 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
1622 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
1623 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
1624 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
1625 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
1626 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
1627 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
1628 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
1629 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
1630 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1631 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
1632 "-ERR no such key\r\n"));
1633 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
1634 "-ERR syntax error\r\n"));
1635 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
1636 "-ERR source and destination objects are the same\r\n"));
1637 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
1638 "-ERR index out of range\r\n"));
1639 shared.space = createObject(REDIS_STRING,sdsnew(" "));
1640 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
1641 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
1642 shared.select0 = createStringObject("select 0\r\n",10);
1643 shared.select1 = createStringObject("select 1\r\n",10);
1644 shared.select2 = createStringObject("select 2\r\n",10);
1645 shared.select3 = createStringObject("select 3\r\n",10);
1646 shared.select4 = createStringObject("select 4\r\n",10);
1647 shared.select5 = createStringObject("select 5\r\n",10);
1648 shared.select6 = createStringObject("select 6\r\n",10);
1649 shared.select7 = createStringObject("select 7\r\n",10);
1650 shared.select8 = createStringObject("select 8\r\n",10);
1651 shared.select9 = createStringObject("select 9\r\n",10);
1652 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
1653 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
1654 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
1655 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
1656 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
1657 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
1658 shared.mbulk3 = createStringObject("*3\r\n",4);
1659 shared.mbulk4 = createStringObject("*4\r\n",4);
1660 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
1661 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
1662 shared.integers[j]->encoding = REDIS_ENCODING_INT;
1663 }
1664 }
1665
1666 static void appendServerSaveParams(time_t seconds, int changes) {
1667 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
1668 server.saveparams[server.saveparamslen].seconds = seconds;
1669 server.saveparams[server.saveparamslen].changes = changes;
1670 server.saveparamslen++;
1671 }
1672
1673 static void resetServerSaveParams() {
1674 zfree(server.saveparams);
1675 server.saveparams = NULL;
1676 server.saveparamslen = 0;
1677 }
1678
1679 static void initServerConfig() {
1680 server.dbnum = REDIS_DEFAULT_DBNUM;
1681 server.port = REDIS_SERVERPORT;
1682 server.verbosity = REDIS_VERBOSE;
1683 server.maxidletime = REDIS_MAXIDLETIME;
1684 server.saveparams = NULL;
1685 server.logfile = NULL; /* NULL = log on standard output */
1686 server.bindaddr = NULL;
1687 server.glueoutputbuf = 1;
1688 server.daemonize = 0;
1689 server.appendonly = 0;
1690 server.appendfsync = APPENDFSYNC_EVERYSEC;
1691 server.lastfsync = time(NULL);
1692 server.appendfd = -1;
1693 server.appendseldb = -1; /* Make sure the first time will not match */
1694 server.pidfile = zstrdup("/var/run/redis.pid");
1695 server.dbfilename = zstrdup("dump.rdb");
1696 server.appendfilename = zstrdup("appendonly.aof");
1697 server.requirepass = NULL;
1698 server.rdbcompression = 1;
1699 server.activerehashing = 1;
1700 server.maxclients = 0;
1701 server.blpop_blocked_clients = 0;
1702 server.maxmemory = 0;
1703 server.vm_enabled = 0;
1704 server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
1705 server.vm_page_size = 256; /* 256 bytes per page */
1706 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
1707 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
1708 server.vm_max_threads = 4;
1709 server.vm_blocked_clients = 0;
1710 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
1711 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
1712 server.shutdown_asap = 0;
1713
1714 resetServerSaveParams();
1715
1716 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1717 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1718 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1719 /* Replication related */
1720 server.isslave = 0;
1721 server.masterauth = NULL;
1722 server.masterhost = NULL;
1723 server.masterport = 6379;
1724 server.master = NULL;
1725 server.replstate = REDIS_REPL_NONE;
1726
1727 /* Double constants initialization */
1728 R_Zero = 0.0;
1729 R_PosInf = 1.0/R_Zero;
1730 R_NegInf = -1.0/R_Zero;
1731 R_Nan = R_Zero/R_Zero;
1732 }
1733
1734 static void initServer() {
1735 int j;
1736
1737 signal(SIGHUP, SIG_IGN);
1738 signal(SIGPIPE, SIG_IGN);
1739 setupSigSegvAction();
1740
1741 server.devnull = fopen("/dev/null","w");
1742 if (server.devnull == NULL) {
1743 redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr);
1744 exit(1);
1745 }
1746 server.clients = listCreate();
1747 server.slaves = listCreate();
1748 server.monitors = listCreate();
1749 server.objfreelist = listCreate();
1750 createSharedObjects();
1751 server.el = aeCreateEventLoop();
1752 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
1753 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
1754 if (server.fd == -1) {
1755 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
1756 exit(1);
1757 }
1758 for (j = 0; j < server.dbnum; j++) {
1759 server.db[j].dict = dictCreate(&dbDictType,NULL);
1760 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
1761 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
1762 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
1763 if (server.vm_enabled)
1764 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
1765 server.db[j].id = j;
1766 }
1767 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1768 server.pubsub_patterns = listCreate();
1769 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1770 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
1771 server.cronloops = 0;
1772 server.bgsavechildpid = -1;
1773 server.bgrewritechildpid = -1;
1774 server.bgrewritebuf = sdsempty();
1775 server.aofbuf = sdsempty();
1776 server.lastsave = time(NULL);
1777 server.dirty = 0;
1778 server.stat_numcommands = 0;
1779 server.stat_numconnections = 0;
1780 server.stat_expiredkeys = 0;
1781 server.stat_starttime = time(NULL);
1782 server.unixtime = time(NULL);
1783 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
1784 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
1785 acceptHandler, NULL) == AE_ERR) oom("creating file event");
1786
1787 if (server.appendonly) {
1788 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
1789 if (server.appendfd == -1) {
1790 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1791 strerror(errno));
1792 exit(1);
1793 }
1794 }
1795
1796 if (server.vm_enabled) vmInit();
1797 }
1798
1799 /* Empty the whole database */
1800 static long long emptyDb() {
1801 int j;
1802 long long removed = 0;
1803
1804 for (j = 0; j < server.dbnum; j++) {
1805 removed += dictSize(server.db[j].dict);
1806 dictEmpty(server.db[j].dict);
1807 dictEmpty(server.db[j].expires);
1808 }
1809 return removed;
1810 }
1811
1812 static int yesnotoi(char *s) {
1813 if (!strcasecmp(s,"yes")) return 1;
1814 else if (!strcasecmp(s,"no")) return 0;
1815 else return -1;
1816 }
1817
1818 /* I agree, this is a very rudimental way to load a configuration...
1819 will improve later if the config gets more complex */
1820 static void loadServerConfig(char *filename) {
1821 FILE *fp;
1822 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
1823 int linenum = 0;
1824 sds line = NULL;
1825
1826 if (filename[0] == '-' && filename[1] == '\0')
1827 fp = stdin;
1828 else {
1829 if ((fp = fopen(filename,"r")) == NULL) {
1830 redisLog(REDIS_WARNING, "Fatal error, can't open config file '%s'", filename);
1831 exit(1);
1832 }
1833 }
1834
1835 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1836 sds *argv;
1837 int argc, j;
1838
1839 linenum++;
1840 line = sdsnew(buf);
1841 line = sdstrim(line," \t\r\n");
1842
1843 /* Skip comments and blank lines*/
1844 if (line[0] == '#' || line[0] == '\0') {
1845 sdsfree(line);
1846 continue;
1847 }
1848
1849 /* Split into arguments */
1850 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
1851 sdstolower(argv[0]);
1852
1853 /* Execute config directives */
1854 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
1855 server.maxidletime = atoi(argv[1]);
1856 if (server.maxidletime < 0) {
1857 err = "Invalid timeout value"; goto loaderr;
1858 }
1859 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
1860 server.port = atoi(argv[1]);
1861 if (server.port < 1 || server.port > 65535) {
1862 err = "Invalid port"; goto loaderr;
1863 }
1864 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
1865 server.bindaddr = zstrdup(argv[1]);
1866 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
1867 int seconds = atoi(argv[1]);
1868 int changes = atoi(argv[2]);
1869 if (seconds < 1 || changes < 0) {
1870 err = "Invalid save parameters"; goto loaderr;
1871 }
1872 appendServerSaveParams(seconds,changes);
1873 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
1874 if (chdir(argv[1]) == -1) {
1875 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
1876 argv[1], strerror(errno));
1877 exit(1);
1878 }
1879 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
1880 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
1881 else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
1882 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
1883 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
1884 else {
1885 err = "Invalid log level. Must be one of debug, notice, warning";
1886 goto loaderr;
1887 }
1888 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
1889 FILE *logfp;
1890
1891 server.logfile = zstrdup(argv[1]);
1892 if (!strcasecmp(server.logfile,"stdout")) {
1893 zfree(server.logfile);
1894 server.logfile = NULL;
1895 }
1896 if (server.logfile) {
1897 /* Test if we are able to open the file. The server will not
1898 * be able to abort just for this problem later... */
1899 logfp = fopen(server.logfile,"a");
1900 if (logfp == NULL) {
1901 err = sdscatprintf(sdsempty(),
1902 "Can't open the log file: %s", strerror(errno));
1903 goto loaderr;
1904 }
1905 fclose(logfp);
1906 }
1907 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
1908 server.dbnum = atoi(argv[1]);
1909 if (server.dbnum < 1) {
1910 err = "Invalid number of databases"; goto loaderr;
1911 }
1912 } else if (!strcasecmp(argv[0],"include") && argc == 2) {
1913 loadServerConfig(argv[1]);
1914 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
1915 server.maxclients = atoi(argv[1]);
1916 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
1917 server.maxmemory = memtoll(argv[1],NULL);
1918 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
1919 server.masterhost = sdsnew(argv[1]);
1920 server.masterport = atoi(argv[2]);
1921 server.replstate = REDIS_REPL_CONNECT;
1922 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
1923 server.masterauth = zstrdup(argv[1]);
1924 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
1925 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
1926 err = "argument must be 'yes' or 'no'"; goto loaderr;
1927 }
1928 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
1929 if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
1930 err = "argument must be 'yes' or 'no'"; goto loaderr;
1931 }
1932 } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
1933 if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
1934 err = "argument must be 'yes' or 'no'"; goto loaderr;
1935 }
1936 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
1937 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
1938 err = "argument must be 'yes' or 'no'"; goto loaderr;
1939 }
1940 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
1941 if ((server.appendonly = yesnotoi(argv[1])) == -1) {
1942 err = "argument must be 'yes' or 'no'"; goto loaderr;
1943 }
1944 } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
1945 zfree(server.appendfilename);
1946 server.appendfilename = zstrdup(argv[1]);
1947 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
1948 if (!strcasecmp(argv[1],"no")) {
1949 server.appendfsync = APPENDFSYNC_NO;
1950 } else if (!strcasecmp(argv[1],"always")) {
1951 server.appendfsync = APPENDFSYNC_ALWAYS;
1952 } else if (!strcasecmp(argv[1],"everysec")) {
1953 server.appendfsync = APPENDFSYNC_EVERYSEC;
1954 } else {
1955 err = "argument must be 'no', 'always' or 'everysec'";
1956 goto loaderr;
1957 }
1958 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
1959 server.requirepass = zstrdup(argv[1]);
1960 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
1961 zfree(server.pidfile);
1962 server.pidfile = zstrdup(argv[1]);
1963 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
1964 zfree(server.dbfilename);
1965 server.dbfilename = zstrdup(argv[1]);
1966 } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
1967 if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
1968 err = "argument must be 'yes' or 'no'"; goto loaderr;
1969 }
1970 } else if (!strcasecmp(argv[0],"vm-swap-file") && argc == 2) {
1971 zfree(server.vm_swap_file);
1972 server.vm_swap_file = zstrdup(argv[1]);
1973 } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
1974 server.vm_max_memory = memtoll(argv[1],NULL);
1975 } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
1976 server.vm_page_size = memtoll(argv[1], NULL);
1977 } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
1978 server.vm_pages = memtoll(argv[1], NULL);
1979 } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
1980 server.vm_max_threads = strtoll(argv[1], NULL, 10);
1981 } else if (!strcasecmp(argv[0],"hash-max-zipmap-entries") && argc == 2){
1982 server.hash_max_zipmap_entries = memtoll(argv[1], NULL);
1983 } else if (!strcasecmp(argv[0],"hash-max-zipmap-value") && argc == 2){
1984 server.hash_max_zipmap_value = memtoll(argv[1], NULL);
1985 } else {
1986 err = "Bad directive or wrong number of arguments"; goto loaderr;
1987 }
1988 for (j = 0; j < argc; j++)
1989 sdsfree(argv[j]);
1990 zfree(argv);
1991 sdsfree(line);
1992 }
1993 if (fp != stdin) fclose(fp);
1994 return;
1995
1996 loaderr:
1997 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
1998 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
1999 fprintf(stderr, ">>> '%s'\n", line);
2000 fprintf(stderr, "%s\n", err);
2001 exit(1);
2002 }
2003
2004 static void freeClientArgv(redisClient *c) {
2005 int j;
2006
2007 for (j = 0; j < c->argc; j++)
2008 decrRefCount(c->argv[j]);
2009 for (j = 0; j < c->mbargc; j++)
2010 decrRefCount(c->mbargv[j]);
2011 c->argc = 0;
2012 c->mbargc = 0;
2013 }
2014
2015 static void freeClient(redisClient *c) {
2016 listNode *ln;
2017
2018 /* Note that if the client we are freeing is blocked into a blocking
2019 * call, we have to set querybuf to NULL *before* to call
2020 * unblockClientWaitingData() to avoid processInputBuffer() will get
2021 * called. Also it is important to remove the file events after
2022 * this, because this call adds the READABLE event. */
2023 sdsfree(c->querybuf);
2024 c->querybuf = NULL;
2025 if (c->flags & REDIS_BLOCKED)
2026 unblockClientWaitingData(c);
2027
2028 /* UNWATCH all the keys */
2029 unwatchAllKeys(c);
2030 listRelease(c->watched_keys);
2031 /* Unsubscribe from all the pubsub channels */
2032 pubsubUnsubscribeAllChannels(c,0);
2033 pubsubUnsubscribeAllPatterns(c,0);
2034 dictRelease(c->pubsub_channels);
2035 listRelease(c->pubsub_patterns);
2036 /* Obvious cleanup */
2037 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
2038 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2039 listRelease(c->reply);
2040 freeClientArgv(c);
2041 close(c->fd);
2042 /* Remove from the list of clients */
2043 ln = listSearchKey(server.clients,c);
2044 redisAssert(ln != NULL);
2045 listDelNode(server.clients,ln);
2046 /* Remove from the list of clients that are now ready to be restarted
2047 * after waiting for swapped keys */
2048 if (c->flags & REDIS_IO_WAIT && listLength(c->io_keys) == 0) {
2049 ln = listSearchKey(server.io_ready_clients,c);
2050 if (ln) {
2051 listDelNode(server.io_ready_clients,ln);
2052 server.vm_blocked_clients--;
2053 }
2054 }
2055 /* Remove from the list of clients waiting for swapped keys */
2056 while (server.vm_enabled && listLength(c->io_keys)) {
2057 ln = listFirst(c->io_keys);
2058 dontWaitForSwappedKey(c,ln->value);
2059 }
2060 listRelease(c->io_keys);
2061 /* Master/slave cleanup */
2062 if (c->flags & REDIS_SLAVE) {
2063 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
2064 close(c->repldbfd);
2065 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
2066 ln = listSearchKey(l,c);
2067 redisAssert(ln != NULL);
2068 listDelNode(l,ln);
2069 }
2070 if (c->flags & REDIS_MASTER) {
2071 server.master = NULL;
2072 server.replstate = REDIS_REPL_CONNECT;
2073 }
2074 /* Release memory */
2075 zfree(c->argv);
2076 zfree(c->mbargv);
2077 freeClientMultiState(c);
2078 zfree(c);
2079 }
2080
2081 #define GLUEREPLY_UP_TO (1024)
2082 static void glueReplyBuffersIfNeeded(redisClient *c) {
2083 int copylen = 0;
2084 char buf[GLUEREPLY_UP_TO];
2085 listNode *ln;
2086 listIter li;
2087 robj *o;
2088
2089 listRewind(c->reply,&li);
2090 while((ln = listNext(&li))) {
2091 int objlen;
2092
2093 o = ln->value;
2094 objlen = sdslen(o->ptr);
2095 if (copylen + objlen <= GLUEREPLY_UP_TO) {
2096 memcpy(buf+copylen,o->ptr,objlen);
2097 copylen += objlen;
2098 listDelNode(c->reply,ln);
2099 } else {
2100 if (copylen == 0) return;
2101 break;
2102 }
2103 }
2104 /* Now the output buffer is empty, add the new single element */
2105 o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
2106 listAddNodeHead(c->reply,o);
2107 }
2108
2109 static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2110 redisClient *c = privdata;
2111 int nwritten = 0, totwritten = 0, objlen;
2112 robj *o;
2113 REDIS_NOTUSED(el);
2114 REDIS_NOTUSED(mask);
2115
2116 /* Use writev() if we have enough buffers to send */
2117 if (!server.glueoutputbuf &&
2118 listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
2119 !(c->flags & REDIS_MASTER))
2120 {
2121 sendReplyToClientWritev(el, fd, privdata, mask);
2122 return;
2123 }
2124
2125 while(listLength(c->reply)) {
2126 if (server.glueoutputbuf && listLength(c->reply) > 1)
2127 glueReplyBuffersIfNeeded(c);
2128
2129 o = listNodeValue(listFirst(c->reply));
2130 objlen = sdslen(o->ptr);
2131
2132 if (objlen == 0) {
2133 listDelNode(c->reply,listFirst(c->reply));
2134 continue;
2135 }
2136
2137 if (c->flags & REDIS_MASTER) {
2138 /* Don't reply to a master */
2139 nwritten = objlen - c->sentlen;
2140 } else {
2141 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
2142 if (nwritten <= 0) break;
2143 }
2144 c->sentlen += nwritten;
2145 totwritten += nwritten;
2146 /* If we fully sent the object on head go to the next one */
2147 if (c->sentlen == objlen) {
2148 listDelNode(c->reply,listFirst(c->reply));
2149 c->sentlen = 0;
2150 }
2151 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
2152 * bytes, in a single threaded server it's a good idea to serve
2153 * other clients as well, even if a very large request comes from
2154 * super fast link that is always able to accept data (in real world
2155 * scenario think about 'KEYS *' against the loopback interfae) */
2156 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
2157 }
2158 if (nwritten == -1) {
2159 if (errno == EAGAIN) {
2160 nwritten = 0;
2161 } else {
2162 redisLog(REDIS_VERBOSE,
2163 "Error writing to client: %s", strerror(errno));
2164 freeClient(c);
2165 return;
2166 }
2167 }
2168 if (totwritten > 0) c->lastinteraction = time(NULL);
2169 if (listLength(c->reply) == 0) {
2170 c->sentlen = 0;
2171 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2172 }
2173 }
2174
2175 static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
2176 {
2177 redisClient *c = privdata;
2178 int nwritten = 0, totwritten = 0, objlen, willwrite;
2179 robj *o;
2180 struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
2181 int offset, ion = 0;
2182 REDIS_NOTUSED(el);
2183 REDIS_NOTUSED(mask);
2184
2185 listNode *node;
2186 while (listLength(c->reply)) {
2187 offset = c->sentlen;
2188 ion = 0;
2189 willwrite = 0;
2190
2191 /* fill-in the iov[] array */
2192 for(node = listFirst(c->reply); node; node = listNextNode(node)) {
2193 o = listNodeValue(node);
2194 objlen = sdslen(o->ptr);
2195
2196 if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
2197 break;
2198
2199 if(ion == REDIS_WRITEV_IOVEC_COUNT)
2200 break; /* no more iovecs */
2201
2202 iov[ion].iov_base = ((char*)o->ptr) + offset;
2203 iov[ion].iov_len = objlen - offset;
2204 willwrite += objlen - offset;
2205 offset = 0; /* just for the first item */
2206 ion++;
2207 }
2208
2209 if(willwrite == 0)
2210 break;
2211
2212 /* write all collected blocks at once */
2213 if((nwritten = writev(fd, iov, ion)) < 0) {
2214 if (errno != EAGAIN) {
2215 redisLog(REDIS_VERBOSE,
2216 "Error writing to client: %s", strerror(errno));
2217 freeClient(c);
2218 return;
2219 }
2220 break;
2221 }
2222
2223 totwritten += nwritten;
2224 offset = c->sentlen;
2225
2226 /* remove written robjs from c->reply */
2227 while (nwritten && listLength(c->reply)) {
2228 o = listNodeValue(listFirst(c->reply));
2229 objlen = sdslen(o->ptr);
2230
2231 if(nwritten >= objlen - offset) {
2232 listDelNode(c->reply, listFirst(c->reply));
2233 nwritten -= objlen - offset;
2234 c->sentlen = 0;
2235 } else {
2236 /* partial write */
2237 c->sentlen += nwritten;
2238 break;
2239 }
2240 offset = 0;
2241 }
2242 }
2243
2244 if (totwritten > 0)
2245 c->lastinteraction = time(NULL);
2246
2247 if (listLength(c->reply) == 0) {
2248 c->sentlen = 0;
2249 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2250 }
2251 }
2252
2253 static int qsortRedisCommands(const void *r1, const void *r2) {
2254 return strcasecmp(
2255 ((struct redisCommand*)r1)->name,
2256 ((struct redisCommand*)r2)->name);
2257 }
2258
2259 static void sortCommandTable() {
2260 /* Copy and sort the read-only version of the command table */
2261 commandTable = (struct redisCommand*)malloc(sizeof(readonlyCommandTable));
2262 memcpy(commandTable,readonlyCommandTable,sizeof(readonlyCommandTable));
2263 qsort(commandTable,
2264 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
2265 sizeof(struct redisCommand),qsortRedisCommands);
2266 }
2267
2268 static struct redisCommand *lookupCommand(char *name) {
2269 struct redisCommand tmp = {name,NULL,0,0,NULL,0,0,0};
2270 return bsearch(
2271 &tmp,
2272 commandTable,
2273 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
2274 sizeof(struct redisCommand),
2275 qsortRedisCommands);
2276 }
2277
2278 /* resetClient prepare the client to process the next command */
2279 static void resetClient(redisClient *c) {
2280 freeClientArgv(c);
2281 c->bulklen = -1;
2282 c->multibulk = 0;
2283 }
2284
2285 /* Call() is the core of Redis execution of a command */
2286 static void call(redisClient *c, struct redisCommand *cmd) {
2287 long long dirty;
2288
2289 dirty = server.dirty;
2290 cmd->proc(c);
2291 dirty = server.dirty-dirty;
2292
2293 if (server.appendonly && dirty)
2294 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
2295 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
2296 listLength(server.slaves))
2297 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
2298 if (listLength(server.monitors))
2299 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
2300 server.stat_numcommands++;
2301 }
2302
2303 /* If this function gets called we already read a whole
2304 * command, argments are in the client argv/argc fields.
2305 * processCommand() execute the command or prepare the
2306 * server for a bulk read from the client.
2307 *
2308 * If 1 is returned the client is still alive and valid and
2309 * and other operations can be performed by the caller. Otherwise
2310 * if 0 is returned the client was destroied (i.e. after QUIT). */
2311 static int processCommand(redisClient *c) {
2312 struct redisCommand *cmd;
2313
2314 /* Free some memory if needed (maxmemory setting) */
2315 if (server.maxmemory) freeMemoryIfNeeded();
2316
2317 /* Handle the multi bulk command type. This is an alternative protocol
2318 * supported by Redis in order to receive commands that are composed of
2319 * multiple binary-safe "bulk" arguments. The latency of processing is
2320 * a bit higher but this allows things like multi-sets, so if this
2321 * protocol is used only for MSET and similar commands this is a big win. */
2322 if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
2323 c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
2324 if (c->multibulk <= 0) {
2325 resetClient(c);
2326 return 1;
2327 } else {
2328 decrRefCount(c->argv[c->argc-1]);
2329 c->argc--;
2330 return 1;
2331 }
2332 } else if (c->multibulk) {
2333 if (c->bulklen == -1) {
2334 if (((char*)c->argv[0]->ptr)[0] != '$') {
2335 addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
2336 resetClient(c);
2337 return 1;
2338 } else {
2339 int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
2340 decrRefCount(c->argv[0]);
2341 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2342 c->argc--;
2343 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2344 resetClient(c);
2345 return 1;
2346 }
2347 c->argc--;
2348 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2349 return 1;
2350 }
2351 } else {
2352 c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
2353 c->mbargv[c->mbargc] = c->argv[0];
2354 c->mbargc++;
2355 c->argc--;
2356 c->multibulk--;
2357 if (c->multibulk == 0) {
2358 robj **auxargv;
2359 int auxargc;
2360
2361 /* Here we need to swap the multi-bulk argc/argv with the
2362 * normal argc/argv of the client structure. */
2363 auxargv = c->argv;
2364 c->argv = c->mbargv;
2365 c->mbargv = auxargv;
2366
2367 auxargc = c->argc;
2368 c->argc = c->mbargc;
2369 c->mbargc = auxargc;
2370
2371 /* We need to set bulklen to something different than -1
2372 * in order for the code below to process the command without
2373 * to try to read the last argument of a bulk command as
2374 * a special argument. */
2375 c->bulklen = 0;
2376 /* continue below and process the command */
2377 } else {
2378 c->bulklen = -1;
2379 return 1;
2380 }
2381 }
2382 }
2383 /* -- end of multi bulk commands processing -- */
2384
2385 /* The QUIT command is handled as a special case. Normal command
2386 * procs are unable to close the client connection safely */
2387 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
2388 freeClient(c);
2389 return 0;
2390 }
2391
2392 /* Now lookup the command and check ASAP about trivial error conditions
2393 * such wrong arity, bad command name and so forth. */
2394 cmd = lookupCommand(c->argv[0]->ptr);
2395 if (!cmd) {
2396 addReplySds(c,
2397 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2398 (char*)c->argv[0]->ptr));
2399 resetClient(c);
2400 return 1;
2401 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
2402 (c->argc < -cmd->arity)) {
2403 addReplySds(c,
2404 sdscatprintf(sdsempty(),
2405 "-ERR wrong number of arguments for '%s' command\r\n",
2406 cmd->name));
2407 resetClient(c);
2408 return 1;
2409 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
2410 /* This is a bulk command, we have to read the last argument yet. */
2411 int bulklen = atoi(c->argv[c->argc-1]->ptr);
2412
2413 decrRefCount(c->argv[c->argc-1]);
2414 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2415 c->argc--;
2416 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2417 resetClient(c);
2418 return 1;
2419 }
2420 c->argc--;
2421 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2422 /* It is possible that the bulk read is already in the
2423 * buffer. Check this condition and handle it accordingly.
2424 * This is just a fast path, alternative to call processInputBuffer().
2425 * It's a good idea since the code is small and this condition
2426 * happens most of the times. */
2427 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
2428 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2429 c->argc++;
2430 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2431 } else {
2432 /* Otherwise return... there is to read the last argument
2433 * from the socket. */
2434 return 1;
2435 }
2436 }
2437 /* Let's try to encode the bulk object to save space. */
2438 if (cmd->flags & REDIS_CMD_BULK)
2439 c->argv[c->argc-1] = tryObjectEncoding(c->argv[c->argc-1]);
2440
2441 /* Check if the user is authenticated */
2442 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
2443 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
2444 resetClient(c);
2445 return 1;
2446 }
2447
2448 /* Handle the maxmemory directive */
2449 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
2450 zmalloc_used_memory() > server.maxmemory)
2451 {
2452 addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2453 resetClient(c);
2454 return 1;
2455 }
2456
2457 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
2458 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
2459 &&
2460 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
2461 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
2462 addReplySds(c,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
2463 resetClient(c);
2464 return 1;
2465 }
2466
2467 /* Exec the command */
2468 if (c->flags & REDIS_MULTI &&
2469 cmd->proc != execCommand && cmd->proc != discardCommand &&
2470 cmd->proc != multiCommand && cmd->proc != watchCommand)
2471 {
2472 queueMultiCommand(c,cmd);
2473 addReply(c,shared.queued);
2474 } else {
2475 if (server.vm_enabled && server.vm_max_threads > 0 &&
2476 blockClientOnSwappedKeys(c,cmd)) return 1;
2477 call(c,cmd);
2478 }
2479
2480 /* Prepare the client for the next command */
2481 resetClient(c);
2482 return 1;
2483 }
2484
2485 static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
2486 listNode *ln;
2487 listIter li;
2488 int outc = 0, j;
2489 robj **outv;
2490 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2491 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2492 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2493 robj *static_outv[REDIS_STATIC_ARGS*3+1];
2494 robj *lenobj;
2495
2496 if (argc <= REDIS_STATIC_ARGS) {
2497 outv = static_outv;
2498 } else {
2499 outv = zmalloc(sizeof(robj*)*(argc*3+1));
2500 }
2501
2502 lenobj = createObject(REDIS_STRING,
2503 sdscatprintf(sdsempty(), "*%d\r\n", argc));
2504 lenobj->refcount = 0;
2505 outv[outc++] = lenobj;
2506 for (j = 0; j < argc; j++) {
2507 lenobj = createObject(REDIS_STRING,
2508 sdscatprintf(sdsempty(),"$%lu\r\n",
2509 (unsigned long) stringObjectLen(argv[j])));
2510 lenobj->refcount = 0;
2511 outv[outc++] = lenobj;
2512 outv[outc++] = argv[j];
2513 outv[outc++] = shared.crlf;
2514 }
2515
2516 /* Increment all the refcounts at start and decrement at end in order to
2517 * be sure to free objects if there is no slave in a replication state
2518 * able to be feed with commands */
2519 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
2520 listRewind(slaves,&li);
2521 while((ln = listNext(&li))) {
2522 redisClient *slave = ln->value;
2523
2524 /* Don't feed slaves that are still waiting for BGSAVE to start */
2525 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
2526
2527 /* Feed all the other slaves, MONITORs and so on */
2528 if (slave->slaveseldb != dictid) {
2529 robj *selectcmd;
2530
2531 switch(dictid) {
2532 case 0: selectcmd = shared.select0; break;
2533 case 1: selectcmd = shared.select1; break;
2534 case 2: selectcmd = shared.select2; break;
2535 case 3: selectcmd = shared.select3; break;
2536 case 4: selectcmd = shared.select4; break;
2537 case 5: selectcmd = shared.select5; break;
2538 case 6: selectcmd = shared.select6; break;
2539 case 7: selectcmd = shared.select7; break;
2540 case 8: selectcmd = shared.select8; break;
2541 case 9: selectcmd = shared.select9; break;
2542 default:
2543 selectcmd = createObject(REDIS_STRING,
2544 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
2545 selectcmd->refcount = 0;
2546 break;
2547 }
2548 addReply(slave,selectcmd);
2549 slave->slaveseldb = dictid;
2550 }
2551 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
2552 }
2553 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
2554 if (outv != static_outv) zfree(outv);
2555 }
2556
2557 static sds sdscatrepr(sds s, char *p, size_t len) {
2558 s = sdscatlen(s,"\"",1);
2559 while(len--) {
2560 switch(*p) {
2561 case '\\':
2562 case '"':
2563 s = sdscatprintf(s,"\\%c",*p);
2564 break;
2565 case '\n': s = sdscatlen(s,"\\n",1); break;
2566 case '\r': s = sdscatlen(s,"\\r",1); break;
2567 case '\t': s = sdscatlen(s,"\\t",1); break;
2568 case '\a': s = sdscatlen(s,"\\a",1); break;
2569 case '\b': s = sdscatlen(s,"\\b",1); break;
2570 default:
2571 if (isprint(*p))
2572 s = sdscatprintf(s,"%c",*p);
2573 else
2574 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
2575 break;
2576 }
2577 p++;
2578 }
2579 return sdscatlen(s,"\"",1);
2580 }
2581
2582 static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc) {
2583 listNode *ln;
2584 listIter li;
2585 int j;
2586 sds cmdrepr = sdsnew("+");
2587 robj *cmdobj;
2588 struct timeval tv;
2589
2590 gettimeofday(&tv,NULL);
2591 cmdrepr = sdscatprintf(cmdrepr,"%ld.%ld ",(long)tv.tv_sec,(long)tv.tv_usec);
2592 if (dictid != 0) cmdrepr = sdscatprintf(cmdrepr,"(db %d) ", dictid);
2593
2594 for (j = 0; j < argc; j++) {
2595 if (argv[j]->encoding == REDIS_ENCODING_INT) {
2596 cmdrepr = sdscatprintf(cmdrepr, "%ld", (long)argv[j]->ptr);
2597 } else {
2598 cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
2599 sdslen(argv[j]->ptr));
2600 }
2601 if (j != argc-1)
2602 cmdrepr = sdscatlen(cmdrepr," ",1);
2603 }
2604 cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
2605 cmdobj = createObject(REDIS_STRING,cmdrepr);
2606
2607 listRewind(monitors,&li);
2608 while((ln = listNext(&li))) {
2609 redisClient *monitor = ln->value;
2610 addReply(monitor,cmdobj);
2611 }
2612 decrRefCount(cmdobj);
2613 }
2614
2615 static void processInputBuffer(redisClient *c) {
2616 again:
2617 /* Before to process the input buffer, make sure the client is not
2618 * waitig for a blocking operation such as BLPOP. Note that the first
2619 * iteration the client is never blocked, otherwise the processInputBuffer
2620 * would not be called at all, but after the execution of the first commands
2621 * in the input buffer the client may be blocked, and the "goto again"
2622 * will try to reiterate. The following line will make it return asap. */
2623 if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
2624 if (c->bulklen == -1) {
2625 /* Read the first line of the query */
2626 char *p = strchr(c->querybuf,'\n');
2627 size_t querylen;
2628
2629 if (p) {
2630 sds query, *argv;
2631 int argc, j;
2632
2633 query = c->querybuf;
2634 c->querybuf = sdsempty();
2635 querylen = 1+(p-(query));
2636 if (sdslen(query) > querylen) {
2637 /* leave data after the first line of the query in the buffer */
2638 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
2639 }
2640 *p = '\0'; /* remove "\n" */
2641 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
2642 sdsupdatelen(query);
2643
2644 /* Now we can split the query in arguments */
2645 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
2646 sdsfree(query);
2647
2648 if (c->argv) zfree(c->argv);
2649 c->argv = zmalloc(sizeof(robj*)*argc);
2650
2651 for (j = 0; j < argc; j++) {
2652 if (sdslen(argv[j])) {
2653 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
2654 c->argc++;
2655 } else {
2656 sdsfree(argv[j]);
2657 }
2658 }
2659 zfree(argv);
2660 if (c->argc) {
2661 /* Execute the command. If the client is still valid
2662 * after processCommand() return and there is something
2663 * on the query buffer try to process the next command. */
2664 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2665 } else {
2666 /* Nothing to process, argc == 0. Just process the query
2667 * buffer if it's not empty or return to the caller */
2668 if (sdslen(c->querybuf)) goto again;
2669 }
2670 return;
2671 } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
2672 redisLog(REDIS_VERBOSE, "Client protocol error");
2673 freeClient(c);
2674 return;
2675 }
2676 } else {
2677 /* Bulk read handling. Note that if we are at this point
2678 the client already sent a command terminated with a newline,
2679 we are reading the bulk data that is actually the last
2680 argument of the command. */
2681 int qbl = sdslen(c->querybuf);
2682
2683 if (c->bulklen <= qbl) {
2684 /* Copy everything but the final CRLF as final argument */
2685 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2686 c->argc++;
2687 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2688 /* Process the command. If the client is still valid after
2689 * the processing and there is more data in the buffer
2690 * try to parse it. */
2691 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2692 return;
2693 }
2694 }
2695 }
2696
2697 static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2698 redisClient *c = (redisClient*) privdata;
2699 char buf[REDIS_IOBUF_LEN];
2700 int nread;
2701 REDIS_NOTUSED(el);
2702 REDIS_NOTUSED(mask);
2703
2704 nread = read(fd, buf, REDIS_IOBUF_LEN);
2705 if (nread == -1) {
2706 if (errno == EAGAIN) {
2707 nread = 0;
2708 } else {
2709 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
2710 freeClient(c);
2711 return;
2712 }
2713 } else if (nread == 0) {
2714 redisLog(REDIS_VERBOSE, "Client closed connection");
2715 freeClient(c);
2716 return;
2717 }
2718 if (nread) {
2719 c->querybuf = sdscatlen(c->querybuf, buf, nread);
2720 c->lastinteraction = time(NULL);
2721 } else {
2722 return;
2723 }
2724 processInputBuffer(c);
2725 }
2726
2727 static int selectDb(redisClient *c, int id) {
2728 if (id < 0 || id >= server.dbnum)
2729 return REDIS_ERR;
2730 c->db = &server.db[id];
2731 return REDIS_OK;
2732 }
2733
2734 static void *dupClientReplyValue(void *o) {
2735 incrRefCount((robj*)o);
2736 return o;
2737 }
2738
2739 static int listMatchObjects(void *a, void *b) {
2740 return equalStringObjects(a,b);
2741 }
2742
2743 static redisClient *createClient(int fd) {
2744 redisClient *c = zmalloc(sizeof(*c));
2745
2746 anetNonBlock(NULL,fd);
2747 anetTcpNoDelay(NULL,fd);
2748 if (!c) return NULL;
2749 selectDb(c,0);
2750 c->fd = fd;
2751 c->querybuf = sdsempty();
2752 c->argc = 0;
2753 c->argv = NULL;
2754 c->bulklen = -1;
2755 c->multibulk = 0;
2756 c->mbargc = 0;
2757 c->mbargv = NULL;
2758 c->sentlen = 0;
2759 c->flags = 0;
2760 c->lastinteraction = time(NULL);
2761 c->authenticated = 0;
2762 c->replstate = REDIS_REPL_NONE;
2763 c->reply = listCreate();
2764 listSetFreeMethod(c->reply,decrRefCount);
2765 listSetDupMethod(c->reply,dupClientReplyValue);
2766 c->blocking_keys = NULL;
2767 c->blocking_keys_num = 0;
2768 c->io_keys = listCreate();
2769 c->watched_keys = listCreate();
2770 listSetFreeMethod(c->io_keys,decrRefCount);
2771 c->pubsub_channels = dictCreate(&setDictType,NULL);
2772 c->pubsub_patterns = listCreate();
2773 listSetFreeMethod(c->pubsub_patterns,decrRefCount);
2774 listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
2775 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
2776 readQueryFromClient, c) == AE_ERR) {
2777 freeClient(c);
2778 return NULL;
2779 }
2780 listAddNodeTail(server.clients,c);
2781 initClientMultiState(c);
2782 return c;
2783 }
2784
2785 static void addReply(redisClient *c, robj *obj) {
2786 if (listLength(c->reply) == 0 &&
2787 (c->replstate == REDIS_REPL_NONE ||
2788 c->replstate == REDIS_REPL_ONLINE) &&
2789 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
2790 sendReplyToClient, c) == AE_ERR) return;
2791
2792 if (server.vm_enabled && obj->storage != REDIS_VM_MEMORY) {
2793 obj = dupStringObject(obj);
2794 obj->refcount = 0; /* getDecodedObject() will increment the refcount */
2795 }
2796 listAddNodeTail(c->reply,getDecodedObject(obj));
2797 }
2798
2799 static void addReplySds(redisClient *c, sds s) {
2800 robj *o = createObject(REDIS_STRING,s);
2801 addReply(c,o);
2802 decrRefCount(o);
2803 }
2804
2805 static void addReplyDouble(redisClient *c, double d) {
2806 char buf[128];
2807
2808 snprintf(buf,sizeof(buf),"%.17g",d);
2809 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2810 (unsigned long) strlen(buf),buf));
2811 }
2812
2813 static void addReplyLongLong(redisClient *c, long long ll) {
2814 char buf[128];
2815 size_t len;
2816
2817 if (ll == 0) {
2818 addReply(c,shared.czero);
2819 return;
2820 } else if (ll == 1) {
2821 addReply(c,shared.cone);
2822 return;
2823 }
2824 buf[0] = ':';
2825 len = ll2string(buf+1,sizeof(buf)-1,ll);
2826 buf[len+1] = '\r';
2827 buf[len+2] = '\n';
2828 addReplySds(c,sdsnewlen(buf,len+3));
2829 }
2830
2831 static void addReplyUlong(redisClient *c, unsigned long ul) {
2832 char buf[128];
2833 size_t len;
2834
2835 if (ul == 0) {
2836 addReply(c,shared.czero);
2837 return;
2838 } else if (ul == 1) {
2839 addReply(c,shared.cone);
2840 return;
2841 }
2842 len = snprintf(buf,sizeof(buf),":%lu\r\n",ul);
2843 addReplySds(c,sdsnewlen(buf,len));
2844 }
2845
2846 static void addReplyBulkLen(redisClient *c, robj *obj) {
2847 size_t len, intlen;
2848 char buf[128];
2849
2850 if (obj->encoding == REDIS_ENCODING_RAW) {
2851 len = sdslen(obj->ptr);
2852 } else {
2853 long n = (long)obj->ptr;
2854
2855 /* Compute how many bytes will take this integer as a radix 10 string */
2856 len = 1;
2857 if (n < 0) {
2858 len++;
2859 n = -n;
2860 }
2861 while((n = n/10) != 0) {
2862 len++;
2863 }
2864 }
2865 buf[0] = '$';
2866 intlen = ll2string(buf+1,sizeof(buf)-1,(long long)len);
2867 buf[intlen+1] = '\r';
2868 buf[intlen+2] = '\n';
2869 addReplySds(c,sdsnewlen(buf,intlen+3));
2870 }
2871
2872 static void addReplyBulk(redisClient *c, robj *obj) {
2873 addReplyBulkLen(c,obj);
2874 addReply(c,obj);
2875 addReply(c,shared.crlf);
2876 }
2877
2878 /* In the CONFIG command we need to add vanilla C string as bulk replies */
2879 static void addReplyBulkCString(redisClient *c, char *s) {
2880 if (s == NULL) {
2881 addReply(c,shared.nullbulk);
2882 } else {
2883 robj *o = createStringObject(s,strlen(s));
2884 addReplyBulk(c,o);
2885 decrRefCount(o);
2886 }
2887 }
2888
2889 static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2890 int cport, cfd;
2891 char cip[128];
2892 redisClient *c;
2893 REDIS_NOTUSED(el);
2894 REDIS_NOTUSED(mask);
2895 REDIS_NOTUSED(privdata);
2896
2897 cfd = anetAccept(server.neterr, fd, cip, &cport);
2898 if (cfd == AE_ERR) {
2899 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
2900 return;
2901 }
2902 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
2903 if ((c = createClient(cfd)) == NULL) {
2904 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2905 close(cfd); /* May be already closed, just ingore errors */
2906 return;
2907 }
2908 /* If maxclient directive is set and this is one client more... close the
2909 * connection. Note that we create the client instead to check before
2910 * for this condition, since now the socket is already set in nonblocking
2911 * mode and we can send an error for free using the Kernel I/O */
2912 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2913 char *err = "-ERR max number of clients reached\r\n";
2914
2915 /* That's a best effort error message, don't check write errors */
2916 if (write(c->fd,err,strlen(err)) == -1) {
2917 /* Nothing to do, Just to avoid the warning... */
2918 }
2919 freeClient(c);
2920 return;
2921 }
2922 server.stat_numconnections++;
2923 }
2924
2925 /* ======================= Redis objects implementation ===================== */
2926
2927 static robj *createObject(int type, void *ptr) {
2928 robj *o;
2929
2930 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
2931 if (listLength(server.objfreelist)) {
2932 listNode *head = listFirst(server.objfreelist);
2933 o = listNodeValue(head);
2934 listDelNode(server.objfreelist,head);
2935 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
2936 } else {
2937 if (server.vm_enabled) {
2938 pthread_mutex_unlock(&server.obj_freelist_mutex);
2939 o = zmalloc(sizeof(*o));
2940 } else {
2941 o = zmalloc(sizeof(*o)-sizeof(struct redisObjectVM));
2942 }
2943 }
2944 o->type = type;
2945 o->encoding = REDIS_ENCODING_RAW;
2946 o->ptr = ptr;
2947 o->refcount = 1;
2948 if (server.vm_enabled) {
2949 /* Note that this code may run in the context of an I/O thread
2950 * and accessing to server.unixtime in theory is an error
2951 * (no locks). But in practice this is safe, and even if we read
2952 * garbage Redis will not fail, as it's just a statistical info */
2953 o->vm.atime = server.unixtime;
2954 o->storage = REDIS_VM_MEMORY;
2955 }
2956 return o;
2957 }
2958
2959 static robj *createStringObject(char *ptr, size_t len) {
2960 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
2961 }
2962
2963 static robj *createStringObjectFromLongLong(long long value) {
2964 robj *o;
2965 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
2966 incrRefCount(shared.integers[value]);
2967 o = shared.integers[value];
2968 } else {
2969 if (value >= LONG_MIN && value <= LONG_MAX) {
2970 o = createObject(REDIS_STRING, NULL);
2971 o->encoding = REDIS_ENCODING_INT;
2972 o->ptr = (void*)((long)value);
2973 } else {
2974 o = createObject(REDIS_STRING,sdsfromlonglong(value));
2975 }
2976 }
2977 return o;
2978 }
2979
2980 static robj *dupStringObject(robj *o) {
2981 assert(o->encoding == REDIS_ENCODING_RAW);
2982 return createStringObject(o->ptr,sdslen(o->ptr));
2983 }
2984
2985 static robj *createListObject(void) {
2986 list *l = listCreate();
2987
2988 listSetFreeMethod(l,decrRefCount);
2989 return createObject(REDIS_LIST,l);
2990 }
2991
2992 static robj *createSetObject(void) {
2993 dict *d = dictCreate(&setDictType,NULL);
2994 return createObject(REDIS_SET,d);
2995 }
2996
2997 static robj *createHashObject(void) {
2998 /* All the Hashes start as zipmaps. Will be automatically converted
2999 * into hash tables if there are enough elements or big elements
3000 * inside. */
3001 unsigned char *zm = zipmapNew();
3002 robj *o = createObject(REDIS_HASH,zm);
3003 o->encoding = REDIS_ENCODING_ZIPMAP;
3004 return o;
3005 }
3006
3007 static robj *createZsetObject(void) {
3008 zset *zs = zmalloc(sizeof(*zs));
3009
3010 zs->dict = dictCreate(&zsetDictType,NULL);
3011 zs->zsl = zslCreate();
3012 return createObject(REDIS_ZSET,zs);
3013 }
3014
3015 static void freeStringObject(robj *o) {
3016 if (o->encoding == REDIS_ENCODING_RAW) {
3017 sdsfree(o->ptr);
3018 }
3019 }
3020
3021 static void freeListObject(robj *o) {
3022 switch (o->encoding) {
3023 case REDIS_ENCODING_LIST:
3024 listRelease((list*) o->ptr);
3025 break;
3026 case REDIS_ENCODING_ZIPLIST:
3027 zfree(o->ptr);
3028 break;
3029 default:
3030 redisPanic("Unknown list encoding type");
3031 }
3032 }
3033
3034 static void freeSetObject(robj *o) {
3035 dictRelease((dict*) o->ptr);
3036 }
3037
3038 static void freeZsetObject(robj *o) {
3039 zset *zs = o->ptr;
3040
3041 dictRelease(zs->dict);
3042 zslFree(zs->zsl);
3043 zfree(zs);
3044 }
3045
3046 static void freeHashObject(robj *o) {
3047 switch (o->encoding) {
3048 case REDIS_ENCODING_HT:
3049 dictRelease((dict*) o->ptr);
3050 break;
3051 case REDIS_ENCODING_ZIPMAP:
3052 zfree(o->ptr);
3053 break;
3054 default:
3055 redisPanic("Unknown hash encoding type");
3056 break;
3057 }
3058 }
3059
3060 static void incrRefCount(robj *o) {
3061 o->refcount++;
3062 }
3063
3064 static void decrRefCount(void *obj) {
3065 robj *o = obj;
3066
3067 if (o->refcount <= 0) redisPanic("decrRefCount against refcount <= 0");
3068 /* Object is a key of a swapped out value, or in the process of being
3069 * loaded. */
3070 if (server.vm_enabled &&
3071 (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
3072 {
3073 if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(obj);
3074 redisAssert(o->type == REDIS_STRING);
3075 freeStringObject(o);
3076 vmMarkPagesFree(o->vm.page,o->vm.usedpages);
3077 pthread_mutex_lock(&server.obj_freelist_mutex);
3078 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3079 !listAddNodeHead(server.objfreelist,o))
3080 zfree(o);
3081 pthread_mutex_unlock(&server.obj_freelist_mutex);
3082 server.vm_stats_swapped_objects--;
3083 return;
3084 }
3085 /* Object is in memory, or in the process of being swapped out. */
3086 if (--(o->refcount) == 0) {
3087 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
3088 vmCancelThreadedIOJob(obj);
3089 switch(o->type) {
3090 case REDIS_STRING: freeStringObject(o); break;
3091 case REDIS_LIST: freeListObject(o); break;
3092 case REDIS_SET: freeSetObject(o); break;
3093 case REDIS_ZSET: freeZsetObject(o); break;
3094 case REDIS_HASH: freeHashObject(o); break;
3095 default: redisPanic("Unknown object type"); break;
3096 }
3097 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
3098 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3099 !listAddNodeHead(server.objfreelist,o))
3100 zfree(o);
3101 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
3102 }
3103 }
3104
3105 static robj *lookupKey(redisDb *db, robj *key) {
3106 dictEntry *de = dictFind(db->dict,key);
3107 if (de) {
3108 robj *key = dictGetEntryKey(de);
3109 robj *val = dictGetEntryVal(de);
3110
3111 if (server.vm_enabled) {
3112 if (key->storage == REDIS_VM_MEMORY ||
3113 key->storage == REDIS_VM_SWAPPING)
3114 {
3115 /* If we were swapping the object out, stop it, this key
3116 * was requested. */
3117 if (key->storage == REDIS_VM_SWAPPING)
3118 vmCancelThreadedIOJob(key);
3119 /* Update the access time of the key for the aging algorithm. */
3120 key->vm.atime = server.unixtime;
3121 } else {
3122 int notify = (key->storage == REDIS_VM_LOADING);
3123
3124 /* Our value was swapped on disk. Bring it at home. */
3125 redisAssert(val == NULL);
3126 val = vmLoadObject(key);
3127 dictGetEntryVal(de) = val;
3128
3129 /* Clients blocked by the VM subsystem may be waiting for
3130 * this key... */
3131 if (notify) handleClientsBlockedOnSwappedKey(db,key);
3132 }
3133 }
3134 return val;
3135 } else {
3136 return NULL;
3137 }
3138 }
3139
3140 static robj *lookupKeyRead(redisDb *db, robj *key) {
3141 expireIfNeeded(db,key);
3142 return lookupKey(db,key);
3143 }
3144
3145 static robj *lookupKeyWrite(redisDb *db, robj *key) {
3146 deleteIfVolatile(db,key);
3147 touchWatchedKey(db,key);
3148 return lookupKey(db,key);
3149 }
3150
3151 static robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
3152 robj *o = lookupKeyRead(c->db, key);
3153 if (!o) addReply(c,reply);
3154 return o;
3155 }
3156
3157 static robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
3158 robj *o = lookupKeyWrite(c->db, key);
3159 if (!o) addReply(c,reply);
3160 return o;
3161 }
3162
3163 static int checkType(redisClient *c, robj *o, int type) {
3164 if (o->type != type) {
3165 addReply(c,shared.wrongtypeerr);
3166 return 1;
3167 }
3168 return 0;
3169 }
3170
3171 static int deleteKey(redisDb *db, robj *key) {
3172 int retval;
3173
3174 /* We need to protect key from destruction: after the first dictDelete()
3175 * it may happen that 'key' is no longer valid if we don't increment
3176 * it's count. This may happen when we get the object reference directly
3177 * from the hash table with dictRandomKey() or dict iterators */
3178 incrRefCount(key);
3179 if (dictSize(db->expires)) dictDelete(db->expires,key);
3180 retval = dictDelete(db->dict,key);
3181 decrRefCount(key);
3182
3183 return retval == DICT_OK;
3184 }
3185
3186 /* Check if the nul-terminated string 's' can be represented by a long
3187 * (that is, is a number that fits into long without any other space or
3188 * character before or after the digits).
3189 *
3190 * If so, the function returns REDIS_OK and *longval is set to the value
3191 * of the number. Otherwise REDIS_ERR is returned */
3192 static int isStringRepresentableAsLong(sds s, long *longval) {
3193 char buf[32], *endptr;
3194 long value;
3195 int slen;
3196
3197 value = strtol(s, &endptr, 10);
3198 if (endptr[0] != '\0') return REDIS_ERR;
3199 slen = ll2string(buf,32,value);
3200
3201 /* If the number converted back into a string is not identical
3202 * then it's not possible to encode the string as integer */
3203 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
3204 if (longval) *longval = value;
3205 return REDIS_OK;
3206 }
3207
3208 /* Try to encode a string object in order to save space */
3209 static robj *tryObjectEncoding(robj *o) {
3210 long value;
3211 sds s = o->ptr;
3212
3213 if (o->encoding != REDIS_ENCODING_RAW)
3214 return o; /* Already encoded */
3215
3216 /* It's not safe to encode shared objects: shared objects can be shared
3217 * everywhere in the "object space" of Redis. Encoded objects can only
3218 * appear as "values" (and not, for instance, as keys) */
3219 if (o->refcount > 1) return o;
3220
3221 /* Currently we try to encode only strings */
3222 redisAssert(o->type == REDIS_STRING);
3223
3224 /* Check if we can represent this string as a long integer */
3225 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return o;
3226
3227 /* Ok, this object can be encoded */
3228 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3229 decrRefCount(o);
3230 incrRefCount(shared.integers[value]);
3231 return shared.integers[value];
3232 } else {
3233 o->encoding = REDIS_ENCODING_INT;
3234 sdsfree(o->ptr);
3235 o->ptr = (void*) value;
3236 return o;
3237 }
3238 }
3239
3240 /* Get a decoded version of an encoded object (returned as a new object).
3241 * If the object is already raw-encoded just increment the ref count. */
3242 static robj *getDecodedObject(robj *o) {
3243 robj *dec;
3244
3245 if (o->encoding == REDIS_ENCODING_RAW) {
3246 incrRefCount(o);
3247 return o;
3248 }
3249 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
3250 char buf[32];
3251
3252 ll2string(buf,32,(long)o->ptr);
3253 dec = createStringObject(buf,strlen(buf));
3254 return dec;
3255 } else {
3256 redisPanic("Unknown encoding type");
3257 }
3258 }
3259
3260 /* Compare two string objects via strcmp() or alike.
3261 * Note that the objects may be integer-encoded. In such a case we
3262 * use ll2string() to get a string representation of the numbers on the stack
3263 * and compare the strings, it's much faster than calling getDecodedObject().
3264 *
3265 * Important note: if objects are not integer encoded, but binary-safe strings,
3266 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3267 * binary safe. */
3268 static int compareStringObjects(robj *a, robj *b) {
3269 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
3270 char bufa[128], bufb[128], *astr, *bstr;
3271 int bothsds = 1;
3272
3273 if (a == b) return 0;
3274 if (a->encoding != REDIS_ENCODING_RAW) {
3275 ll2string(bufa,sizeof(bufa),(long) a->ptr);
3276 astr = bufa;
3277 bothsds = 0;
3278 } else {
3279 astr = a->ptr;
3280 }
3281 if (b->encoding != REDIS_ENCODING_RAW) {
3282 ll2string(bufb,sizeof(bufb),(long) b->ptr);
3283 bstr = bufb;
3284 bothsds = 0;
3285 } else {
3286 bstr = b->ptr;
3287 }
3288 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
3289 }
3290
3291 /* Equal string objects return 1 if the two objects are the same from the
3292 * point of view of a string comparison, otherwise 0 is returned. Note that
3293 * this function is faster then checking for (compareStringObject(a,b) == 0)
3294 * because it can perform some more optimization. */
3295 static int equalStringObjects(robj *a, robj *b) {
3296 if (a->encoding != REDIS_ENCODING_RAW && b->encoding != REDIS_ENCODING_RAW){
3297 return a->ptr == b->ptr;
3298 } else {
3299 return compareStringObjects(a,b) == 0;
3300 }
3301 }
3302
3303 static size_t stringObjectLen(robj *o) {
3304 redisAssert(o->type == REDIS_STRING);
3305 if (o->encoding == REDIS_ENCODING_RAW) {
3306 return sdslen(o->ptr);
3307 } else {
3308 char buf[32];
3309
3310 return ll2string(buf,32,(long)o->ptr);
3311 }
3312 }
3313
3314 static int getDoubleFromObject(robj *o, double *target) {
3315 double value;
3316 char *eptr;
3317
3318 if (o == NULL) {
3319 value = 0;
3320 } else {
3321 redisAssert(o->type == REDIS_STRING);
3322 if (o->encoding == REDIS_ENCODING_RAW) {
3323 value = strtod(o->ptr, &eptr);
3324 if (eptr[0] != '\0') return REDIS_ERR;
3325 } else if (o->encoding == REDIS_ENCODING_INT) {
3326 value = (long)o->ptr;
3327 } else {
3328 redisPanic("Unknown string encoding");
3329 }
3330 }
3331
3332 *target = value;
3333 return REDIS_OK;
3334 }
3335
3336 static int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg) {
3337 double value;
3338 if (getDoubleFromObject(o, &value) != REDIS_OK) {
3339 if (msg != NULL) {
3340 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3341 } else {
3342 addReplySds(c, sdsnew("-ERR value is not a double\r\n"));
3343 }
3344 return REDIS_ERR;
3345 }
3346
3347 *target = value;
3348 return REDIS_OK;
3349 }
3350
3351 static int getLongLongFromObject(robj *o, long long *target) {
3352 long long value;
3353 char *eptr;
3354
3355 if (o == NULL) {
3356 value = 0;
3357 } else {
3358 redisAssert(o->type == REDIS_STRING);
3359 if (o->encoding == REDIS_ENCODING_RAW) {
3360 value = strtoll(o->ptr, &eptr, 10);
3361 if (eptr[0] != '\0') return REDIS_ERR;
3362 } else if (o->encoding == REDIS_ENCODING_INT) {
3363 value = (long)o->ptr;
3364 } else {
3365 redisPanic("Unknown string encoding");
3366 }
3367 }
3368
3369 *target = value;
3370 return REDIS_OK;
3371 }
3372
3373 static int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg) {
3374 long long value;
3375 if (getLongLongFromObject(o, &value) != REDIS_OK) {
3376 if (msg != NULL) {
3377 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3378 } else {
3379 addReplySds(c, sdsnew("-ERR value is not an integer\r\n"));
3380 }
3381 return REDIS_ERR;
3382 }
3383
3384 *target = value;
3385 return REDIS_OK;
3386 }
3387
3388 static int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg) {
3389 long long value;
3390
3391 if (getLongLongFromObjectOrReply(c, o, &value, msg) != REDIS_OK) return REDIS_ERR;
3392 if (value < LONG_MIN || value > LONG_MAX) {
3393 if (msg != NULL) {
3394 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3395 } else {
3396 addReplySds(c, sdsnew("-ERR value is out of range\r\n"));
3397 }
3398 return REDIS_ERR;
3399 }
3400
3401 *target = value;
3402 return REDIS_OK;
3403 }
3404
3405 /*============================ RDB saving/loading =========================== */
3406
3407 static int rdbSaveType(FILE *fp, unsigned char type) {
3408 if (fwrite(&type,1,1,fp) == 0) return -1;
3409 return 0;
3410 }
3411
3412 static int rdbSaveTime(FILE *fp, time_t t) {
3413 int32_t t32 = (int32_t) t;
3414 if (fwrite(&t32,4,1,fp) == 0) return -1;
3415 return 0;
3416 }
3417
3418 /* check rdbLoadLen() comments for more info */
3419 static int rdbSaveLen(FILE *fp, uint32_t len) {
3420 unsigned char buf[2];
3421
3422 if (len < (1<<6)) {
3423 /* Save a 6 bit len */
3424 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
3425 if (fwrite(buf,1,1,fp) == 0) return -1;
3426 } else if (len < (1<<14)) {
3427 /* Save a 14 bit len */
3428 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
3429 buf[1] = len&0xFF;
3430 if (fwrite(buf,2,1,fp) == 0) return -1;
3431 } else {
3432 /* Save a 32 bit len */
3433 buf[0] = (REDIS_RDB_32BITLEN<<6);
3434 if (fwrite(buf,1,1,fp) == 0) return -1;
3435 len = htonl(len);
3436 if (fwrite(&len,4,1,fp) == 0) return -1;
3437 }
3438 return 0;
3439 }
3440
3441 /* Encode 'value' as an integer if possible (if integer will fit the
3442 * supported range). If the function sucessful encoded the integer
3443 * then the (up to 5 bytes) encoded representation is written in the
3444 * string pointed by 'enc' and the length is returned. Otherwise
3445 * 0 is returned. */
3446 static int rdbEncodeInteger(long long value, unsigned char *enc) {
3447 /* Finally check if it fits in our ranges */
3448 if (value >= -(1<<7) && value <= (1<<7)-1) {
3449 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
3450 enc[1] = value&0xFF;
3451 return 2;
3452 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
3453 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
3454 enc[1] = value&0xFF;
3455 enc[2] = (value>>8)&0xFF;
3456 return 3;
3457 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
3458 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
3459 enc[1] = value&0xFF;
3460 enc[2] = (value>>8)&0xFF;
3461 enc[3] = (value>>16)&0xFF;
3462 enc[4] = (value>>24)&0xFF;
3463 return 5;
3464 } else {
3465 return 0;
3466 }
3467 }
3468
3469 /* String objects in the form "2391" "-100" without any space and with a
3470 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3471 * encoded as integers to save space */
3472 static int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
3473 long long value;
3474 char *endptr, buf[32];
3475
3476 /* Check if it's possible to encode this value as a number */
3477 value = strtoll(s, &endptr, 10);
3478 if (endptr[0] != '\0') return 0;
3479 ll2string(buf,32,value);
3480
3481 /* If the number converted back into a string is not identical
3482 * then it's not possible to encode the string as integer */
3483 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
3484
3485 return rdbEncodeInteger(value,enc);
3486 }
3487
3488 static int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
3489 size_t comprlen, outlen;
3490 unsigned char byte;
3491 void *out;
3492
3493 /* We require at least four bytes compression for this to be worth it */
3494 if (len <= 4) return 0;
3495 outlen = len-4;
3496 if ((out = zmalloc(outlen+1)) == NULL) return 0;
3497 comprlen = lzf_compress(s, len, out, outlen);
3498 if (comprlen == 0) {
3499 zfree(out);
3500 return 0;
3501 }
3502 /* Data compressed! Let's save it on disk */
3503 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
3504 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
3505 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
3506 if (rdbSaveLen(fp,len) == -1) goto writeerr;
3507 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
3508 zfree(out);
3509 return comprlen;
3510
3511 writeerr:
3512 zfree(out);
3513 return -1;
3514 }
3515
3516 /* Save a string objet as [len][data] on disk. If the object is a string
3517 * representation of an integer value we try to safe it in a special form */
3518 static int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
3519 int enclen;
3520
3521 /* Try integer encoding */
3522 if (len <= 11) {
3523 unsigned char buf[5];
3524 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
3525 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3526 return 0;
3527 }
3528 }
3529
3530 /* Try LZF compression - under 20 bytes it's unable to compress even
3531 * aaaaaaaaaaaaaaaaaa so skip it */
3532 if (server.rdbcompression && len > 20) {
3533 int retval;
3534
3535 retval = rdbSaveLzfStringObject(fp,s,len);
3536 if (retval == -1) return -1;
3537 if (retval > 0) return 0;
3538 /* retval == 0 means data can't be compressed, save the old way */
3539 }
3540
3541 /* Store verbatim */
3542 if (rdbSaveLen(fp,len) == -1) return -1;
3543 if (len && fwrite(s,len,1,fp) == 0) return -1;
3544 return 0;
3545 }
3546
3547 /* Save a long long value as either an encoded string or a string. */
3548 static int rdbSaveLongLongAsStringObject(FILE *fp, long long value) {
3549 unsigned char buf[32];
3550 int enclen = rdbEncodeInteger(value,buf);
3551 if (enclen > 0) {
3552 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3553 } else {
3554 /* Encode as string */
3555 enclen = ll2string((char*)buf,32,value);
3556 redisAssert(enclen < 32);
3557 if (rdbSaveLen(fp,enclen) == -1) return -1;
3558 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3559 }
3560 return 0;
3561 }
3562
3563 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3564 static int rdbSaveStringObject(FILE *fp, robj *obj) {
3565 /* Avoid to decode the object, then encode it again, if the
3566 * object is alrady integer encoded. */
3567 if (obj->encoding == REDIS_ENCODING_INT) {
3568 return rdbSaveLongLongAsStringObject(fp,(long)obj->ptr);
3569 } else {
3570 redisAssert(obj->encoding == REDIS_ENCODING_RAW);
3571 return rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
3572 }
3573 }
3574
3575 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3576 * 8 bit integer specifing the length of the representation.
3577 * This 8 bit integer has special values in order to specify the following
3578 * conditions:
3579 * 253: not a number
3580 * 254: + inf
3581 * 255: - inf
3582 */
3583 static int rdbSaveDoubleValue(FILE *fp, double val) {
3584 unsigned char buf[128];
3585 int len;
3586
3587 if (isnan(val)) {
3588 buf[0] = 253;
3589 len = 1;
3590 } else if (!isfinite(val)) {
3591 len = 1;
3592 buf[0] = (val < 0) ? 255 : 254;
3593 } else {
3594 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
3595 /* Check if the float is in a safe range to be casted into a
3596 * long long. We are assuming that long long is 64 bit here.
3597 * Also we are assuming that there are no implementations around where
3598 * double has precision < 52 bit.
3599 *
3600 * Under this assumptions we test if a double is inside an interval
3601 * where casting to long long is safe. Then using two castings we
3602 * make sure the decimal part is zero. If all this is true we use
3603 * integer printing function that is much faster. */
3604 double min = -4503599627370495; /* (2^52)-1 */
3605 double max = 4503599627370496; /* -(2^52) */
3606 if (val > min && val < max && val == ((double)((long long)val)))
3607 ll2string((char*)buf+1,sizeof(buf),(long long)val);
3608 else
3609 #endif
3610 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
3611 buf[0] = strlen((char*)buf+1);
3612 len = buf[0]+1;
3613 }
3614 if (fwrite(buf,len,1,fp) == 0) return -1;
3615 return 0;
3616 }
3617
3618 /* Save a Redis object. */
3619 static int rdbSaveObject(FILE *fp, robj *o) {
3620 if (o->type == REDIS_STRING) {
3621 /* Save a string value */
3622 if (rdbSaveStringObject(fp,o) == -1) return -1;
3623 } else if (o->type == REDIS_LIST) {
3624 /* Save a list value */
3625 list *list = o->ptr;
3626 listIter li;
3627 listNode *ln;
3628
3629 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
3630 listRewind(list,&li);
3631 while((ln = listNext(&li))) {
3632 robj *eleobj = listNodeValue(ln);
3633
3634 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3635 }
3636 } else if (o->type == REDIS_SET) {
3637 /* Save a set value */
3638 dict *set = o->ptr;
3639 dictIterator *di = dictGetIterator(set);
3640 dictEntry *de;
3641
3642 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
3643 while((de = dictNext(di)) != NULL) {
3644 robj *eleobj = dictGetEntryKey(de);
3645
3646 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3647 }
3648 dictReleaseIterator(di);
3649 } else if (o->type == REDIS_ZSET) {
3650 /* Save a set value */
3651 zset *zs = o->ptr;
3652 dictIterator *di = dictGetIterator(zs->dict);
3653 dictEntry *de;
3654
3655 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
3656 while((de = dictNext(di)) != NULL) {
3657 robj *eleobj = dictGetEntryKey(de);
3658 double *score = dictGetEntryVal(de);
3659
3660 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3661 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
3662 }
3663 dictReleaseIterator(di);
3664 } else if (o->type == REDIS_HASH) {
3665 /* Save a hash value */
3666 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3667 unsigned char *p = zipmapRewind(o->ptr);
3668 unsigned int count = zipmapLen(o->ptr);
3669 unsigned char *key, *val;
3670 unsigned int klen, vlen;
3671
3672 if (rdbSaveLen(fp,count) == -1) return -1;
3673 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
3674 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
3675 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
3676 }
3677 } else {
3678 dictIterator *di = dictGetIterator(o->ptr);
3679 dictEntry *de;
3680
3681 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
3682 while((de = dictNext(di)) != NULL) {
3683 robj *key = dictGetEntryKey(de);
3684 robj *val = dictGetEntryVal(de);
3685
3686 if (rdbSaveStringObject(fp,key) == -1) return -1;
3687 if (rdbSaveStringObject(fp,val) == -1) return -1;
3688 }
3689 dictReleaseIterator(di);
3690 }
3691 } else {
3692 redisPanic("Unknown object type");
3693 }
3694 return 0;
3695 }
3696
3697 /* Return the length the object will have on disk if saved with
3698 * the rdbSaveObject() function. Currently we use a trick to get
3699 * this length with very little changes to the code. In the future
3700 * we could switch to a faster solution. */
3701 static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
3702 if (fp == NULL) fp = server.devnull;
3703 rewind(fp);
3704 assert(rdbSaveObject(fp,o) != 1);
3705 return ftello(fp);
3706 }
3707
3708 /* Return the number of pages required to save this object in the swap file */
3709 static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
3710 off_t bytes = rdbSavedObjectLen(o,fp);
3711
3712 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
3713 }
3714
3715 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3716 static int rdbSave(char *filename) {
3717 dictIterator *di = NULL;
3718 dictEntry *de;
3719 FILE *fp;
3720 char tmpfile[256];
3721 int j;
3722 time_t now = time(NULL);
3723
3724 /* Wait for I/O therads to terminate, just in case this is a
3725 * foreground-saving, to avoid seeking the swap file descriptor at the
3726 * same time. */
3727 if (server.vm_enabled)
3728 waitEmptyIOJobsQueue();
3729
3730 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
3731 fp = fopen(tmpfile,"w");
3732 if (!fp) {
3733 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
3734 return REDIS_ERR;
3735 }
3736 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
3737 for (j = 0; j < server.dbnum; j++) {
3738 redisDb *db = server.db+j;
3739 dict *d = db->dict;
3740 if (dictSize(d) == 0) continue;
3741 di = dictGetIterator(d);
3742 if (!di) {
3743 fclose(fp);
3744 return REDIS_ERR;
3745 }
3746
3747 /* Write the SELECT DB opcode */
3748 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
3749 if (rdbSaveLen(fp,j) == -1) goto werr;
3750
3751 /* Iterate this DB writing every entry */
3752 while((de = dictNext(di)) != NULL) {
3753 robj *key = dictGetEntryKey(de);
3754 robj *o = dictGetEntryVal(de);
3755 time_t expiretime = getExpire(db,key);
3756
3757 /* Save the expire time */
3758 if (expiretime != -1) {
3759 /* If this key is already expired skip it */
3760 if (expiretime < now) continue;
3761 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
3762 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
3763 }
3764 /* Save the key and associated value. This requires special
3765 * handling if the value is swapped out. */
3766 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
3767 key->storage == REDIS_VM_SWAPPING) {
3768 /* Save type, key, value */
3769 if (rdbSaveType(fp,o->type) == -1) goto werr;
3770 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3771 if (rdbSaveObject(fp,o) == -1) goto werr;
3772 } else {
3773 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3774 robj *po;
3775 /* Get a preview of the object in memory */
3776 po = vmPreviewObject(key);
3777 /* Save type, key, value */
3778 if (rdbSaveType(fp,key->vtype) == -1) goto werr;
3779 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3780 if (rdbSaveObject(fp,po) == -1) goto werr;
3781 /* Remove the loaded object from memory */
3782 decrRefCount(po);
3783 }
3784 }
3785 dictReleaseIterator(di);
3786 }
3787 /* EOF opcode */
3788 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
3789
3790 /* Make sure data will not remain on the OS's output buffers */
3791 fflush(fp);
3792 fsync(fileno(fp));
3793 fclose(fp);
3794
3795 /* Use RENAME to make sure the DB file is changed atomically only
3796 * if the generate DB file is ok. */
3797 if (rename(tmpfile,filename) == -1) {
3798 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
3799 unlink(tmpfile);
3800 return REDIS_ERR;
3801 }
3802 redisLog(REDIS_NOTICE,"DB saved on disk");
3803 server.dirty = 0;
3804 server.lastsave = time(NULL);
3805 return REDIS_OK;
3806
3807 werr:
3808 fclose(fp);
3809 unlink(tmpfile);
3810 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
3811 if (di) dictReleaseIterator(di);
3812 return REDIS_ERR;
3813 }
3814
3815 static int rdbSaveBackground(char *filename) {
3816 pid_t childpid;
3817
3818 if (server.bgsavechildpid != -1) return REDIS_ERR;
3819 if (server.vm_enabled) waitEmptyIOJobsQueue();
3820 if ((childpid = fork()) == 0) {
3821 /* Child */
3822 if (server.vm_enabled) vmReopenSwapFile();
3823 close(server.fd);
3824 if (rdbSave(filename) == REDIS_OK) {
3825 _exit(0);
3826 } else {
3827 _exit(1);
3828 }
3829 } else {
3830 /* Parent */
3831 if (childpid == -1) {
3832 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
3833 strerror(errno));
3834 return REDIS_ERR;
3835 }
3836 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
3837 server.bgsavechildpid = childpid;
3838 updateDictResizePolicy();
3839 return REDIS_OK;
3840 }
3841 return REDIS_OK; /* unreached */
3842 }
3843
3844 static void rdbRemoveTempFile(pid_t childpid) {
3845 char tmpfile[256];
3846
3847 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
3848 unlink(tmpfile);
3849 }
3850
3851 static int rdbLoadType(FILE *fp) {
3852 unsigned char type;
3853 if (fread(&type,1,1,fp) == 0) return -1;
3854 return type;
3855 }
3856
3857 static time_t rdbLoadTime(FILE *fp) {
3858 int32_t t32;
3859 if (fread(&t32,4,1,fp) == 0) return -1;
3860 return (time_t) t32;
3861 }
3862
3863 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3864 * of this file for a description of how this are stored on disk.
3865 *
3866 * isencoded is set to 1 if the readed length is not actually a length but
3867 * an "encoding type", check the above comments for more info */
3868 static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
3869 unsigned char buf[2];
3870 uint32_t len;
3871 int type;
3872
3873 if (isencoded) *isencoded = 0;
3874 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
3875 type = (buf[0]&0xC0)>>6;
3876 if (type == REDIS_RDB_6BITLEN) {
3877 /* Read a 6 bit len */
3878 return buf[0]&0x3F;
3879 } else if (type == REDIS_RDB_ENCVAL) {
3880 /* Read a 6 bit len encoding type */
3881 if (isencoded) *isencoded = 1;
3882 return buf[0]&0x3F;
3883 } else if (type == REDIS_RDB_14BITLEN) {
3884 /* Read a 14 bit len */
3885 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
3886 return ((buf[0]&0x3F)<<8)|buf[1];
3887 } else {
3888 /* Read a 32 bit len */
3889 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
3890 return ntohl(len);
3891 }
3892 }
3893
3894 /* Load an integer-encoded object from file 'fp', with the specified
3895 * encoding type 'enctype'. If encode is true the function may return
3896 * an integer-encoded object as reply, otherwise the returned object
3897 * will always be encoded as a raw string. */
3898 static robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
3899 unsigned char enc[4];
3900 long long val;
3901
3902 if (enctype == REDIS_RDB_ENC_INT8) {
3903 if (fread(enc,1,1,fp) == 0) return NULL;
3904 val = (signed char)enc[0];
3905 } else if (enctype == REDIS_RDB_ENC_INT16) {
3906 uint16_t v;
3907 if (fread(enc,2,1,fp) == 0) return NULL;
3908 v = enc[0]|(enc[1]<<8);
3909 val = (int16_t)v;
3910 } else if (enctype == REDIS_RDB_ENC_INT32) {
3911 uint32_t v;
3912 if (fread(enc,4,1,fp) == 0) return NULL;
3913 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
3914 val = (int32_t)v;
3915 } else {
3916 val = 0; /* anti-warning */
3917 redisPanic("Unknown RDB integer encoding type");
3918 }
3919 if (encode)
3920 return createStringObjectFromLongLong(val);
3921 else
3922 return createObject(REDIS_STRING,sdsfromlonglong(val));
3923 }
3924
3925 static robj *rdbLoadLzfStringObject(FILE*fp) {
3926 unsigned int len, clen;
3927 unsigned char *c = NULL;
3928 sds val = NULL;
3929
3930 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3931 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3932 if ((c = zmalloc(clen)) == NULL) goto err;
3933 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
3934 if (fread(c,clen,1,fp) == 0) goto err;
3935 if (lzf_decompress(c,clen,val,len) == 0) goto err;
3936 zfree(c);
3937 return createObject(REDIS_STRING,val);
3938 err:
3939 zfree(c);
3940 sdsfree(val);
3941 return NULL;
3942 }
3943
3944 static robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
3945 int isencoded;
3946 uint32_t len;
3947 sds val;
3948
3949 len = rdbLoadLen(fp,&isencoded);
3950 if (isencoded) {
3951 switch(len) {
3952 case REDIS_RDB_ENC_INT8:
3953 case REDIS_RDB_ENC_INT16:
3954 case REDIS_RDB_ENC_INT32:
3955 return rdbLoadIntegerObject(fp,len,encode);
3956 case REDIS_RDB_ENC_LZF:
3957 return rdbLoadLzfStringObject(fp);
3958 default:
3959 redisPanic("Unknown RDB encoding type");
3960 }
3961 }
3962
3963 if (len == REDIS_RDB_LENERR) return NULL;
3964 val = sdsnewlen(NULL,len);
3965 if (len && fread(val,len,1,fp) == 0) {
3966 sdsfree(val);
3967 return NULL;
3968 }
3969 return createObject(REDIS_STRING,val);
3970 }
3971
3972 static robj *rdbLoadStringObject(FILE *fp) {
3973 return rdbGenericLoadStringObject(fp,0);
3974 }
3975
3976 static robj *rdbLoadEncodedStringObject(FILE *fp) {
3977 return rdbGenericLoadStringObject(fp,1);
3978 }
3979
3980 /* For information about double serialization check rdbSaveDoubleValue() */
3981 static int rdbLoadDoubleValue(FILE *fp, double *val) {
3982 char buf[128];
3983 unsigned char len;
3984
3985 if (fread(&len,1,1,fp) == 0) return -1;
3986 switch(len) {
3987 case 255: *val = R_NegInf; return 0;
3988 case 254: *val = R_PosInf; return 0;
3989 case 253: *val = R_Nan; return 0;
3990 default:
3991 if (fread(buf,len,1,fp) == 0) return -1;
3992 buf[len] = '\0';
3993 sscanf(buf, "%lg", val);
3994 return 0;
3995 }
3996 }
3997
3998 /* Load a Redis object of the specified type from the specified file.
3999 * On success a newly allocated object is returned, otherwise NULL. */
4000 static robj *rdbLoadObject(int type, FILE *fp) {
4001 robj *o;
4002
4003 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
4004 if (type == REDIS_STRING) {
4005 /* Read string value */
4006 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4007 o = tryObjectEncoding(o);
4008 } else if (type == REDIS_LIST || type == REDIS_SET) {
4009 /* Read list/set value */
4010 uint32_t listlen;
4011
4012 if ((listlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4013 o = (type == REDIS_LIST) ? createListObject() : createSetObject();
4014 /* It's faster to expand the dict to the right size asap in order
4015 * to avoid rehashing */
4016 if (type == REDIS_SET && listlen > DICT_HT_INITIAL_SIZE)
4017 dictExpand(o->ptr,listlen);
4018 /* Load every single element of the list/set */
4019 while(listlen--) {
4020 robj *ele;
4021
4022 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4023 ele = tryObjectEncoding(ele);
4024 if (type == REDIS_LIST) {
4025 listAddNodeTail((list*)o->ptr,ele);
4026 } else {
4027 dictAdd((dict*)o->ptr,ele,NULL);
4028 }
4029 }
4030 } else if (type == REDIS_ZSET) {
4031 /* Read list/set value */
4032 size_t zsetlen;
4033 zset *zs;
4034
4035 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4036 o = createZsetObject();
4037 zs = o->ptr;
4038 /* Load every single element of the list/set */
4039 while(zsetlen--) {
4040 robj *ele;
4041 double *score = zmalloc(sizeof(double));
4042
4043 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4044 ele = tryObjectEncoding(ele);
4045 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
4046 dictAdd(zs->dict,ele,score);
4047 zslInsert(zs->zsl,*score,ele);
4048 incrRefCount(ele); /* added to skiplist */
4049 }
4050 } else if (type == REDIS_HASH) {
4051 size_t hashlen;
4052
4053 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4054 o = createHashObject();
4055 /* Too many entries? Use an hash table. */
4056 if (hashlen > server.hash_max_zipmap_entries)
4057 convertToRealHash(o);
4058 /* Load every key/value, then set it into the zipmap or hash
4059 * table, as needed. */
4060 while(hashlen--) {
4061 robj *key, *val;
4062
4063 if ((key = rdbLoadStringObject(fp)) == NULL) return NULL;
4064 if ((val = rdbLoadStringObject(fp)) == NULL) return NULL;
4065 /* If we are using a zipmap and there are too big values
4066 * the object is converted to real hash table encoding. */
4067 if (o->encoding != REDIS_ENCODING_HT &&
4068 (sdslen(key->ptr) > server.hash_max_zipmap_value ||
4069 sdslen(val->ptr) > server.hash_max_zipmap_value))
4070 {
4071 convertToRealHash(o);
4072 }
4073
4074 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
4075 unsigned char *zm = o->ptr;
4076
4077 zm = zipmapSet(zm,key->ptr,sdslen(key->ptr),
4078 val->ptr,sdslen(val->ptr),NULL);
4079 o->ptr = zm;
4080 decrRefCount(key);
4081 decrRefCount(val);
4082 } else {
4083 key = tryObjectEncoding(key);
4084 val = tryObjectEncoding(val);
4085 dictAdd((dict*)o->ptr,key,val);
4086 }
4087 }
4088 } else {
4089 redisPanic("Unknown object type");
4090 }
4091 return o;
4092 }
4093
4094 static int rdbLoad(char *filename) {
4095 FILE *fp;
4096 uint32_t dbid;
4097 int type, retval, rdbver;
4098 int swap_all_values = 0;
4099 dict *d = server.db[0].dict;
4100 redisDb *db = server.db+0;
4101 char buf[1024];
4102 time_t expiretime, now = time(NULL);
4103 long long loadedkeys = 0;
4104
4105 fp = fopen(filename,"r");
4106 if (!fp) return REDIS_ERR;
4107 if (fread(buf,9,1,fp) == 0) goto eoferr;
4108 buf[9] = '\0';
4109 if (memcmp(buf,"REDIS",5) != 0) {
4110 fclose(fp);
4111 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
4112 return REDIS_ERR;
4113 }
4114 rdbver = atoi(buf+5);
4115 if (rdbver != 1) {
4116 fclose(fp);
4117 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
4118 return REDIS_ERR;
4119 }
4120 while(1) {
4121 robj *key, *val;
4122
4123 expiretime = -1;
4124 /* Read type. */
4125 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4126 if (type == REDIS_EXPIRETIME) {
4127 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
4128 /* We read the time so we need to read the object type again */
4129 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4130 }
4131 if (type == REDIS_EOF) break;
4132 /* Handle SELECT DB opcode as a special case */
4133 if (type == REDIS_SELECTDB) {
4134 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
4135 goto eoferr;
4136 if (dbid >= (unsigned)server.dbnum) {
4137 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
4138 exit(1);
4139 }
4140 db = server.db+dbid;
4141 d = db->dict;
4142 continue;
4143 }
4144 /* Read key */
4145 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
4146 /* Read value */
4147 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
4148 /* Check if the key already expired */
4149 if (expiretime != -1 && expiretime < now) {
4150 decrRefCount(key);
4151 decrRefCount(val);
4152 continue;
4153 }
4154 /* Add the new object in the hash table */
4155 retval = dictAdd(d,key,val);
4156 if (retval == DICT_ERR) {
4157 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
4158 exit(1);
4159 }
4160 loadedkeys++;
4161 /* Set the expire time if needed */
4162 if (expiretime != -1) setExpire(db,key,expiretime);
4163
4164 /* Handle swapping while loading big datasets when VM is on */
4165
4166 /* If we detecter we are hopeless about fitting something in memory
4167 * we just swap every new key on disk. Directly...
4168 * Note that's important to check for this condition before resorting
4169 * to random sampling, otherwise we may try to swap already
4170 * swapped keys. */
4171 if (swap_all_values) {
4172 dictEntry *de = dictFind(d,key);
4173
4174 /* de may be NULL since the key already expired */
4175 if (de) {
4176 key = dictGetEntryKey(de);
4177 val = dictGetEntryVal(de);
4178
4179 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
4180 dictGetEntryVal(de) = NULL;
4181 }
4182 }
4183 continue;
4184 }
4185
4186 /* If we have still some hope of having some value fitting memory
4187 * then we try random sampling. */
4188 if (!swap_all_values && server.vm_enabled && (loadedkeys % 5000) == 0) {
4189 while (zmalloc_used_memory() > server.vm_max_memory) {
4190 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
4191 }
4192 if (zmalloc_used_memory() > server.vm_max_memory)
4193 swap_all_values = 1; /* We are already using too much mem */
4194 }
4195 }
4196 fclose(fp);
4197 return REDIS_OK;
4198
4199 eoferr: /* unexpected end of file is handled here with a fatal exit */
4200 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
4201 exit(1);
4202 return REDIS_ERR; /* Just to avoid warning */
4203 }
4204
4205 /*================================== Shutdown =============================== */
4206 static int prepareForShutdown() {
4207 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
4208 /* Kill the saving child if there is a background saving in progress.
4209 We want to avoid race conditions, for instance our saving child may
4210 overwrite the synchronous saving did by SHUTDOWN. */
4211 if (server.bgsavechildpid != -1) {
4212 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
4213 kill(server.bgsavechildpid,SIGKILL);
4214 rdbRemoveTempFile(server.bgsavechildpid);
4215 }
4216 if (server.appendonly) {
4217 /* Append only file: fsync() the AOF and exit */
4218 fsync(server.appendfd);
4219 if (server.vm_enabled) unlink(server.vm_swap_file);
4220 } else {
4221 /* Snapshotting. Perform a SYNC SAVE and exit */
4222 if (rdbSave(server.dbfilename) == REDIS_OK) {
4223 if (server.daemonize)
4224 unlink(server.pidfile);
4225 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
4226 } else {
4227 /* Ooops.. error saving! The best we can do is to continue
4228 * operating. Note that if there was a background saving process,
4229 * in the next cron() Redis will be notified that the background
4230 * saving aborted, handling special stuff like slaves pending for
4231 * synchronization... */
4232 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
4233 return REDIS_ERR;
4234 }
4235 }
4236 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
4237 return REDIS_OK;
4238 }
4239
4240 /*================================== Commands =============================== */
4241
4242 static void authCommand(redisClient *c) {
4243 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
4244 c->authenticated = 1;
4245 addReply(c,shared.ok);
4246 } else {
4247 c->authenticated = 0;
4248 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
4249 }
4250 }
4251
4252 static void pingCommand(redisClient *c) {
4253 addReply(c,shared.pong);
4254 }
4255
4256 static void echoCommand(redisClient *c) {
4257 addReplyBulk(c,c->argv[1]);
4258 }
4259
4260 /*=================================== Strings =============================== */
4261
4262 static void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
4263 int retval;
4264 long seconds = 0; /* initialized to avoid an harmness warning */
4265
4266 if (expire) {
4267 if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
4268 return;
4269 if (seconds <= 0) {
4270 addReplySds(c,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4271 return;
4272 }
4273 }
4274
4275 touchWatchedKey(c->db,key);
4276 if (nx) deleteIfVolatile(c->db,key);
4277 retval = dictAdd(c->db->dict,key,val);
4278 if (retval == DICT_ERR) {
4279 if (!nx) {
4280 /* If the key is about a swapped value, we want a new key object
4281 * to overwrite the old. So we delete the old key in the database.
4282 * This will also make sure that swap pages about the old object
4283 * will be marked as free. */
4284 if (server.vm_enabled && deleteIfSwapped(c->db,key))
4285 incrRefCount(key);
4286 dictReplace(c->db->dict,key,val);
4287 incrRefCount(val);
4288 } else {
4289 addReply(c,shared.czero);
4290 return;
4291 }
4292 } else {
4293 incrRefCount(key);
4294 incrRefCount(val);
4295 }
4296 server.dirty++;
4297 removeExpire(c->db,key);
4298 if (expire) setExpire(c->db,key,time(NULL)+seconds);
4299 addReply(c, nx ? shared.cone : shared.ok);
4300 }
4301
4302 static void setCommand(redisClient *c) {
4303 setGenericCommand(c,0,c->argv[1],c->argv[2],NULL);
4304 }
4305
4306 static void setnxCommand(redisClient *c) {
4307 setGenericCommand(c,1,c->argv[1],c->argv[2],NULL);
4308 }
4309
4310 static void setexCommand(redisClient *c) {
4311 setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
4312 }
4313
4314 static int getGenericCommand(redisClient *c) {
4315 robj *o;
4316
4317 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
4318 return REDIS_OK;
4319
4320 if (o->type != REDIS_STRING) {
4321 addReply(c,shared.wrongtypeerr);
4322 return REDIS_ERR;
4323 } else {
4324 addReplyBulk(c,o);
4325 return REDIS_OK;
4326 }
4327 }
4328
4329 static void getCommand(redisClient *c) {
4330 getGenericCommand(c);
4331 }
4332
4333 static void getsetCommand(redisClient *c) {
4334 if (getGenericCommand(c) == REDIS_ERR) return;
4335 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
4336 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
4337 } else {
4338 incrRefCount(c->argv[1]);
4339 }
4340 incrRefCount(c->argv[2]);
4341 server.dirty++;
4342 removeExpire(c->db,c->argv[1]);
4343 }
4344
4345 static void mgetCommand(redisClient *c) {
4346 int j;
4347
4348 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
4349 for (j = 1; j < c->argc; j++) {
4350 robj *o = lookupKeyRead(c->db,c->argv[j]);
4351 if (o == NULL) {
4352 addReply(c,shared.nullbulk);
4353 } else {
4354 if (o->type != REDIS_STRING) {
4355 addReply(c,shared.nullbulk);
4356 } else {
4357 addReplyBulk(c,o);
4358 }
4359 }
4360 }
4361 }
4362
4363 static void msetGenericCommand(redisClient *c, int nx) {
4364 int j, busykeys = 0;
4365
4366 if ((c->argc % 2) == 0) {
4367 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
4368 return;
4369 }
4370 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4371 * set nothing at all if at least one already key exists. */
4372 if (nx) {
4373 for (j = 1; j < c->argc; j += 2) {
4374 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
4375 busykeys++;
4376 }
4377 }
4378 }
4379 if (busykeys) {
4380 addReply(c, shared.czero);
4381 return;
4382 }
4383
4384 for (j = 1; j < c->argc; j += 2) {
4385 int retval;
4386
4387 c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
4388 retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
4389 if (retval == DICT_ERR) {
4390 dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
4391 incrRefCount(c->argv[j+1]);
4392 } else {
4393 incrRefCount(c->argv[j]);
4394 incrRefCount(c->argv[j+1]);
4395 }
4396 removeExpire(c->db,c->argv[j]);
4397 }
4398 server.dirty += (c->argc-1)/2;
4399 addReply(c, nx ? shared.cone : shared.ok);
4400 }
4401
4402 static void msetCommand(redisClient *c) {
4403 msetGenericCommand(c,0);
4404 }
4405
4406 static void msetnxCommand(redisClient *c) {
4407 msetGenericCommand(c,1);
4408 }
4409
4410 static void incrDecrCommand(redisClient *c, long long incr) {
4411 long long value;
4412 int retval;
4413 robj *o;
4414
4415 o = lookupKeyWrite(c->db,c->argv[1]);
4416 if (o != NULL && checkType(c,o,REDIS_STRING)) return;
4417 if (getLongLongFromObjectOrReply(c,o,&value,NULL) != REDIS_OK) return;
4418
4419 value += incr;
4420 o = createStringObjectFromLongLong(value);
4421 retval = dictAdd(c->db->dict,c->argv[1],o);
4422 if (retval == DICT_ERR) {
4423 dictReplace(c->db->dict,c->argv[1],o);
4424 removeExpire(c->db,c->argv[1]);
4425 } else {
4426 incrRefCount(c->argv[1]);
4427 }
4428 server.dirty++;
4429 addReply(c,shared.colon);
4430 addReply(c,o);
4431 addReply(c,shared.crlf);
4432 }
4433
4434 static void incrCommand(redisClient *c) {
4435 incrDecrCommand(c,1);
4436 }
4437
4438 static void decrCommand(redisClient *c) {
4439 incrDecrCommand(c,-1);
4440 }
4441
4442 static void incrbyCommand(redisClient *c) {
4443 long long incr;
4444
4445 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
4446 incrDecrCommand(c,incr);
4447 }
4448
4449 static void decrbyCommand(redisClient *c) {
4450 long long incr;
4451
4452 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
4453 incrDecrCommand(c,-incr);
4454 }
4455
4456 static void appendCommand(redisClient *c) {
4457 int retval;
4458 size_t totlen;
4459 robj *o;
4460
4461 o = lookupKeyWrite(c->db,c->argv[1]);
4462 if (o == NULL) {
4463 /* Create the key */
4464 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
4465 incrRefCount(c->argv[1]);
4466 incrRefCount(c->argv[2]);
4467 totlen = stringObjectLen(c->argv[2]);
4468 } else {
4469 dictEntry *de;
4470
4471 de = dictFind(c->db->dict,c->argv[1]);
4472 assert(de != NULL);
4473
4474 o = dictGetEntryVal(de);
4475 if (o->type != REDIS_STRING) {
4476 addReply(c,shared.wrongtypeerr);
4477 return;
4478 }
4479 /* If the object is specially encoded or shared we have to make
4480 * a copy */
4481 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
4482 robj *decoded = getDecodedObject(o);
4483
4484 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
4485 decrRefCount(decoded);
4486 dictReplace(c->db->dict,c->argv[1],o);
4487 }
4488 /* APPEND! */
4489 if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
4490 o->ptr = sdscatlen(o->ptr,
4491 c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
4492 } else {
4493 o->ptr = sdscatprintf(o->ptr, "%ld",
4494 (unsigned long) c->argv[2]->ptr);
4495 }
4496 totlen = sdslen(o->ptr);
4497 }
4498 server.dirty++;
4499 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
4500 }
4501
4502 static void substrCommand(redisClient *c) {
4503 robj *o;
4504 long start = atoi(c->argv[2]->ptr);
4505 long end = atoi(c->argv[3]->ptr);
4506 size_t rangelen, strlen;
4507 sds range;
4508
4509 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4510 checkType(c,o,REDIS_STRING)) return;
4511
4512 o = getDecodedObject(o);
4513 strlen = sdslen(o->ptr);
4514
4515 /* convert negative indexes */
4516 if (start < 0) start = strlen+start;
4517 if (end < 0) end = strlen+end;
4518 if (start < 0) start = 0;
4519 if (end < 0) end = 0;
4520
4521 /* indexes sanity checks */
4522 if (start > end || (size_t)start >= strlen) {
4523 /* Out of range start or start > end result in null reply */
4524 addReply(c,shared.nullbulk);
4525 decrRefCount(o);
4526 return;
4527 }
4528 if ((size_t)end >= strlen) end = strlen-1;
4529 rangelen = (end-start)+1;
4530
4531 /* Return the result */
4532 addReplySds(c,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen));
4533 range = sdsnewlen((char*)o->ptr+start,rangelen);
4534 addReplySds(c,range);
4535 addReply(c,shared.crlf);
4536 decrRefCount(o);
4537 }
4538
4539 /* ========================= Type agnostic commands ========================= */
4540
4541 static void delCommand(redisClient *c) {
4542 int deleted = 0, j;
4543
4544 for (j = 1; j < c->argc; j++) {
4545 if (deleteKey(c->db,c->argv[j])) {
4546 touchWatchedKey(c->db,c->argv[j]);
4547 server.dirty++;
4548 deleted++;
4549 }
4550 }
4551 addReplyLongLong(c,deleted);
4552 }
4553
4554 static void existsCommand(redisClient *c) {
4555 expireIfNeeded(c->db,c->argv[1]);
4556 if (dictFind(c->db->dict,c->argv[1])) {
4557 addReply(c, shared.cone);
4558 } else {
4559 addReply(c, shared.czero);
4560 }
4561 }
4562
4563 static void selectCommand(redisClient *c) {
4564 int id = atoi(c->argv[1]->ptr);
4565
4566 if (selectDb(c,id) == REDIS_ERR) {
4567 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
4568 } else {
4569 addReply(c,shared.ok);
4570 }
4571 }
4572
4573 static void randomkeyCommand(redisClient *c) {
4574 dictEntry *de;
4575 robj *key;
4576
4577 while(1) {
4578 de = dictGetRandomKey(c->db->dict);
4579 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
4580 }
4581
4582 if (de == NULL) {
4583 addReply(c,shared.nullbulk);
4584 return;
4585 }
4586
4587 key = dictGetEntryKey(de);
4588 if (server.vm_enabled) {
4589 key = dupStringObject(key);
4590 addReplyBulk(c,key);
4591 decrRefCount(key);
4592 } else {
4593 addReplyBulk(c,key);
4594 }
4595 }
4596
4597 static void keysCommand(redisClient *c) {
4598 dictIterator *di;
4599 dictEntry *de;
4600 sds pattern = c->argv[1]->ptr;
4601 int plen = sdslen(pattern);
4602 unsigned long numkeys = 0;
4603 robj *lenobj = createObject(REDIS_STRING,NULL);
4604
4605 di = dictGetIterator(c->db->dict);
4606 addReply(c,lenobj);
4607 decrRefCount(lenobj);
4608 while((de = dictNext(di)) != NULL) {
4609 robj *keyobj = dictGetEntryKey(de);
4610
4611 sds key = keyobj->ptr;
4612 if ((pattern[0] == '*' && pattern[1] == '\0') ||
4613 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
4614 if (expireIfNeeded(c->db,keyobj) == 0) {
4615 addReplyBulk(c,keyobj);
4616 numkeys++;
4617 }
4618 }
4619 }
4620 dictReleaseIterator(di);
4621 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
4622 }
4623
4624 static void dbsizeCommand(redisClient *c) {
4625 addReplySds(c,
4626 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
4627 }
4628
4629 static void lastsaveCommand(redisClient *c) {
4630 addReplySds(c,
4631 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
4632 }
4633
4634 static void typeCommand(redisClient *c) {
4635 robj *o;
4636 char *type;
4637
4638 o = lookupKeyRead(c->db,c->argv[1]);
4639 if (o == NULL) {
4640 type = "+none";
4641 } else {
4642 switch(o->type) {
4643 case REDIS_STRING: type = "+string"; break;
4644 case REDIS_LIST: type = "+list"; break;
4645 case REDIS_SET: type = "+set"; break;
4646 case REDIS_ZSET: type = "+zset"; break;
4647 case REDIS_HASH: type = "+hash"; break;
4648 default: type = "+unknown"; break;
4649 }
4650 }
4651 addReplySds(c,sdsnew(type));
4652 addReply(c,shared.crlf);
4653 }
4654
4655 static void saveCommand(redisClient *c) {
4656 if (server.bgsavechildpid != -1) {
4657 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
4658 return;
4659 }
4660 if (rdbSave(server.dbfilename) == REDIS_OK) {
4661 addReply(c,shared.ok);
4662 } else {
4663 addReply(c,shared.err);
4664 }
4665 }
4666
4667 static void bgsaveCommand(redisClient *c) {
4668 if (server.bgsavechildpid != -1) {
4669 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
4670 return;
4671 }
4672 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
4673 char *status = "+Background saving started\r\n";
4674 addReplySds(c,sdsnew(status));
4675 } else {
4676 addReply(c,shared.err);
4677 }
4678 }
4679
4680 static void shutdownCommand(redisClient *c) {
4681 if (prepareForShutdown() == REDIS_OK)
4682 exit(0);
4683 addReplySds(c, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
4684 }
4685
4686 static void renameGenericCommand(redisClient *c, int nx) {
4687 robj *o;
4688
4689 /* To use the same key as src and dst is probably an error */
4690 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
4691 addReply(c,shared.sameobjecterr);
4692 return;
4693 }
4694
4695 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
4696 return;
4697
4698 incrRefCount(o);
4699 deleteIfVolatile(c->db,c->argv[2]);
4700 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
4701 if (nx) {
4702 decrRefCount(o);
4703 addReply(c,shared.czero);
4704 return;
4705 }
4706 dictReplace(c->db->dict,c->argv[2],o);
4707 } else {
4708 incrRefCount(c->argv[2]);
4709 }
4710 deleteKey(c->db,c->argv[1]);
4711 touchWatchedKey(c->db,c->argv[2]);
4712 server.dirty++;
4713 addReply(c,nx ? shared.cone : shared.ok);
4714 }
4715
4716 static void renameCommand(redisClient *c) {
4717 renameGenericCommand(c,0);
4718 }
4719
4720 static void renamenxCommand(redisClient *c) {
4721 renameGenericCommand(c,1);
4722 }
4723
4724 static void moveCommand(redisClient *c) {
4725 robj *o;
4726 redisDb *src, *dst;
4727 int srcid;
4728
4729 /* Obtain source and target DB pointers */
4730 src = c->db;
4731 srcid = c->db->id;
4732 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
4733 addReply(c,shared.outofrangeerr);
4734 return;
4735 }
4736 dst = c->db;
4737 selectDb(c,srcid); /* Back to the source DB */
4738
4739 /* If the user is moving using as target the same
4740 * DB as the source DB it is probably an error. */
4741 if (src == dst) {
4742 addReply(c,shared.sameobjecterr);
4743 return;
4744 }
4745
4746 /* Check if the element exists and get a reference */
4747 o = lookupKeyWrite(c->db,c->argv[1]);
4748 if (!o) {
4749 addReply(c,shared.czero);
4750 return;
4751 }
4752
4753 /* Try to add the element to the target DB */
4754 deleteIfVolatile(dst,c->argv[1]);
4755 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
4756 addReply(c,shared.czero);
4757 return;
4758 }
4759 incrRefCount(c->argv[1]);
4760 incrRefCount(o);
4761
4762 /* OK! key moved, free the entry in the source DB */
4763 deleteKey(src,c->argv[1]);
4764 server.dirty++;
4765 addReply(c,shared.cone);
4766 }
4767
4768 /* =================================== Lists ================================ */
4769 static void lPush(robj *subject, robj *value, int where) {
4770 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4771 int pos = (where == REDIS_HEAD) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
4772 value = getDecodedObject(value);
4773 subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),pos);
4774 decrRefCount(value);
4775 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4776 if (where == REDIS_HEAD) {
4777 listAddNodeHead(subject->ptr,value);
4778 } else {
4779 listAddNodeTail(subject->ptr,value);
4780 }
4781 incrRefCount(value);
4782 } else {
4783 redisPanic("Unknown list encoding");
4784 }
4785 }
4786
4787 static robj *lPop(robj *subject, int where) {
4788 robj *value = NULL;
4789 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4790 unsigned char *p;
4791 unsigned char *vstr;
4792 unsigned int vlen;
4793 long long vlong;
4794 int pos = (where == REDIS_HEAD) ? 0 : -1;
4795 p = ziplistIndex(subject->ptr,pos);
4796 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
4797 if (vstr) {
4798 value = createStringObject((char*)vstr,vlen);
4799 } else {
4800 value = createStringObjectFromLongLong(vlong);
4801 }
4802 /* We only need to delete an element when it exists */
4803 subject->ptr = ziplistDelete(subject->ptr,&p);
4804 }
4805 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4806 list *list = subject->ptr;
4807 listNode *ln;
4808 if (where == REDIS_HEAD) {
4809 ln = listFirst(list);
4810 } else {
4811 ln = listLast(list);
4812 }
4813 if (ln != NULL) {
4814 value = listNodeValue(ln);
4815 incrRefCount(value);
4816 listDelNode(list,ln);
4817 }
4818 } else {
4819 redisPanic("Unknown list encoding");
4820 }
4821 return value;
4822 }
4823
4824 static unsigned long lLength(robj *subject) {
4825 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4826 return ziplistLen(subject->ptr);
4827 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4828 return listLength((list*)subject->ptr);
4829 } else {
4830 redisPanic("Unknown list encoding");
4831 }
4832 }
4833
4834 /* Structure to hold set iteration abstraction. */
4835 typedef struct {
4836 robj *subject;
4837 unsigned char encoding;
4838 unsigned char direction; /* Iteration direction */
4839 unsigned char *zi;
4840 listNode *ln;
4841 } lIterator;
4842
4843 /* Structure for an entry while iterating over a list. */
4844 typedef struct {
4845 lIterator *li;
4846 unsigned char *zi; /* Entry in ziplist */
4847 listNode *ln; /* Entry in linked list */
4848 } lEntry;
4849
4850 /* Initialize an iterator at the specified index. */
4851 static lIterator *lInitIterator(robj *subject, int index, unsigned char direction) {
4852 lIterator *li = zmalloc(sizeof(lIterator));
4853 li->subject = subject;
4854 li->encoding = subject->encoding;
4855 li->direction = direction;
4856 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4857 li->zi = ziplistIndex(subject->ptr,index);
4858 } else if (li->encoding == REDIS_ENCODING_LIST) {
4859 li->ln = listIndex(subject->ptr,index);
4860 } else {
4861 redisPanic("Unknown list encoding");
4862 }
4863 return li;
4864 }
4865
4866 /* Clean up the iterator. */
4867 static void lReleaseIterator(lIterator *li) {
4868 zfree(li);
4869 }
4870
4871 /* Stores pointer to current the entry in the provided entry structure
4872 * and advances the position of the iterator. Returns 1 when the current
4873 * entry is in fact an entry, 0 otherwise. */
4874 static int lNext(lIterator *li, lEntry *entry) {
4875 entry->li = li;
4876 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4877 entry->zi = li->zi;
4878 if (entry->zi != NULL) {
4879 if (li->direction == REDIS_TAIL)
4880 li->zi = ziplistNext(li->subject->ptr,li->zi);
4881 else
4882 li->zi = ziplistPrev(li->subject->ptr,li->zi);
4883 return 1;
4884 }
4885 } else if (li->encoding == REDIS_ENCODING_LIST) {
4886 entry->ln = li->ln;
4887 if (entry->ln != NULL) {
4888 if (li->direction == REDIS_TAIL)
4889 li->ln = li->ln->next;
4890 else
4891 li->ln = li->ln->prev;
4892 return 1;
4893 }
4894 } else {
4895 redisPanic("Unknown list encoding");
4896 }
4897 return 0;
4898 }
4899
4900 /* Return entry or NULL at the current position of the iterator. */
4901 static robj *lGet(lEntry *entry) {
4902 lIterator *li = entry->li;
4903 robj *value = NULL;
4904 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4905 unsigned char *vstr;
4906 unsigned int vlen;
4907 long long vlong;
4908 redisAssert(entry->zi != NULL);
4909 if (ziplistGet(entry->zi,&vstr,&vlen,&vlong)) {
4910 if (vstr) {
4911 value = createStringObject((char*)vstr,vlen);
4912 } else {
4913 value = createStringObjectFromLongLong(vlong);
4914 }
4915 }
4916 } else if (li->encoding == REDIS_ENCODING_LIST) {
4917 redisAssert(entry->ln != NULL);
4918 value = listNodeValue(entry->ln);
4919 incrRefCount(value);
4920 } else {
4921 redisPanic("Unknown list encoding");
4922 }
4923 return value;
4924 }
4925
4926 /* Compare the given object with the entry at the current position. */
4927 static int lEqual(lEntry *entry, robj *o) {
4928 lIterator *li = entry->li;
4929 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4930 redisAssert(o->encoding == REDIS_ENCODING_RAW);
4931 return ziplistCompare(entry->zi,o->ptr,sdslen(o->ptr));
4932 } else if (li->encoding == REDIS_ENCODING_LIST) {
4933 return equalStringObjects(o,listNodeValue(entry->ln));
4934 } else {
4935 redisPanic("Unknown list encoding");
4936 }
4937 }
4938
4939 /* Delete the element pointed to. */
4940 static void lDelete(lEntry *entry) {
4941 lIterator *li = entry->li;
4942 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4943 unsigned char *p = entry->zi;
4944 li->subject->ptr = ziplistDelete(li->subject->ptr,&p);
4945
4946 /* Update position of the iterator depending on the direction */
4947 if (li->direction == REDIS_TAIL)
4948 li->zi = p;
4949 else
4950 li->zi = ziplistPrev(li->subject->ptr,p);
4951 } else if (entry->li->encoding == REDIS_ENCODING_LIST) {
4952 listNode *next;
4953 if (li->direction == REDIS_TAIL)
4954 next = entry->ln->next;
4955 else
4956 next = entry->ln->prev;
4957 listDelNode(li->subject->ptr,entry->ln);
4958 li->ln = next;
4959 } else {
4960 redisPanic("Unknown list encoding");
4961 }
4962 }
4963
4964 static void pushGenericCommand(redisClient *c, int where) {
4965 robj *lobj = lookupKeyWrite(c->db,c->argv[1]);
4966 if (lobj == NULL) {
4967 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
4968 addReply(c,shared.cone);
4969 return;
4970 }
4971 lobj = createObject(REDIS_LIST,ziplistNew());
4972 lobj->encoding = REDIS_ENCODING_ZIPLIST;
4973 dictAdd(c->db->dict,c->argv[1],lobj);
4974 incrRefCount(c->argv[1]);
4975 } else {
4976 if (lobj->type != REDIS_LIST) {
4977 addReply(c,shared.wrongtypeerr);
4978 return;
4979 }
4980 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
4981 addReply(c,shared.cone);
4982 return;
4983 }
4984 }
4985 lPush(lobj,c->argv[2],where);
4986 addReplyLongLong(c,lLength(lobj));
4987 server.dirty++;
4988 }
4989
4990 static void lpushCommand(redisClient *c) {
4991 pushGenericCommand(c,REDIS_HEAD);
4992 }
4993
4994 static void rpushCommand(redisClient *c) {
4995 pushGenericCommand(c,REDIS_TAIL);
4996 }
4997
4998 static void llenCommand(redisClient *c) {
4999 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.czero);
5000 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5001 addReplyUlong(c,lLength(o));
5002 }
5003
5004 static void lindexCommand(redisClient *c) {
5005 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk);
5006 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5007 int index = atoi(c->argv[2]->ptr);
5008 robj *value = NULL;
5009
5010 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5011 unsigned char *p;
5012 unsigned char *vstr;
5013 unsigned int vlen;
5014 long long vlong;
5015 p = ziplistIndex(o->ptr,index);
5016 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
5017 if (vstr) {
5018 value = createStringObject((char*)vstr,vlen);
5019 } else {
5020 value = createStringObjectFromLongLong(vlong);
5021 }
5022 addReplyBulk(c,value);
5023 decrRefCount(value);
5024 } else {
5025 addReply(c,shared.nullbulk);
5026 }
5027 } else if (o->encoding == REDIS_ENCODING_LIST) {
5028 listNode *ln = listIndex(o->ptr,index);
5029 if (ln != NULL) {
5030 value = listNodeValue(ln);
5031 addReplyBulk(c,value);
5032 } else {
5033 addReply(c,shared.nullbulk);
5034 }
5035 } else {
5036 redisPanic("Unknown list encoding");
5037 }
5038 }
5039
5040 static void lsetCommand(redisClient *c) {
5041 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr);
5042 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5043 int index = atoi(c->argv[2]->ptr);
5044 robj *value = c->argv[3];
5045
5046 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5047 unsigned char *p, *zl = o->ptr;
5048 p = ziplistIndex(zl,index);
5049 if (p == NULL) {
5050 addReply(c,shared.outofrangeerr);
5051 } else {
5052 o->ptr = ziplistDelete(o->ptr,&p);
5053 value = getDecodedObject(value);
5054 o->ptr = ziplistInsert(o->ptr,p,value->ptr,sdslen(value->ptr));
5055 decrRefCount(value);
5056 addReply(c,shared.ok);
5057 server.dirty++;
5058 }
5059 } else if (o->encoding == REDIS_ENCODING_LIST) {
5060 listNode *ln = listIndex(o->ptr,index);
5061 if (ln == NULL) {
5062 addReply(c,shared.outofrangeerr);
5063 } else {
5064 decrRefCount((robj*)listNodeValue(ln));
5065 listNodeValue(ln) = value;
5066 incrRefCount(value);
5067 addReply(c,shared.ok);
5068 server.dirty++;
5069 }
5070 } else {
5071 redisPanic("Unknown list encoding");
5072 }
5073 }
5074
5075 static void popGenericCommand(redisClient *c, int where) {
5076 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk);
5077 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5078
5079 robj *value = lPop(o,where);
5080 if (value == NULL) {
5081 addReply(c,shared.nullbulk);
5082 } else {
5083 addReplyBulk(c,value);
5084 decrRefCount(value);
5085 if (lLength(o) == 0) deleteKey(c->db,c->argv[1]);
5086 server.dirty++;
5087 }
5088 }
5089
5090 static void lpopCommand(redisClient *c) {
5091 popGenericCommand(c,REDIS_HEAD);
5092 }
5093
5094 static void rpopCommand(redisClient *c) {
5095 popGenericCommand(c,REDIS_TAIL);
5096 }
5097
5098 static void lrangeCommand(redisClient *c) {
5099 robj *o, *value;
5100 int start = atoi(c->argv[2]->ptr);
5101 int end = atoi(c->argv[3]->ptr);
5102 int llen;
5103 int rangelen, j;
5104 lEntry entry;
5105
5106 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
5107 || checkType(c,o,REDIS_LIST)) return;
5108 llen = lLength(o);
5109
5110 /* convert negative indexes */
5111 if (start < 0) start = llen+start;
5112 if (end < 0) end = llen+end;
5113 if (start < 0) start = 0;
5114 if (end < 0) end = 0;
5115
5116 /* indexes sanity checks */
5117 if (start > end || start >= llen) {
5118 /* Out of range start or start > end result in empty list */
5119 addReply(c,shared.emptymultibulk);
5120 return;
5121 }
5122 if (end >= llen) end = llen-1;
5123 rangelen = (end-start)+1;
5124
5125 /* Return the result in form of a multi-bulk reply */
5126 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
5127 lIterator *li = lInitIterator(o,start,REDIS_TAIL);
5128 for (j = 0; j < rangelen; j++) {
5129 redisAssert(lNext(li,&entry));
5130 value = lGet(&entry);
5131 addReplyBulk(c,value);
5132 decrRefCount(value);
5133 }
5134 lReleaseIterator(li);
5135 }
5136
5137 static void ltrimCommand(redisClient *c) {
5138 robj *o;
5139 int start = atoi(c->argv[2]->ptr);
5140 int end = atoi(c->argv[3]->ptr);
5141 int llen;
5142 int j, ltrim, rtrim;
5143 list *list;
5144 listNode *ln;
5145
5146 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
5147 checkType(c,o,REDIS_LIST)) return;
5148 llen = lLength(o);
5149
5150 /* convert negative indexes */
5151 if (start < 0) start = llen+start;
5152 if (end < 0) end = llen+end;
5153 if (start < 0) start = 0;
5154 if (end < 0) end = 0;
5155
5156 /* indexes sanity checks */
5157 if (start > end || start >= llen) {
5158 /* Out of range start or start > end result in empty list */
5159 ltrim = llen;
5160 rtrim = 0;
5161 } else {
5162 if (end >= llen) end = llen-1;
5163 ltrim = start;
5164 rtrim = llen-end-1;
5165 }
5166
5167 /* Remove list elements to perform the trim */
5168 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5169 o->ptr = ziplistDeleteRange(o->ptr,0,ltrim);
5170 o->ptr = ziplistDeleteRange(o->ptr,-rtrim,rtrim);
5171 } else if (o->encoding == REDIS_ENCODING_LIST) {
5172 list = o->ptr;
5173 for (j = 0; j < ltrim; j++) {
5174 ln = listFirst(list);
5175 listDelNode(list,ln);
5176 }
5177 for (j = 0; j < rtrim; j++) {
5178 ln = listLast(list);
5179 listDelNode(list,ln);
5180 }
5181 } else {
5182 redisPanic("Unknown list encoding");
5183 }
5184 if (lLength(o) == 0) deleteKey(c->db,c->argv[1]);
5185 server.dirty++;
5186 addReply(c,shared.ok);
5187 }
5188
5189 static void lremCommand(redisClient *c) {
5190 robj *subject, *obj = c->argv[3];
5191 int toremove = atoi(c->argv[2]->ptr);
5192 int removed = 0;
5193 lEntry entry;
5194
5195 subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero);
5196 if (subject == NULL || checkType(c,subject,REDIS_LIST)) return;
5197
5198 /* Make sure obj is raw when we're dealing with a ziplist */
5199 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
5200 obj = getDecodedObject(obj);
5201
5202 lIterator *li;
5203 if (toremove < 0) {
5204 toremove = -toremove;
5205 li = lInitIterator(subject,-1,REDIS_HEAD);
5206 } else {
5207 li = lInitIterator(subject,0,REDIS_TAIL);
5208 }
5209
5210 while (lNext(li,&entry)) {
5211 if (lEqual(&entry,obj)) {
5212 lDelete(&entry);
5213 server.dirty++;
5214 removed++;
5215 if (toremove && removed == toremove) break;
5216 }
5217 }
5218 lReleaseIterator(li);
5219
5220 /* Clean up raw encoded object */
5221 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
5222 decrRefCount(obj);
5223
5224 if (lLength(subject) == 0) deleteKey(c->db,c->argv[1]);
5225 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
5226 }
5227
5228 /* This is the semantic of this command:
5229 * RPOPLPUSH srclist dstlist:
5230 * IF LLEN(srclist) > 0
5231 * element = RPOP srclist
5232 * LPUSH dstlist element
5233 * RETURN element
5234 * ELSE
5235 * RETURN nil
5236 * END
5237 * END
5238 *
5239 * The idea is to be able to get an element from a list in a reliable way
5240 * since the element is not just returned but pushed against another list
5241 * as well. This command was originally proposed by Ezra Zygmuntowicz.
5242 */
5243 static void rpoplpushcommand(redisClient *c) {
5244 robj *sobj, *value;
5245 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5246 checkType(c,sobj,REDIS_LIST)) return;
5247
5248 if (lLength(sobj) == 0) {
5249 addReply(c,shared.nullbulk);
5250 } else {
5251 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
5252 if (dobj && checkType(c,dobj,REDIS_LIST)) return;
5253 value = lPop(sobj,REDIS_TAIL);
5254
5255 /* Add the element to the target list (unless it's directly
5256 * passed to some BLPOP-ing client */
5257 if (!handleClientsWaitingListPush(c,c->argv[2],value)) {
5258 /* Create the list if the key does not exist */
5259 if (!dobj) {
5260 dobj = createObject(REDIS_LIST,ziplistNew());
5261 dobj->encoding = REDIS_ENCODING_ZIPLIST;
5262 dictAdd(c->db->dict,c->argv[2],dobj);
5263 incrRefCount(c->argv[2]);
5264 }
5265 lPush(dobj,value,REDIS_HEAD);
5266 }
5267
5268 /* Send the element to the client as reply as well */
5269 addReplyBulk(c,value);
5270
5271 /* lPop returns an object with its refcount incremented */
5272 decrRefCount(value);
5273
5274 /* Delete the source list when it is empty */
5275 if (lLength(sobj) == 0) deleteKey(c->db,c->argv[1]);
5276 server.dirty++;
5277 }
5278 }
5279
5280 /* ==================================== Sets ================================ */
5281
5282 static void saddCommand(redisClient *c) {
5283 robj *set;
5284
5285 set = lookupKeyWrite(c->db,c->argv[1]);
5286 if (set == NULL) {
5287 set = createSetObject();
5288 dictAdd(c->db->dict,c->argv[1],set);
5289 incrRefCount(c->argv[1]);
5290 } else {
5291 if (set->type != REDIS_SET) {
5292 addReply(c,shared.wrongtypeerr);
5293 return;
5294 }
5295 }
5296 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
5297 incrRefCount(c->argv[2]);
5298 server.dirty++;
5299 addReply(c,shared.cone);
5300 } else {
5301 addReply(c,shared.czero);
5302 }
5303 }
5304
5305 static void sremCommand(redisClient *c) {
5306 robj *set;
5307
5308 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5309 checkType(c,set,REDIS_SET)) return;
5310
5311 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
5312 server.dirty++;
5313 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
5314 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
5315 addReply(c,shared.cone);
5316 } else {
5317 addReply(c,shared.czero);
5318 }
5319 }
5320
5321 static void smoveCommand(redisClient *c) {
5322 robj *srcset, *dstset;
5323
5324 srcset = lookupKeyWrite(c->db,c->argv[1]);
5325 dstset = lookupKeyWrite(c->db,c->argv[2]);
5326
5327 /* If the source key does not exist return 0, if it's of the wrong type
5328 * raise an error */
5329 if (srcset == NULL || srcset->type != REDIS_SET) {
5330 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
5331 return;
5332 }
5333 /* Error if the destination key is not a set as well */
5334 if (dstset && dstset->type != REDIS_SET) {
5335 addReply(c,shared.wrongtypeerr);
5336 return;
5337 }
5338 /* Remove the element from the source set */
5339 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
5340 /* Key not found in the src set! return zero */
5341 addReply(c,shared.czero);
5342 return;
5343 }
5344 if (dictSize((dict*)srcset->ptr) == 0 && srcset != dstset)
5345 deleteKey(c->db,c->argv[1]);
5346 server.dirty++;
5347 /* Add the element to the destination set */
5348 if (!dstset) {
5349 dstset = createSetObject();
5350 dictAdd(c->db->dict,c->argv[2],dstset);
5351 incrRefCount(c->argv[2]);
5352 }
5353 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
5354 incrRefCount(c->argv[3]);
5355 addReply(c,shared.cone);
5356 }
5357
5358 static void sismemberCommand(redisClient *c) {
5359 robj *set;
5360
5361 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5362 checkType(c,set,REDIS_SET)) return;
5363
5364 if (dictFind(set->ptr,c->argv[2]))
5365 addReply(c,shared.cone);
5366 else
5367 addReply(c,shared.czero);
5368 }
5369
5370 static void scardCommand(redisClient *c) {
5371 robj *o;
5372 dict *s;
5373
5374 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5375 checkType(c,o,REDIS_SET)) return;
5376
5377 s = o->ptr;
5378 addReplyUlong(c,dictSize(s));
5379 }
5380
5381 static void spopCommand(redisClient *c) {
5382 robj *set;
5383 dictEntry *de;
5384
5385 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5386 checkType(c,set,REDIS_SET)) return;
5387
5388 de = dictGetRandomKey(set->ptr);
5389 if (de == NULL) {
5390 addReply(c,shared.nullbulk);
5391 } else {
5392 robj *ele = dictGetEntryKey(de);
5393
5394 addReplyBulk(c,ele);
5395 dictDelete(set->ptr,ele);
5396 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
5397 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
5398 server.dirty++;
5399 }
5400 }
5401
5402 static void srandmemberCommand(redisClient *c) {
5403 robj *set;
5404 dictEntry *de;
5405
5406 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5407 checkType(c,set,REDIS_SET)) return;
5408
5409 de = dictGetRandomKey(set->ptr);
5410 if (de == NULL) {
5411 addReply(c,shared.nullbulk);
5412 } else {
5413 robj *ele = dictGetEntryKey(de);
5414
5415 addReplyBulk(c,ele);
5416 }
5417 }
5418
5419 static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
5420 dict **d1 = (void*) s1, **d2 = (void*) s2;
5421
5422 return dictSize(*d1)-dictSize(*d2);
5423 }
5424
5425 static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
5426 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5427 dictIterator *di;
5428 dictEntry *de;
5429 robj *lenobj = NULL, *dstset = NULL;
5430 unsigned long j, cardinality = 0;
5431
5432 for (j = 0; j < setsnum; j++) {
5433 robj *setobj;
5434
5435 setobj = dstkey ?
5436 lookupKeyWrite(c->db,setskeys[j]) :
5437 lookupKeyRead(c->db,setskeys[j]);
5438 if (!setobj) {
5439 zfree(dv);
5440 if (dstkey) {
5441 if (deleteKey(c->db,dstkey))
5442 server.dirty++;
5443 addReply(c,shared.czero);
5444 } else {
5445 addReply(c,shared.emptymultibulk);
5446 }
5447 return;
5448 }
5449 if (setobj->type != REDIS_SET) {
5450 zfree(dv);
5451 addReply(c,shared.wrongtypeerr);
5452 return;
5453 }
5454 dv[j] = setobj->ptr;
5455 }
5456 /* Sort sets from the smallest to largest, this will improve our
5457 * algorithm's performace */
5458 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
5459
5460 /* The first thing we should output is the total number of elements...
5461 * since this is a multi-bulk write, but at this stage we don't know
5462 * the intersection set size, so we use a trick, append an empty object
5463 * to the output list and save the pointer to later modify it with the
5464 * right length */
5465 if (!dstkey) {
5466 lenobj = createObject(REDIS_STRING,NULL);
5467 addReply(c,lenobj);
5468 decrRefCount(lenobj);
5469 } else {
5470 /* If we have a target key where to store the resulting set
5471 * create this key with an empty set inside */
5472 dstset = createSetObject();
5473 }
5474
5475 /* Iterate all the elements of the first (smallest) set, and test
5476 * the element against all the other sets, if at least one set does
5477 * not include the element it is discarded */
5478 di = dictGetIterator(dv[0]);
5479
5480 while((de = dictNext(di)) != NULL) {
5481 robj *ele;
5482
5483 for (j = 1; j < setsnum; j++)
5484 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
5485 if (j != setsnum)
5486 continue; /* at least one set does not contain the member */
5487 ele = dictGetEntryKey(de);
5488 if (!dstkey) {
5489 addReplyBulk(c,ele);
5490 cardinality++;
5491 } else {
5492 dictAdd(dstset->ptr,ele,NULL);
5493 incrRefCount(ele);
5494 }
5495 }
5496 dictReleaseIterator(di);
5497
5498 if (dstkey) {
5499 /* Store the resulting set into the target, if the intersection
5500 * is not an empty set. */
5501 deleteKey(c->db,dstkey);
5502 if (dictSize((dict*)dstset->ptr) > 0) {
5503 dictAdd(c->db->dict,dstkey,dstset);
5504 incrRefCount(dstkey);
5505 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
5506 } else {
5507 decrRefCount(dstset);
5508 addReply(c,shared.czero);
5509 }
5510 server.dirty++;
5511 } else {
5512 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
5513 }
5514 zfree(dv);
5515 }
5516
5517 static void sinterCommand(redisClient *c) {
5518 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
5519 }
5520
5521 static void sinterstoreCommand(redisClient *c) {
5522 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
5523 }
5524
5525 #define REDIS_OP_UNION 0
5526 #define REDIS_OP_DIFF 1
5527 #define REDIS_OP_INTER 2
5528
5529 static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
5530 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5531 dictIterator *di;
5532 dictEntry *de;
5533 robj *dstset = NULL;
5534 int j, cardinality = 0;
5535
5536 for (j = 0; j < setsnum; j++) {
5537 robj *setobj;
5538
5539 setobj = dstkey ?
5540 lookupKeyWrite(c->db,setskeys[j]) :
5541 lookupKeyRead(c->db,setskeys[j]);
5542 if (!setobj) {
5543 dv[j] = NULL;
5544 continue;
5545 }
5546 if (setobj->type != REDIS_SET) {
5547 zfree(dv);
5548 addReply(c,shared.wrongtypeerr);
5549 return;
5550 }
5551 dv[j] = setobj->ptr;
5552 }
5553
5554 /* We need a temp set object to store our union. If the dstkey
5555 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5556 * this set object will be the resulting object to set into the target key*/
5557 dstset = createSetObject();
5558
5559 /* Iterate all the elements of all the sets, add every element a single
5560 * time to the result set */
5561 for (j = 0; j < setsnum; j++) {
5562 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
5563 if (!dv[j]) continue; /* non existing keys are like empty sets */
5564
5565 di = dictGetIterator(dv[j]);
5566
5567 while((de = dictNext(di)) != NULL) {
5568 robj *ele;
5569
5570 /* dictAdd will not add the same element multiple times */
5571 ele = dictGetEntryKey(de);
5572 if (op == REDIS_OP_UNION || j == 0) {
5573 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
5574 incrRefCount(ele);
5575 cardinality++;
5576 }
5577 } else if (op == REDIS_OP_DIFF) {
5578 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
5579 cardinality--;
5580 }
5581 }
5582 }
5583 dictReleaseIterator(di);
5584
5585 /* result set is empty? Exit asap. */
5586 if (op == REDIS_OP_DIFF && cardinality == 0) break;
5587 }
5588
5589 /* Output the content of the resulting set, if not in STORE mode */
5590 if (!dstkey) {
5591 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
5592 di = dictGetIterator(dstset->ptr);
5593 while((de = dictNext(di)) != NULL) {
5594 robj *ele;
5595
5596 ele = dictGetEntryKey(de);
5597 addReplyBulk(c,ele);
5598 }
5599 dictReleaseIterator(di);
5600 decrRefCount(dstset);
5601 } else {
5602 /* If we have a target key where to store the resulting set
5603 * create this key with the result set inside */
5604 deleteKey(c->db,dstkey);
5605 if (dictSize((dict*)dstset->ptr) > 0) {
5606 dictAdd(c->db->dict,dstkey,dstset);
5607 incrRefCount(dstkey);
5608 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
5609 } else {
5610 decrRefCount(dstset);
5611 addReply(c,shared.czero);
5612 }
5613 server.dirty++;
5614 }
5615 zfree(dv);
5616 }
5617
5618 static void sunionCommand(redisClient *c) {
5619 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
5620 }
5621
5622 static void sunionstoreCommand(redisClient *c) {
5623 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
5624 }
5625
5626 static void sdiffCommand(redisClient *c) {
5627 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
5628 }
5629
5630 static void sdiffstoreCommand(redisClient *c) {
5631 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
5632 }
5633
5634 /* ==================================== ZSets =============================== */
5635
5636 /* ZSETs are ordered sets using two data structures to hold the same elements
5637 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5638 * data structure.
5639 *
5640 * The elements are added to an hash table mapping Redis objects to scores.
5641 * At the same time the elements are added to a skip list mapping scores
5642 * to Redis objects (so objects are sorted by scores in this "view"). */
5643
5644 /* This skiplist implementation is almost a C translation of the original
5645 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5646 * Alternative to Balanced Trees", modified in three ways:
5647 * a) this implementation allows for repeated values.
5648 * b) the comparison is not just by key (our 'score') but by satellite data.
5649 * c) there is a back pointer, so it's a doubly linked list with the back
5650 * pointers being only at "level 1". This allows to traverse the list
5651 * from tail to head, useful for ZREVRANGE. */
5652
5653 static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
5654 zskiplistNode *zn = zmalloc(sizeof(*zn));
5655
5656 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
5657 if (level > 1)
5658 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
5659 else
5660 zn->span = NULL;
5661 zn->score = score;
5662 zn->obj = obj;
5663 return zn;
5664 }
5665
5666 static zskiplist *zslCreate(void) {
5667 int j;
5668 zskiplist *zsl;
5669
5670 zsl = zmalloc(sizeof(*zsl));
5671 zsl->level = 1;
5672 zsl->length = 0;
5673 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
5674 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
5675 zsl->header->forward[j] = NULL;
5676
5677 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5678 if (j < ZSKIPLIST_MAXLEVEL-1)
5679 zsl->header->span[j] = 0;
5680 }
5681 zsl->header->backward = NULL;
5682 zsl->tail = NULL;
5683 return zsl;
5684 }
5685
5686 static void zslFreeNode(zskiplistNode *node) {
5687 decrRefCount(node->obj);
5688 zfree(node->forward);
5689 zfree(node->span);
5690 zfree(node);
5691 }
5692
5693 static void zslFree(zskiplist *zsl) {
5694 zskiplistNode *node = zsl->header->forward[0], *next;
5695
5696 zfree(zsl->header->forward);
5697 zfree(zsl->header->span);
5698 zfree(zsl->header);
5699 while(node) {
5700 next = node->forward[0];
5701 zslFreeNode(node);
5702 node = next;
5703 }
5704 zfree(zsl);
5705 }
5706
5707 static int zslRandomLevel(void) {
5708 int level = 1;
5709 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
5710 level += 1;
5711 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
5712 }
5713
5714 static void zslInsert(zskiplist *zsl, double score, robj *obj) {
5715 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5716 unsigned int rank[ZSKIPLIST_MAXLEVEL];
5717 int i, level;
5718
5719 x = zsl->header;
5720 for (i = zsl->level-1; i >= 0; i--) {
5721 /* store rank that is crossed to reach the insert position */
5722 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
5723
5724 while (x->forward[i] &&
5725 (x->forward[i]->score < score ||
5726 (x->forward[i]->score == score &&
5727 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
5728 rank[i] += i > 0 ? x->span[i-1] : 1;
5729 x = x->forward[i];
5730 }
5731 update[i] = x;
5732 }
5733 /* we assume the key is not already inside, since we allow duplicated
5734 * scores, and the re-insertion of score and redis object should never
5735 * happpen since the caller of zslInsert() should test in the hash table
5736 * if the element is already inside or not. */
5737 level = zslRandomLevel();
5738 if (level > zsl->level) {
5739 for (i = zsl->level; i < level; i++) {
5740 rank[i] = 0;
5741 update[i] = zsl->header;
5742 update[i]->span[i-1] = zsl->length;
5743 }
5744 zsl->level = level;
5745 }
5746 x = zslCreateNode(level,score,obj);
5747 for (i = 0; i < level; i++) {
5748 x->forward[i] = update[i]->forward[i];
5749 update[i]->forward[i] = x;
5750
5751 /* update span covered by update[i] as x is inserted here */
5752 if (i > 0) {
5753 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
5754 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
5755 }
5756 }
5757
5758 /* increment span for untouched levels */
5759 for (i = level; i < zsl->level; i++) {
5760 update[i]->span[i-1]++;
5761 }
5762
5763 x->backward = (update[0] == zsl->header) ? NULL : update[0];
5764 if (x->forward[0])
5765 x->forward[0]->backward = x;
5766 else
5767 zsl->tail = x;
5768 zsl->length++;
5769 }
5770
5771 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5772 void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
5773 int i;
5774 for (i = 0; i < zsl->level; i++) {
5775 if (update[i]->forward[i] == x) {
5776 if (i > 0) {
5777 update[i]->span[i-1] += x->span[i-1] - 1;
5778 }
5779 update[i]->forward[i] = x->forward[i];
5780 } else {
5781 /* invariant: i > 0, because update[0]->forward[0]
5782 * is always equal to x */
5783 update[i]->span[i-1] -= 1;
5784 }
5785 }
5786 if (x->forward[0]) {
5787 x->forward[0]->backward = x->backward;
5788 } else {
5789 zsl->tail = x->backward;
5790 }
5791 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
5792 zsl->level--;
5793 zsl->length--;
5794 }
5795
5796 /* Delete an element with matching score/object from the skiplist. */
5797 static int zslDelete(zskiplist *zsl, double score, robj *obj) {
5798 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5799 int i;
5800
5801 x = zsl->header;
5802 for (i = zsl->level-1; i >= 0; i--) {
5803 while (x->forward[i] &&
5804 (x->forward[i]->score < score ||
5805 (x->forward[i]->score == score &&
5806 compareStringObjects(x->forward[i]->obj,obj) < 0)))
5807 x = x->forward[i];
5808 update[i] = x;
5809 }
5810 /* We may have multiple elements with the same score, what we need
5811 * is to find the element with both the right score and object. */
5812 x = x->forward[0];
5813 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
5814 zslDeleteNode(zsl, x, update);
5815 zslFreeNode(x);
5816 return 1;
5817 } else {
5818 return 0; /* not found */
5819 }
5820 return 0; /* not found */
5821 }
5822
5823 /* Delete all the elements with score between min and max from the skiplist.
5824 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5825 * Note that this function takes the reference to the hash table view of the
5826 * sorted set, in order to remove the elements from the hash table too. */
5827 static unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
5828 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5829 unsigned long removed = 0;
5830 int i;
5831
5832 x = zsl->header;
5833 for (i = zsl->level-1; i >= 0; i--) {
5834 while (x->forward[i] && x->forward[i]->score < min)
5835 x = x->forward[i];
5836 update[i] = x;
5837 }
5838 /* We may have multiple elements with the same score, what we need
5839 * is to find the element with both the right score and object. */
5840 x = x->forward[0];
5841 while (x && x->score <= max) {
5842 zskiplistNode *next = x->forward[0];
5843 zslDeleteNode(zsl, x, update);
5844 dictDelete(dict,x->obj);
5845 zslFreeNode(x);
5846 removed++;
5847 x = next;
5848 }
5849 return removed; /* not found */
5850 }
5851
5852 /* Delete all the elements with rank between start and end from the skiplist.
5853 * Start and end are inclusive. Note that start and end need to be 1-based */
5854 static unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
5855 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5856 unsigned long traversed = 0, removed = 0;
5857 int i;
5858
5859 x = zsl->header;
5860 for (i = zsl->level-1; i >= 0; i--) {
5861 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
5862 traversed += i > 0 ? x->span[i-1] : 1;
5863 x = x->forward[i];
5864 }
5865 update[i] = x;
5866 }
5867
5868 traversed++;
5869 x = x->forward[0];
5870 while (x && traversed <= end) {
5871 zskiplistNode *next = x->forward[0];
5872 zslDeleteNode(zsl, x, update);
5873 dictDelete(dict,x->obj);
5874 zslFreeNode(x);
5875 removed++;
5876 traversed++;
5877 x = next;
5878 }
5879 return removed;
5880 }
5881
5882 /* Find the first node having a score equal or greater than the specified one.
5883 * Returns NULL if there is no match. */
5884 static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
5885 zskiplistNode *x;
5886 int i;
5887
5888 x = zsl->header;
5889 for (i = zsl->level-1; i >= 0; i--) {
5890 while (x->forward[i] && x->forward[i]->score < score)
5891 x = x->forward[i];
5892 }
5893 /* We may have multiple elements with the same score, what we need
5894 * is to find the element with both the right score and object. */
5895 return x->forward[0];
5896 }
5897
5898 /* Find the rank for an element by both score and key.
5899 * Returns 0 when the element cannot be found, rank otherwise.
5900 * Note that the rank is 1-based due to the span of zsl->header to the
5901 * first element. */
5902 static unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
5903 zskiplistNode *x;
5904 unsigned long rank = 0;
5905 int i;
5906
5907 x = zsl->header;
5908 for (i = zsl->level-1; i >= 0; i--) {
5909 while (x->forward[i] &&
5910 (x->forward[i]->score < score ||
5911 (x->forward[i]->score == score &&
5912 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
5913 rank += i > 0 ? x->span[i-1] : 1;
5914 x = x->forward[i];
5915 }
5916
5917 /* x might be equal to zsl->header, so test if obj is non-NULL */
5918 if (x->obj && equalStringObjects(x->obj,o)) {
5919 return rank;
5920 }
5921 }
5922 return 0;
5923 }
5924
5925 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5926 zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
5927 zskiplistNode *x;
5928 unsigned long traversed = 0;
5929 int i;
5930
5931 x = zsl->header;
5932 for (i = zsl->level-1; i >= 0; i--) {
5933 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
5934 {
5935 traversed += i > 0 ? x->span[i-1] : 1;
5936 x = x->forward[i];
5937 }
5938 if (traversed == rank) {
5939 return x;
5940 }
5941 }
5942 return NULL;
5943 }
5944
5945 /* The actual Z-commands implementations */
5946
5947 /* This generic command implements both ZADD and ZINCRBY.
5948 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5949 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5950 static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
5951 robj *zsetobj;
5952 zset *zs;
5953 double *score;
5954
5955 if (isnan(scoreval)) {
5956 addReplySds(c,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
5957 return;
5958 }
5959
5960 zsetobj = lookupKeyWrite(c->db,key);
5961 if (zsetobj == NULL) {
5962 zsetobj = createZsetObject();
5963 dictAdd(c->db->dict,key,zsetobj);
5964 incrRefCount(key);
5965 } else {
5966 if (zsetobj->type != REDIS_ZSET) {
5967 addReply(c,shared.wrongtypeerr);
5968 return;
5969 }
5970 }
5971 zs = zsetobj->ptr;
5972
5973 /* Ok now since we implement both ZADD and ZINCRBY here the code
5974 * needs to handle the two different conditions. It's all about setting
5975 * '*score', that is, the new score to set, to the right value. */
5976 score = zmalloc(sizeof(double));
5977 if (doincrement) {
5978 dictEntry *de;
5979
5980 /* Read the old score. If the element was not present starts from 0 */
5981 de = dictFind(zs->dict,ele);
5982 if (de) {
5983 double *oldscore = dictGetEntryVal(de);
5984 *score = *oldscore + scoreval;
5985 } else {
5986 *score = scoreval;
5987 }
5988 if (isnan(*score)) {
5989 addReplySds(c,
5990 sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
5991 zfree(score);
5992 /* Note that we don't need to check if the zset may be empty and
5993 * should be removed here, as we can only obtain Nan as score if
5994 * there was already an element in the sorted set. */
5995 return;
5996 }
5997 } else {
5998 *score = scoreval;
5999 }
6000
6001 /* What follows is a simple remove and re-insert operation that is common
6002 * to both ZADD and ZINCRBY... */
6003 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
6004 /* case 1: New element */
6005 incrRefCount(ele); /* added to hash */
6006 zslInsert(zs->zsl,*score,ele);
6007 incrRefCount(ele); /* added to skiplist */
6008 server.dirty++;
6009 if (doincrement)
6010 addReplyDouble(c,*score);
6011 else
6012 addReply(c,shared.cone);
6013 } else {
6014 dictEntry *de;
6015 double *oldscore;
6016
6017 /* case 2: Score update operation */
6018 de = dictFind(zs->dict,ele);
6019 redisAssert(de != NULL);
6020 oldscore = dictGetEntryVal(de);
6021 if (*score != *oldscore) {
6022 int deleted;
6023
6024 /* Remove and insert the element in the skip list with new score */
6025 deleted = zslDelete(zs->zsl,*oldscore,ele);
6026 redisAssert(deleted != 0);
6027 zslInsert(zs->zsl,*score,ele);
6028 incrRefCount(ele);
6029 /* Update the score in the hash table */
6030 dictReplace(zs->dict,ele,score);
6031 server.dirty++;
6032 } else {
6033 zfree(score);
6034 }
6035 if (doincrement)
6036 addReplyDouble(c,*score);
6037 else
6038 addReply(c,shared.czero);
6039 }
6040 }
6041
6042 static void zaddCommand(redisClient *c) {
6043 double scoreval;
6044
6045 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
6046 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
6047 }
6048
6049 static void zincrbyCommand(redisClient *c) {
6050 double scoreval;
6051
6052 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
6053 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
6054 }
6055
6056 static void zremCommand(redisClient *c) {
6057 robj *zsetobj;
6058 zset *zs;
6059 dictEntry *de;
6060 double *oldscore;
6061 int deleted;
6062
6063 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6064 checkType(c,zsetobj,REDIS_ZSET)) return;
6065
6066 zs = zsetobj->ptr;
6067 de = dictFind(zs->dict,c->argv[2]);
6068 if (de == NULL) {
6069 addReply(c,shared.czero);
6070 return;
6071 }
6072 /* Delete from the skiplist */
6073 oldscore = dictGetEntryVal(de);
6074 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
6075 redisAssert(deleted != 0);
6076
6077 /* Delete from the hash table */
6078 dictDelete(zs->dict,c->argv[2]);
6079 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
6080 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
6081 server.dirty++;
6082 addReply(c,shared.cone);
6083 }
6084
6085 static void zremrangebyscoreCommand(redisClient *c) {
6086 double min;
6087 double max;
6088 long deleted;
6089 robj *zsetobj;
6090 zset *zs;
6091
6092 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
6093 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
6094
6095 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6096 checkType(c,zsetobj,REDIS_ZSET)) return;
6097
6098 zs = zsetobj->ptr;
6099 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
6100 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
6101 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
6102 server.dirty += deleted;
6103 addReplyLongLong(c,deleted);
6104 }
6105
6106 static void zremrangebyrankCommand(redisClient *c) {
6107 long start;
6108 long end;
6109 int llen;
6110 long deleted;
6111 robj *zsetobj;
6112 zset *zs;
6113
6114 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6115 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
6116
6117 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6118 checkType(c,zsetobj,REDIS_ZSET)) return;
6119 zs = zsetobj->ptr;
6120 llen = zs->zsl->length;
6121
6122 /* convert negative indexes */
6123 if (start < 0) start = llen+start;
6124 if (end < 0) end = llen+end;
6125 if (start < 0) start = 0;
6126 if (end < 0) end = 0;
6127
6128 /* indexes sanity checks */
6129 if (start > end || start >= llen) {
6130 addReply(c,shared.czero);
6131 return;
6132 }
6133 if (end >= llen) end = llen-1;
6134
6135 /* increment start and end because zsl*Rank functions
6136 * use 1-based rank */
6137 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
6138 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
6139 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
6140 server.dirty += deleted;
6141 addReplyLongLong(c, deleted);
6142 }
6143
6144 typedef struct {
6145 dict *dict;
6146 double weight;
6147 } zsetopsrc;
6148
6149 static int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
6150 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
6151 unsigned long size1, size2;
6152 size1 = d1->dict ? dictSize(d1->dict) : 0;
6153 size2 = d2->dict ? dictSize(d2->dict) : 0;
6154 return size1 - size2;
6155 }
6156
6157 #define REDIS_AGGR_SUM 1
6158 #define REDIS_AGGR_MIN 2
6159 #define REDIS_AGGR_MAX 3
6160 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
6161
6162 inline static void zunionInterAggregate(double *target, double val, int aggregate) {
6163 if (aggregate == REDIS_AGGR_SUM) {
6164 *target = *target + val;
6165 } else if (aggregate == REDIS_AGGR_MIN) {
6166 *target = val < *target ? val : *target;
6167 } else if (aggregate == REDIS_AGGR_MAX) {
6168 *target = val > *target ? val : *target;
6169 } else {
6170 /* safety net */
6171 redisPanic("Unknown ZUNION/INTER aggregate type");
6172 }
6173 }
6174
6175 static void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
6176 int i, j, setnum;
6177 int aggregate = REDIS_AGGR_SUM;
6178 zsetopsrc *src;
6179 robj *dstobj;
6180 zset *dstzset;
6181 dictIterator *di;
6182 dictEntry *de;
6183
6184 /* expect setnum input keys to be given */
6185 setnum = atoi(c->argv[2]->ptr);
6186 if (setnum < 1) {
6187 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
6188 return;
6189 }
6190
6191 /* test if the expected number of keys would overflow */
6192 if (3+setnum > c->argc) {
6193 addReply(c,shared.syntaxerr);
6194 return;
6195 }
6196
6197 /* read keys to be used for input */
6198 src = zmalloc(sizeof(zsetopsrc) * setnum);
6199 for (i = 0, j = 3; i < setnum; i++, j++) {
6200 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
6201 if (!obj) {
6202 src[i].dict = NULL;
6203 } else {
6204 if (obj->type == REDIS_ZSET) {
6205 src[i].dict = ((zset*)obj->ptr)->dict;
6206 } else if (obj->type == REDIS_SET) {
6207 src[i].dict = (obj->ptr);
6208 } else {
6209 zfree(src);
6210 addReply(c,shared.wrongtypeerr);
6211 return;
6212 }
6213 }
6214
6215 /* default all weights to 1 */
6216 src[i].weight = 1.0;
6217 }
6218
6219 /* parse optional extra arguments */
6220 if (j < c->argc) {
6221 int remaining = c->argc - j;
6222
6223 while (remaining) {
6224 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
6225 j++; remaining--;
6226 for (i = 0; i < setnum; i++, j++, remaining--) {
6227 if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK)
6228 return;
6229 }
6230 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
6231 j++; remaining--;
6232 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
6233 aggregate = REDIS_AGGR_SUM;
6234 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
6235 aggregate = REDIS_AGGR_MIN;
6236 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
6237 aggregate = REDIS_AGGR_MAX;
6238 } else {
6239 zfree(src);
6240 addReply(c,shared.syntaxerr);
6241 return;
6242 }
6243 j++; remaining--;
6244 } else {
6245 zfree(src);
6246 addReply(c,shared.syntaxerr);
6247 return;
6248 }
6249 }
6250 }
6251
6252 /* sort sets from the smallest to largest, this will improve our
6253 * algorithm's performance */
6254 qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);
6255
6256 dstobj = createZsetObject();
6257 dstzset = dstobj->ptr;
6258
6259 if (op == REDIS_OP_INTER) {
6260 /* skip going over all entries if the smallest zset is NULL or empty */
6261 if (src[0].dict && dictSize(src[0].dict) > 0) {
6262 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6263 * from small to large, all src[i > 0].dict are non-empty too */
6264 di = dictGetIterator(src[0].dict);
6265 while((de = dictNext(di)) != NULL) {
6266 double *score = zmalloc(sizeof(double)), value;
6267 *score = src[0].weight * zunionInterDictValue(de);
6268
6269 for (j = 1; j < setnum; j++) {
6270 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
6271 if (other) {
6272 value = src[j].weight * zunionInterDictValue(other);
6273 zunionInterAggregate(score, value, aggregate);
6274 } else {
6275 break;
6276 }
6277 }
6278
6279 /* skip entry when not present in every source dict */
6280 if (j != setnum) {
6281 zfree(score);
6282 } else {
6283 robj *o = dictGetEntryKey(de);
6284 dictAdd(dstzset->dict,o,score);
6285 incrRefCount(o); /* added to dictionary */
6286 zslInsert(dstzset->zsl,*score,o);
6287 incrRefCount(o); /* added to skiplist */
6288 }
6289 }
6290 dictReleaseIterator(di);
6291 }
6292 } else if (op == REDIS_OP_UNION) {
6293 for (i = 0; i < setnum; i++) {
6294 if (!src[i].dict) continue;
6295
6296 di = dictGetIterator(src[i].dict);
6297 while((de = dictNext(di)) != NULL) {
6298 /* skip key when already processed */
6299 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
6300
6301 double *score = zmalloc(sizeof(double)), value;
6302 *score = src[i].weight * zunionInterDictValue(de);
6303
6304 /* because the zsets are sorted by size, its only possible
6305 * for sets at larger indices to hold this entry */
6306 for (j = (i+1); j < setnum; j++) {
6307 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
6308 if (other) {
6309 value = src[j].weight * zunionInterDictValue(other);
6310 zunionInterAggregate(score, value, aggregate);
6311 }
6312 }
6313
6314 robj *o = dictGetEntryKey(de);
6315 dictAdd(dstzset->dict,o,score);
6316 incrRefCount(o); /* added to dictionary */
6317 zslInsert(dstzset->zsl,*score,o);
6318 incrRefCount(o); /* added to skiplist */
6319 }
6320 dictReleaseIterator(di);
6321 }
6322 } else {
6323 /* unknown operator */
6324 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
6325 }
6326
6327 deleteKey(c->db,dstkey);
6328 if (dstzset->zsl->length) {
6329 dictAdd(c->db->dict,dstkey,dstobj);
6330 incrRefCount(dstkey);
6331 addReplyLongLong(c, dstzset->zsl->length);
6332 server.dirty++;
6333 } else {
6334 decrRefCount(dstobj);
6335 addReply(c, shared.czero);
6336 }
6337 zfree(src);
6338 }
6339
6340 static void zunionstoreCommand(redisClient *c) {
6341 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
6342 }
6343
6344 static void zinterstoreCommand(redisClient *c) {
6345 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
6346 }
6347
6348 static void zrangeGenericCommand(redisClient *c, int reverse) {
6349 robj *o;
6350 long start;
6351 long end;
6352 int withscores = 0;
6353 int llen;
6354 int rangelen, j;
6355 zset *zsetobj;
6356 zskiplist *zsl;
6357 zskiplistNode *ln;
6358 robj *ele;
6359
6360 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6361 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
6362
6363 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
6364 withscores = 1;
6365 } else if (c->argc >= 5) {
6366 addReply(c,shared.syntaxerr);
6367 return;
6368 }
6369
6370 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6371 || checkType(c,o,REDIS_ZSET)) return;
6372 zsetobj = o->ptr;
6373 zsl = zsetobj->zsl;
6374 llen = zsl->length;
6375
6376 /* convert negative indexes */
6377 if (start < 0) start = llen+start;
6378 if (end < 0) end = llen+end;
6379 if (start < 0) start = 0;
6380 if (end < 0) end = 0;
6381
6382 /* indexes sanity checks */
6383 if (start > end || start >= llen) {
6384 /* Out of range start or start > end result in empty list */
6385 addReply(c,shared.emptymultibulk);
6386 return;
6387 }
6388 if (end >= llen) end = llen-1;
6389 rangelen = (end-start)+1;
6390
6391 /* check if starting point is trivial, before searching
6392 * the element in log(N) time */
6393 if (reverse) {
6394 ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start);
6395 } else {
6396 ln = start == 0 ?
6397 zsl->header->forward[0] : zslGetElementByRank(zsl, start+1);
6398 }
6399
6400 /* Return the result in form of a multi-bulk reply */
6401 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
6402 withscores ? (rangelen*2) : rangelen));
6403 for (j = 0; j < rangelen; j++) {
6404 ele = ln->obj;
6405 addReplyBulk(c,ele);
6406 if (withscores)
6407 addReplyDouble(c,ln->score);
6408 ln = reverse ? ln->backward : ln->forward[0];
6409 }
6410 }
6411
6412 static void zrangeCommand(redisClient *c) {
6413 zrangeGenericCommand(c,0);
6414 }
6415
6416 static void zrevrangeCommand(redisClient *c) {
6417 zrangeGenericCommand(c,1);
6418 }
6419
6420 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
6421 * If justcount is non-zero, just the count is returned. */
6422 static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
6423 robj *o;
6424 double min, max;
6425 int minex = 0, maxex = 0; /* are min or max exclusive? */
6426 int offset = 0, limit = -1;
6427 int withscores = 0;
6428 int badsyntax = 0;
6429
6430 /* Parse the min-max interval. If one of the values is prefixed
6431 * by the "(" character, it's considered "open". For instance
6432 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6433 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6434 if (((char*)c->argv[2]->ptr)[0] == '(') {
6435 min = strtod((char*)c->argv[2]->ptr+1,NULL);
6436 minex = 1;
6437 } else {
6438 min = strtod(c->argv[2]->ptr,NULL);
6439 }
6440 if (((char*)c->argv[3]->ptr)[0] == '(') {
6441 max = strtod((char*)c->argv[3]->ptr+1,NULL);
6442 maxex = 1;
6443 } else {
6444 max = strtod(c->argv[3]->ptr,NULL);
6445 }
6446
6447 /* Parse "WITHSCORES": note that if the command was called with
6448 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6449 * enter the following paths to parse WITHSCORES and LIMIT. */
6450 if (c->argc == 5 || c->argc == 8) {
6451 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
6452 withscores = 1;
6453 else
6454 badsyntax = 1;
6455 }
6456 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
6457 badsyntax = 1;
6458 if (badsyntax) {
6459 addReplySds(c,
6460 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
6461 return;
6462 }
6463
6464 /* Parse "LIMIT" */
6465 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
6466 addReply(c,shared.syntaxerr);
6467 return;
6468 } else if (c->argc == (7 + withscores)) {
6469 offset = atoi(c->argv[5]->ptr);
6470 limit = atoi(c->argv[6]->ptr);
6471 if (offset < 0) offset = 0;
6472 }
6473
6474 /* Ok, lookup the key and get the range */
6475 o = lookupKeyRead(c->db,c->argv[1]);
6476 if (o == NULL) {
6477 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
6478 } else {
6479 if (o->type != REDIS_ZSET) {
6480 addReply(c,shared.wrongtypeerr);
6481 } else {
6482 zset *zsetobj = o->ptr;
6483 zskiplist *zsl = zsetobj->zsl;
6484 zskiplistNode *ln;
6485 robj *ele, *lenobj = NULL;
6486 unsigned long rangelen = 0;
6487
6488 /* Get the first node with the score >= min, or with
6489 * score > min if 'minex' is true. */
6490 ln = zslFirstWithScore(zsl,min);
6491 while (minex && ln && ln->score == min) ln = ln->forward[0];
6492
6493 if (ln == NULL) {
6494 /* No element matching the speciifed interval */
6495 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
6496 return;
6497 }
6498
6499 /* We don't know in advance how many matching elements there
6500 * are in the list, so we push this object that will represent
6501 * the multi-bulk length in the output buffer, and will "fix"
6502 * it later */
6503 if (!justcount) {
6504 lenobj = createObject(REDIS_STRING,NULL);
6505 addReply(c,lenobj);
6506 decrRefCount(lenobj);
6507 }
6508
6509 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
6510 if (offset) {
6511 offset--;
6512 ln = ln->forward[0];
6513 continue;
6514 }
6515 if (limit == 0) break;
6516 if (!justcount) {
6517 ele = ln->obj;
6518 addReplyBulk(c,ele);
6519 if (withscores)
6520 addReplyDouble(c,ln->score);
6521 }
6522 ln = ln->forward[0];
6523 rangelen++;
6524 if (limit > 0) limit--;
6525 }
6526 if (justcount) {
6527 addReplyLongLong(c,(long)rangelen);
6528 } else {
6529 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
6530 withscores ? (rangelen*2) : rangelen);
6531 }
6532 }
6533 }
6534 }
6535
6536 static void zrangebyscoreCommand(redisClient *c) {
6537 genericZrangebyscoreCommand(c,0);
6538 }
6539
6540 static void zcountCommand(redisClient *c) {
6541 genericZrangebyscoreCommand(c,1);
6542 }
6543
6544 static void zcardCommand(redisClient *c) {
6545 robj *o;
6546 zset *zs;
6547
6548 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6549 checkType(c,o,REDIS_ZSET)) return;
6550
6551 zs = o->ptr;
6552 addReplyUlong(c,zs->zsl->length);
6553 }
6554
6555 static void zscoreCommand(redisClient *c) {
6556 robj *o;
6557 zset *zs;
6558 dictEntry *de;
6559
6560 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6561 checkType(c,o,REDIS_ZSET)) return;
6562
6563 zs = o->ptr;
6564 de = dictFind(zs->dict,c->argv[2]);
6565 if (!de) {
6566 addReply(c,shared.nullbulk);
6567 } else {
6568 double *score = dictGetEntryVal(de);
6569
6570 addReplyDouble(c,*score);
6571 }
6572 }
6573
6574 static void zrankGenericCommand(redisClient *c, int reverse) {
6575 robj *o;
6576 zset *zs;
6577 zskiplist *zsl;
6578 dictEntry *de;
6579 unsigned long rank;
6580 double *score;
6581
6582 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6583 checkType(c,o,REDIS_ZSET)) return;
6584
6585 zs = o->ptr;
6586 zsl = zs->zsl;
6587 de = dictFind(zs->dict,c->argv[2]);
6588 if (!de) {
6589 addReply(c,shared.nullbulk);
6590 return;
6591 }
6592
6593 score = dictGetEntryVal(de);
6594 rank = zslGetRank(zsl, *score, c->argv[2]);
6595 if (rank) {
6596 if (reverse) {
6597 addReplyLongLong(c, zsl->length - rank);
6598 } else {
6599 addReplyLongLong(c, rank-1);
6600 }
6601 } else {
6602 addReply(c,shared.nullbulk);
6603 }
6604 }
6605
6606 static void zrankCommand(redisClient *c) {
6607 zrankGenericCommand(c, 0);
6608 }
6609
6610 static void zrevrankCommand(redisClient *c) {
6611 zrankGenericCommand(c, 1);
6612 }
6613
6614 /* ========================= Hashes utility functions ======================= */
6615 #define REDIS_HASH_KEY 1
6616 #define REDIS_HASH_VALUE 2
6617
6618 /* Check the length of a number of objects to see if we need to convert a
6619 * zipmap to a real hash. Note that we only check string encoded objects
6620 * as their string length can be queried in constant time. */
6621 static void hashTryConversion(robj *subject, robj **argv, int start, int end) {
6622 int i;
6623 if (subject->encoding != REDIS_ENCODING_ZIPMAP) return;
6624
6625 for (i = start; i <= end; i++) {
6626 if (argv[i]->encoding == REDIS_ENCODING_RAW &&
6627 sdslen(argv[i]->ptr) > server.hash_max_zipmap_value)
6628 {
6629 convertToRealHash(subject);
6630 return;
6631 }
6632 }
6633 }
6634
6635 /* Encode given objects in-place when the hash uses a dict. */
6636 static void hashTryObjectEncoding(robj *subject, robj **o1, robj **o2) {
6637 if (subject->encoding == REDIS_ENCODING_HT) {
6638 if (o1) *o1 = tryObjectEncoding(*o1);
6639 if (o2) *o2 = tryObjectEncoding(*o2);
6640 }
6641 }
6642
6643 /* Get the value from a hash identified by key. Returns either a string
6644 * object or NULL if the value cannot be found. The refcount of the object
6645 * is always increased by 1 when the value was found. */
6646 static robj *hashGet(robj *o, robj *key) {
6647 robj *value = NULL;
6648 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6649 unsigned char *v;
6650 unsigned int vlen;
6651 key = getDecodedObject(key);
6652 if (zipmapGet(o->ptr,key->ptr,sdslen(key->ptr),&v,&vlen)) {
6653 value = createStringObject((char*)v,vlen);
6654 }
6655 decrRefCount(key);
6656 } else {
6657 dictEntry *de = dictFind(o->ptr,key);
6658 if (de != NULL) {
6659 value = dictGetEntryVal(de);
6660 incrRefCount(value);
6661 }
6662 }
6663 return value;
6664 }
6665
6666 /* Test if the key exists in the given hash. Returns 1 if the key
6667 * exists and 0 when it doesn't. */
6668 static int hashExists(robj *o, robj *key) {
6669 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6670 key = getDecodedObject(key);
6671 if (zipmapExists(o->ptr,key->ptr,sdslen(key->ptr))) {
6672 decrRefCount(key);
6673 return 1;
6674 }
6675 decrRefCount(key);
6676 } else {
6677 if (dictFind(o->ptr,key) != NULL) {
6678 return 1;
6679 }
6680 }
6681 return 0;
6682 }
6683
6684 /* Add an element, discard the old if the key already exists.
6685 * Return 0 on insert and 1 on update. */
6686 static int hashSet(robj *o, robj *key, robj *value) {
6687 int update = 0;
6688 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6689 key = getDecodedObject(key);
6690 value = getDecodedObject(value);
6691 o->ptr = zipmapSet(o->ptr,
6692 key->ptr,sdslen(key->ptr),
6693 value->ptr,sdslen(value->ptr), &update);
6694 decrRefCount(key);
6695 decrRefCount(value);
6696
6697 /* Check if the zipmap needs to be upgraded to a real hash table */
6698 if (zipmapLen(o->ptr) > server.hash_max_zipmap_entries)
6699 convertToRealHash(o);
6700 } else {
6701 if (dictReplace(o->ptr,key,value)) {
6702 /* Insert */
6703 incrRefCount(key);
6704 } else {
6705 /* Update */
6706 update = 1;
6707 }
6708 incrRefCount(value);
6709 }
6710 return update;
6711 }
6712
6713 /* Delete an element from a hash.
6714 * Return 1 on deleted and 0 on not found. */
6715 static int hashDelete(robj *o, robj *key) {
6716 int deleted = 0;
6717 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6718 key = getDecodedObject(key);
6719 o->ptr = zipmapDel(o->ptr,key->ptr,sdslen(key->ptr), &deleted);
6720 decrRefCount(key);
6721 } else {
6722 deleted = dictDelete((dict*)o->ptr,key) == DICT_OK;
6723 /* Always check if the dictionary needs a resize after a delete. */
6724 if (deleted && htNeedsResize(o->ptr)) dictResize(o->ptr);
6725 }
6726 return deleted;
6727 }
6728
6729 /* Return the number of elements in a hash. */
6730 static unsigned long hashLength(robj *o) {
6731 return (o->encoding == REDIS_ENCODING_ZIPMAP) ?
6732 zipmapLen((unsigned char*)o->ptr) : dictSize((dict*)o->ptr);
6733 }
6734
6735 /* Structure to hold hash iteration abstration. Note that iteration over
6736 * hashes involves both fields and values. Because it is possible that
6737 * not both are required, store pointers in the iterator to avoid
6738 * unnecessary memory allocation for fields/values. */
6739 typedef struct {
6740 int encoding;
6741 unsigned char *zi;
6742 unsigned char *zk, *zv;
6743 unsigned int zklen, zvlen;
6744
6745 dictIterator *di;
6746 dictEntry *de;
6747 } hashIterator;
6748
6749 static hashIterator *hashInitIterator(robj *subject) {
6750 hashIterator *hi = zmalloc(sizeof(hashIterator));
6751 hi->encoding = subject->encoding;
6752 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6753 hi->zi = zipmapRewind(subject->ptr);
6754 } else if (hi->encoding == REDIS_ENCODING_HT) {
6755 hi->di = dictGetIterator(subject->ptr);
6756 } else {
6757 redisAssert(NULL);
6758 }
6759 return hi;
6760 }
6761
6762 static void hashReleaseIterator(hashIterator *hi) {
6763 if (hi->encoding == REDIS_ENCODING_HT) {
6764 dictReleaseIterator(hi->di);
6765 }
6766 zfree(hi);
6767 }
6768
6769 /* Move to the next entry in the hash. Return REDIS_OK when the next entry
6770 * could be found and REDIS_ERR when the iterator reaches the end. */
6771 static int hashNext(hashIterator *hi) {
6772 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6773 if ((hi->zi = zipmapNext(hi->zi, &hi->zk, &hi->zklen,
6774 &hi->zv, &hi->zvlen)) == NULL) return REDIS_ERR;
6775 } else {
6776 if ((hi->de = dictNext(hi->di)) == NULL) return REDIS_ERR;
6777 }
6778 return REDIS_OK;
6779 }
6780
6781 /* Get key or value object at current iteration position.
6782 * This increases the refcount of the field object by 1. */
6783 static robj *hashCurrent(hashIterator *hi, int what) {
6784 robj *o;
6785 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6786 if (what & REDIS_HASH_KEY) {
6787 o = createStringObject((char*)hi->zk,hi->zklen);
6788 } else {
6789 o = createStringObject((char*)hi->zv,hi->zvlen);
6790 }
6791 } else {
6792 if (what & REDIS_HASH_KEY) {
6793 o = dictGetEntryKey(hi->de);
6794 } else {
6795 o = dictGetEntryVal(hi->de);
6796 }
6797 incrRefCount(o);
6798 }
6799 return o;
6800 }
6801
6802 static robj *hashLookupWriteOrCreate(redisClient *c, robj *key) {
6803 robj *o = lookupKeyWrite(c->db,key);
6804 if (o == NULL) {
6805 o = createHashObject();
6806 dictAdd(c->db->dict,key,o);
6807 incrRefCount(key);
6808 } else {
6809 if (o->type != REDIS_HASH) {
6810 addReply(c,shared.wrongtypeerr);
6811 return NULL;
6812 }
6813 }
6814 return o;
6815 }
6816
6817 /* ============================= Hash commands ============================== */
6818 static void hsetCommand(redisClient *c) {
6819 int update;
6820 robj *o;
6821
6822 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6823 hashTryConversion(o,c->argv,2,3);
6824 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
6825 update = hashSet(o,c->argv[2],c->argv[3]);
6826 addReply(c, update ? shared.czero : shared.cone);
6827 server.dirty++;
6828 }
6829
6830 static void hsetnxCommand(redisClient *c) {
6831 robj *o;
6832 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6833 hashTryConversion(o,c->argv,2,3);
6834
6835 if (hashExists(o, c->argv[2])) {
6836 addReply(c, shared.czero);
6837 } else {
6838 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
6839 hashSet(o,c->argv[2],c->argv[3]);
6840 addReply(c, shared.cone);
6841 server.dirty++;
6842 }
6843 }
6844
6845 static void hmsetCommand(redisClient *c) {
6846 int i;
6847 robj *o;
6848
6849 if ((c->argc % 2) == 1) {
6850 addReplySds(c,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6851 return;
6852 }
6853
6854 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6855 hashTryConversion(o,c->argv,2,c->argc-1);
6856 for (i = 2; i < c->argc; i += 2) {
6857 hashTryObjectEncoding(o,&c->argv[i], &c->argv[i+1]);
6858 hashSet(o,c->argv[i],c->argv[i+1]);
6859 }
6860 addReply(c, shared.ok);
6861 server.dirty++;
6862 }
6863
6864 static void hincrbyCommand(redisClient *c) {
6865 long long value, incr;
6866 robj *o, *current, *new;
6867
6868 if (getLongLongFromObjectOrReply(c,c->argv[3],&incr,NULL) != REDIS_OK) return;
6869 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6870 if ((current = hashGet(o,c->argv[2])) != NULL) {
6871 if (getLongLongFromObjectOrReply(c,current,&value,
6872 "hash value is not an integer") != REDIS_OK) {
6873 decrRefCount(current);
6874 return;
6875 }
6876 decrRefCount(current);
6877 } else {
6878 value = 0;
6879 }
6880
6881 value += incr;
6882 new = createStringObjectFromLongLong(value);
6883 hashTryObjectEncoding(o,&c->argv[2],NULL);
6884 hashSet(o,c->argv[2],new);
6885 decrRefCount(new);
6886 addReplyLongLong(c,value);
6887 server.dirty++;
6888 }
6889
6890 static void hgetCommand(redisClient *c) {
6891 robj *o, *value;
6892 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6893 checkType(c,o,REDIS_HASH)) return;
6894
6895 if ((value = hashGet(o,c->argv[2])) != NULL) {
6896 addReplyBulk(c,value);
6897 decrRefCount(value);
6898 } else {
6899 addReply(c,shared.nullbulk);
6900 }
6901 }
6902
6903 static void hmgetCommand(redisClient *c) {
6904 int i;
6905 robj *o, *value;
6906 o = lookupKeyRead(c->db,c->argv[1]);
6907 if (o != NULL && o->type != REDIS_HASH) {
6908 addReply(c,shared.wrongtypeerr);
6909 }
6910
6911 /* Note the check for o != NULL happens inside the loop. This is
6912 * done because objects that cannot be found are considered to be
6913 * an empty hash. The reply should then be a series of NULLs. */
6914 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-2));
6915 for (i = 2; i < c->argc; i++) {
6916 if (o != NULL && (value = hashGet(o,c->argv[i])) != NULL) {
6917 addReplyBulk(c,value);
6918 decrRefCount(value);
6919 } else {
6920 addReply(c,shared.nullbulk);
6921 }
6922 }
6923 }
6924
6925 static void hdelCommand(redisClient *c) {
6926 robj *o;
6927 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6928 checkType(c,o,REDIS_HASH)) return;
6929
6930 if (hashDelete(o,c->argv[2])) {
6931 if (hashLength(o) == 0) deleteKey(c->db,c->argv[1]);
6932 addReply(c,shared.cone);
6933 server.dirty++;
6934 } else {
6935 addReply(c,shared.czero);
6936 }
6937 }
6938
6939 static void hlenCommand(redisClient *c) {
6940 robj *o;
6941 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6942 checkType(c,o,REDIS_HASH)) return;
6943
6944 addReplyUlong(c,hashLength(o));
6945 }
6946
6947 static void genericHgetallCommand(redisClient *c, int flags) {
6948 robj *o, *lenobj, *obj;
6949 unsigned long count = 0;
6950 hashIterator *hi;
6951
6952 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6953 || checkType(c,o,REDIS_HASH)) return;
6954
6955 lenobj = createObject(REDIS_STRING,NULL);
6956 addReply(c,lenobj);
6957 decrRefCount(lenobj);
6958
6959 hi = hashInitIterator(o);
6960 while (hashNext(hi) != REDIS_ERR) {
6961 if (flags & REDIS_HASH_KEY) {
6962 obj = hashCurrent(hi,REDIS_HASH_KEY);
6963 addReplyBulk(c,obj);
6964 decrRefCount(obj);
6965 count++;
6966 }
6967 if (flags & REDIS_HASH_VALUE) {
6968 obj = hashCurrent(hi,REDIS_HASH_VALUE);
6969 addReplyBulk(c,obj);
6970 decrRefCount(obj);
6971 count++;
6972 }
6973 }
6974 hashReleaseIterator(hi);
6975
6976 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",count);
6977 }
6978
6979 static void hkeysCommand(redisClient *c) {
6980 genericHgetallCommand(c,REDIS_HASH_KEY);
6981 }
6982
6983 static void hvalsCommand(redisClient *c) {
6984 genericHgetallCommand(c,REDIS_HASH_VALUE);
6985 }
6986
6987 static void hgetallCommand(redisClient *c) {
6988 genericHgetallCommand(c,REDIS_HASH_KEY|REDIS_HASH_VALUE);
6989 }
6990
6991 static void hexistsCommand(redisClient *c) {
6992 robj *o;
6993 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6994 checkType(c,o,REDIS_HASH)) return;
6995
6996 addReply(c, hashExists(o,c->argv[2]) ? shared.cone : shared.czero);
6997 }
6998
6999 static void convertToRealHash(robj *o) {
7000 unsigned char *key, *val, *p, *zm = o->ptr;
7001 unsigned int klen, vlen;
7002 dict *dict = dictCreate(&hashDictType,NULL);
7003
7004 assert(o->type == REDIS_HASH && o->encoding != REDIS_ENCODING_HT);
7005 p = zipmapRewind(zm);
7006 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
7007 robj *keyobj, *valobj;
7008
7009 keyobj = createStringObject((char*)key,klen);
7010 valobj = createStringObject((char*)val,vlen);
7011 keyobj = tryObjectEncoding(keyobj);
7012 valobj = tryObjectEncoding(valobj);
7013 dictAdd(dict,keyobj,valobj);
7014 }
7015 o->encoding = REDIS_ENCODING_HT;
7016 o->ptr = dict;
7017 zfree(zm);
7018 }
7019
7020 /* ========================= Non type-specific commands ==================== */
7021
7022 static void flushdbCommand(redisClient *c) {
7023 server.dirty += dictSize(c->db->dict);
7024 touchWatchedKeysOnFlush(c->db->id);
7025 dictEmpty(c->db->dict);
7026 dictEmpty(c->db->expires);
7027 addReply(c,shared.ok);
7028 }
7029
7030 static void flushallCommand(redisClient *c) {
7031 touchWatchedKeysOnFlush(-1);
7032 server.dirty += emptyDb();
7033 addReply(c,shared.ok);
7034 if (server.bgsavechildpid != -1) {
7035 kill(server.bgsavechildpid,SIGKILL);
7036 rdbRemoveTempFile(server.bgsavechildpid);
7037 }
7038 rdbSave(server.dbfilename);
7039 server.dirty++;
7040 }
7041
7042 static redisSortOperation *createSortOperation(int type, robj *pattern) {
7043 redisSortOperation *so = zmalloc(sizeof(*so));
7044 so->type = type;
7045 so->pattern = pattern;
7046 return so;
7047 }
7048
7049 /* Return the value associated to the key with a name obtained
7050 * substituting the first occurence of '*' in 'pattern' with 'subst'.
7051 * The returned object will always have its refcount increased by 1
7052 * when it is non-NULL. */
7053 static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
7054 char *p, *f;
7055 sds spat, ssub;
7056 robj keyobj, fieldobj, *o;
7057 int prefixlen, sublen, postfixlen, fieldlen;
7058 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
7059 struct {
7060 long len;
7061 long free;
7062 char buf[REDIS_SORTKEY_MAX+1];
7063 } keyname, fieldname;
7064
7065 /* If the pattern is "#" return the substitution object itself in order
7066 * to implement the "SORT ... GET #" feature. */
7067 spat = pattern->ptr;
7068 if (spat[0] == '#' && spat[1] == '\0') {
7069 incrRefCount(subst);
7070 return subst;
7071 }
7072
7073 /* The substitution object may be specially encoded. If so we create
7074 * a decoded object on the fly. Otherwise getDecodedObject will just
7075 * increment the ref count, that we'll decrement later. */
7076 subst = getDecodedObject(subst);
7077
7078 ssub = subst->ptr;
7079 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
7080 p = strchr(spat,'*');
7081 if (!p) {
7082 decrRefCount(subst);
7083 return NULL;
7084 }
7085
7086 /* Find out if we're dealing with a hash dereference. */
7087 if ((f = strstr(p+1, "->")) != NULL) {
7088 fieldlen = sdslen(spat)-(f-spat);
7089 /* this also copies \0 character */
7090 memcpy(fieldname.buf,f+2,fieldlen-1);
7091 fieldname.len = fieldlen-2;
7092 } else {
7093 fieldlen = 0;
7094 }
7095
7096 prefixlen = p-spat;
7097 sublen = sdslen(ssub);
7098 postfixlen = sdslen(spat)-(prefixlen+1)-fieldlen;
7099 memcpy(keyname.buf,spat,prefixlen);
7100 memcpy(keyname.buf+prefixlen,ssub,sublen);
7101 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
7102 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
7103 keyname.len = prefixlen+sublen+postfixlen;
7104 decrRefCount(subst);
7105
7106 /* Lookup substituted key */
7107 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2));
7108 o = lookupKeyRead(db,&keyobj);
7109 if (o == NULL) return NULL;
7110
7111 if (fieldlen > 0) {
7112 if (o->type != REDIS_HASH || fieldname.len < 1) return NULL;
7113
7114 /* Retrieve value from hash by the field name. This operation
7115 * already increases the refcount of the returned object. */
7116 initStaticStringObject(fieldobj,((char*)&fieldname)+(sizeof(long)*2));
7117 o = hashGet(o, &fieldobj);
7118 } else {
7119 if (o->type != REDIS_STRING) return NULL;
7120
7121 /* Every object that this function returns needs to have its refcount
7122 * increased. sortCommand decreases it again. */
7123 incrRefCount(o);
7124 }
7125
7126 return o;
7127 }
7128
7129 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
7130 * the additional parameter is not standard but a BSD-specific we have to
7131 * pass sorting parameters via the global 'server' structure */
7132 static int sortCompare(const void *s1, const void *s2) {
7133 const redisSortObject *so1 = s1, *so2 = s2;
7134 int cmp;
7135
7136 if (!server.sort_alpha) {
7137 /* Numeric sorting. Here it's trivial as we precomputed scores */
7138 if (so1->u.score > so2->u.score) {
7139 cmp = 1;
7140 } else if (so1->u.score < so2->u.score) {
7141 cmp = -1;
7142 } else {
7143 cmp = 0;
7144 }
7145 } else {
7146 /* Alphanumeric sorting */
7147 if (server.sort_bypattern) {
7148 if (!so1->u.cmpobj || !so2->u.cmpobj) {
7149 /* At least one compare object is NULL */
7150 if (so1->u.cmpobj == so2->u.cmpobj)
7151 cmp = 0;
7152 else if (so1->u.cmpobj == NULL)
7153 cmp = -1;
7154 else
7155 cmp = 1;
7156 } else {
7157 /* We have both the objects, use strcoll */
7158 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
7159 }
7160 } else {
7161 /* Compare elements directly. */
7162 cmp = compareStringObjects(so1->obj,so2->obj);
7163 }
7164 }
7165 return server.sort_desc ? -cmp : cmp;
7166 }
7167
7168 /* The SORT command is the most complex command in Redis. Warning: this code
7169 * is optimized for speed and a bit less for readability */
7170 static void sortCommand(redisClient *c) {
7171 list *operations;
7172 int outputlen = 0;
7173 int desc = 0, alpha = 0;
7174 int limit_start = 0, limit_count = -1, start, end;
7175 int j, dontsort = 0, vectorlen;
7176 int getop = 0; /* GET operation counter */
7177 robj *sortval, *sortby = NULL, *storekey = NULL;
7178 redisSortObject *vector; /* Resulting vector to sort */
7179
7180 /* Lookup the key to sort. It must be of the right types */
7181 sortval = lookupKeyRead(c->db,c->argv[1]);
7182 if (sortval == NULL) {
7183 addReply(c,shared.emptymultibulk);
7184 return;
7185 }
7186 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
7187 sortval->type != REDIS_ZSET)
7188 {
7189 addReply(c,shared.wrongtypeerr);
7190 return;
7191 }
7192
7193 /* Create a list of operations to perform for every sorted element.
7194 * Operations can be GET/DEL/INCR/DECR */
7195 operations = listCreate();
7196 listSetFreeMethod(operations,zfree);
7197 j = 2;
7198
7199 /* Now we need to protect sortval incrementing its count, in the future
7200 * SORT may have options able to overwrite/delete keys during the sorting
7201 * and the sorted key itself may get destroied */
7202 incrRefCount(sortval);
7203
7204 /* The SORT command has an SQL-alike syntax, parse it */
7205 while(j < c->argc) {
7206 int leftargs = c->argc-j-1;
7207 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
7208 desc = 0;
7209 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
7210 desc = 1;
7211 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
7212 alpha = 1;
7213 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
7214 limit_start = atoi(c->argv[j+1]->ptr);
7215 limit_count = atoi(c->argv[j+2]->ptr);
7216 j+=2;
7217 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
7218 storekey = c->argv[j+1];
7219 j++;
7220 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
7221 sortby = c->argv[j+1];
7222 /* If the BY pattern does not contain '*', i.e. it is constant,
7223 * we don't need to sort nor to lookup the weight keys. */
7224 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
7225 j++;
7226 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
7227 listAddNodeTail(operations,createSortOperation(
7228 REDIS_SORT_GET,c->argv[j+1]));
7229 getop++;
7230 j++;
7231 } else {
7232 decrRefCount(sortval);
7233 listRelease(operations);
7234 addReply(c,shared.syntaxerr);
7235 return;
7236 }
7237 j++;
7238 }
7239
7240 /* Load the sorting vector with all the objects to sort */
7241 switch(sortval->type) {
7242 case REDIS_LIST: vectorlen = listLength((list*)sortval->ptr); break;
7243 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
7244 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
7245 default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
7246 }
7247 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
7248 j = 0;
7249
7250 if (sortval->type == REDIS_LIST) {
7251 list *list = sortval->ptr;
7252 listNode *ln;
7253 listIter li;
7254
7255 listRewind(list,&li);
7256 while((ln = listNext(&li))) {
7257 robj *ele = ln->value;
7258 vector[j].obj = ele;
7259 vector[j].u.score = 0;
7260 vector[j].u.cmpobj = NULL;
7261 j++;
7262 }
7263 } else {
7264 dict *set;
7265 dictIterator *di;
7266 dictEntry *setele;
7267
7268 if (sortval->type == REDIS_SET) {
7269 set = sortval->ptr;
7270 } else {
7271 zset *zs = sortval->ptr;
7272 set = zs->dict;
7273 }
7274
7275 di = dictGetIterator(set);
7276 while((setele = dictNext(di)) != NULL) {
7277 vector[j].obj = dictGetEntryKey(setele);
7278 vector[j].u.score = 0;
7279 vector[j].u.cmpobj = NULL;
7280 j++;
7281 }
7282 dictReleaseIterator(di);
7283 }
7284 redisAssert(j == vectorlen);
7285
7286 /* Now it's time to load the right scores in the sorting vector */
7287 if (dontsort == 0) {
7288 for (j = 0; j < vectorlen; j++) {
7289 robj *byval;
7290 if (sortby) {
7291 /* lookup value to sort by */
7292 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
7293 if (!byval) continue;
7294 } else {
7295 /* use object itself to sort by */
7296 byval = vector[j].obj;
7297 }
7298
7299 if (alpha) {
7300 if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
7301 } else {
7302 if (byval->encoding == REDIS_ENCODING_RAW) {
7303 vector[j].u.score = strtod(byval->ptr,NULL);
7304 } else if (byval->encoding == REDIS_ENCODING_INT) {
7305 /* Don't need to decode the object if it's
7306 * integer-encoded (the only encoding supported) so
7307 * far. We can just cast it */
7308 vector[j].u.score = (long)byval->ptr;
7309 } else {
7310 redisAssert(1 != 1);
7311 }
7312 }
7313
7314 /* when the object was retrieved using lookupKeyByPattern,
7315 * its refcount needs to be decreased. */
7316 if (sortby) {
7317 decrRefCount(byval);
7318 }
7319 }
7320 }
7321
7322 /* We are ready to sort the vector... perform a bit of sanity check
7323 * on the LIMIT option too. We'll use a partial version of quicksort. */
7324 start = (limit_start < 0) ? 0 : limit_start;
7325 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
7326 if (start >= vectorlen) {
7327 start = vectorlen-1;
7328 end = vectorlen-2;
7329 }
7330 if (end >= vectorlen) end = vectorlen-1;
7331
7332 if (dontsort == 0) {
7333 server.sort_desc = desc;
7334 server.sort_alpha = alpha;
7335 server.sort_bypattern = sortby ? 1 : 0;
7336 if (sortby && (start != 0 || end != vectorlen-1))
7337 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
7338 else
7339 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
7340 }
7341
7342 /* Send command output to the output buffer, performing the specified
7343 * GET/DEL/INCR/DECR operations if any. */
7344 outputlen = getop ? getop*(end-start+1) : end-start+1;
7345 if (storekey == NULL) {
7346 /* STORE option not specified, sent the sorting result to client */
7347 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
7348 for (j = start; j <= end; j++) {
7349 listNode *ln;
7350 listIter li;
7351
7352 if (!getop) addReplyBulk(c,vector[j].obj);
7353 listRewind(operations,&li);
7354 while((ln = listNext(&li))) {
7355 redisSortOperation *sop = ln->value;
7356 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7357 vector[j].obj);
7358
7359 if (sop->type == REDIS_SORT_GET) {
7360 if (!val) {
7361 addReply(c,shared.nullbulk);
7362 } else {
7363 addReplyBulk(c,val);
7364 decrRefCount(val);
7365 }
7366 } else {
7367 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
7368 }
7369 }
7370 }
7371 } else {
7372 robj *listObject = createListObject();
7373 list *listPtr = (list*) listObject->ptr;
7374
7375 /* STORE option specified, set the sorting result as a List object */
7376 for (j = start; j <= end; j++) {
7377 listNode *ln;
7378 listIter li;
7379
7380 if (!getop) {
7381 listAddNodeTail(listPtr,vector[j].obj);
7382 incrRefCount(vector[j].obj);
7383 }
7384 listRewind(operations,&li);
7385 while((ln = listNext(&li))) {
7386 redisSortOperation *sop = ln->value;
7387 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7388 vector[j].obj);
7389
7390 if (sop->type == REDIS_SORT_GET) {
7391 if (!val) {
7392 listAddNodeTail(listPtr,createStringObject("",0));
7393 } else {
7394 /* We should do a incrRefCount on val because it is
7395 * added to the list, but also a decrRefCount because
7396 * it is returned by lookupKeyByPattern. This results
7397 * in doing nothing at all. */
7398 listAddNodeTail(listPtr,val);
7399 }
7400 } else {
7401 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
7402 }
7403 }
7404 }
7405 if (dictReplace(c->db->dict,storekey,listObject)) {
7406 incrRefCount(storekey);
7407 }
7408 /* Note: we add 1 because the DB is dirty anyway since even if the
7409 * SORT result is empty a new key is set and maybe the old content
7410 * replaced. */
7411 server.dirty += 1+outputlen;
7412 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
7413 }
7414
7415 /* Cleanup */
7416 decrRefCount(sortval);
7417 listRelease(operations);
7418 for (j = 0; j < vectorlen; j++) {
7419 if (alpha && vector[j].u.cmpobj)
7420 decrRefCount(vector[j].u.cmpobj);
7421 }
7422 zfree(vector);
7423 }
7424
7425 /* Convert an amount of bytes into a human readable string in the form
7426 * of 100B, 2G, 100M, 4K, and so forth. */
7427 static void bytesToHuman(char *s, unsigned long long n) {
7428 double d;
7429
7430 if (n < 1024) {
7431 /* Bytes */
7432 sprintf(s,"%lluB",n);
7433 return;
7434 } else if (n < (1024*1024)) {
7435 d = (double)n/(1024);
7436 sprintf(s,"%.2fK",d);
7437 } else if (n < (1024LL*1024*1024)) {
7438 d = (double)n/(1024*1024);
7439 sprintf(s,"%.2fM",d);
7440 } else if (n < (1024LL*1024*1024*1024)) {
7441 d = (double)n/(1024LL*1024*1024);
7442 sprintf(s,"%.2fG",d);
7443 }
7444 }
7445
7446 /* Create the string returned by the INFO command. This is decoupled
7447 * by the INFO command itself as we need to report the same information
7448 * on memory corruption problems. */
7449 static sds genRedisInfoString(void) {
7450 sds info;
7451 time_t uptime = time(NULL)-server.stat_starttime;
7452 int j;
7453 char hmem[64];
7454
7455 bytesToHuman(hmem,zmalloc_used_memory());
7456 info = sdscatprintf(sdsempty(),
7457 "redis_version:%s\r\n"
7458 "redis_git_sha1:%s\r\n"
7459 "redis_git_dirty:%d\r\n"
7460 "arch_bits:%s\r\n"
7461 "multiplexing_api:%s\r\n"
7462 "process_id:%ld\r\n"
7463 "uptime_in_seconds:%ld\r\n"
7464 "uptime_in_days:%ld\r\n"
7465 "connected_clients:%d\r\n"
7466 "connected_slaves:%d\r\n"
7467 "blocked_clients:%d\r\n"
7468 "used_memory:%zu\r\n"
7469 "used_memory_human:%s\r\n"
7470 "changes_since_last_save:%lld\r\n"
7471 "bgsave_in_progress:%d\r\n"
7472 "last_save_time:%ld\r\n"
7473 "bgrewriteaof_in_progress:%d\r\n"
7474 "total_connections_received:%lld\r\n"
7475 "total_commands_processed:%lld\r\n"
7476 "expired_keys:%lld\r\n"
7477 "hash_max_zipmap_entries:%zu\r\n"
7478 "hash_max_zipmap_value:%zu\r\n"
7479 "pubsub_channels:%ld\r\n"
7480 "pubsub_patterns:%u\r\n"
7481 "vm_enabled:%d\r\n"
7482 "role:%s\r\n"
7483 ,REDIS_VERSION,
7484 REDIS_GIT_SHA1,
7485 strtol(REDIS_GIT_DIRTY,NULL,10) > 0,
7486 (sizeof(long) == 8) ? "64" : "32",
7487 aeGetApiName(),
7488 (long) getpid(),
7489 uptime,
7490 uptime/(3600*24),
7491 listLength(server.clients)-listLength(server.slaves),
7492 listLength(server.slaves),
7493 server.blpop_blocked_clients,
7494 zmalloc_used_memory(),
7495 hmem,
7496 server.dirty,
7497 server.bgsavechildpid != -1,
7498 server.lastsave,
7499 server.bgrewritechildpid != -1,
7500 server.stat_numconnections,
7501 server.stat_numcommands,
7502 server.stat_expiredkeys,
7503 server.hash_max_zipmap_entries,
7504 server.hash_max_zipmap_value,
7505 dictSize(server.pubsub_channels),
7506 listLength(server.pubsub_patterns),
7507 server.vm_enabled != 0,
7508 server.masterhost == NULL ? "master" : "slave"
7509 );
7510 if (server.masterhost) {
7511 info = sdscatprintf(info,
7512 "master_host:%s\r\n"
7513 "master_port:%d\r\n"
7514 "master_link_status:%s\r\n"
7515 "master_last_io_seconds_ago:%d\r\n"
7516 ,server.masterhost,
7517 server.masterport,
7518 (server.replstate == REDIS_REPL_CONNECTED) ?
7519 "up" : "down",
7520 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
7521 );
7522 }
7523 if (server.vm_enabled) {
7524 lockThreadedIO();
7525 info = sdscatprintf(info,
7526 "vm_conf_max_memory:%llu\r\n"
7527 "vm_conf_page_size:%llu\r\n"
7528 "vm_conf_pages:%llu\r\n"
7529 "vm_stats_used_pages:%llu\r\n"
7530 "vm_stats_swapped_objects:%llu\r\n"
7531 "vm_stats_swappin_count:%llu\r\n"
7532 "vm_stats_swappout_count:%llu\r\n"
7533 "vm_stats_io_newjobs_len:%lu\r\n"
7534 "vm_stats_io_processing_len:%lu\r\n"
7535 "vm_stats_io_processed_len:%lu\r\n"
7536 "vm_stats_io_active_threads:%lu\r\n"
7537 "vm_stats_blocked_clients:%lu\r\n"
7538 ,(unsigned long long) server.vm_max_memory,
7539 (unsigned long long) server.vm_page_size,
7540 (unsigned long long) server.vm_pages,
7541 (unsigned long long) server.vm_stats_used_pages,
7542 (unsigned long long) server.vm_stats_swapped_objects,
7543 (unsigned long long) server.vm_stats_swapins,
7544 (unsigned long long) server.vm_stats_swapouts,
7545 (unsigned long) listLength(server.io_newjobs),
7546 (unsigned long) listLength(server.io_processing),
7547 (unsigned long) listLength(server.io_processed),
7548 (unsigned long) server.io_active_threads,
7549 (unsigned long) server.vm_blocked_clients
7550 );
7551 unlockThreadedIO();
7552 }
7553 for (j = 0; j < server.dbnum; j++) {
7554 long long keys, vkeys;
7555
7556 keys = dictSize(server.db[j].dict);
7557 vkeys = dictSize(server.db[j].expires);
7558 if (keys || vkeys) {
7559 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
7560 j, keys, vkeys);
7561 }
7562 }
7563 return info;
7564 }
7565
7566 static void infoCommand(redisClient *c) {
7567 sds info = genRedisInfoString();
7568 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
7569 (unsigned long)sdslen(info)));
7570 addReplySds(c,info);
7571 addReply(c,shared.crlf);
7572 }
7573
7574 static void monitorCommand(redisClient *c) {
7575 /* ignore MONITOR if aleady slave or in monitor mode */
7576 if (c->flags & REDIS_SLAVE) return;
7577
7578 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
7579 c->slaveseldb = 0;
7580 listAddNodeTail(server.monitors,c);
7581 addReply(c,shared.ok);
7582 }
7583
7584 /* ================================= Expire ================================= */
7585 static int removeExpire(redisDb *db, robj *key) {
7586 if (dictDelete(db->expires,key) == DICT_OK) {
7587 return 1;
7588 } else {
7589 return 0;
7590 }
7591 }
7592
7593 static int setExpire(redisDb *db, robj *key, time_t when) {
7594 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
7595 return 0;
7596 } else {
7597 incrRefCount(key);
7598 return 1;
7599 }
7600 }
7601
7602 /* Return the expire time of the specified key, or -1 if no expire
7603 * is associated with this key (i.e. the key is non volatile) */
7604 static time_t getExpire(redisDb *db, robj *key) {
7605 dictEntry *de;
7606
7607 /* No expire? return ASAP */
7608 if (dictSize(db->expires) == 0 ||
7609 (de = dictFind(db->expires,key)) == NULL) return -1;
7610
7611 return (time_t) dictGetEntryVal(de);
7612 }
7613
7614 static int expireIfNeeded(redisDb *db, robj *key) {
7615 time_t when;
7616 dictEntry *de;
7617
7618 /* No expire? return ASAP */
7619 if (dictSize(db->expires) == 0 ||
7620 (de = dictFind(db->expires,key)) == NULL) return 0;
7621
7622 /* Lookup the expire */
7623 when = (time_t) dictGetEntryVal(de);
7624 if (time(NULL) <= when) return 0;
7625
7626 /* Delete the key */
7627 dictDelete(db->expires,key);
7628 server.stat_expiredkeys++;
7629 return dictDelete(db->dict,key) == DICT_OK;
7630 }
7631
7632 static int deleteIfVolatile(redisDb *db, robj *key) {
7633 dictEntry *de;
7634
7635 /* No expire? return ASAP */
7636 if (dictSize(db->expires) == 0 ||
7637 (de = dictFind(db->expires,key)) == NULL) return 0;
7638
7639 /* Delete the key */
7640 server.dirty++;
7641 server.stat_expiredkeys++;
7642 dictDelete(db->expires,key);
7643 return dictDelete(db->dict,key) == DICT_OK;
7644 }
7645
7646 static void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
7647 dictEntry *de;
7648 time_t seconds;
7649
7650 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
7651
7652 seconds -= offset;
7653
7654 de = dictFind(c->db->dict,key);
7655 if (de == NULL) {
7656 addReply(c,shared.czero);
7657 return;
7658 }
7659 if (seconds <= 0) {
7660 if (deleteKey(c->db,key)) server.dirty++;
7661 addReply(c, shared.cone);
7662 return;
7663 } else {
7664 time_t when = time(NULL)+seconds;
7665 if (setExpire(c->db,key,when)) {
7666 addReply(c,shared.cone);
7667 server.dirty++;
7668 } else {
7669 addReply(c,shared.czero);
7670 }
7671 return;
7672 }
7673 }
7674
7675 static void expireCommand(redisClient *c) {
7676 expireGenericCommand(c,c->argv[1],c->argv[2],0);
7677 }
7678
7679 static void expireatCommand(redisClient *c) {
7680 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
7681 }
7682
7683 static void ttlCommand(redisClient *c) {
7684 time_t expire;
7685 int ttl = -1;
7686
7687 expire = getExpire(c->db,c->argv[1]);
7688 if (expire != -1) {
7689 ttl = (int) (expire-time(NULL));
7690 if (ttl < 0) ttl = -1;
7691 }
7692 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
7693 }
7694
7695 /* ================================ MULTI/EXEC ============================== */
7696
7697 /* Client state initialization for MULTI/EXEC */
7698 static void initClientMultiState(redisClient *c) {
7699 c->mstate.commands = NULL;
7700 c->mstate.count = 0;
7701 }
7702
7703 /* Release all the resources associated with MULTI/EXEC state */
7704 static void freeClientMultiState(redisClient *c) {
7705 int j;
7706
7707 for (j = 0; j < c->mstate.count; j++) {
7708 int i;
7709 multiCmd *mc = c->mstate.commands+j;
7710
7711 for (i = 0; i < mc->argc; i++)
7712 decrRefCount(mc->argv[i]);
7713 zfree(mc->argv);
7714 }
7715 zfree(c->mstate.commands);
7716 }
7717
7718 /* Add a new command into the MULTI commands queue */
7719 static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
7720 multiCmd *mc;
7721 int j;
7722
7723 c->mstate.commands = zrealloc(c->mstate.commands,
7724 sizeof(multiCmd)*(c->mstate.count+1));
7725 mc = c->mstate.commands+c->mstate.count;
7726 mc->cmd = cmd;
7727 mc->argc = c->argc;
7728 mc->argv = zmalloc(sizeof(robj*)*c->argc);
7729 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
7730 for (j = 0; j < c->argc; j++)
7731 incrRefCount(mc->argv[j]);
7732 c->mstate.count++;
7733 }
7734
7735 static void multiCommand(redisClient *c) {
7736 if (c->flags & REDIS_MULTI) {
7737 addReplySds(c,sdsnew("-ERR MULTI calls can not be nested\r\n"));
7738 return;
7739 }
7740 c->flags |= REDIS_MULTI;
7741 addReply(c,shared.ok);
7742 }
7743
7744 static void discardCommand(redisClient *c) {
7745 if (!(c->flags & REDIS_MULTI)) {
7746 addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
7747 return;
7748 }
7749
7750 freeClientMultiState(c);
7751 initClientMultiState(c);
7752 c->flags &= (~REDIS_MULTI);
7753 addReply(c,shared.ok);
7754 }
7755
7756 /* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7757 * implememntation for more information. */
7758 static void execCommandReplicateMulti(redisClient *c) {
7759 struct redisCommand *cmd;
7760 robj *multistring = createStringObject("MULTI",5);
7761
7762 cmd = lookupCommand("multi");
7763 if (server.appendonly)
7764 feedAppendOnlyFile(cmd,c->db->id,&multistring,1);
7765 if (listLength(server.slaves))
7766 replicationFeedSlaves(server.slaves,c->db->id,&multistring,1);
7767 decrRefCount(multistring);
7768 }
7769
7770 static void execCommand(redisClient *c) {
7771 int j;
7772 robj **orig_argv;
7773 int orig_argc;
7774
7775 if (!(c->flags & REDIS_MULTI)) {
7776 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
7777 return;
7778 }
7779
7780 /* Check if we need to abort the EXEC if some WATCHed key was touched.
7781 * A failed EXEC will return a multi bulk nil object. */
7782 if (c->flags & REDIS_DIRTY_CAS) {
7783 freeClientMultiState(c);
7784 initClientMultiState(c);
7785 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
7786 unwatchAllKeys(c);
7787 addReply(c,shared.nullmultibulk);
7788 return;
7789 }
7790
7791 /* Replicate a MULTI request now that we are sure the block is executed.
7792 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7793 * both the AOF and the replication link will have the same consistency
7794 * and atomicity guarantees. */
7795 execCommandReplicateMulti(c);
7796
7797 /* Exec all the queued commands */
7798 unwatchAllKeys(c); /* Unwatch ASAP otherwise we'll waste CPU cycles */
7799 orig_argv = c->argv;
7800 orig_argc = c->argc;
7801 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
7802 for (j = 0; j < c->mstate.count; j++) {
7803 c->argc = c->mstate.commands[j].argc;
7804 c->argv = c->mstate.commands[j].argv;
7805 call(c,c->mstate.commands[j].cmd);
7806 }
7807 c->argv = orig_argv;
7808 c->argc = orig_argc;
7809 freeClientMultiState(c);
7810 initClientMultiState(c);
7811 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
7812 /* Make sure the EXEC command is always replicated / AOF, since we
7813 * always send the MULTI command (we can't know beforehand if the
7814 * next operations will contain at least a modification to the DB). */
7815 server.dirty++;
7816 }
7817
7818 /* =========================== Blocking Operations ========================= */
7819
7820 /* Currently Redis blocking operations support is limited to list POP ops,
7821 * so the current implementation is not fully generic, but it is also not
7822 * completely specific so it will not require a rewrite to support new
7823 * kind of blocking operations in the future.
7824 *
7825 * Still it's important to note that list blocking operations can be already
7826 * used as a notification mechanism in order to implement other blocking
7827 * operations at application level, so there must be a very strong evidence
7828 * of usefulness and generality before new blocking operations are implemented.
7829 *
7830 * This is how the current blocking POP works, we use BLPOP as example:
7831 * - If the user calls BLPOP and the key exists and contains a non empty list
7832 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7833 * if there is not to block.
7834 * - If instead BLPOP is called and the key does not exists or the list is
7835 * empty we need to block. In order to do so we remove the notification for
7836 * new data to read in the client socket (so that we'll not serve new
7837 * requests if the blocking request is not served). Also we put the client
7838 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
7839 * blocking for this keys.
7840 * - If a PUSH operation against a key with blocked clients waiting is
7841 * performed, we serve the first in the list: basically instead to push
7842 * the new element inside the list we return it to the (first / oldest)
7843 * blocking client, unblock the client, and remove it form the list.
7844 *
7845 * The above comment and the source code should be enough in order to understand
7846 * the implementation and modify / fix it later.
7847 */
7848
7849 /* Set a client in blocking mode for the specified key, with the specified
7850 * timeout */
7851 static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
7852 dictEntry *de;
7853 list *l;
7854 int j;
7855
7856 c->blocking_keys = zmalloc(sizeof(robj*)*numkeys);
7857 c->blocking_keys_num = numkeys;
7858 c->blockingto = timeout;
7859 for (j = 0; j < numkeys; j++) {
7860 /* Add the key in the client structure, to map clients -> keys */
7861 c->blocking_keys[j] = keys[j];
7862 incrRefCount(keys[j]);
7863
7864 /* And in the other "side", to map keys -> clients */
7865 de = dictFind(c->db->blocking_keys,keys[j]);
7866 if (de == NULL) {
7867 int retval;
7868
7869 /* For every key we take a list of clients blocked for it */
7870 l = listCreate();
7871 retval = dictAdd(c->db->blocking_keys,keys[j],l);
7872 incrRefCount(keys[j]);
7873 assert(retval == DICT_OK);
7874 } else {
7875 l = dictGetEntryVal(de);
7876 }
7877 listAddNodeTail(l,c);
7878 }
7879 /* Mark the client as a blocked client */
7880 c->flags |= REDIS_BLOCKED;
7881 server.blpop_blocked_clients++;
7882 }
7883
7884 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
7885 static void unblockClientWaitingData(redisClient *c) {
7886 dictEntry *de;
7887 list *l;
7888 int j;
7889
7890 assert(c->blocking_keys != NULL);
7891 /* The client may wait for multiple keys, so unblock it for every key. */
7892 for (j = 0; j < c->blocking_keys_num; j++) {
7893 /* Remove this client from the list of clients waiting for this key. */
7894 de = dictFind(c->db->blocking_keys,c->blocking_keys[j]);
7895 assert(de != NULL);
7896 l = dictGetEntryVal(de);
7897 listDelNode(l,listSearchKey(l,c));
7898 /* If the list is empty we need to remove it to avoid wasting memory */
7899 if (listLength(l) == 0)
7900 dictDelete(c->db->blocking_keys,c->blocking_keys[j]);
7901 decrRefCount(c->blocking_keys[j]);
7902 }
7903 /* Cleanup the client structure */
7904 zfree(c->blocking_keys);
7905 c->blocking_keys = NULL;
7906 c->flags &= (~REDIS_BLOCKED);
7907 server.blpop_blocked_clients--;
7908 /* We want to process data if there is some command waiting
7909 * in the input buffer. Note that this is safe even if
7910 * unblockClientWaitingData() gets called from freeClient() because
7911 * freeClient() will be smart enough to call this function
7912 * *after* c->querybuf was set to NULL. */
7913 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
7914 }
7915
7916 /* This should be called from any function PUSHing into lists.
7917 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7918 * 'ele' is the element pushed.
7919 *
7920 * If the function returns 0 there was no client waiting for a list push
7921 * against this key.
7922 *
7923 * If the function returns 1 there was a client waiting for a list push
7924 * against this key, the element was passed to this client thus it's not
7925 * needed to actually add it to the list and the caller should return asap. */
7926 static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
7927 struct dictEntry *de;
7928 redisClient *receiver;
7929 list *l;
7930 listNode *ln;
7931
7932 de = dictFind(c->db->blocking_keys,key);
7933 if (de == NULL) return 0;
7934 l = dictGetEntryVal(de);
7935 ln = listFirst(l);
7936 assert(ln != NULL);
7937 receiver = ln->value;
7938
7939 addReplySds(receiver,sdsnew("*2\r\n"));
7940 addReplyBulk(receiver,key);
7941 addReplyBulk(receiver,ele);
7942 unblockClientWaitingData(receiver);
7943 return 1;
7944 }
7945
7946 /* Blocking RPOP/LPOP */
7947 static void blockingPopGenericCommand(redisClient *c, int where) {
7948 robj *o;
7949 time_t timeout;
7950 int j;
7951
7952 for (j = 1; j < c->argc-1; j++) {
7953 o = lookupKeyWrite(c->db,c->argv[j]);
7954 if (o != NULL) {
7955 if (o->type != REDIS_LIST) {
7956 addReply(c,shared.wrongtypeerr);
7957 return;
7958 } else {
7959 list *list = o->ptr;
7960 if (listLength(list) != 0) {
7961 /* If the list contains elements fall back to the usual
7962 * non-blocking POP operation */
7963 robj *argv[2], **orig_argv;
7964 int orig_argc;
7965
7966 /* We need to alter the command arguments before to call
7967 * popGenericCommand() as the command takes a single key. */
7968 orig_argv = c->argv;
7969 orig_argc = c->argc;
7970 argv[1] = c->argv[j];
7971 c->argv = argv;
7972 c->argc = 2;
7973
7974 /* Also the return value is different, we need to output
7975 * the multi bulk reply header and the key name. The
7976 * "real" command will add the last element (the value)
7977 * for us. If this souds like an hack to you it's just
7978 * because it is... */
7979 addReplySds(c,sdsnew("*2\r\n"));
7980 addReplyBulk(c,argv[1]);
7981 popGenericCommand(c,where);
7982
7983 /* Fix the client structure with the original stuff */
7984 c->argv = orig_argv;
7985 c->argc = orig_argc;
7986 return;
7987 }
7988 }
7989 }
7990 }
7991 /* If the list is empty or the key does not exists we must block */
7992 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
7993 if (timeout > 0) timeout += time(NULL);
7994 blockForKeys(c,c->argv+1,c->argc-2,timeout);
7995 }
7996
7997 static void blpopCommand(redisClient *c) {
7998 blockingPopGenericCommand(c,REDIS_HEAD);
7999 }
8000
8001 static void brpopCommand(redisClient *c) {
8002 blockingPopGenericCommand(c,REDIS_TAIL);
8003 }
8004
8005 /* =============================== Replication ============================= */
8006
8007 static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
8008 ssize_t nwritten, ret = size;
8009 time_t start = time(NULL);
8010
8011 timeout++;
8012 while(size) {
8013 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
8014 nwritten = write(fd,ptr,size);
8015 if (nwritten == -1) return -1;
8016 ptr += nwritten;
8017 size -= nwritten;
8018 }
8019 if ((time(NULL)-start) > timeout) {
8020 errno = ETIMEDOUT;
8021 return -1;
8022 }
8023 }
8024 return ret;
8025 }
8026
8027 static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
8028 ssize_t nread, totread = 0;
8029 time_t start = time(NULL);
8030
8031 timeout++;
8032 while(size) {
8033 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
8034 nread = read(fd,ptr,size);
8035 if (nread == -1) return -1;
8036 ptr += nread;
8037 size -= nread;
8038 totread += nread;
8039 }
8040 if ((time(NULL)-start) > timeout) {
8041 errno = ETIMEDOUT;
8042 return -1;
8043 }
8044 }
8045 return totread;
8046 }
8047
8048 static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
8049 ssize_t nread = 0;
8050
8051 size--;
8052 while(size) {
8053 char c;
8054
8055 if (syncRead(fd,&c,1,timeout) == -1) return -1;
8056 if (c == '\n') {
8057 *ptr = '\0';
8058 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
8059 return nread;
8060 } else {
8061 *ptr++ = c;
8062 *ptr = '\0';
8063 nread++;
8064 }
8065 }
8066 return nread;
8067 }
8068
8069 static void syncCommand(redisClient *c) {
8070 /* ignore SYNC if aleady slave or in monitor mode */
8071 if (c->flags & REDIS_SLAVE) return;
8072
8073 /* SYNC can't be issued when the server has pending data to send to
8074 * the client about already issued commands. We need a fresh reply
8075 * buffer registering the differences between the BGSAVE and the current
8076 * dataset, so that we can copy to other slaves if needed. */
8077 if (listLength(c->reply) != 0) {
8078 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
8079 return;
8080 }
8081
8082 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
8083 /* Here we need to check if there is a background saving operation
8084 * in progress, or if it is required to start one */
8085 if (server.bgsavechildpid != -1) {
8086 /* Ok a background save is in progress. Let's check if it is a good
8087 * one for replication, i.e. if there is another slave that is
8088 * registering differences since the server forked to save */
8089 redisClient *slave;
8090 listNode *ln;
8091 listIter li;
8092
8093 listRewind(server.slaves,&li);
8094 while((ln = listNext(&li))) {
8095 slave = ln->value;
8096 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
8097 }
8098 if (ln) {
8099 /* Perfect, the server is already registering differences for
8100 * another slave. Set the right state, and copy the buffer. */
8101 listRelease(c->reply);
8102 c->reply = listDup(slave->reply);
8103 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8104 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
8105 } else {
8106 /* No way, we need to wait for the next BGSAVE in order to
8107 * register differences */
8108 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
8109 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
8110 }
8111 } else {
8112 /* Ok we don't have a BGSAVE in progress, let's start one */
8113 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
8114 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
8115 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
8116 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
8117 return;
8118 }
8119 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8120 }
8121 c->repldbfd = -1;
8122 c->flags |= REDIS_SLAVE;
8123 c->slaveseldb = 0;
8124 listAddNodeTail(server.slaves,c);
8125 return;
8126 }
8127
8128 static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
8129 redisClient *slave = privdata;
8130 REDIS_NOTUSED(el);
8131 REDIS_NOTUSED(mask);
8132 char buf[REDIS_IOBUF_LEN];
8133 ssize_t nwritten, buflen;
8134
8135 if (slave->repldboff == 0) {
8136 /* Write the bulk write count before to transfer the DB. In theory here
8137 * we don't know how much room there is in the output buffer of the
8138 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
8139 * operations) will never be smaller than the few bytes we need. */
8140 sds bulkcount;
8141
8142 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
8143 slave->repldbsize);
8144 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
8145 {
8146 sdsfree(bulkcount);
8147 freeClient(slave);
8148 return;
8149 }
8150 sdsfree(bulkcount);
8151 }
8152 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
8153 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
8154 if (buflen <= 0) {
8155 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
8156 (buflen == 0) ? "premature EOF" : strerror(errno));
8157 freeClient(slave);
8158 return;
8159 }
8160 if ((nwritten = write(fd,buf,buflen)) == -1) {
8161 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
8162 strerror(errno));
8163 freeClient(slave);
8164 return;
8165 }
8166 slave->repldboff += nwritten;
8167 if (slave->repldboff == slave->repldbsize) {
8168 close(slave->repldbfd);
8169 slave->repldbfd = -1;
8170 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8171 slave->replstate = REDIS_REPL_ONLINE;
8172 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
8173 sendReplyToClient, slave) == AE_ERR) {
8174 freeClient(slave);
8175 return;
8176 }
8177 addReplySds(slave,sdsempty());
8178 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
8179 }
8180 }
8181
8182 /* This function is called at the end of every backgrond saving.
8183 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
8184 * otherwise REDIS_ERR is passed to the function.
8185 *
8186 * The goal of this function is to handle slaves waiting for a successful
8187 * background saving in order to perform non-blocking synchronization. */
8188 static void updateSlavesWaitingBgsave(int bgsaveerr) {
8189 listNode *ln;
8190 int startbgsave = 0;
8191 listIter li;
8192
8193 listRewind(server.slaves,&li);
8194 while((ln = listNext(&li))) {
8195 redisClient *slave = ln->value;
8196
8197 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
8198 startbgsave = 1;
8199 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8200 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
8201 struct redis_stat buf;
8202
8203 if (bgsaveerr != REDIS_OK) {
8204 freeClient(slave);
8205 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
8206 continue;
8207 }
8208 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
8209 redis_fstat(slave->repldbfd,&buf) == -1) {
8210 freeClient(slave);
8211 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
8212 continue;
8213 }
8214 slave->repldboff = 0;
8215 slave->repldbsize = buf.st_size;
8216 slave->replstate = REDIS_REPL_SEND_BULK;
8217 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8218 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
8219 freeClient(slave);
8220 continue;
8221 }
8222 }
8223 }
8224 if (startbgsave) {
8225 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
8226 listIter li;
8227
8228 listRewind(server.slaves,&li);
8229 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
8230 while((ln = listNext(&li))) {
8231 redisClient *slave = ln->value;
8232
8233 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
8234 freeClient(slave);
8235 }
8236 }
8237 }
8238 }
8239
8240 static int syncWithMaster(void) {
8241 char buf[1024], tmpfile[256], authcmd[1024];
8242 long dumpsize;
8243 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
8244 int dfd, maxtries = 5;
8245
8246 if (fd == -1) {
8247 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
8248 strerror(errno));
8249 return REDIS_ERR;
8250 }
8251
8252 /* AUTH with the master if required. */
8253 if(server.masterauth) {
8254 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
8255 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
8256 close(fd);
8257 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
8258 strerror(errno));
8259 return REDIS_ERR;
8260 }
8261 /* Read the AUTH result. */
8262 if (syncReadLine(fd,buf,1024,3600) == -1) {
8263 close(fd);
8264 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
8265 strerror(errno));
8266 return REDIS_ERR;
8267 }
8268 if (buf[0] != '+') {
8269 close(fd);
8270 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
8271 return REDIS_ERR;
8272 }
8273 }
8274
8275 /* Issue the SYNC command */
8276 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
8277 close(fd);
8278 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
8279 strerror(errno));
8280 return REDIS_ERR;
8281 }
8282 /* Read the bulk write count */
8283 if (syncReadLine(fd,buf,1024,3600) == -1) {
8284 close(fd);
8285 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
8286 strerror(errno));
8287 return REDIS_ERR;
8288 }
8289 if (buf[0] != '$') {
8290 close(fd);
8291 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8292 return REDIS_ERR;
8293 }
8294 dumpsize = strtol(buf+1,NULL,10);
8295 redisLog(REDIS_NOTICE,"Receiving %ld bytes data dump from MASTER",dumpsize);
8296 /* Read the bulk write data on a temp file */
8297 while(maxtries--) {
8298 snprintf(tmpfile,256,
8299 "temp-%d.%ld.rdb",(int)time(NULL),(long int)getpid());
8300 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
8301 if (dfd != -1) break;
8302 sleep(1);
8303 }
8304 if (dfd == -1) {
8305 close(fd);
8306 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
8307 return REDIS_ERR;
8308 }
8309 while(dumpsize) {
8310 int nread, nwritten;
8311
8312 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
8313 if (nread == -1) {
8314 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
8315 strerror(errno));
8316 close(fd);
8317 close(dfd);
8318 return REDIS_ERR;
8319 }
8320 nwritten = write(dfd,buf,nread);
8321 if (nwritten == -1) {
8322 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
8323 close(fd);
8324 close(dfd);
8325 return REDIS_ERR;
8326 }
8327 dumpsize -= nread;
8328 }
8329 close(dfd);
8330 if (rename(tmpfile,server.dbfilename) == -1) {
8331 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
8332 unlink(tmpfile);
8333 close(fd);
8334 return REDIS_ERR;
8335 }
8336 emptyDb();
8337 if (rdbLoad(server.dbfilename) != REDIS_OK) {
8338 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
8339 close(fd);
8340 return REDIS_ERR;
8341 }
8342 server.master = createClient(fd);
8343 server.master->flags |= REDIS_MASTER;
8344 server.master->authenticated = 1;
8345 server.replstate = REDIS_REPL_CONNECTED;
8346 return REDIS_OK;
8347 }
8348
8349 static void slaveofCommand(redisClient *c) {
8350 if (!strcasecmp(c->argv[1]->ptr,"no") &&
8351 !strcasecmp(c->argv[2]->ptr,"one")) {
8352 if (server.masterhost) {
8353 sdsfree(server.masterhost);
8354 server.masterhost = NULL;
8355 if (server.master) freeClient(server.master);
8356 server.replstate = REDIS_REPL_NONE;
8357 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
8358 }
8359 } else {
8360 sdsfree(server.masterhost);
8361 server.masterhost = sdsdup(c->argv[1]->ptr);
8362 server.masterport = atoi(c->argv[2]->ptr);
8363 if (server.master) freeClient(server.master);
8364 server.replstate = REDIS_REPL_CONNECT;
8365 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
8366 server.masterhost, server.masterport);
8367 }
8368 addReply(c,shared.ok);
8369 }
8370
8371 /* ============================ Maxmemory directive ======================== */
8372
8373 /* Try to free one object form the pre-allocated objects free list.
8374 * This is useful under low mem conditions as by default we take 1 million
8375 * free objects allocated. On success REDIS_OK is returned, otherwise
8376 * REDIS_ERR. */
8377 static int tryFreeOneObjectFromFreelist(void) {
8378 robj *o;
8379
8380 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
8381 if (listLength(server.objfreelist)) {
8382 listNode *head = listFirst(server.objfreelist);
8383 o = listNodeValue(head);
8384 listDelNode(server.objfreelist,head);
8385 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8386 zfree(o);
8387 return REDIS_OK;
8388 } else {
8389 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8390 return REDIS_ERR;
8391 }
8392 }
8393
8394 /* This function gets called when 'maxmemory' is set on the config file to limit
8395 * the max memory used by the server, and we are out of memory.
8396 * This function will try to, in order:
8397 *
8398 * - Free objects from the free list
8399 * - Try to remove keys with an EXPIRE set
8400 *
8401 * It is not possible to free enough memory to reach used-memory < maxmemory
8402 * the server will start refusing commands that will enlarge even more the
8403 * memory usage.
8404 */
8405 static void freeMemoryIfNeeded(void) {
8406 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
8407 int j, k, freed = 0;
8408
8409 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
8410 for (j = 0; j < server.dbnum; j++) {
8411 int minttl = -1;
8412 robj *minkey = NULL;
8413 struct dictEntry *de;
8414
8415 if (dictSize(server.db[j].expires)) {
8416 freed = 1;
8417 /* From a sample of three keys drop the one nearest to
8418 * the natural expire */
8419 for (k = 0; k < 3; k++) {
8420 time_t t;
8421
8422 de = dictGetRandomKey(server.db[j].expires);
8423 t = (time_t) dictGetEntryVal(de);
8424 if (minttl == -1 || t < minttl) {
8425 minkey = dictGetEntryKey(de);
8426 minttl = t;
8427 }
8428 }
8429 deleteKey(server.db+j,minkey);
8430 }
8431 }
8432 if (!freed) return; /* nothing to free... */
8433 }
8434 }
8435
8436 /* ============================== Append Only file ========================== */
8437
8438 /* Write the append only file buffer on disk.
8439 *
8440 * Since we are required to write the AOF before replying to the client,
8441 * and the only way the client socket can get a write is entering when the
8442 * the event loop, we accumulate all the AOF writes in a memory
8443 * buffer and write it on disk using this function just before entering
8444 * the event loop again. */
8445 static void flushAppendOnlyFile(void) {
8446 time_t now;
8447 ssize_t nwritten;
8448
8449 if (sdslen(server.aofbuf) == 0) return;
8450
8451 /* We want to perform a single write. This should be guaranteed atomic
8452 * at least if the filesystem we are writing is a real physical one.
8453 * While this will save us against the server being killed I don't think
8454 * there is much to do about the whole server stopping for power problems
8455 * or alike */
8456 nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf));
8457 if (nwritten != (signed)sdslen(server.aofbuf)) {
8458 /* Ooops, we are in troubles. The best thing to do for now is
8459 * aborting instead of giving the illusion that everything is
8460 * working as expected. */
8461 if (nwritten == -1) {
8462 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
8463 } else {
8464 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
8465 }
8466 exit(1);
8467 }
8468 sdsfree(server.aofbuf);
8469 server.aofbuf = sdsempty();
8470
8471 /* Fsync if needed */
8472 now = time(NULL);
8473 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
8474 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
8475 now-server.lastfsync > 1))
8476 {
8477 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8478 * flushing metadata. */
8479 aof_fsync(server.appendfd); /* Let's try to get this data on the disk */
8480 server.lastfsync = now;
8481 }
8482 }
8483
8484 static sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) {
8485 int j;
8486 buf = sdscatprintf(buf,"*%d\r\n",argc);
8487 for (j = 0; j < argc; j++) {
8488 robj *o = getDecodedObject(argv[j]);
8489 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
8490 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
8491 buf = sdscatlen(buf,"\r\n",2);
8492 decrRefCount(o);
8493 }
8494 return buf;
8495 }
8496
8497 static sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) {
8498 int argc = 3;
8499 long when;
8500 robj *argv[3];
8501
8502 /* Make sure we can use strtol */
8503 seconds = getDecodedObject(seconds);
8504 when = time(NULL)+strtol(seconds->ptr,NULL,10);
8505 decrRefCount(seconds);
8506
8507 argv[0] = createStringObject("EXPIREAT",8);
8508 argv[1] = key;
8509 argv[2] = createObject(REDIS_STRING,
8510 sdscatprintf(sdsempty(),"%ld",when));
8511 buf = catAppendOnlyGenericCommand(buf, argc, argv);
8512 decrRefCount(argv[0]);
8513 decrRefCount(argv[2]);
8514 return buf;
8515 }
8516
8517 static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
8518 sds buf = sdsempty();
8519 robj *tmpargv[3];
8520
8521 /* The DB this command was targetting is not the same as the last command
8522 * we appendend. To issue a SELECT command is needed. */
8523 if (dictid != server.appendseldb) {
8524 char seldb[64];
8525
8526 snprintf(seldb,sizeof(seldb),"%d",dictid);
8527 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
8528 (unsigned long)strlen(seldb),seldb);
8529 server.appendseldb = dictid;
8530 }
8531
8532 if (cmd->proc == expireCommand) {
8533 /* Translate EXPIRE into EXPIREAT */
8534 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8535 } else if (cmd->proc == setexCommand) {
8536 /* Translate SETEX to SET and EXPIREAT */
8537 tmpargv[0] = createStringObject("SET",3);
8538 tmpargv[1] = argv[1];
8539 tmpargv[2] = argv[3];
8540 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
8541 decrRefCount(tmpargv[0]);
8542 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8543 } else {
8544 buf = catAppendOnlyGenericCommand(buf,argc,argv);
8545 }
8546
8547 /* Append to the AOF buffer. This will be flushed on disk just before
8548 * of re-entering the event loop, so before the client will get a
8549 * positive reply about the operation performed. */
8550 server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf));
8551
8552 /* If a background append only file rewriting is in progress we want to
8553 * accumulate the differences between the child DB and the current one
8554 * in a buffer, so that when the child process will do its work we
8555 * can append the differences to the new append only file. */
8556 if (server.bgrewritechildpid != -1)
8557 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
8558
8559 sdsfree(buf);
8560 }
8561
8562 /* In Redis commands are always executed in the context of a client, so in
8563 * order to load the append only file we need to create a fake client. */
8564 static struct redisClient *createFakeClient(void) {
8565 struct redisClient *c = zmalloc(sizeof(*c));
8566
8567 selectDb(c,0);
8568 c->fd = -1;
8569 c->querybuf = sdsempty();
8570 c->argc = 0;
8571 c->argv = NULL;
8572 c->flags = 0;
8573 /* We set the fake client as a slave waiting for the synchronization
8574 * so that Redis will not try to send replies to this client. */
8575 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
8576 c->reply = listCreate();
8577 listSetFreeMethod(c->reply,decrRefCount);
8578 listSetDupMethod(c->reply,dupClientReplyValue);
8579 initClientMultiState(c);
8580 return c;
8581 }
8582
8583 static void freeFakeClient(struct redisClient *c) {
8584 sdsfree(c->querybuf);
8585 listRelease(c->reply);
8586 freeClientMultiState(c);
8587 zfree(c);
8588 }
8589
8590 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
8591 * error (the append only file is zero-length) REDIS_ERR is returned. On
8592 * fatal error an error message is logged and the program exists. */
8593 int loadAppendOnlyFile(char *filename) {
8594 struct redisClient *fakeClient;
8595 FILE *fp = fopen(filename,"r");
8596 struct redis_stat sb;
8597 unsigned long long loadedkeys = 0;
8598 int appendonly = server.appendonly;
8599
8600 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
8601 return REDIS_ERR;
8602
8603 if (fp == NULL) {
8604 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
8605 exit(1);
8606 }
8607
8608 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8609 * to the same file we're about to read. */
8610 server.appendonly = 0;
8611
8612 fakeClient = createFakeClient();
8613 while(1) {
8614 int argc, j;
8615 unsigned long len;
8616 robj **argv;
8617 char buf[128];
8618 sds argsds;
8619 struct redisCommand *cmd;
8620
8621 if (fgets(buf,sizeof(buf),fp) == NULL) {
8622 if (feof(fp))
8623 break;
8624 else
8625 goto readerr;
8626 }
8627 if (buf[0] != '*') goto fmterr;
8628 argc = atoi(buf+1);
8629 argv = zmalloc(sizeof(robj*)*argc);
8630 for (j = 0; j < argc; j++) {
8631 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
8632 if (buf[0] != '$') goto fmterr;
8633 len = strtol(buf+1,NULL,10);
8634 argsds = sdsnewlen(NULL,len);
8635 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
8636 argv[j] = createObject(REDIS_STRING,argsds);
8637 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
8638 }
8639
8640 /* Command lookup */
8641 cmd = lookupCommand(argv[0]->ptr);
8642 if (!cmd) {
8643 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
8644 exit(1);
8645 }
8646 /* Try object encoding */
8647 if (cmd->flags & REDIS_CMD_BULK)
8648 argv[argc-1] = tryObjectEncoding(argv[argc-1]);
8649 /* Run the command in the context of a fake client */
8650 fakeClient->argc = argc;
8651 fakeClient->argv = argv;
8652 cmd->proc(fakeClient);
8653 /* Discard the reply objects list from the fake client */
8654 while(listLength(fakeClient->reply))
8655 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
8656 /* Clean up, ready for the next command */
8657 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
8658 zfree(argv);
8659 /* Handle swapping while loading big datasets when VM is on */
8660 loadedkeys++;
8661 if (server.vm_enabled && (loadedkeys % 5000) == 0) {
8662 while (zmalloc_used_memory() > server.vm_max_memory) {
8663 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
8664 }
8665 }
8666 }
8667
8668 /* This point can only be reached when EOF is reached without errors.
8669 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8670 if (fakeClient->flags & REDIS_MULTI) goto readerr;
8671
8672 fclose(fp);
8673 freeFakeClient(fakeClient);
8674 server.appendonly = appendonly;
8675 return REDIS_OK;
8676
8677 readerr:
8678 if (feof(fp)) {
8679 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
8680 } else {
8681 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
8682 }
8683 exit(1);
8684 fmterr:
8685 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
8686 exit(1);
8687 }
8688
8689 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
8690 static int fwriteBulkObject(FILE *fp, robj *obj) {
8691 char buf[128];
8692 int decrrc = 0;
8693
8694 /* Avoid the incr/decr ref count business if possible to help
8695 * copy-on-write (we are often in a child process when this function
8696 * is called).
8697 * Also makes sure that key objects don't get incrRefCount-ed when VM
8698 * is enabled */
8699 if (obj->encoding != REDIS_ENCODING_RAW) {
8700 obj = getDecodedObject(obj);
8701 decrrc = 1;
8702 }
8703 snprintf(buf,sizeof(buf),"$%ld\r\n",(long)sdslen(obj->ptr));
8704 if (fwrite(buf,strlen(buf),1,fp) == 0) goto err;
8705 if (sdslen(obj->ptr) && fwrite(obj->ptr,sdslen(obj->ptr),1,fp) == 0)
8706 goto err;
8707 if (fwrite("\r\n",2,1,fp) == 0) goto err;
8708 if (decrrc) decrRefCount(obj);
8709 return 1;
8710 err:
8711 if (decrrc) decrRefCount(obj);
8712 return 0;
8713 }
8714
8715 /* Write binary-safe string into a file in the bulkformat
8716 * $<count>\r\n<payload>\r\n */
8717 static int fwriteBulkString(FILE *fp, char *s, unsigned long len) {
8718 char buf[128];
8719
8720 snprintf(buf,sizeof(buf),"$%ld\r\n",(unsigned long)len);
8721 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8722 if (len && fwrite(s,len,1,fp) == 0) return 0;
8723 if (fwrite("\r\n",2,1,fp) == 0) return 0;
8724 return 1;
8725 }
8726
8727 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8728 static int fwriteBulkDouble(FILE *fp, double d) {
8729 char buf[128], dbuf[128];
8730
8731 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
8732 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
8733 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8734 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
8735 return 1;
8736 }
8737
8738 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8739 static int fwriteBulkLong(FILE *fp, long l) {
8740 char buf[128], lbuf[128];
8741
8742 snprintf(lbuf,sizeof(lbuf),"%ld\r\n",l);
8743 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(lbuf)-2);
8744 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8745 if (fwrite(lbuf,strlen(lbuf),1,fp) == 0) return 0;
8746 return 1;
8747 }
8748
8749 /* Write a sequence of commands able to fully rebuild the dataset into
8750 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8751 static int rewriteAppendOnlyFile(char *filename) {
8752 dictIterator *di = NULL;
8753 dictEntry *de;
8754 FILE *fp;
8755 char tmpfile[256];
8756 int j;
8757 time_t now = time(NULL);
8758
8759 /* Note that we have to use a different temp name here compared to the
8760 * one used by rewriteAppendOnlyFileBackground() function. */
8761 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
8762 fp = fopen(tmpfile,"w");
8763 if (!fp) {
8764 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
8765 return REDIS_ERR;
8766 }
8767 for (j = 0; j < server.dbnum; j++) {
8768 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
8769 redisDb *db = server.db+j;
8770 dict *d = db->dict;
8771 if (dictSize(d) == 0) continue;
8772 di = dictGetIterator(d);
8773 if (!di) {
8774 fclose(fp);
8775 return REDIS_ERR;
8776 }
8777
8778 /* SELECT the new DB */
8779 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
8780 if (fwriteBulkLong(fp,j) == 0) goto werr;
8781
8782 /* Iterate this DB writing every entry */
8783 while((de = dictNext(di)) != NULL) {
8784 robj *key, *o;
8785 time_t expiretime;
8786 int swapped;
8787
8788 key = dictGetEntryKey(de);
8789 /* If the value for this key is swapped, load a preview in memory.
8790 * We use a "swapped" flag to remember if we need to free the
8791 * value object instead to just increment the ref count anyway
8792 * in order to avoid copy-on-write of pages if we are forked() */
8793 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
8794 key->storage == REDIS_VM_SWAPPING) {
8795 o = dictGetEntryVal(de);
8796 swapped = 0;
8797 } else {
8798 o = vmPreviewObject(key);
8799 swapped = 1;
8800 }
8801 expiretime = getExpire(db,key);
8802
8803 /* Save the key and associated value */
8804 if (o->type == REDIS_STRING) {
8805 /* Emit a SET command */
8806 char cmd[]="*3\r\n$3\r\nSET\r\n";
8807 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8808 /* Key and value */
8809 if (fwriteBulkObject(fp,key) == 0) goto werr;
8810 if (fwriteBulkObject(fp,o) == 0) goto werr;
8811 } else if (o->type == REDIS_LIST) {
8812 /* Emit the RPUSHes needed to rebuild the list */
8813 list *list = o->ptr;
8814 listNode *ln;
8815 listIter li;
8816
8817 listRewind(list,&li);
8818 while((ln = listNext(&li))) {
8819 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
8820 robj *eleobj = listNodeValue(ln);
8821
8822 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8823 if (fwriteBulkObject(fp,key) == 0) goto werr;
8824 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8825 }
8826 } else if (o->type == REDIS_SET) {
8827 /* Emit the SADDs needed to rebuild the set */
8828 dict *set = o->ptr;
8829 dictIterator *di = dictGetIterator(set);
8830 dictEntry *de;
8831
8832 while((de = dictNext(di)) != NULL) {
8833 char cmd[]="*3\r\n$4\r\nSADD\r\n";
8834 robj *eleobj = dictGetEntryKey(de);
8835
8836 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8837 if (fwriteBulkObject(fp,key) == 0) goto werr;
8838 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8839 }
8840 dictReleaseIterator(di);
8841 } else if (o->type == REDIS_ZSET) {
8842 /* Emit the ZADDs needed to rebuild the sorted set */
8843 zset *zs = o->ptr;
8844 dictIterator *di = dictGetIterator(zs->dict);
8845 dictEntry *de;
8846
8847 while((de = dictNext(di)) != NULL) {
8848 char cmd[]="*4\r\n$4\r\nZADD\r\n";
8849 robj *eleobj = dictGetEntryKey(de);
8850 double *score = dictGetEntryVal(de);
8851
8852 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8853 if (fwriteBulkObject(fp,key) == 0) goto werr;
8854 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
8855 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
8856 }
8857 dictReleaseIterator(di);
8858 } else if (o->type == REDIS_HASH) {
8859 char cmd[]="*4\r\n$4\r\nHSET\r\n";
8860
8861 /* Emit the HSETs needed to rebuild the hash */
8862 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
8863 unsigned char *p = zipmapRewind(o->ptr);
8864 unsigned char *field, *val;
8865 unsigned int flen, vlen;
8866
8867 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
8868 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8869 if (fwriteBulkObject(fp,key) == 0) goto werr;
8870 if (fwriteBulkString(fp,(char*)field,flen) == -1)
8871 return -1;
8872 if (fwriteBulkString(fp,(char*)val,vlen) == -1)
8873 return -1;
8874 }
8875 } else {
8876 dictIterator *di = dictGetIterator(o->ptr);
8877 dictEntry *de;
8878
8879 while((de = dictNext(di)) != NULL) {
8880 robj *field = dictGetEntryKey(de);
8881 robj *val = dictGetEntryVal(de);
8882
8883 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8884 if (fwriteBulkObject(fp,key) == 0) goto werr;
8885 if (fwriteBulkObject(fp,field) == -1) return -1;
8886 if (fwriteBulkObject(fp,val) == -1) return -1;
8887 }
8888 dictReleaseIterator(di);
8889 }
8890 } else {
8891 redisPanic("Unknown object type");
8892 }
8893 /* Save the expire time */
8894 if (expiretime != -1) {
8895 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
8896 /* If this key is already expired skip it */
8897 if (expiretime < now) continue;
8898 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8899 if (fwriteBulkObject(fp,key) == 0) goto werr;
8900 if (fwriteBulkLong(fp,expiretime) == 0) goto werr;
8901 }
8902 if (swapped) decrRefCount(o);
8903 }
8904 dictReleaseIterator(di);
8905 }
8906
8907 /* Make sure data will not remain on the OS's output buffers */
8908 fflush(fp);
8909 fsync(fileno(fp));
8910 fclose(fp);
8911
8912 /* Use RENAME to make sure the DB file is changed atomically only
8913 * if the generate DB file is ok. */
8914 if (rename(tmpfile,filename) == -1) {
8915 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
8916 unlink(tmpfile);
8917 return REDIS_ERR;
8918 }
8919 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
8920 return REDIS_OK;
8921
8922 werr:
8923 fclose(fp);
8924 unlink(tmpfile);
8925 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
8926 if (di) dictReleaseIterator(di);
8927 return REDIS_ERR;
8928 }
8929
8930 /* This is how rewriting of the append only file in background works:
8931 *
8932 * 1) The user calls BGREWRITEAOF
8933 * 2) Redis calls this function, that forks():
8934 * 2a) the child rewrite the append only file in a temp file.
8935 * 2b) the parent accumulates differences in server.bgrewritebuf.
8936 * 3) When the child finished '2a' exists.
8937 * 4) The parent will trap the exit code, if it's OK, will append the
8938 * data accumulated into server.bgrewritebuf into the temp file, and
8939 * finally will rename(2) the temp file in the actual file name.
8940 * The the new file is reopened as the new append only file. Profit!
8941 */
8942 static int rewriteAppendOnlyFileBackground(void) {
8943 pid_t childpid;
8944
8945 if (server.bgrewritechildpid != -1) return REDIS_ERR;
8946 if (server.vm_enabled) waitEmptyIOJobsQueue();
8947 if ((childpid = fork()) == 0) {
8948 /* Child */
8949 char tmpfile[256];
8950
8951 if (server.vm_enabled) vmReopenSwapFile();
8952 close(server.fd);
8953 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
8954 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
8955 _exit(0);
8956 } else {
8957 _exit(1);
8958 }
8959 } else {
8960 /* Parent */
8961 if (childpid == -1) {
8962 redisLog(REDIS_WARNING,
8963 "Can't rewrite append only file in background: fork: %s",
8964 strerror(errno));
8965 return REDIS_ERR;
8966 }
8967 redisLog(REDIS_NOTICE,
8968 "Background append only file rewriting started by pid %d",childpid);
8969 server.bgrewritechildpid = childpid;
8970 updateDictResizePolicy();
8971 /* We set appendseldb to -1 in order to force the next call to the
8972 * feedAppendOnlyFile() to issue a SELECT command, so the differences
8973 * accumulated by the parent into server.bgrewritebuf will start
8974 * with a SELECT statement and it will be safe to merge. */
8975 server.appendseldb = -1;
8976 return REDIS_OK;
8977 }
8978 return REDIS_OK; /* unreached */
8979 }
8980
8981 static void bgrewriteaofCommand(redisClient *c) {
8982 if (server.bgrewritechildpid != -1) {
8983 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
8984 return;
8985 }
8986 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
8987 char *status = "+Background append only file rewriting started\r\n";
8988 addReplySds(c,sdsnew(status));
8989 } else {
8990 addReply(c,shared.err);
8991 }
8992 }
8993
8994 static void aofRemoveTempFile(pid_t childpid) {
8995 char tmpfile[256];
8996
8997 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
8998 unlink(tmpfile);
8999 }
9000
9001 /* Virtual Memory is composed mainly of two subsystems:
9002 * - Blocking Virutal Memory
9003 * - Threaded Virtual Memory I/O
9004 * The two parts are not fully decoupled, but functions are split among two
9005 * different sections of the source code (delimited by comments) in order to
9006 * make more clear what functionality is about the blocking VM and what about
9007 * the threaded (not blocking) VM.
9008 *
9009 * Redis VM design:
9010 *
9011 * Redis VM is a blocking VM (one that blocks reading swapped values from
9012 * disk into memory when a value swapped out is needed in memory) that is made
9013 * unblocking by trying to examine the command argument vector in order to
9014 * load in background values that will likely be needed in order to exec
9015 * the command. The command is executed only once all the relevant keys
9016 * are loaded into memory.
9017 *
9018 * This basically is almost as simple of a blocking VM, but almost as parallel
9019 * as a fully non-blocking VM.
9020 */
9021
9022 /* Called when the user switches from "appendonly yes" to "appendonly no"
9023 * at runtime using the CONFIG command. */
9024 static void stopAppendOnly(void) {
9025 flushAppendOnlyFile();
9026 fsync(server.appendfd);
9027 close(server.appendfd);
9028
9029 server.appendfd = -1;
9030 server.appendseldb = -1;
9031 server.appendonly = 0;
9032 /* rewrite operation in progress? kill it, wait child exit */
9033 if (server.bgsavechildpid != -1) {
9034 int statloc;
9035
9036 if (kill(server.bgsavechildpid,SIGKILL) != -1)
9037 wait3(&statloc,0,NULL);
9038 /* reset the buffer accumulating changes while the child saves */
9039 sdsfree(server.bgrewritebuf);
9040 server.bgrewritebuf = sdsempty();
9041 server.bgsavechildpid = -1;
9042 }
9043 }
9044
9045 /* Called when the user switches from "appendonly no" to "appendonly yes"
9046 * at runtime using the CONFIG command. */
9047 static int startAppendOnly(void) {
9048 server.appendonly = 1;
9049 server.lastfsync = time(NULL);
9050 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
9051 if (server.appendfd == -1) {
9052 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno));
9053 return REDIS_ERR;
9054 }
9055 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
9056 server.appendonly = 0;
9057 close(server.appendfd);
9058 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, I can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.",strerror(errno));
9059 return REDIS_ERR;
9060 }
9061 return REDIS_OK;
9062 }
9063
9064 /* =================== Virtual Memory - Blocking Side ====================== */
9065
9066 static void vmInit(void) {
9067 off_t totsize;
9068 int pipefds[2];
9069 size_t stacksize;
9070 struct flock fl;
9071
9072 if (server.vm_max_threads != 0)
9073 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
9074
9075 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
9076 /* Try to open the old swap file, otherwise create it */
9077 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
9078 server.vm_fp = fopen(server.vm_swap_file,"w+b");
9079 }
9080 if (server.vm_fp == NULL) {
9081 redisLog(REDIS_WARNING,
9082 "Can't open the swap file: %s. Exiting.",
9083 strerror(errno));
9084 exit(1);
9085 }
9086 server.vm_fd = fileno(server.vm_fp);
9087 /* Lock the swap file for writing, this is useful in order to avoid
9088 * another instance to use the same swap file for a config error. */
9089 fl.l_type = F_WRLCK;
9090 fl.l_whence = SEEK_SET;
9091 fl.l_start = fl.l_len = 0;
9092 if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
9093 redisLog(REDIS_WARNING,
9094 "Can't lock the swap file at '%s': %s. Make sure it is not used by another Redis instance.", server.vm_swap_file, strerror(errno));
9095 exit(1);
9096 }
9097 /* Initialize */
9098 server.vm_next_page = 0;
9099 server.vm_near_pages = 0;
9100 server.vm_stats_used_pages = 0;
9101 server.vm_stats_swapped_objects = 0;
9102 server.vm_stats_swapouts = 0;
9103 server.vm_stats_swapins = 0;
9104 totsize = server.vm_pages*server.vm_page_size;
9105 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
9106 if (ftruncate(server.vm_fd,totsize) == -1) {
9107 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
9108 strerror(errno));
9109 exit(1);
9110 } else {
9111 redisLog(REDIS_NOTICE,"Swap file allocated with success");
9112 }
9113 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
9114 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
9115 (long long) (server.vm_pages+7)/8, server.vm_pages);
9116 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
9117
9118 /* Initialize threaded I/O (used by Virtual Memory) */
9119 server.io_newjobs = listCreate();
9120 server.io_processing = listCreate();
9121 server.io_processed = listCreate();
9122 server.io_ready_clients = listCreate();
9123 pthread_mutex_init(&server.io_mutex,NULL);
9124 pthread_mutex_init(&server.obj_freelist_mutex,NULL);
9125 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
9126 server.io_active_threads = 0;
9127 if (pipe(pipefds) == -1) {
9128 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
9129 ,strerror(errno));
9130 exit(1);
9131 }
9132 server.io_ready_pipe_read = pipefds[0];
9133 server.io_ready_pipe_write = pipefds[1];
9134 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
9135 /* LZF requires a lot of stack */
9136 pthread_attr_init(&server.io_threads_attr);
9137 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
9138 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
9139 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
9140 /* Listen for events in the threaded I/O pipe */
9141 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
9142 vmThreadedIOCompletedJob, NULL) == AE_ERR)
9143 oom("creating file event");
9144 }
9145
9146 /* Mark the page as used */
9147 static void vmMarkPageUsed(off_t page) {
9148 off_t byte = page/8;
9149 int bit = page&7;
9150 redisAssert(vmFreePage(page) == 1);
9151 server.vm_bitmap[byte] |= 1<<bit;
9152 }
9153
9154 /* Mark N contiguous pages as used, with 'page' being the first. */
9155 static void vmMarkPagesUsed(off_t page, off_t count) {
9156 off_t j;
9157
9158 for (j = 0; j < count; j++)
9159 vmMarkPageUsed(page+j);
9160 server.vm_stats_used_pages += count;
9161 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
9162 (long long)count, (long long)page);
9163 }
9164
9165 /* Mark the page as free */
9166 static void vmMarkPageFree(off_t page) {
9167 off_t byte = page/8;
9168 int bit = page&7;
9169 redisAssert(vmFreePage(page) == 0);
9170 server.vm_bitmap[byte] &= ~(1<<bit);
9171 }
9172
9173 /* Mark N contiguous pages as free, with 'page' being the first. */
9174 static void vmMarkPagesFree(off_t page, off_t count) {
9175 off_t j;
9176
9177 for (j = 0; j < count; j++)
9178 vmMarkPageFree(page+j);
9179 server.vm_stats_used_pages -= count;
9180 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
9181 (long long)count, (long long)page);
9182 }
9183
9184 /* Test if the page is free */
9185 static int vmFreePage(off_t page) {
9186 off_t byte = page/8;
9187 int bit = page&7;
9188 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
9189 }
9190
9191 /* Find N contiguous free pages storing the first page of the cluster in *first.
9192 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
9193 * REDIS_ERR is returned.
9194 *
9195 * This function uses a simple algorithm: we try to allocate
9196 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
9197 * again from the start of the swap file searching for free spaces.
9198 *
9199 * If it looks pretty clear that there are no free pages near our offset
9200 * we try to find less populated places doing a forward jump of
9201 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
9202 * without hurry, and then we jump again and so forth...
9203 *
9204 * This function can be improved using a free list to avoid to guess
9205 * too much, since we could collect data about freed pages.
9206 *
9207 * note: I implemented this function just after watching an episode of
9208 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
9209 */
9210 static int vmFindContiguousPages(off_t *first, off_t n) {
9211 off_t base, offset = 0, since_jump = 0, numfree = 0;
9212
9213 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
9214 server.vm_near_pages = 0;
9215 server.vm_next_page = 0;
9216 }
9217 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
9218 base = server.vm_next_page;
9219
9220 while(offset < server.vm_pages) {
9221 off_t this = base+offset;
9222
9223 /* If we overflow, restart from page zero */
9224 if (this >= server.vm_pages) {
9225 this -= server.vm_pages;
9226 if (this == 0) {
9227 /* Just overflowed, what we found on tail is no longer
9228 * interesting, as it's no longer contiguous. */
9229 numfree = 0;
9230 }
9231 }
9232 if (vmFreePage(this)) {
9233 /* This is a free page */
9234 numfree++;
9235 /* Already got N free pages? Return to the caller, with success */
9236 if (numfree == n) {
9237 *first = this-(n-1);
9238 server.vm_next_page = this+1;
9239 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
9240 return REDIS_OK;
9241 }
9242 } else {
9243 /* The current one is not a free page */
9244 numfree = 0;
9245 }
9246
9247 /* Fast-forward if the current page is not free and we already
9248 * searched enough near this place. */
9249 since_jump++;
9250 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
9251 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
9252 since_jump = 0;
9253 /* Note that even if we rewind after the jump, we are don't need
9254 * to make sure numfree is set to zero as we only jump *if* it
9255 * is set to zero. */
9256 } else {
9257 /* Otherwise just check the next page */
9258 offset++;
9259 }
9260 }
9261 return REDIS_ERR;
9262 }
9263
9264 /* Write the specified object at the specified page of the swap file */
9265 static int vmWriteObjectOnSwap(robj *o, off_t page) {
9266 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9267 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9268 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9269 redisLog(REDIS_WARNING,
9270 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
9271 strerror(errno));
9272 return REDIS_ERR;
9273 }
9274 rdbSaveObject(server.vm_fp,o);
9275 fflush(server.vm_fp);
9276 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9277 return REDIS_OK;
9278 }
9279
9280 /* Swap the 'val' object relative to 'key' into disk. Store all the information
9281 * needed to later retrieve the object into the key object.
9282 * If we can't find enough contiguous empty pages to swap the object on disk
9283 * REDIS_ERR is returned. */
9284 static int vmSwapObjectBlocking(robj *key, robj *val) {
9285 off_t pages = rdbSavedObjectPages(val,NULL);
9286 off_t page;
9287
9288 assert(key->storage == REDIS_VM_MEMORY);
9289 assert(key->refcount == 1);
9290 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return REDIS_ERR;
9291 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return REDIS_ERR;
9292 key->vm.page = page;
9293 key->vm.usedpages = pages;
9294 key->storage = REDIS_VM_SWAPPED;
9295 key->vtype = val->type;
9296 decrRefCount(val); /* Deallocate the object from memory. */
9297 vmMarkPagesUsed(page,pages);
9298 redisLog(REDIS_DEBUG,"VM: object %s swapped out at %lld (%lld pages)",
9299 (unsigned char*) key->ptr,
9300 (unsigned long long) page, (unsigned long long) pages);
9301 server.vm_stats_swapped_objects++;
9302 server.vm_stats_swapouts++;
9303 return REDIS_OK;
9304 }
9305
9306 static robj *vmReadObjectFromSwap(off_t page, int type) {
9307 robj *o;
9308
9309 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9310 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9311 redisLog(REDIS_WARNING,
9312 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
9313 strerror(errno));
9314 _exit(1);
9315 }
9316 o = rdbLoadObject(type,server.vm_fp);
9317 if (o == NULL) {
9318 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
9319 _exit(1);
9320 }
9321 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9322 return o;
9323 }
9324
9325 /* Load the value object relative to the 'key' object from swap to memory.
9326 * The newly allocated object is returned.
9327 *
9328 * If preview is true the unserialized object is returned to the caller but
9329 * no changes are made to the key object, nor the pages are marked as freed */
9330 static robj *vmGenericLoadObject(robj *key, int preview) {
9331 robj *val;
9332
9333 redisAssert(key->storage == REDIS_VM_SWAPPED || key->storage == REDIS_VM_LOADING);
9334 val = vmReadObjectFromSwap(key->vm.page,key->vtype);
9335 if (!preview) {
9336 key->storage = REDIS_VM_MEMORY;
9337 key->vm.atime = server.unixtime;
9338 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9339 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk",
9340 (unsigned char*) key->ptr);
9341 server.vm_stats_swapped_objects--;
9342 } else {
9343 redisLog(REDIS_DEBUG, "VM: object %s previewed from disk",
9344 (unsigned char*) key->ptr);
9345 }
9346 server.vm_stats_swapins++;
9347 return val;
9348 }
9349
9350 /* Plain object loading, from swap to memory */
9351 static robj *vmLoadObject(robj *key) {
9352 /* If we are loading the object in background, stop it, we
9353 * need to load this object synchronously ASAP. */
9354 if (key->storage == REDIS_VM_LOADING)
9355 vmCancelThreadedIOJob(key);
9356 return vmGenericLoadObject(key,0);
9357 }
9358
9359 /* Just load the value on disk, without to modify the key.
9360 * This is useful when we want to perform some operation on the value
9361 * without to really bring it from swap to memory, like while saving the
9362 * dataset or rewriting the append only log. */
9363 static robj *vmPreviewObject(robj *key) {
9364 return vmGenericLoadObject(key,1);
9365 }
9366
9367 /* How a good candidate is this object for swapping?
9368 * The better candidate it is, the greater the returned value.
9369 *
9370 * Currently we try to perform a fast estimation of the object size in
9371 * memory, and combine it with aging informations.
9372 *
9373 * Basically swappability = idle-time * log(estimated size)
9374 *
9375 * Bigger objects are preferred over smaller objects, but not
9376 * proportionally, this is why we use the logarithm. This algorithm is
9377 * just a first try and will probably be tuned later. */
9378 static double computeObjectSwappability(robj *o) {
9379 time_t age = server.unixtime - o->vm.atime;
9380 long asize = 0;
9381 list *l;
9382 dict *d;
9383 struct dictEntry *de;
9384 int z;
9385
9386 if (age <= 0) return 0;
9387 switch(o->type) {
9388 case REDIS_STRING:
9389 if (o->encoding != REDIS_ENCODING_RAW) {
9390 asize = sizeof(*o);
9391 } else {
9392 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
9393 }
9394 break;
9395 case REDIS_LIST:
9396 l = o->ptr;
9397 listNode *ln = listFirst(l);
9398
9399 asize = sizeof(list);
9400 if (ln) {
9401 robj *ele = ln->value;
9402 long elesize;
9403
9404 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9405 (sizeof(*o)+sdslen(ele->ptr)) :
9406 sizeof(*o);
9407 asize += (sizeof(listNode)+elesize)*listLength(l);
9408 }
9409 break;
9410 case REDIS_SET:
9411 case REDIS_ZSET:
9412 z = (o->type == REDIS_ZSET);
9413 d = z ? ((zset*)o->ptr)->dict : o->ptr;
9414
9415 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9416 if (z) asize += sizeof(zset)-sizeof(dict);
9417 if (dictSize(d)) {
9418 long elesize;
9419 robj *ele;
9420
9421 de = dictGetRandomKey(d);
9422 ele = dictGetEntryKey(de);
9423 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9424 (sizeof(*o)+sdslen(ele->ptr)) :
9425 sizeof(*o);
9426 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9427 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
9428 }
9429 break;
9430 case REDIS_HASH:
9431 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9432 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
9433 unsigned int len = zipmapLen((unsigned char*)o->ptr);
9434 unsigned int klen, vlen;
9435 unsigned char *key, *val;
9436
9437 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
9438 klen = 0;
9439 vlen = 0;
9440 }
9441 asize = len*(klen+vlen+3);
9442 } else if (o->encoding == REDIS_ENCODING_HT) {
9443 d = o->ptr;
9444 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9445 if (dictSize(d)) {
9446 long elesize;
9447 robj *ele;
9448
9449 de = dictGetRandomKey(d);
9450 ele = dictGetEntryKey(de);
9451 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9452 (sizeof(*o)+sdslen(ele->ptr)) :
9453 sizeof(*o);
9454 ele = dictGetEntryVal(de);
9455 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9456 (sizeof(*o)+sdslen(ele->ptr)) :
9457 sizeof(*o);
9458 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9459 }
9460 }
9461 break;
9462 }
9463 return (double)age*log(1+asize);
9464 }
9465
9466 /* Try to swap an object that's a good candidate for swapping.
9467 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
9468 * to swap any object at all.
9469 *
9470 * If 'usethreaded' is true, Redis will try to swap the object in background
9471 * using I/O threads. */
9472 static int vmSwapOneObject(int usethreads) {
9473 int j, i;
9474 struct dictEntry *best = NULL;
9475 double best_swappability = 0;
9476 redisDb *best_db = NULL;
9477 robj *key, *val;
9478
9479 for (j = 0; j < server.dbnum; j++) {
9480 redisDb *db = server.db+j;
9481 /* Why maxtries is set to 100?
9482 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9483 * are swappable objects */
9484 int maxtries = 100;
9485
9486 if (dictSize(db->dict) == 0) continue;
9487 for (i = 0; i < 5; i++) {
9488 dictEntry *de;
9489 double swappability;
9490
9491 if (maxtries) maxtries--;
9492 de = dictGetRandomKey(db->dict);
9493 key = dictGetEntryKey(de);
9494 val = dictGetEntryVal(de);
9495 /* Only swap objects that are currently in memory.
9496 *
9497 * Also don't swap shared objects if threaded VM is on, as we
9498 * try to ensure that the main thread does not touch the
9499 * object while the I/O thread is using it, but we can't
9500 * control other keys without adding additional mutex. */
9501 if (key->storage != REDIS_VM_MEMORY ||
9502 (server.vm_max_threads != 0 && val->refcount != 1)) {
9503 if (maxtries) i--; /* don't count this try */
9504 continue;
9505 }
9506 swappability = computeObjectSwappability(val);
9507 if (!best || swappability > best_swappability) {
9508 best = de;
9509 best_swappability = swappability;
9510 best_db = db;
9511 }
9512 }
9513 }
9514 if (best == NULL) return REDIS_ERR;
9515 key = dictGetEntryKey(best);
9516 val = dictGetEntryVal(best);
9517
9518 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
9519 key->ptr, best_swappability);
9520
9521 /* Unshare the key if needed */
9522 if (key->refcount > 1) {
9523 robj *newkey = dupStringObject(key);
9524 decrRefCount(key);
9525 key = dictGetEntryKey(best) = newkey;
9526 }
9527 /* Swap it */
9528 if (usethreads) {
9529 vmSwapObjectThreaded(key,val,best_db);
9530 return REDIS_OK;
9531 } else {
9532 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
9533 dictGetEntryVal(best) = NULL;
9534 return REDIS_OK;
9535 } else {
9536 return REDIS_ERR;
9537 }
9538 }
9539 }
9540
9541 static int vmSwapOneObjectBlocking() {
9542 return vmSwapOneObject(0);
9543 }
9544
9545 static int vmSwapOneObjectThreaded() {
9546 return vmSwapOneObject(1);
9547 }
9548
9549 /* Return true if it's safe to swap out objects in a given moment.
9550 * Basically we don't want to swap objects out while there is a BGSAVE
9551 * or a BGAEOREWRITE running in backgroud. */
9552 static int vmCanSwapOut(void) {
9553 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
9554 }
9555
9556 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
9557 * and was deleted. Otherwise 0 is returned. */
9558 static int deleteIfSwapped(redisDb *db, robj *key) {
9559 dictEntry *de;
9560 robj *foundkey;
9561
9562 if ((de = dictFind(db->dict,key)) == NULL) return 0;
9563 foundkey = dictGetEntryKey(de);
9564 if (foundkey->storage == REDIS_VM_MEMORY) return 0;
9565 deleteKey(db,key);
9566 return 1;
9567 }
9568
9569 /* =================== Virtual Memory - Threaded I/O ======================= */
9570
9571 static void freeIOJob(iojob *j) {
9572 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
9573 j->type == REDIS_IOJOB_DO_SWAP ||
9574 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
9575 decrRefCount(j->val);
9576 /* We don't decrRefCount the j->key field as we did't incremented
9577 * the count creating IO Jobs. This is because the key field here is
9578 * just used as an indentifier and if a key is removed the Job should
9579 * never be touched again. */
9580 zfree(j);
9581 }
9582
9583 /* Every time a thread finished a Job, it writes a byte into the write side
9584 * of an unix pipe in order to "awake" the main thread, and this function
9585 * is called. */
9586 static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
9587 int mask)
9588 {
9589 char buf[1];
9590 int retval, processed = 0, toprocess = -1, trytoswap = 1;
9591 REDIS_NOTUSED(el);
9592 REDIS_NOTUSED(mask);
9593 REDIS_NOTUSED(privdata);
9594
9595 /* For every byte we read in the read side of the pipe, there is one
9596 * I/O job completed to process. */
9597 while((retval = read(fd,buf,1)) == 1) {
9598 iojob *j;
9599 listNode *ln;
9600 robj *key;
9601 struct dictEntry *de;
9602
9603 redisLog(REDIS_DEBUG,"Processing I/O completed job");
9604
9605 /* Get the processed element (the oldest one) */
9606 lockThreadedIO();
9607 assert(listLength(server.io_processed) != 0);
9608 if (toprocess == -1) {
9609 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
9610 if (toprocess <= 0) toprocess = 1;
9611 }
9612 ln = listFirst(server.io_processed);
9613 j = ln->value;
9614 listDelNode(server.io_processed,ln);
9615 unlockThreadedIO();
9616 /* If this job is marked as canceled, just ignore it */
9617 if (j->canceled) {
9618 freeIOJob(j);
9619 continue;
9620 }
9621 /* Post process it in the main thread, as there are things we
9622 * can do just here to avoid race conditions and/or invasive locks */
9623 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);
9624 de = dictFind(j->db->dict,j->key);
9625 assert(de != NULL);
9626 key = dictGetEntryKey(de);
9627 if (j->type == REDIS_IOJOB_LOAD) {
9628 redisDb *db;
9629
9630 /* Key loaded, bring it at home */
9631 key->storage = REDIS_VM_MEMORY;
9632 key->vm.atime = server.unixtime;
9633 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9634 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
9635 (unsigned char*) key->ptr);
9636 server.vm_stats_swapped_objects--;
9637 server.vm_stats_swapins++;
9638 dictGetEntryVal(de) = j->val;
9639 incrRefCount(j->val);
9640 db = j->db;
9641 freeIOJob(j);
9642 /* Handle clients waiting for this key to be loaded. */
9643 handleClientsBlockedOnSwappedKey(db,key);
9644 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9645 /* Now we know the amount of pages required to swap this object.
9646 * Let's find some space for it, and queue this task again
9647 * rebranded as REDIS_IOJOB_DO_SWAP. */
9648 if (!vmCanSwapOut() ||
9649 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
9650 {
9651 /* Ooops... no space or we can't swap as there is
9652 * a fork()ed Redis trying to save stuff on disk. */
9653 freeIOJob(j);
9654 key->storage = REDIS_VM_MEMORY; /* undo operation */
9655 } else {
9656 /* Note that we need to mark this pages as used now,
9657 * if the job will be canceled, we'll mark them as freed
9658 * again. */
9659 vmMarkPagesUsed(j->page,j->pages);
9660 j->type = REDIS_IOJOB_DO_SWAP;
9661 lockThreadedIO();
9662 queueIOJob(j);
9663 unlockThreadedIO();
9664 }
9665 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9666 robj *val;
9667
9668 /* Key swapped. We can finally free some memory. */
9669 if (key->storage != REDIS_VM_SWAPPING) {
9670 printf("key->storage: %d\n",key->storage);
9671 printf("key->name: %s\n",(char*)key->ptr);
9672 printf("key->refcount: %d\n",key->refcount);
9673 printf("val: %p\n",(void*)j->val);
9674 printf("val->type: %d\n",j->val->type);
9675 printf("val->ptr: %s\n",(char*)j->val->ptr);
9676 }
9677 redisAssert(key->storage == REDIS_VM_SWAPPING);
9678 val = dictGetEntryVal(de);
9679 key->vm.page = j->page;
9680 key->vm.usedpages = j->pages;
9681 key->storage = REDIS_VM_SWAPPED;
9682 key->vtype = j->val->type;
9683 decrRefCount(val); /* Deallocate the object from memory. */
9684 dictGetEntryVal(de) = NULL;
9685 redisLog(REDIS_DEBUG,
9686 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9687 (unsigned char*) key->ptr,
9688 (unsigned long long) j->page, (unsigned long long) j->pages);
9689 server.vm_stats_swapped_objects++;
9690 server.vm_stats_swapouts++;
9691 freeIOJob(j);
9692 /* Put a few more swap requests in queue if we are still
9693 * out of memory */
9694 if (trytoswap && vmCanSwapOut() &&
9695 zmalloc_used_memory() > server.vm_max_memory)
9696 {
9697 int more = 1;
9698 while(more) {
9699 lockThreadedIO();
9700 more = listLength(server.io_newjobs) <
9701 (unsigned) server.vm_max_threads;
9702 unlockThreadedIO();
9703 /* Don't waste CPU time if swappable objects are rare. */
9704 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
9705 trytoswap = 0;
9706 break;
9707 }
9708 }
9709 }
9710 }
9711 processed++;
9712 if (processed == toprocess) return;
9713 }
9714 if (retval < 0 && errno != EAGAIN) {
9715 redisLog(REDIS_WARNING,
9716 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9717 strerror(errno));
9718 }
9719 }
9720
9721 static void lockThreadedIO(void) {
9722 pthread_mutex_lock(&server.io_mutex);
9723 }
9724
9725 static void unlockThreadedIO(void) {
9726 pthread_mutex_unlock(&server.io_mutex);
9727 }
9728
9729 /* Remove the specified object from the threaded I/O queue if still not
9730 * processed, otherwise make sure to flag it as canceled. */
9731 static void vmCancelThreadedIOJob(robj *o) {
9732 list *lists[3] = {
9733 server.io_newjobs, /* 0 */
9734 server.io_processing, /* 1 */
9735 server.io_processed /* 2 */
9736 };
9737 int i;
9738
9739 assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
9740 again:
9741 lockThreadedIO();
9742 /* Search for a matching key in one of the queues */
9743 for (i = 0; i < 3; i++) {
9744 listNode *ln;
9745 listIter li;
9746
9747 listRewind(lists[i],&li);
9748 while ((ln = listNext(&li)) != NULL) {
9749 iojob *job = ln->value;
9750
9751 if (job->canceled) continue; /* Skip this, already canceled. */
9752 if (job->key == o) {
9753 redisLog(REDIS_DEBUG,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
9754 (void*)job, (char*)o->ptr, job->type, i);
9755 /* Mark the pages as free since the swap didn't happened
9756 * or happened but is now discarded. */
9757 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
9758 vmMarkPagesFree(job->page,job->pages);
9759 /* Cancel the job. It depends on the list the job is
9760 * living in. */
9761 switch(i) {
9762 case 0: /* io_newjobs */
9763 /* If the job was yet not processed the best thing to do
9764 * is to remove it from the queue at all */
9765 freeIOJob(job);
9766 listDelNode(lists[i],ln);
9767 break;
9768 case 1: /* io_processing */
9769 /* Oh Shi- the thread is messing with the Job:
9770 *
9771 * Probably it's accessing the object if this is a
9772 * PREPARE_SWAP or DO_SWAP job.
9773 * If it's a LOAD job it may be reading from disk and
9774 * if we don't wait for the job to terminate before to
9775 * cancel it, maybe in a few microseconds data can be
9776 * corrupted in this pages. So the short story is:
9777 *
9778 * Better to wait for the job to move into the
9779 * next queue (processed)... */
9780
9781 /* We try again and again until the job is completed. */
9782 unlockThreadedIO();
9783 /* But let's wait some time for the I/O thread
9784 * to finish with this job. After all this condition
9785 * should be very rare. */
9786 usleep(1);
9787 goto again;
9788 case 2: /* io_processed */
9789 /* The job was already processed, that's easy...
9790 * just mark it as canceled so that we'll ignore it
9791 * when processing completed jobs. */
9792 job->canceled = 1;
9793 break;
9794 }
9795 /* Finally we have to adjust the storage type of the object
9796 * in order to "UNDO" the operaiton. */
9797 if (o->storage == REDIS_VM_LOADING)
9798 o->storage = REDIS_VM_SWAPPED;
9799 else if (o->storage == REDIS_VM_SWAPPING)
9800 o->storage = REDIS_VM_MEMORY;
9801 unlockThreadedIO();
9802 return;
9803 }
9804 }
9805 }
9806 unlockThreadedIO();
9807 assert(1 != 1); /* We should never reach this */
9808 }
9809
9810 static void *IOThreadEntryPoint(void *arg) {
9811 iojob *j;
9812 listNode *ln;
9813 REDIS_NOTUSED(arg);
9814
9815 pthread_detach(pthread_self());
9816 while(1) {
9817 /* Get a new job to process */
9818 lockThreadedIO();
9819 if (listLength(server.io_newjobs) == 0) {
9820 /* No new jobs in queue, exit. */
9821 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
9822 (long) pthread_self());
9823 server.io_active_threads--;
9824 unlockThreadedIO();
9825 return NULL;
9826 }
9827 ln = listFirst(server.io_newjobs);
9828 j = ln->value;
9829 listDelNode(server.io_newjobs,ln);
9830 /* Add the job in the processing queue */
9831 j->thread = pthread_self();
9832 listAddNodeTail(server.io_processing,j);
9833 ln = listLast(server.io_processing); /* We use ln later to remove it */
9834 unlockThreadedIO();
9835 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
9836 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
9837
9838 /* Process the Job */
9839 if (j->type == REDIS_IOJOB_LOAD) {
9840 j->val = vmReadObjectFromSwap(j->page,j->key->vtype);
9841 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9842 FILE *fp = fopen("/dev/null","w+");
9843 j->pages = rdbSavedObjectPages(j->val,fp);
9844 fclose(fp);
9845 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9846 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
9847 j->canceled = 1;
9848 }
9849
9850 /* Done: insert the job into the processed queue */
9851 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
9852 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
9853 lockThreadedIO();
9854 listDelNode(server.io_processing,ln);
9855 listAddNodeTail(server.io_processed,j);
9856 unlockThreadedIO();
9857
9858 /* Signal the main thread there is new stuff to process */
9859 assert(write(server.io_ready_pipe_write,"x",1) == 1);
9860 }
9861 return NULL; /* never reached */
9862 }
9863
9864 static void spawnIOThread(void) {
9865 pthread_t thread;
9866 sigset_t mask, omask;
9867 int err;
9868
9869 sigemptyset(&mask);
9870 sigaddset(&mask,SIGCHLD);
9871 sigaddset(&mask,SIGHUP);
9872 sigaddset(&mask,SIGPIPE);
9873 pthread_sigmask(SIG_SETMASK, &mask, &omask);
9874 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
9875 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
9876 strerror(err));
9877 usleep(1000000);
9878 }
9879 pthread_sigmask(SIG_SETMASK, &omask, NULL);
9880 server.io_active_threads++;
9881 }
9882
9883 /* We need to wait for the last thread to exit before we are able to
9884 * fork() in order to BGSAVE or BGREWRITEAOF. */
9885 static void waitEmptyIOJobsQueue(void) {
9886 while(1) {
9887 int io_processed_len;
9888
9889 lockThreadedIO();
9890 if (listLength(server.io_newjobs) == 0 &&
9891 listLength(server.io_processing) == 0 &&
9892 server.io_active_threads == 0)
9893 {
9894 unlockThreadedIO();
9895 return;
9896 }
9897 /* While waiting for empty jobs queue condition we post-process some
9898 * finshed job, as I/O threads may be hanging trying to write against
9899 * the io_ready_pipe_write FD but there are so much pending jobs that
9900 * it's blocking. */
9901 io_processed_len = listLength(server.io_processed);
9902 unlockThreadedIO();
9903 if (io_processed_len) {
9904 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
9905 usleep(1000); /* 1 millisecond */
9906 } else {
9907 usleep(10000); /* 10 milliseconds */
9908 }
9909 }
9910 }
9911
9912 static void vmReopenSwapFile(void) {
9913 /* Note: we don't close the old one as we are in the child process
9914 * and don't want to mess at all with the original file object. */
9915 server.vm_fp = fopen(server.vm_swap_file,"r+b");
9916 if (server.vm_fp == NULL) {
9917 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
9918 server.vm_swap_file);
9919 _exit(1);
9920 }
9921 server.vm_fd = fileno(server.vm_fp);
9922 }
9923
9924 /* This function must be called while with threaded IO locked */
9925 static void queueIOJob(iojob *j) {
9926 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
9927 (void*)j, j->type, (char*)j->key->ptr);
9928 listAddNodeTail(server.io_newjobs,j);
9929 if (server.io_active_threads < server.vm_max_threads)
9930 spawnIOThread();
9931 }
9932
9933 static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
9934 iojob *j;
9935
9936 assert(key->storage == REDIS_VM_MEMORY);
9937 assert(key->refcount == 1);
9938
9939 j = zmalloc(sizeof(*j));
9940 j->type = REDIS_IOJOB_PREPARE_SWAP;
9941 j->db = db;
9942 j->key = key;
9943 j->val = val;
9944 incrRefCount(val);
9945 j->canceled = 0;
9946 j->thread = (pthread_t) -1;
9947 key->storage = REDIS_VM_SWAPPING;
9948
9949 lockThreadedIO();
9950 queueIOJob(j);
9951 unlockThreadedIO();
9952 return REDIS_OK;
9953 }
9954
9955 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
9956
9957 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
9958 * If there is not already a job loading the key, it is craeted.
9959 * The key is added to the io_keys list in the client structure, and also
9960 * in the hash table mapping swapped keys to waiting clients, that is,
9961 * server.io_waited_keys. */
9962 static int waitForSwappedKey(redisClient *c, robj *key) {
9963 struct dictEntry *de;
9964 robj *o;
9965 list *l;
9966
9967 /* If the key does not exist or is already in RAM we don't need to
9968 * block the client at all. */
9969 de = dictFind(c->db->dict,key);
9970 if (de == NULL) return 0;
9971 o = dictGetEntryKey(de);
9972 if (o->storage == REDIS_VM_MEMORY) {
9973 return 0;
9974 } else if (o->storage == REDIS_VM_SWAPPING) {
9975 /* We were swapping the key, undo it! */
9976 vmCancelThreadedIOJob(o);
9977 return 0;
9978 }
9979
9980 /* OK: the key is either swapped, or being loaded just now. */
9981
9982 /* Add the key to the list of keys this client is waiting for.
9983 * This maps clients to keys they are waiting for. */
9984 listAddNodeTail(c->io_keys,key);
9985 incrRefCount(key);
9986
9987 /* Add the client to the swapped keys => clients waiting map. */
9988 de = dictFind(c->db->io_keys,key);
9989 if (de == NULL) {
9990 int retval;
9991
9992 /* For every key we take a list of clients blocked for it */
9993 l = listCreate();
9994 retval = dictAdd(c->db->io_keys,key,l);
9995 incrRefCount(key);
9996 assert(retval == DICT_OK);
9997 } else {
9998 l = dictGetEntryVal(de);
9999 }
10000 listAddNodeTail(l,c);
10001
10002 /* Are we already loading the key from disk? If not create a job */
10003 if (o->storage == REDIS_VM_SWAPPED) {
10004 iojob *j;
10005
10006 o->storage = REDIS_VM_LOADING;
10007 j = zmalloc(sizeof(*j));
10008 j->type = REDIS_IOJOB_LOAD;
10009 j->db = c->db;
10010 j->key = o;
10011 j->key->vtype = o->vtype;
10012 j->page = o->vm.page;
10013 j->val = NULL;
10014 j->canceled = 0;
10015 j->thread = (pthread_t) -1;
10016 lockThreadedIO();
10017 queueIOJob(j);
10018 unlockThreadedIO();
10019 }
10020 return 1;
10021 }
10022
10023 /* Preload keys for any command with first, last and step values for
10024 * the command keys prototype, as defined in the command table. */
10025 static void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10026 int j, last;
10027 if (cmd->vm_firstkey == 0) return;
10028 last = cmd->vm_lastkey;
10029 if (last < 0) last = argc+last;
10030 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
10031 redisAssert(j < argc);
10032 waitForSwappedKey(c,argv[j]);
10033 }
10034 }
10035
10036 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
10037 * Note that the number of keys to preload is user-defined, so we need to
10038 * apply a sanity check against argc. */
10039 static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10040 int i, num;
10041 REDIS_NOTUSED(cmd);
10042
10043 num = atoi(argv[2]->ptr);
10044 if (num > (argc-3)) return;
10045 for (i = 0; i < num; i++) {
10046 waitForSwappedKey(c,argv[3+i]);
10047 }
10048 }
10049
10050 /* Preload keys needed to execute the entire MULTI/EXEC block.
10051 *
10052 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
10053 * and will block the client when any command requires a swapped out value. */
10054 static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10055 int i, margc;
10056 struct redisCommand *mcmd;
10057 robj **margv;
10058 REDIS_NOTUSED(cmd);
10059 REDIS_NOTUSED(argc);
10060 REDIS_NOTUSED(argv);
10061
10062 if (!(c->flags & REDIS_MULTI)) return;
10063 for (i = 0; i < c->mstate.count; i++) {
10064 mcmd = c->mstate.commands[i].cmd;
10065 margc = c->mstate.commands[i].argc;
10066 margv = c->mstate.commands[i].argv;
10067
10068 if (mcmd->vm_preload_proc != NULL) {
10069 mcmd->vm_preload_proc(c,mcmd,margc,margv);
10070 } else {
10071 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
10072 }
10073 }
10074 }
10075
10076 /* Is this client attempting to run a command against swapped keys?
10077 * If so, block it ASAP, load the keys in background, then resume it.
10078 *
10079 * The important idea about this function is that it can fail! If keys will
10080 * still be swapped when the client is resumed, this key lookups will
10081 * just block loading keys from disk. In practical terms this should only
10082 * happen with SORT BY command or if there is a bug in this function.
10083 *
10084 * Return 1 if the client is marked as blocked, 0 if the client can
10085 * continue as the keys it is going to access appear to be in memory. */
10086 static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
10087 if (cmd->vm_preload_proc != NULL) {
10088 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
10089 } else {
10090 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
10091 }
10092
10093 /* If the client was blocked for at least one key, mark it as blocked. */
10094 if (listLength(c->io_keys)) {
10095 c->flags |= REDIS_IO_WAIT;
10096 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
10097 server.vm_blocked_clients++;
10098 return 1;
10099 } else {
10100 return 0;
10101 }
10102 }
10103
10104 /* Remove the 'key' from the list of blocked keys for a given client.
10105 *
10106 * The function returns 1 when there are no longer blocking keys after
10107 * the current one was removed (and the client can be unblocked). */
10108 static int dontWaitForSwappedKey(redisClient *c, robj *key) {
10109 list *l;
10110 listNode *ln;
10111 listIter li;
10112 struct dictEntry *de;
10113
10114 /* Remove the key from the list of keys this client is waiting for. */
10115 listRewind(c->io_keys,&li);
10116 while ((ln = listNext(&li)) != NULL) {
10117 if (equalStringObjects(ln->value,key)) {
10118 listDelNode(c->io_keys,ln);
10119 break;
10120 }
10121 }
10122 assert(ln != NULL);
10123
10124 /* Remove the client form the key => waiting clients map. */
10125 de = dictFind(c->db->io_keys,key);
10126 assert(de != NULL);
10127 l = dictGetEntryVal(de);
10128 ln = listSearchKey(l,c);
10129 assert(ln != NULL);
10130 listDelNode(l,ln);
10131 if (listLength(l) == 0)
10132 dictDelete(c->db->io_keys,key);
10133
10134 return listLength(c->io_keys) == 0;
10135 }
10136
10137 static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
10138 struct dictEntry *de;
10139 list *l;
10140 listNode *ln;
10141 int len;
10142
10143 de = dictFind(db->io_keys,key);
10144 if (!de) return;
10145
10146 l = dictGetEntryVal(de);
10147 len = listLength(l);
10148 /* Note: we can't use something like while(listLength(l)) as the list
10149 * can be freed by the calling function when we remove the last element. */
10150 while (len--) {
10151 ln = listFirst(l);
10152 redisClient *c = ln->value;
10153
10154 if (dontWaitForSwappedKey(c,key)) {
10155 /* Put the client in the list of clients ready to go as we
10156 * loaded all the keys about it. */
10157 listAddNodeTail(server.io_ready_clients,c);
10158 }
10159 }
10160 }
10161
10162 /* =========================== Remote Configuration ========================= */
10163
10164 static void configSetCommand(redisClient *c) {
10165 robj *o = getDecodedObject(c->argv[3]);
10166 long long ll;
10167
10168 if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
10169 zfree(server.dbfilename);
10170 server.dbfilename = zstrdup(o->ptr);
10171 } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
10172 zfree(server.requirepass);
10173 server.requirepass = zstrdup(o->ptr);
10174 } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
10175 zfree(server.masterauth);
10176 server.masterauth = zstrdup(o->ptr);
10177 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
10178 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10179 ll < 0) goto badfmt;
10180 server.maxmemory = ll;
10181 } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
10182 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10183 ll < 0 || ll > LONG_MAX) goto badfmt;
10184 server.maxidletime = ll;
10185 } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
10186 if (!strcasecmp(o->ptr,"no")) {
10187 server.appendfsync = APPENDFSYNC_NO;
10188 } else if (!strcasecmp(o->ptr,"everysec")) {
10189 server.appendfsync = APPENDFSYNC_EVERYSEC;
10190 } else if (!strcasecmp(o->ptr,"always")) {
10191 server.appendfsync = APPENDFSYNC_ALWAYS;
10192 } else {
10193 goto badfmt;
10194 }
10195 } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
10196 int old = server.appendonly;
10197 int new = yesnotoi(o->ptr);
10198
10199 if (new == -1) goto badfmt;
10200 if (old != new) {
10201 if (new == 0) {
10202 stopAppendOnly();
10203 } else {
10204 if (startAppendOnly() == REDIS_ERR) {
10205 addReplySds(c,sdscatprintf(sdsempty(),
10206 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
10207 decrRefCount(o);
10208 return;
10209 }
10210 }
10211 }
10212 } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
10213 int vlen, j;
10214 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
10215
10216 /* Perform sanity check before setting the new config:
10217 * - Even number of args
10218 * - Seconds >= 1, changes >= 0 */
10219 if (vlen & 1) {
10220 sdsfreesplitres(v,vlen);
10221 goto badfmt;
10222 }
10223 for (j = 0; j < vlen; j++) {
10224 char *eptr;
10225 long val;
10226
10227 val = strtoll(v[j], &eptr, 10);
10228 if (eptr[0] != '\0' ||
10229 ((j & 1) == 0 && val < 1) ||
10230 ((j & 1) == 1 && val < 0)) {
10231 sdsfreesplitres(v,vlen);
10232 goto badfmt;
10233 }
10234 }
10235 /* Finally set the new config */
10236 resetServerSaveParams();
10237 for (j = 0; j < vlen; j += 2) {
10238 time_t seconds;
10239 int changes;
10240
10241 seconds = strtoll(v[j],NULL,10);
10242 changes = strtoll(v[j+1],NULL,10);
10243 appendServerSaveParams(seconds, changes);
10244 }
10245 sdsfreesplitres(v,vlen);
10246 } else {
10247 addReplySds(c,sdscatprintf(sdsempty(),
10248 "-ERR not supported CONFIG parameter %s\r\n",
10249 (char*)c->argv[2]->ptr));
10250 decrRefCount(o);
10251 return;
10252 }
10253 decrRefCount(o);
10254 addReply(c,shared.ok);
10255 return;
10256
10257 badfmt: /* Bad format errors */
10258 addReplySds(c,sdscatprintf(sdsempty(),
10259 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
10260 (char*)o->ptr,
10261 (char*)c->argv[2]->ptr));
10262 decrRefCount(o);
10263 }
10264
10265 static void configGetCommand(redisClient *c) {
10266 robj *o = getDecodedObject(c->argv[2]);
10267 robj *lenobj = createObject(REDIS_STRING,NULL);
10268 char *pattern = o->ptr;
10269 int matches = 0;
10270
10271 addReply(c,lenobj);
10272 decrRefCount(lenobj);
10273
10274 if (stringmatch(pattern,"dbfilename",0)) {
10275 addReplyBulkCString(c,"dbfilename");
10276 addReplyBulkCString(c,server.dbfilename);
10277 matches++;
10278 }
10279 if (stringmatch(pattern,"requirepass",0)) {
10280 addReplyBulkCString(c,"requirepass");
10281 addReplyBulkCString(c,server.requirepass);
10282 matches++;
10283 }
10284 if (stringmatch(pattern,"masterauth",0)) {
10285 addReplyBulkCString(c,"masterauth");
10286 addReplyBulkCString(c,server.masterauth);
10287 matches++;
10288 }
10289 if (stringmatch(pattern,"maxmemory",0)) {
10290 char buf[128];
10291
10292 ll2string(buf,128,server.maxmemory);
10293 addReplyBulkCString(c,"maxmemory");
10294 addReplyBulkCString(c,buf);
10295 matches++;
10296 }
10297 if (stringmatch(pattern,"timeout",0)) {
10298 char buf[128];
10299
10300 ll2string(buf,128,server.maxidletime);
10301 addReplyBulkCString(c,"timeout");
10302 addReplyBulkCString(c,buf);
10303 matches++;
10304 }
10305 if (stringmatch(pattern,"appendonly",0)) {
10306 addReplyBulkCString(c,"appendonly");
10307 addReplyBulkCString(c,server.appendonly ? "yes" : "no");
10308 matches++;
10309 }
10310 if (stringmatch(pattern,"appendfsync",0)) {
10311 char *policy;
10312
10313 switch(server.appendfsync) {
10314 case APPENDFSYNC_NO: policy = "no"; break;
10315 case APPENDFSYNC_EVERYSEC: policy = "everysec"; break;
10316 case APPENDFSYNC_ALWAYS: policy = "always"; break;
10317 default: policy = "unknown"; break; /* too harmless to panic */
10318 }
10319 addReplyBulkCString(c,"appendfsync");
10320 addReplyBulkCString(c,policy);
10321 matches++;
10322 }
10323 if (stringmatch(pattern,"save",0)) {
10324 sds buf = sdsempty();
10325 int j;
10326
10327 for (j = 0; j < server.saveparamslen; j++) {
10328 buf = sdscatprintf(buf,"%ld %d",
10329 server.saveparams[j].seconds,
10330 server.saveparams[j].changes);
10331 if (j != server.saveparamslen-1)
10332 buf = sdscatlen(buf," ",1);
10333 }
10334 addReplyBulkCString(c,"save");
10335 addReplyBulkCString(c,buf);
10336 sdsfree(buf);
10337 matches++;
10338 }
10339 decrRefCount(o);
10340 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",matches*2);
10341 }
10342
10343 static void configCommand(redisClient *c) {
10344 if (!strcasecmp(c->argv[1]->ptr,"set")) {
10345 if (c->argc != 4) goto badarity;
10346 configSetCommand(c);
10347 } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
10348 if (c->argc != 3) goto badarity;
10349 configGetCommand(c);
10350 } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
10351 if (c->argc != 2) goto badarity;
10352 server.stat_numcommands = 0;
10353 server.stat_numconnections = 0;
10354 server.stat_expiredkeys = 0;
10355 server.stat_starttime = time(NULL);
10356 addReply(c,shared.ok);
10357 } else {
10358 addReplySds(c,sdscatprintf(sdsempty(),
10359 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10360 }
10361 return;
10362
10363 badarity:
10364 addReplySds(c,sdscatprintf(sdsempty(),
10365 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10366 (char*) c->argv[1]->ptr));
10367 }
10368
10369 /* =========================== Pubsub implementation ======================== */
10370
10371 static void freePubsubPattern(void *p) {
10372 pubsubPattern *pat = p;
10373
10374 decrRefCount(pat->pattern);
10375 zfree(pat);
10376 }
10377
10378 static int listMatchPubsubPattern(void *a, void *b) {
10379 pubsubPattern *pa = a, *pb = b;
10380
10381 return (pa->client == pb->client) &&
10382 (equalStringObjects(pa->pattern,pb->pattern));
10383 }
10384
10385 /* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10386 * 0 if the client was already subscribed to that channel. */
10387 static int pubsubSubscribeChannel(redisClient *c, robj *channel) {
10388 struct dictEntry *de;
10389 list *clients = NULL;
10390 int retval = 0;
10391
10392 /* Add the channel to the client -> channels hash table */
10393 if (dictAdd(c->pubsub_channels,channel,NULL) == DICT_OK) {
10394 retval = 1;
10395 incrRefCount(channel);
10396 /* Add the client to the channel -> list of clients hash table */
10397 de = dictFind(server.pubsub_channels,channel);
10398 if (de == NULL) {
10399 clients = listCreate();
10400 dictAdd(server.pubsub_channels,channel,clients);
10401 incrRefCount(channel);
10402 } else {
10403 clients = dictGetEntryVal(de);
10404 }
10405 listAddNodeTail(clients,c);
10406 }
10407 /* Notify the client */
10408 addReply(c,shared.mbulk3);
10409 addReply(c,shared.subscribebulk);
10410 addReplyBulk(c,channel);
10411 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10412 return retval;
10413 }
10414
10415 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10416 * 0 if the client was not subscribed to the specified channel. */
10417 static int pubsubUnsubscribeChannel(redisClient *c, robj *channel, int notify) {
10418 struct dictEntry *de;
10419 list *clients;
10420 listNode *ln;
10421 int retval = 0;
10422
10423 /* Remove the channel from the client -> channels hash table */
10424 incrRefCount(channel); /* channel may be just a pointer to the same object
10425 we have in the hash tables. Protect it... */
10426 if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
10427 retval = 1;
10428 /* Remove the client from the channel -> clients list hash table */
10429 de = dictFind(server.pubsub_channels,channel);
10430 assert(de != NULL);
10431 clients = dictGetEntryVal(de);
10432 ln = listSearchKey(clients,c);
10433 assert(ln != NULL);
10434 listDelNode(clients,ln);
10435 if (listLength(clients) == 0) {
10436 /* Free the list and associated hash entry at all if this was
10437 * the latest client, so that it will be possible to abuse
10438 * Redis PUBSUB creating millions of channels. */
10439 dictDelete(server.pubsub_channels,channel);
10440 }
10441 }
10442 /* Notify the client */
10443 if (notify) {
10444 addReply(c,shared.mbulk3);
10445 addReply(c,shared.unsubscribebulk);
10446 addReplyBulk(c,channel);
10447 addReplyLongLong(c,dictSize(c->pubsub_channels)+
10448 listLength(c->pubsub_patterns));
10449
10450 }
10451 decrRefCount(channel); /* it is finally safe to release it */
10452 return retval;
10453 }
10454
10455 /* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10456 static int pubsubSubscribePattern(redisClient *c, robj *pattern) {
10457 int retval = 0;
10458
10459 if (listSearchKey(c->pubsub_patterns,pattern) == NULL) {
10460 retval = 1;
10461 pubsubPattern *pat;
10462 listAddNodeTail(c->pubsub_patterns,pattern);
10463 incrRefCount(pattern);
10464 pat = zmalloc(sizeof(*pat));
10465 pat->pattern = getDecodedObject(pattern);
10466 pat->client = c;
10467 listAddNodeTail(server.pubsub_patterns,pat);
10468 }
10469 /* Notify the client */
10470 addReply(c,shared.mbulk3);
10471 addReply(c,shared.psubscribebulk);
10472 addReplyBulk(c,pattern);
10473 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10474 return retval;
10475 }
10476
10477 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10478 * 0 if the client was not subscribed to the specified channel. */
10479 static int pubsubUnsubscribePattern(redisClient *c, robj *pattern, int notify) {
10480 listNode *ln;
10481 pubsubPattern pat;
10482 int retval = 0;
10483
10484 incrRefCount(pattern); /* Protect the object. May be the same we remove */
10485 if ((ln = listSearchKey(c->pubsub_patterns,pattern)) != NULL) {
10486 retval = 1;
10487 listDelNode(c->pubsub_patterns,ln);
10488 pat.client = c;
10489 pat.pattern = pattern;
10490 ln = listSearchKey(server.pubsub_patterns,&pat);
10491 listDelNode(server.pubsub_patterns,ln);
10492 }
10493 /* Notify the client */
10494 if (notify) {
10495 addReply(c,shared.mbulk3);
10496 addReply(c,shared.punsubscribebulk);
10497 addReplyBulk(c,pattern);
10498 addReplyLongLong(c,dictSize(c->pubsub_channels)+
10499 listLength(c->pubsub_patterns));
10500 }
10501 decrRefCount(pattern);
10502 return retval;
10503 }
10504
10505 /* Unsubscribe from all the channels. Return the number of channels the
10506 * client was subscribed from. */
10507 static int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
10508 dictIterator *di = dictGetIterator(c->pubsub_channels);
10509 dictEntry *de;
10510 int count = 0;
10511
10512 while((de = dictNext(di)) != NULL) {
10513 robj *channel = dictGetEntryKey(de);
10514
10515 count += pubsubUnsubscribeChannel(c,channel,notify);
10516 }
10517 dictReleaseIterator(di);
10518 return count;
10519 }
10520
10521 /* Unsubscribe from all the patterns. Return the number of patterns the
10522 * client was subscribed from. */
10523 static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify) {
10524 listNode *ln;
10525 listIter li;
10526 int count = 0;
10527
10528 listRewind(c->pubsub_patterns,&li);
10529 while ((ln = listNext(&li)) != NULL) {
10530 robj *pattern = ln->value;
10531
10532 count += pubsubUnsubscribePattern(c,pattern,notify);
10533 }
10534 return count;
10535 }
10536
10537 /* Publish a message */
10538 static int pubsubPublishMessage(robj *channel, robj *message) {
10539 int receivers = 0;
10540 struct dictEntry *de;
10541 listNode *ln;
10542 listIter li;
10543
10544 /* Send to clients listening for that channel */
10545 de = dictFind(server.pubsub_channels,channel);
10546 if (de) {
10547 list *list = dictGetEntryVal(de);
10548 listNode *ln;
10549 listIter li;
10550
10551 listRewind(list,&li);
10552 while ((ln = listNext(&li)) != NULL) {
10553 redisClient *c = ln->value;
10554
10555 addReply(c,shared.mbulk3);
10556 addReply(c,shared.messagebulk);
10557 addReplyBulk(c,channel);
10558 addReplyBulk(c,message);
10559 receivers++;
10560 }
10561 }
10562 /* Send to clients listening to matching channels */
10563 if (listLength(server.pubsub_patterns)) {
10564 listRewind(server.pubsub_patterns,&li);
10565 channel = getDecodedObject(channel);
10566 while ((ln = listNext(&li)) != NULL) {
10567 pubsubPattern *pat = ln->value;
10568
10569 if (stringmatchlen((char*)pat->pattern->ptr,
10570 sdslen(pat->pattern->ptr),
10571 (char*)channel->ptr,
10572 sdslen(channel->ptr),0)) {
10573 addReply(pat->client,shared.mbulk4);
10574 addReply(pat->client,shared.pmessagebulk);
10575 addReplyBulk(pat->client,pat->pattern);
10576 addReplyBulk(pat->client,channel);
10577 addReplyBulk(pat->client,message);
10578 receivers++;
10579 }
10580 }
10581 decrRefCount(channel);
10582 }
10583 return receivers;
10584 }
10585
10586 static void subscribeCommand(redisClient *c) {
10587 int j;
10588
10589 for (j = 1; j < c->argc; j++)
10590 pubsubSubscribeChannel(c,c->argv[j]);
10591 }
10592
10593 static void unsubscribeCommand(redisClient *c) {
10594 if (c->argc == 1) {
10595 pubsubUnsubscribeAllChannels(c,1);
10596 return;
10597 } else {
10598 int j;
10599
10600 for (j = 1; j < c->argc; j++)
10601 pubsubUnsubscribeChannel(c,c->argv[j],1);
10602 }
10603 }
10604
10605 static void psubscribeCommand(redisClient *c) {
10606 int j;
10607
10608 for (j = 1; j < c->argc; j++)
10609 pubsubSubscribePattern(c,c->argv[j]);
10610 }
10611
10612 static void punsubscribeCommand(redisClient *c) {
10613 if (c->argc == 1) {
10614 pubsubUnsubscribeAllPatterns(c,1);
10615 return;
10616 } else {
10617 int j;
10618
10619 for (j = 1; j < c->argc; j++)
10620 pubsubUnsubscribePattern(c,c->argv[j],1);
10621 }
10622 }
10623
10624 static void publishCommand(redisClient *c) {
10625 int receivers = pubsubPublishMessage(c->argv[1],c->argv[2]);
10626 addReplyLongLong(c,receivers);
10627 }
10628
10629 /* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
10630 *
10631 * The implementation uses a per-DB hash table mapping keys to list of clients
10632 * WATCHing those keys, so that given a key that is going to be modified
10633 * we can mark all the associated clients as dirty.
10634 *
10635 * Also every client contains a list of WATCHed keys so that's possible to
10636 * un-watch such keys when the client is freed or when UNWATCH is called. */
10637
10638 /* In the client->watched_keys list we need to use watchedKey structures
10639 * as in order to identify a key in Redis we need both the key name and the
10640 * DB */
10641 typedef struct watchedKey {
10642 robj *key;
10643 redisDb *db;
10644 } watchedKey;
10645
10646 /* Watch for the specified key */
10647 static void watchForKey(redisClient *c, robj *key) {
10648 list *clients = NULL;
10649 listIter li;
10650 listNode *ln;
10651 watchedKey *wk;
10652
10653 /* Check if we are already watching for this key */
10654 listRewind(c->watched_keys,&li);
10655 while((ln = listNext(&li))) {
10656 wk = listNodeValue(ln);
10657 if (wk->db == c->db && equalStringObjects(key,wk->key))
10658 return; /* Key already watched */
10659 }
10660 /* This key is not already watched in this DB. Let's add it */
10661 clients = dictFetchValue(c->db->watched_keys,key);
10662 if (!clients) {
10663 clients = listCreate();
10664 dictAdd(c->db->watched_keys,key,clients);
10665 incrRefCount(key);
10666 }
10667 listAddNodeTail(clients,c);
10668 /* Add the new key to the lits of keys watched by this client */
10669 wk = zmalloc(sizeof(*wk));
10670 wk->key = key;
10671 wk->db = c->db;
10672 incrRefCount(key);
10673 listAddNodeTail(c->watched_keys,wk);
10674 }
10675
10676 /* Unwatch all the keys watched by this client. To clean the EXEC dirty
10677 * flag is up to the caller. */
10678 static void unwatchAllKeys(redisClient *c) {
10679 listIter li;
10680 listNode *ln;
10681
10682 if (listLength(c->watched_keys) == 0) return;
10683 listRewind(c->watched_keys,&li);
10684 while((ln = listNext(&li))) {
10685 list *clients;
10686 watchedKey *wk;
10687
10688 /* Lookup the watched key -> clients list and remove the client
10689 * from the list */
10690 wk = listNodeValue(ln);
10691 clients = dictFetchValue(wk->db->watched_keys, wk->key);
10692 assert(clients != NULL);
10693 listDelNode(clients,listSearchKey(clients,c));
10694 /* Kill the entry at all if this was the only client */
10695 if (listLength(clients) == 0)
10696 dictDelete(wk->db->watched_keys, wk->key);
10697 /* Remove this watched key from the client->watched list */
10698 listDelNode(c->watched_keys,ln);
10699 decrRefCount(wk->key);
10700 zfree(wk);
10701 }
10702 }
10703
10704 /* "Touch" a key, so that if this key is being WATCHed by some client the
10705 * next EXEC will fail. */
10706 static void touchWatchedKey(redisDb *db, robj *key) {
10707 list *clients;
10708 listIter li;
10709 listNode *ln;
10710
10711 if (dictSize(db->watched_keys) == 0) return;
10712 clients = dictFetchValue(db->watched_keys, key);
10713 if (!clients) return;
10714
10715 /* Mark all the clients watching this key as REDIS_DIRTY_CAS */
10716 /* Check if we are already watching for this key */
10717 listRewind(clients,&li);
10718 while((ln = listNext(&li))) {
10719 redisClient *c = listNodeValue(ln);
10720
10721 c->flags |= REDIS_DIRTY_CAS;
10722 }
10723 }
10724
10725 /* On FLUSHDB or FLUSHALL all the watched keys that are present before the
10726 * flush but will be deleted as effect of the flushing operation should
10727 * be touched. "dbid" is the DB that's getting the flush. -1 if it is
10728 * a FLUSHALL operation (all the DBs flushed). */
10729 static void touchWatchedKeysOnFlush(int dbid) {
10730 listIter li1, li2;
10731 listNode *ln;
10732
10733 /* For every client, check all the waited keys */
10734 listRewind(server.clients,&li1);
10735 while((ln = listNext(&li1))) {
10736 redisClient *c = listNodeValue(ln);
10737 listRewind(c->watched_keys,&li2);
10738 while((ln = listNext(&li2))) {
10739 watchedKey *wk = listNodeValue(ln);
10740
10741 /* For every watched key matching the specified DB, if the
10742 * key exists, mark the client as dirty, as the key will be
10743 * removed. */
10744 if (dbid == -1 || wk->db->id == dbid) {
10745 if (dictFind(wk->db->dict, wk->key) != NULL)
10746 c->flags |= REDIS_DIRTY_CAS;
10747 }
10748 }
10749 }
10750 }
10751
10752 static void watchCommand(redisClient *c) {
10753 int j;
10754
10755 if (c->flags & REDIS_MULTI) {
10756 addReplySds(c,sdsnew("-ERR WATCH inside MULTI is not allowed\r\n"));
10757 return;
10758 }
10759 for (j = 1; j < c->argc; j++)
10760 watchForKey(c,c->argv[j]);
10761 addReply(c,shared.ok);
10762 }
10763
10764 static void unwatchCommand(redisClient *c) {
10765 unwatchAllKeys(c);
10766 c->flags &= (~REDIS_DIRTY_CAS);
10767 addReply(c,shared.ok);
10768 }
10769
10770 /* ================================= Debugging ============================== */
10771
10772 /* Compute the sha1 of string at 's' with 'len' bytes long.
10773 * The SHA1 is then xored againt the string pointed by digest.
10774 * Since xor is commutative, this operation is used in order to
10775 * "add" digests relative to unordered elements.
10776 *
10777 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10778 static void xorDigest(unsigned char *digest, void *ptr, size_t len) {
10779 SHA1_CTX ctx;
10780 unsigned char hash[20], *s = ptr;
10781 int j;
10782
10783 SHA1Init(&ctx);
10784 SHA1Update(&ctx,s,len);
10785 SHA1Final(hash,&ctx);
10786
10787 for (j = 0; j < 20; j++)
10788 digest[j] ^= hash[j];
10789 }
10790
10791 static void xorObjectDigest(unsigned char *digest, robj *o) {
10792 o = getDecodedObject(o);
10793 xorDigest(digest,o->ptr,sdslen(o->ptr));
10794 decrRefCount(o);
10795 }
10796
10797 /* This function instead of just computing the SHA1 and xoring it
10798 * against diget, also perform the digest of "digest" itself and
10799 * replace the old value with the new one.
10800 *
10801 * So the final digest will be:
10802 *
10803 * digest = SHA1(digest xor SHA1(data))
10804 *
10805 * This function is used every time we want to preserve the order so
10806 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
10807 *
10808 * Also note that mixdigest("foo") followed by mixdigest("bar")
10809 * will lead to a different digest compared to "fo", "obar".
10810 */
10811 static void mixDigest(unsigned char *digest, void *ptr, size_t len) {
10812 SHA1_CTX ctx;
10813 char *s = ptr;
10814
10815 xorDigest(digest,s,len);
10816 SHA1Init(&ctx);
10817 SHA1Update(&ctx,digest,20);
10818 SHA1Final(digest,&ctx);
10819 }
10820
10821 static void mixObjectDigest(unsigned char *digest, robj *o) {
10822 o = getDecodedObject(o);
10823 mixDigest(digest,o->ptr,sdslen(o->ptr));
10824 decrRefCount(o);
10825 }
10826
10827 /* Compute the dataset digest. Since keys, sets elements, hashes elements
10828 * are not ordered, we use a trick: every aggregate digest is the xor
10829 * of the digests of their elements. This way the order will not change
10830 * the result. For list instead we use a feedback entering the output digest
10831 * as input in order to ensure that a different ordered list will result in
10832 * a different digest. */
10833 static void computeDatasetDigest(unsigned char *final) {
10834 unsigned char digest[20];
10835 char buf[128];
10836 dictIterator *di = NULL;
10837 dictEntry *de;
10838 int j;
10839 uint32_t aux;
10840
10841 memset(final,0,20); /* Start with a clean result */
10842
10843 for (j = 0; j < server.dbnum; j++) {
10844 redisDb *db = server.db+j;
10845
10846 if (dictSize(db->dict) == 0) continue;
10847 di = dictGetIterator(db->dict);
10848
10849 /* hash the DB id, so the same dataset moved in a different
10850 * DB will lead to a different digest */
10851 aux = htonl(j);
10852 mixDigest(final,&aux,sizeof(aux));
10853
10854 /* Iterate this DB writing every entry */
10855 while((de = dictNext(di)) != NULL) {
10856 robj *key, *o, *kcopy;
10857 time_t expiretime;
10858
10859 memset(digest,0,20); /* This key-val digest */
10860 key = dictGetEntryKey(de);
10861
10862 if (!server.vm_enabled) {
10863 mixObjectDigest(digest,key);
10864 o = dictGetEntryVal(de);
10865 } else {
10866 /* Don't work with the key directly as when VM is active
10867 * this is unsafe: TODO: fix decrRefCount to check if the
10868 * count really reached 0 to avoid this mess */
10869 kcopy = dupStringObject(key);
10870 mixObjectDigest(digest,kcopy);
10871 o = lookupKeyRead(db,kcopy);
10872 decrRefCount(kcopy);
10873 }
10874 aux = htonl(o->type);
10875 mixDigest(digest,&aux,sizeof(aux));
10876 expiretime = getExpire(db,key);
10877
10878 /* Save the key and associated value */
10879 if (o->type == REDIS_STRING) {
10880 mixObjectDigest(digest,o);
10881 } else if (o->type == REDIS_LIST) {
10882 list *list = o->ptr;
10883 listNode *ln;
10884 listIter li;
10885
10886 listRewind(list,&li);
10887 while((ln = listNext(&li))) {
10888 robj *eleobj = listNodeValue(ln);
10889
10890 mixObjectDigest(digest,eleobj);
10891 }
10892 } else if (o->type == REDIS_SET) {
10893 dict *set = o->ptr;
10894 dictIterator *di = dictGetIterator(set);
10895 dictEntry *de;
10896
10897 while((de = dictNext(di)) != NULL) {
10898 robj *eleobj = dictGetEntryKey(de);
10899
10900 xorObjectDigest(digest,eleobj);
10901 }
10902 dictReleaseIterator(di);
10903 } else if (o->type == REDIS_ZSET) {
10904 zset *zs = o->ptr;
10905 dictIterator *di = dictGetIterator(zs->dict);
10906 dictEntry *de;
10907
10908 while((de = dictNext(di)) != NULL) {
10909 robj *eleobj = dictGetEntryKey(de);
10910 double *score = dictGetEntryVal(de);
10911 unsigned char eledigest[20];
10912
10913 snprintf(buf,sizeof(buf),"%.17g",*score);
10914 memset(eledigest,0,20);
10915 mixObjectDigest(eledigest,eleobj);
10916 mixDigest(eledigest,buf,strlen(buf));
10917 xorDigest(digest,eledigest,20);
10918 }
10919 dictReleaseIterator(di);
10920 } else if (o->type == REDIS_HASH) {
10921 hashIterator *hi;
10922 robj *obj;
10923
10924 hi = hashInitIterator(o);
10925 while (hashNext(hi) != REDIS_ERR) {
10926 unsigned char eledigest[20];
10927
10928 memset(eledigest,0,20);
10929 obj = hashCurrent(hi,REDIS_HASH_KEY);
10930 mixObjectDigest(eledigest,obj);
10931 decrRefCount(obj);
10932 obj = hashCurrent(hi,REDIS_HASH_VALUE);
10933 mixObjectDigest(eledigest,obj);
10934 decrRefCount(obj);
10935 xorDigest(digest,eledigest,20);
10936 }
10937 hashReleaseIterator(hi);
10938 } else {
10939 redisPanic("Unknown object type");
10940 }
10941 /* If the key has an expire, add it to the mix */
10942 if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
10943 /* We can finally xor the key-val digest to the final digest */
10944 xorDigest(final,digest,20);
10945 }
10946 dictReleaseIterator(di);
10947 }
10948 }
10949
10950 static void debugCommand(redisClient *c) {
10951 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
10952 *((char*)-1) = 'x';
10953 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
10954 if (rdbSave(server.dbfilename) != REDIS_OK) {
10955 addReply(c,shared.err);
10956 return;
10957 }
10958 emptyDb();
10959 if (rdbLoad(server.dbfilename) != REDIS_OK) {
10960 addReply(c,shared.err);
10961 return;
10962 }
10963 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
10964 addReply(c,shared.ok);
10965 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
10966 emptyDb();
10967 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
10968 addReply(c,shared.err);
10969 return;
10970 }
10971 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
10972 addReply(c,shared.ok);
10973 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
10974 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
10975 robj *key, *val;
10976
10977 if (!de) {
10978 addReply(c,shared.nokeyerr);
10979 return;
10980 }
10981 key = dictGetEntryKey(de);
10982 val = dictGetEntryVal(de);
10983 if (!server.vm_enabled || (key->storage == REDIS_VM_MEMORY ||
10984 key->storage == REDIS_VM_SWAPPING)) {
10985 char *strenc;
10986 char buf[128];
10987
10988 if (val->encoding < (sizeof(strencoding)/sizeof(char*))) {
10989 strenc = strencoding[val->encoding];
10990 } else {
10991 snprintf(buf,64,"unknown encoding %d\n", val->encoding);
10992 strenc = buf;
10993 }
10994 addReplySds(c,sdscatprintf(sdsempty(),
10995 "+Key at:%p refcount:%d, value at:%p refcount:%d "
10996 "encoding:%s serializedlength:%lld\r\n",
10997 (void*)key, key->refcount, (void*)val, val->refcount,
10998 strenc, (long long) rdbSavedObjectLen(val,NULL)));
10999 } else {
11000 addReplySds(c,sdscatprintf(sdsempty(),
11001 "+Key at:%p refcount:%d, value swapped at: page %llu "
11002 "using %llu pages\r\n",
11003 (void*)key, key->refcount, (unsigned long long) key->vm.page,
11004 (unsigned long long) key->vm.usedpages));
11005 }
11006 } else if (!strcasecmp(c->argv[1]->ptr,"swapin") && c->argc == 3) {
11007 lookupKeyRead(c->db,c->argv[2]);
11008 addReply(c,shared.ok);
11009 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
11010 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
11011 robj *key, *val;
11012
11013 if (!server.vm_enabled) {
11014 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
11015 return;
11016 }
11017 if (!de) {
11018 addReply(c,shared.nokeyerr);
11019 return;
11020 }
11021 key = dictGetEntryKey(de);
11022 val = dictGetEntryVal(de);
11023 /* If the key is shared we want to create a copy */
11024 if (key->refcount > 1) {
11025 robj *newkey = dupStringObject(key);
11026 decrRefCount(key);
11027 key = dictGetEntryKey(de) = newkey;
11028 }
11029 /* Swap it */
11030 if (key->storage != REDIS_VM_MEMORY) {
11031 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
11032 } else if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
11033 dictGetEntryVal(de) = NULL;
11034 addReply(c,shared.ok);
11035 } else {
11036 addReply(c,shared.err);
11037 }
11038 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
11039 long keys, j;
11040 robj *key, *val;
11041 char buf[128];
11042
11043 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
11044 return;
11045 for (j = 0; j < keys; j++) {
11046 snprintf(buf,sizeof(buf),"key:%lu",j);
11047 key = createStringObject(buf,strlen(buf));
11048 if (lookupKeyRead(c->db,key) != NULL) {
11049 decrRefCount(key);
11050 continue;
11051 }
11052 snprintf(buf,sizeof(buf),"value:%lu",j);
11053 val = createStringObject(buf,strlen(buf));
11054 dictAdd(c->db->dict,key,val);
11055 }
11056 addReply(c,shared.ok);
11057 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
11058 unsigned char digest[20];
11059 sds d = sdsnew("+");
11060 int j;
11061
11062 computeDatasetDigest(digest);
11063 for (j = 0; j < 20; j++)
11064 d = sdscatprintf(d, "%02x",digest[j]);
11065
11066 d = sdscatlen(d,"\r\n",2);
11067 addReplySds(c,d);
11068 } else {
11069 addReplySds(c,sdsnew(
11070 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
11071 }
11072 }
11073
11074 static void _redisAssert(char *estr, char *file, int line) {
11075 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
11076 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
11077 #ifdef HAVE_BACKTRACE
11078 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
11079 *((char*)-1) = 'x';
11080 #endif
11081 }
11082
11083 static void _redisPanic(char *msg, char *file, int line) {
11084 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
11085 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
11086 #ifdef HAVE_BACKTRACE
11087 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
11088 *((char*)-1) = 'x';
11089 #endif
11090 }
11091
11092 /* =================================== Main! ================================ */
11093
11094 #ifdef __linux__
11095 int linuxOvercommitMemoryValue(void) {
11096 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
11097 char buf[64];
11098
11099 if (!fp) return -1;
11100 if (fgets(buf,64,fp) == NULL) {
11101 fclose(fp);
11102 return -1;
11103 }
11104 fclose(fp);
11105
11106 return atoi(buf);
11107 }
11108
11109 void linuxOvercommitMemoryWarning(void) {
11110 if (linuxOvercommitMemoryValue() == 0) {
11111 redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.");
11112 }
11113 }
11114 #endif /* __linux__ */
11115
11116 static void daemonize(void) {
11117 int fd;
11118 FILE *fp;
11119
11120 if (fork() != 0) exit(0); /* parent exits */
11121 setsid(); /* create a new session */
11122
11123 /* Every output goes to /dev/null. If Redis is daemonized but
11124 * the 'logfile' is set to 'stdout' in the configuration file
11125 * it will not log at all. */
11126 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
11127 dup2(fd, STDIN_FILENO);
11128 dup2(fd, STDOUT_FILENO);
11129 dup2(fd, STDERR_FILENO);
11130 if (fd > STDERR_FILENO) close(fd);
11131 }
11132 /* Try to write the pid file */
11133 fp = fopen(server.pidfile,"w");
11134 if (fp) {
11135 fprintf(fp,"%d\n",getpid());
11136 fclose(fp);
11137 }
11138 }
11139
11140 static void version() {
11141 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
11142 REDIS_GIT_SHA1, atoi(REDIS_GIT_DIRTY) > 0);
11143 exit(0);
11144 }
11145
11146 static void usage() {
11147 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
11148 fprintf(stderr," ./redis-server - (read config from stdin)\n");
11149 exit(1);
11150 }
11151
11152 int main(int argc, char **argv) {
11153 time_t start;
11154
11155 initServerConfig();
11156 sortCommandTable();
11157 if (argc == 2) {
11158 if (strcmp(argv[1], "-v") == 0 ||
11159 strcmp(argv[1], "--version") == 0) version();
11160 if (strcmp(argv[1], "--help") == 0) usage();
11161 resetServerSaveParams();
11162 loadServerConfig(argv[1]);
11163 } else if ((argc > 2)) {
11164 usage();
11165 } else {
11166 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'");
11167 }
11168 if (server.daemonize) daemonize();
11169 initServer();
11170 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
11171 #ifdef __linux__
11172 linuxOvercommitMemoryWarning();
11173 #endif
11174 start = time(NULL);
11175 if (server.appendonly) {
11176 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
11177 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
11178 } else {
11179 if (rdbLoad(server.dbfilename) == REDIS_OK)
11180 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
11181 }
11182 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
11183 aeSetBeforeSleepProc(server.el,beforeSleep);
11184 aeMain(server.el);
11185 aeDeleteEventLoop(server.el);
11186 return 0;
11187 }
11188
11189 /* ============================= Backtrace support ========================= */
11190
11191 #ifdef HAVE_BACKTRACE
11192 static char *findFuncName(void *pointer, unsigned long *offset);
11193
11194 static void *getMcontextEip(ucontext_t *uc) {
11195 #if defined(__FreeBSD__)
11196 return (void*) uc->uc_mcontext.mc_eip;
11197 #elif defined(__dietlibc__)
11198 return (void*) uc->uc_mcontext.eip;
11199 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
11200 #if __x86_64__
11201 return (void*) uc->uc_mcontext->__ss.__rip;
11202 #else
11203 return (void*) uc->uc_mcontext->__ss.__eip;
11204 #endif
11205 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
11206 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
11207 return (void*) uc->uc_mcontext->__ss.__rip;
11208 #else
11209 return (void*) uc->uc_mcontext->__ss.__eip;
11210 #endif
11211 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
11212 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
11213 #elif defined(__ia64__) /* Linux IA64 */
11214 return (void*) uc->uc_mcontext.sc_ip;
11215 #else
11216 return NULL;
11217 #endif
11218 }
11219
11220 static void segvHandler(int sig, siginfo_t *info, void *secret) {
11221 void *trace[100];
11222 char **messages = NULL;
11223 int i, trace_size = 0;
11224 unsigned long offset=0;
11225 ucontext_t *uc = (ucontext_t*) secret;
11226 sds infostring;
11227 REDIS_NOTUSED(info);
11228
11229 redisLog(REDIS_WARNING,
11230 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
11231 infostring = genRedisInfoString();
11232 redisLog(REDIS_WARNING, "%s",infostring);
11233 /* It's not safe to sdsfree() the returned string under memory
11234 * corruption conditions. Let it leak as we are going to abort */
11235
11236 trace_size = backtrace(trace, 100);
11237 /* overwrite sigaction with caller's address */
11238 if (getMcontextEip(uc) != NULL) {
11239 trace[1] = getMcontextEip(uc);
11240 }
11241 messages = backtrace_symbols(trace, trace_size);
11242
11243 for (i=1; i<trace_size; ++i) {
11244 char *fn = findFuncName(trace[i], &offset), *p;
11245
11246 p = strchr(messages[i],'+');
11247 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
11248 redisLog(REDIS_WARNING,"%s", messages[i]);
11249 } else {
11250 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
11251 }
11252 }
11253 /* free(messages); Don't call free() with possibly corrupted memory. */
11254 _exit(0);
11255 }
11256
11257 static void sigtermHandler(int sig) {
11258 REDIS_NOTUSED(sig);
11259
11260 redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
11261 server.shutdown_asap = 1;
11262 }
11263
11264 static void setupSigSegvAction(void) {
11265 struct sigaction act;
11266
11267 sigemptyset (&act.sa_mask);
11268 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
11269 * is used. Otherwise, sa_handler is used */
11270 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
11271 act.sa_sigaction = segvHandler;
11272 sigaction (SIGSEGV, &act, NULL);
11273 sigaction (SIGBUS, &act, NULL);
11274 sigaction (SIGFPE, &act, NULL);
11275 sigaction (SIGILL, &act, NULL);
11276 sigaction (SIGBUS, &act, NULL);
11277
11278 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
11279 act.sa_handler = sigtermHandler;
11280 sigaction (SIGTERM, &act, NULL);
11281 return;
11282 }
11283
11284 #include "staticsymbols.h"
11285 /* This function try to convert a pointer into a function name. It's used in
11286 * oreder to provide a backtrace under segmentation fault that's able to
11287 * display functions declared as static (otherwise the backtrace is useless). */
11288 static char *findFuncName(void *pointer, unsigned long *offset){
11289 int i, ret = -1;
11290 unsigned long off, minoff = 0;
11291
11292 /* Try to match against the Symbol with the smallest offset */
11293 for (i=0; symsTable[i].pointer; i++) {
11294 unsigned long lp = (unsigned long) pointer;
11295
11296 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
11297 off=lp-symsTable[i].pointer;
11298 if (ret < 0 || off < minoff) {
11299 minoff=off;
11300 ret=i;
11301 }
11302 }
11303 }
11304 if (ret == -1) return NULL;
11305 *offset = minoff;
11306 return symsTable[ret].name;
11307 }
11308 #else /* HAVE_BACKTRACE */
11309 static void setupSigSegvAction(void) {
11310 }
11311 #endif /* HAVE_BACKTRACE */
11312
11313
11314
11315 /* The End */
11316
11317
11318