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