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