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