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