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