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