]> git.saurik.com Git - redis.git/blame - redis.c
conflicts resolved
[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
24df7698 30#define REDIS_VERSION "1.3.10"
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>
40#include <signal.h>
fbf9bcdb 41
42#ifdef HAVE_BACKTRACE
c9468bcf 43#include <execinfo.h>
44#include <ucontext.h>
fbf9bcdb 45#endif /* HAVE_BACKTRACE */
46
ed9b544e 47#include <sys/wait.h>
48#include <errno.h>
49#include <assert.h>
50#include <ctype.h>
51#include <stdarg.h>
52#include <inttypes.h>
53#include <arpa/inet.h>
54#include <sys/stat.h>
55#include <fcntl.h>
56#include <sys/time.h>
57#include <sys/resource.h>
2895e862 58#include <sys/uio.h>
f78fd11b 59#include <limits.h>
fb82e75c 60#include <float.h>
a7866db6 61#include <math.h>
92f8e882 62#include <pthread.h>
0bc1b2f6 63
64#if defined(__sun)
5043dff3 65#include "solarisfixes.h"
66#endif
ed9b544e 67
c9468bcf 68#include "redis.h"
ed9b544e 69#include "ae.h" /* Event driven programming library */
70#include "sds.h" /* Dynamic safe strings */
71#include "anet.h" /* Networking the easy way */
72#include "dict.h" /* Hash tables */
73#include "adlist.h" /* Linked lists */
74#include "zmalloc.h" /* total memory usage aware version of malloc/free */
5f5b9840 75#include "lzf.h" /* LZF compression library */
76#include "pqsort.h" /* Partial qsort for SORT+LIMIT */
5234952b 77#include "zipmap.h"
ed9b544e 78
79/* Error codes */
80#define REDIS_OK 0
81#define REDIS_ERR -1
82
83/* Static server configuration */
84#define REDIS_SERVERPORT 6379 /* TCP port */
85#define REDIS_MAXIDLETIME (60*5) /* default client timeout */
6208b3a7 86#define REDIS_IOBUF_LEN 1024
ed9b544e 87#define REDIS_LOADBUF_LEN 1024
248ea310 88#define REDIS_STATIC_ARGS 8
ed9b544e 89#define REDIS_DEFAULT_DBNUM 16
90#define REDIS_CONFIGLINE_MAX 1024
91#define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
92#define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
8ca3e9d1 93#define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
6f376729 94#define REDIS_MAX_WRITE_PER_EVENT (1024*64)
2895e862 95#define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
96
97/* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
98#define REDIS_WRITEV_THRESHOLD 3
99/* Max number of iovecs used for each writev call */
100#define REDIS_WRITEV_IOVEC_COUNT 256
ed9b544e 101
102/* Hash table parameters */
103#define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
ed9b544e 104
105/* Command flags */
3fd78bcd 106#define REDIS_CMD_BULK 1 /* Bulk write command */
107#define REDIS_CMD_INLINE 2 /* Inline command */
108/* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
109 this flags will return an error when the 'maxmemory' option is set in the
110 config file and the server is using more than maxmemory bytes of memory.
111 In short this commands are denied on low memory conditions. */
112#define REDIS_CMD_DENYOOM 4
4005fef1 113#define REDIS_CMD_FORCE_REPLICATION 8 /* Force replication even if dirty is 0 */
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
07efaf74 130static char* strencoding[] = {
131 "raw", "int", "zipmap", "hashtable"
132};
133
f78fd11b 134/* Object types only used for dumping to disk */
bb32ede5 135#define REDIS_EXPIRETIME 253
ed9b544e 136#define REDIS_SELECTDB 254
137#define REDIS_EOF 255
138
f78fd11b 139/* Defines related to the dump file format. To store 32 bits lengths for short
140 * keys requires a lot of space, so we check the most significant 2 bits of
141 * the first byte to interpreter the length:
142 *
143 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
144 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
145 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
a4d1ba9a 146 * 11|000000 this means: specially encoded object will follow. The six bits
147 * number specify the kind of object that follows.
148 * See the REDIS_RDB_ENC_* defines.
f78fd11b 149 *
10c43610 150 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
151 * values, will fit inside. */
f78fd11b 152#define REDIS_RDB_6BITLEN 0
153#define REDIS_RDB_14BITLEN 1
154#define REDIS_RDB_32BITLEN 2
17be1a4a 155#define REDIS_RDB_ENCVAL 3
f78fd11b 156#define REDIS_RDB_LENERR UINT_MAX
157
a4d1ba9a 158/* When a length of a string object stored on disk has the first two bits
159 * set, the remaining two bits specify a special encoding for the object
160 * accordingly to the following defines: */
161#define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
162#define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
163#define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
774e3047 164#define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
a4d1ba9a 165
75680a3c 166/* Virtual memory object->where field. */
167#define REDIS_VM_MEMORY 0 /* The object is on memory */
168#define REDIS_VM_SWAPPED 1 /* The object is on disk */
169#define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
170#define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
171
06224fec 172/* Virtual memory static configuration stuff.
173 * Check vmFindContiguousPages() to know more about this magic numbers. */
174#define REDIS_VM_MAX_NEAR_PAGES 65536
175#define REDIS_VM_MAX_RANDOM_JUMP 4096
92f8e882 176#define REDIS_VM_MAX_THREADS 32
bcaa7a4f 177#define REDIS_THREAD_STACK_SIZE (1024*1024*4)
f6c0bba8 178/* The following is the *percentage* of completed I/O jobs to process when the
179 * handelr is called. While Virtual Memory I/O operations are performed by
180 * threads, this operations must be processed by the main thread when completed
181 * in order to take effect. */
c953f24b 182#define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
06224fec 183
ed9b544e 184/* Client flags */
d5d55fc3 185#define REDIS_SLAVE 1 /* This client is a slave server */
186#define REDIS_MASTER 2 /* This client is a master server */
187#define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
188#define REDIS_MULTI 8 /* This client is in a MULTI context */
189#define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
190#define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
ed9b544e 191
40d224a9 192/* Slave replication state - slave side */
ed9b544e 193#define REDIS_REPL_NONE 0 /* No active replication */
194#define REDIS_REPL_CONNECT 1 /* Must connect to master */
195#define REDIS_REPL_CONNECTED 2 /* Connected to master */
196
40d224a9 197/* Slave replication state - from the point of view of master
198 * Note that in SEND_BULK and ONLINE state the slave receives new updates
199 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
200 * to start the next background saving in order to send updates to it. */
201#define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
202#define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
203#define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
204#define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
205
ed9b544e 206/* List related stuff */
207#define REDIS_HEAD 0
208#define REDIS_TAIL 1
209
210/* Sort operations */
211#define REDIS_SORT_GET 0
443c6409 212#define REDIS_SORT_ASC 1
213#define REDIS_SORT_DESC 2
ed9b544e 214#define REDIS_SORTKEY_MAX 1024
215
216/* Log levels */
217#define REDIS_DEBUG 0
f870935d 218#define REDIS_VERBOSE 1
219#define REDIS_NOTICE 2
220#define REDIS_WARNING 3
ed9b544e 221
222/* Anti-warning macro... */
223#define REDIS_NOTUSED(V) ((void) V)
224
6b47e12e 225#define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
226#define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
ed9b544e 227
48f0308a 228/* Append only defines */
229#define APPENDFSYNC_NO 0
230#define APPENDFSYNC_ALWAYS 1
231#define APPENDFSYNC_EVERYSEC 2
232
cbba7dd7 233/* Hashes related defaults */
234#define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
235#define REDIS_HASH_MAX_ZIPMAP_VALUE 512
236
dfc5e96c 237/* We can print the stacktrace, so our assert is defined this way: */
478c2c6f 238#define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
c651fd9e 239#define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
6c96ba7d 240static void _redisAssert(char *estr, char *file, int line);
c651fd9e 241static void _redisPanic(char *msg, char *file, int line);
dfc5e96c 242
ed9b544e 243/*================================= Data types ============================== */
244
245/* A redis object, that is a type able to hold a string / list / set */
75680a3c 246
247/* The VM object structure */
248struct redisObjectVM {
3a66edc7 249 off_t page; /* the page at witch the object is stored on disk */
250 off_t usedpages; /* number of pages used on disk */
251 time_t atime; /* Last access time */
75680a3c 252} vm;
253
254/* The actual Redis Object */
ed9b544e 255typedef struct redisObject {
ed9b544e 256 void *ptr;
942a3961 257 unsigned char type;
258 unsigned char encoding;
d894161b 259 unsigned char storage; /* If this object is a key, where is the value?
260 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
261 unsigned char vtype; /* If this object is a key, and value is swapped out,
262 * this is the type of the swapped out object. */
ed9b544e 263 int refcount;
75680a3c 264 /* VM fields, this are only allocated if VM is active, otherwise the
265 * object allocation function will just allocate
266 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
267 * Redis without VM active will not have any overhead. */
268 struct redisObjectVM vm;
ed9b544e 269} robj;
270
dfc5e96c 271/* Macro used to initalize a Redis object allocated on the stack.
272 * Note that this macro is taken near the structure definition to make sure
273 * we'll update it when the structure is changed, to avoid bugs like
274 * bug #85 introduced exactly in this way. */
275#define initStaticStringObject(_var,_ptr) do { \
276 _var.refcount = 1; \
277 _var.type = REDIS_STRING; \
278 _var.encoding = REDIS_ENCODING_RAW; \
279 _var.ptr = _ptr; \
3a66edc7 280 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
dfc5e96c 281} while(0);
282
3305306f 283typedef struct redisDb {
4409877e 284 dict *dict; /* The keyspace for this DB */
285 dict *expires; /* Timeout of keys with a timeout set */
286 dict *blockingkeys; /* Keys with clients waiting for data (BLPOP) */
d5d55fc3 287 dict *io_keys; /* Keys with clients waiting for VM I/O */
3305306f 288 int id;
289} redisDb;
290
6e469882 291/* Client MULTI/EXEC state */
292typedef struct multiCmd {
293 robj **argv;
294 int argc;
295 struct redisCommand *cmd;
296} multiCmd;
297
298typedef struct multiState {
299 multiCmd *commands; /* Array of MULTI commands */
300 int count; /* Total number of MULTI commands */
301} multiState;
302
ed9b544e 303/* With multiplexing we need to take per-clinet state.
304 * Clients are taken in a liked list. */
305typedef struct redisClient {
306 int fd;
3305306f 307 redisDb *db;
ed9b544e 308 int dictid;
309 sds querybuf;
e8a74421 310 robj **argv, **mbargv;
311 int argc, mbargc;
40d224a9 312 int bulklen; /* bulk read len. -1 if not in bulk read mode */
e8a74421 313 int multibulk; /* multi bulk command format active */
ed9b544e 314 list *reply;
315 int sentlen;
316 time_t lastinteraction; /* time of the last interaction, used for timeout */
d5d55fc3 317 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
40d224a9 318 int slaveseldb; /* slave selected db, if this client is a slave */
319 int authenticated; /* when requirepass is non-NULL */
320 int replstate; /* replication state if this is a slave */
321 int repldbfd; /* replication DB file descriptor */
6e469882 322 long repldboff; /* replication DB file offset */
40d224a9 323 off_t repldbsize; /* replication DB file size */
6e469882 324 multiState mstate; /* MULTI/EXEC state */
d5d55fc3 325 robj **blockingkeys; /* The key we are waiting to terminate a blocking
4409877e 326 * operation such as BLPOP. Otherwise NULL. */
b177fd30 327 int blockingkeysnum; /* Number of blocking keys */
4409877e 328 time_t blockingto; /* Blocking operation timeout. If UNIX current time
329 * is >= blockingto then the operation timed out. */
92f8e882 330 list *io_keys; /* Keys this client is waiting to be loaded from the
331 * swap file in order to continue. */
ffc6b7f8 332 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
333 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
ed9b544e 334} redisClient;
335
336struct saveparam {
337 time_t seconds;
338 int changes;
339};
340
341/* Global server state structure */
342struct redisServer {
343 int port;
344 int fd;
3305306f 345 redisDb *db;
ed9b544e 346 long long dirty; /* changes to DB from the last save */
347 list *clients;
87eca727 348 list *slaves, *monitors;
ed9b544e 349 char neterr[ANET_ERR_LEN];
350 aeEventLoop *el;
351 int cronloops; /* number of times the cron function run */
352 list *objfreelist; /* A list of freed objects to avoid malloc() */
353 time_t lastsave; /* Unix time of last save succeeede */
ed9b544e 354 /* Fields used only for stats */
355 time_t stat_starttime; /* server start time */
356 long long stat_numcommands; /* number of processed commands */
357 long long stat_numconnections; /* number of connections received */
2a6a2ed1 358 long long stat_expiredkeys; /* number of expired keys */
ed9b544e 359 /* Configuration */
360 int verbosity;
361 int glueoutputbuf;
362 int maxidletime;
363 int dbnum;
364 int daemonize;
44b38ef4 365 int appendonly;
48f0308a 366 int appendfsync;
367 time_t lastfsync;
44b38ef4 368 int appendfd;
369 int appendseldb;
ed329fcf 370 char *pidfile;
9f3c422c 371 pid_t bgsavechildpid;
9d65a1bb 372 pid_t bgrewritechildpid;
373 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
28ed1f33 374 sds aofbuf; /* AOF buffer, written before entering the event loop */
ed9b544e 375 struct saveparam *saveparams;
376 int saveparamslen;
377 char *logfile;
378 char *bindaddr;
379 char *dbfilename;
44b38ef4 380 char *appendfilename;
abcb223e 381 char *requirepass;
121f70cf 382 int rdbcompression;
8ca3e9d1 383 int activerehashing;
ed9b544e 384 /* Replication related */
385 int isslave;
d0ccebcf 386 char *masterauth;
ed9b544e 387 char *masterhost;
388 int masterport;
40d224a9 389 redisClient *master; /* client that is master for this slave */
ed9b544e 390 int replstate;
285add55 391 unsigned int maxclients;
4ef8de8a 392 unsigned long long maxmemory;
d5d55fc3 393 unsigned int blpop_blocked_clients;
394 unsigned int vm_blocked_clients;
ed9b544e 395 /* Sort parameters - qsort_r() is only available under BSD so we
396 * have to take this state global, in order to pass it to sortCompare() */
397 int sort_desc;
398 int sort_alpha;
399 int sort_bypattern;
75680a3c 400 /* Virtual memory configuration */
401 int vm_enabled;
054e426d 402 char *vm_swap_file;
75680a3c 403 off_t vm_page_size;
404 off_t vm_pages;
4ef8de8a 405 unsigned long long vm_max_memory;
cbba7dd7 406 /* Hashes config */
407 size_t hash_max_zipmap_entries;
408 size_t hash_max_zipmap_value;
75680a3c 409 /* Virtual memory state */
410 FILE *vm_fp;
411 int vm_fd;
412 off_t vm_next_page; /* Next probably empty page */
413 off_t vm_near_pages; /* Number of pages allocated sequentially */
06224fec 414 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
3a66edc7 415 time_t unixtime; /* Unix time sampled every second. */
92f8e882 416 /* Virtual memory I/O threads stuff */
92f8e882 417 /* An I/O thread process an element taken from the io_jobs queue and
996cb5f7 418 * put the result of the operation in the io_done list. While the
419 * job is being processed, it's put on io_processing queue. */
420 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
421 list *io_processing; /* List of VM I/O jobs being processed */
422 list *io_processed; /* List of VM I/O jobs already processed */
d5d55fc3 423 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
996cb5f7 424 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
a5819310 425 pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
426 pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
bcaa7a4f 427 pthread_attr_t io_threads_attr; /* attributes for threads creation */
92f8e882 428 int io_active_threads; /* Number of running I/O threads */
429 int vm_max_threads; /* Max number of I/O threads running at the same time */
996cb5f7 430 /* Our main thread is blocked on the event loop, locking for sockets ready
431 * to be read or written, so when a threaded I/O operation is ready to be
432 * processed by the main thread, the I/O thread will use a unix pipe to
433 * awake the main thread. The followings are the two pipe FDs. */
434 int io_ready_pipe_read;
435 int io_ready_pipe_write;
7d98e08c 436 /* Virtual memory stats */
437 unsigned long long vm_stats_used_pages;
438 unsigned long long vm_stats_swapped_objects;
439 unsigned long long vm_stats_swapouts;
440 unsigned long long vm_stats_swapins;
befec3cd 441 /* Pubsub */
ffc6b7f8 442 dict *pubsub_channels; /* Map channels to list of subscribed clients */
443 list *pubsub_patterns; /* A list of pubsub_patterns */
befec3cd 444 /* Misc */
b9bc0eef 445 FILE *devnull;
ed9b544e 446};
447
ffc6b7f8 448typedef struct pubsubPattern {
449 redisClient *client;
450 robj *pattern;
451} pubsubPattern;
452
ed9b544e 453typedef void redisCommandProc(redisClient *c);
ca1788b5 454typedef void redisVmPreloadProc(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
ed9b544e 455struct redisCommand {
456 char *name;
457 redisCommandProc *proc;
458 int arity;
459 int flags;
76583ea4
PN
460 /* Use a function to determine which keys need to be loaded
461 * in the background prior to executing this command. Takes precedence
462 * over vm_firstkey and others, ignored when NULL */
ca1788b5 463 redisVmPreloadProc *vm_preload_proc;
7c775e09 464 /* What keys should be loaded in background when calling this command? */
465 int vm_firstkey; /* The first argument that's a key (0 = no keys) */
466 int vm_lastkey; /* THe last argument that's a key */
467 int vm_keystep; /* The step between first and last key */
ed9b544e 468};
469
de96dbfe 470struct redisFunctionSym {
471 char *name;
56906eef 472 unsigned long pointer;
de96dbfe 473};
474
ed9b544e 475typedef struct _redisSortObject {
476 robj *obj;
477 union {
478 double score;
479 robj *cmpobj;
480 } u;
481} redisSortObject;
482
483typedef struct _redisSortOperation {
484 int type;
485 robj *pattern;
486} redisSortOperation;
487
6b47e12e 488/* ZSETs use a specialized version of Skiplists */
489
490typedef struct zskiplistNode {
491 struct zskiplistNode **forward;
e3870fab 492 struct zskiplistNode *backward;
912b9165 493 unsigned int *span;
6b47e12e 494 double score;
495 robj *obj;
496} zskiplistNode;
497
498typedef struct zskiplist {
e3870fab 499 struct zskiplistNode *header, *tail;
d13f767c 500 unsigned long length;
6b47e12e 501 int level;
502} zskiplist;
503
1812e024 504typedef struct zset {
505 dict *dict;
6b47e12e 506 zskiplist *zsl;
1812e024 507} zset;
508
6b47e12e 509/* Our shared "common" objects */
510
05df7621 511#define REDIS_SHARED_INTEGERS 10000
ed9b544e 512struct sharedObjectsStruct {
c937aa89 513 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
6e469882 514 *colon, *nullbulk, *nullmultibulk, *queued,
c937aa89 515 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
516 *outofrangeerr, *plus,
ed9b544e 517 *select0, *select1, *select2, *select3, *select4,
befec3cd 518 *select5, *select6, *select7, *select8, *select9,
c8d0ea0e 519 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk, *mbulk3,
520 *mbulk4, *psubscribebulk, *punsubscribebulk,
521 *integers[REDIS_SHARED_INTEGERS];
ed9b544e 522} shared;
523
a7866db6 524/* Global vars that are actally used as constants. The following double
525 * values are used for double on-disk serialization, and are initialized
526 * at runtime to avoid strange compiler optimizations. */
527
528static double R_Zero, R_PosInf, R_NegInf, R_Nan;
529
92f8e882 530/* VM threaded I/O request message */
b9bc0eef 531#define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
532#define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
533#define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
d5d55fc3 534typedef struct iojob {
996cb5f7 535 int type; /* Request type, REDIS_IOJOB_* */
b9bc0eef 536 redisDb *db;/* Redis database */
92f8e882 537 robj *key; /* This I/O request is about swapping this key */
b9bc0eef 538 robj *val; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
92f8e882 539 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
540 off_t page; /* Swap page where to read/write the object */
248ea310 541 off_t pages; /* Swap pages needed to save object. PREPARE_SWAP return val */
996cb5f7 542 int canceled; /* True if this command was canceled by blocking side of VM */
543 pthread_t thread; /* ID of the thread processing this entry */
544} iojob;
92f8e882 545
ed9b544e 546/*================================ Prototypes =============================== */
547
548static void freeStringObject(robj *o);
549static void freeListObject(robj *o);
550static void freeSetObject(robj *o);
551static void decrRefCount(void *o);
552static robj *createObject(int type, void *ptr);
553static void freeClient(redisClient *c);
f78fd11b 554static int rdbLoad(char *filename);
ed9b544e 555static void addReply(redisClient *c, robj *obj);
556static void addReplySds(redisClient *c, sds s);
557static void incrRefCount(robj *o);
f78fd11b 558static int rdbSaveBackground(char *filename);
ed9b544e 559static robj *createStringObject(char *ptr, size_t len);
4ef8de8a 560static robj *dupStringObject(robj *o);
248ea310 561static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
dd142b9c 562static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
28ed1f33 563static void flushAppendOnlyFile(void);
44b38ef4 564static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
ed9b544e 565static int syncWithMaster(void);
05df7621 566static robj *tryObjectEncoding(robj *o);
9d65a1bb 567static robj *getDecodedObject(robj *o);
3305306f 568static int removeExpire(redisDb *db, robj *key);
569static int expireIfNeeded(redisDb *db, robj *key);
570static int deleteIfVolatile(redisDb *db, robj *key);
1b03836c 571static int deleteIfSwapped(redisDb *db, robj *key);
94754ccc 572static int deleteKey(redisDb *db, robj *key);
bb32ede5 573static time_t getExpire(redisDb *db, robj *key);
574static int setExpire(redisDb *db, robj *key, time_t when);
a3b21203 575static void updateSlavesWaitingBgsave(int bgsaveerr);
3fd78bcd 576static void freeMemoryIfNeeded(void);
de96dbfe 577static int processCommand(redisClient *c);
56906eef 578static void setupSigSegvAction(void);
a3b21203 579static void rdbRemoveTempFile(pid_t childpid);
9d65a1bb 580static void aofRemoveTempFile(pid_t childpid);
0ea663ea 581static size_t stringObjectLen(robj *o);
638e42ac 582static void processInputBuffer(redisClient *c);
6b47e12e 583static zskiplist *zslCreate(void);
fd8ccf44 584static void zslFree(zskiplist *zsl);
2b59cfdf 585static void zslInsert(zskiplist *zsl, double score, robj *obj);
2895e862 586static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
6e469882 587static void initClientMultiState(redisClient *c);
588static void freeClientMultiState(redisClient *c);
589static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
b0d8747d 590static void unblockClientWaitingData(redisClient *c);
4409877e 591static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
75680a3c 592static void vmInit(void);
a35ddf12 593static void vmMarkPagesFree(off_t page, off_t count);
55cf8433 594static robj *vmLoadObject(robj *key);
7e69548d 595static robj *vmPreviewObject(robj *key);
a69a0c9c 596static int vmSwapOneObjectBlocking(void);
597static int vmSwapOneObjectThreaded(void);
7e69548d 598static int vmCanSwapOut(void);
a5819310 599static int tryFreeOneObjectFromFreelist(void);
996cb5f7 600static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
601static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
602static void vmCancelThreadedIOJob(robj *o);
b9bc0eef 603static void lockThreadedIO(void);
604static void unlockThreadedIO(void);
605static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
606static void freeIOJob(iojob *j);
607static void queueIOJob(iojob *j);
a5819310 608static int vmWriteObjectOnSwap(robj *o, off_t page);
609static robj *vmReadObjectFromSwap(off_t page, int type);
054e426d 610static void waitEmptyIOJobsQueue(void);
611static void vmReopenSwapFile(void);
970e10bb 612static int vmFreePage(off_t page);
ca1788b5 613static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
3805e04f 614static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
0a6f3f0f 615static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd);
d5d55fc3 616static int dontWaitForSwappedKey(redisClient *c, robj *key);
617static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
618static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
619static struct redisCommand *lookupCommand(char *name);
620static void call(redisClient *c, struct redisCommand *cmd);
621static void resetClient(redisClient *c);
ada386b2 622static void convertToRealHash(robj *o);
ffc6b7f8 623static int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
624static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
625static void freePubsubPattern(void *p);
626static int listMatchPubsubPattern(void *a, void *b);
627static int compareStringObjects(robj *a, robj *b);
bf028098 628static int equalStringObjects(robj *a, robj *b);
befec3cd 629static void usage();
8f63ddca 630static int rewriteAppendOnlyFileBackground(void);
242a64f3 631static int vmSwapObjectBlocking(robj *key, robj *val);
ed9b544e 632
abcb223e 633static void authCommand(redisClient *c);
ed9b544e 634static void pingCommand(redisClient *c);
635static void echoCommand(redisClient *c);
636static void setCommand(redisClient *c);
637static void setnxCommand(redisClient *c);
526d00a5 638static void setexCommand(redisClient *c);
ed9b544e 639static void getCommand(redisClient *c);
640static void delCommand(redisClient *c);
641static void existsCommand(redisClient *c);
642static void incrCommand(redisClient *c);
643static void decrCommand(redisClient *c);
644static void incrbyCommand(redisClient *c);
645static void decrbyCommand(redisClient *c);
646static void selectCommand(redisClient *c);
647static void randomkeyCommand(redisClient *c);
648static void keysCommand(redisClient *c);
649static void dbsizeCommand(redisClient *c);
650static void lastsaveCommand(redisClient *c);
651static void saveCommand(redisClient *c);
652static void bgsaveCommand(redisClient *c);
9d65a1bb 653static void bgrewriteaofCommand(redisClient *c);
ed9b544e 654static void shutdownCommand(redisClient *c);
655static void moveCommand(redisClient *c);
656static void renameCommand(redisClient *c);
657static void renamenxCommand(redisClient *c);
658static void lpushCommand(redisClient *c);
659static void rpushCommand(redisClient *c);
660static void lpopCommand(redisClient *c);
661static void rpopCommand(redisClient *c);
662static void llenCommand(redisClient *c);
663static void lindexCommand(redisClient *c);
664static void lrangeCommand(redisClient *c);
665static void ltrimCommand(redisClient *c);
666static void typeCommand(redisClient *c);
667static void lsetCommand(redisClient *c);
668static void saddCommand(redisClient *c);
669static void sremCommand(redisClient *c);
a4460ef4 670static void smoveCommand(redisClient *c);
ed9b544e 671static void sismemberCommand(redisClient *c);
672static void scardCommand(redisClient *c);
12fea928 673static void spopCommand(redisClient *c);
2abb95a9 674static void srandmemberCommand(redisClient *c);
ed9b544e 675static void sinterCommand(redisClient *c);
676static void sinterstoreCommand(redisClient *c);
40d224a9 677static void sunionCommand(redisClient *c);
678static void sunionstoreCommand(redisClient *c);
f4f56e1d 679static void sdiffCommand(redisClient *c);
680static void sdiffstoreCommand(redisClient *c);
ed9b544e 681static void syncCommand(redisClient *c);
682static void flushdbCommand(redisClient *c);
683static void flushallCommand(redisClient *c);
684static void sortCommand(redisClient *c);
685static void lremCommand(redisClient *c);
0f5f7e9a 686static void rpoplpushcommand(redisClient *c);
ed9b544e 687static void infoCommand(redisClient *c);
70003d28 688static void mgetCommand(redisClient *c);
87eca727 689static void monitorCommand(redisClient *c);
3305306f 690static void expireCommand(redisClient *c);
802e8373 691static void expireatCommand(redisClient *c);
f6b141c5 692static void getsetCommand(redisClient *c);
fd88489a 693static void ttlCommand(redisClient *c);
321b0e13 694static void slaveofCommand(redisClient *c);
7f957c92 695static void debugCommand(redisClient *c);
f6b141c5 696static void msetCommand(redisClient *c);
697static void msetnxCommand(redisClient *c);
fd8ccf44 698static void zaddCommand(redisClient *c);
7db723ad 699static void zincrbyCommand(redisClient *c);
cc812361 700static void zrangeCommand(redisClient *c);
50c55df5 701static void zrangebyscoreCommand(redisClient *c);
f44dd428 702static void zcountCommand(redisClient *c);
e3870fab 703static void zrevrangeCommand(redisClient *c);
3c41331e 704static void zcardCommand(redisClient *c);
1b7106e7 705static void zremCommand(redisClient *c);
6e333bbe 706static void zscoreCommand(redisClient *c);
1807985b 707static void zremrangebyscoreCommand(redisClient *c);
6e469882 708static void multiCommand(redisClient *c);
709static void execCommand(redisClient *c);
18b6cb76 710static void discardCommand(redisClient *c);
4409877e 711static void blpopCommand(redisClient *c);
712static void brpopCommand(redisClient *c);
4b00bebd 713static void appendCommand(redisClient *c);
39191553 714static void substrCommand(redisClient *c);
69d95c3e 715static void zrankCommand(redisClient *c);
798d9e55 716static void zrevrankCommand(redisClient *c);
978c2c94 717static void hsetCommand(redisClient *c);
1f1c7695 718static void hsetnxCommand(redisClient *c);
978c2c94 719static void hgetCommand(redisClient *c);
09aeb579
PN
720static void hmsetCommand(redisClient *c);
721static void hmgetCommand(redisClient *c);
07efaf74 722static void hdelCommand(redisClient *c);
92b27fe9 723static void hlenCommand(redisClient *c);
9212eafd 724static void zremrangebyrankCommand(redisClient *c);
2830ca53
PN
725static void zunionCommand(redisClient *c);
726static void zinterCommand(redisClient *c);
78409a0f 727static void hkeysCommand(redisClient *c);
728static void hvalsCommand(redisClient *c);
729static void hgetallCommand(redisClient *c);
a86f14b1 730static void hexistsCommand(redisClient *c);
500ece7c 731static void configCommand(redisClient *c);
01426b05 732static void hincrbyCommand(redisClient *c);
befec3cd 733static void subscribeCommand(redisClient *c);
734static void unsubscribeCommand(redisClient *c);
ffc6b7f8 735static void psubscribeCommand(redisClient *c);
736static void punsubscribeCommand(redisClient *c);
befec3cd 737static void publishCommand(redisClient *c);
f6b141c5 738
ed9b544e 739/*================================= Globals ================================= */
740
741/* Global vars */
742static struct redisServer server; /* server global state */
743static struct redisCommand cmdTable[] = {
76583ea4
PN
744 {"get",getCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
745 {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
746 {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
526d00a5 747 {"setex",setexCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
76583ea4
PN
748 {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
749 {"substr",substrCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
750 {"del",delCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
751 {"exists",existsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
752 {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
753 {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
754 {"mget",mgetCommand,-2,REDIS_CMD_INLINE,NULL,1,-1,1},
755 {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
756 {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
757 {"rpop",rpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
758 {"lpop",lpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
759 {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
760 {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
761 {"llen",llenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
762 {"lindex",lindexCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
763 {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
764 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
765 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
766 {"lrem",lremCommand,4,REDIS_CMD_BULK,NULL,1,1,1},
767 {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,2,1},
768 {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
769 {"srem",sremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
770 {"smove",smoveCommand,4,REDIS_CMD_BULK,NULL,1,2,1},
771 {"sismember",sismemberCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
772 {"scard",scardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
773 {"spop",spopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
774 {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
775 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
776 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
777 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
778 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
779 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
780 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
781 {"smembers",sinterCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
782 {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
783 {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
784 {"zrem",zremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
785 {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
786 {"zremrangebyrank",zremrangebyrankCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
787 {"zunion",zunionCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
788 {"zinter",zinterCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
789 {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
790 {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
791 {"zcount",zcountCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
792 {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
793 {"zcard",zcardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
794 {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
795 {"zrank",zrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
796 {"zrevrank",zrevrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
797 {"hset",hsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
1f1c7695 798 {"hsetnx",hsetnxCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
09aeb579 799 {"hget",hgetCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
d33278d1 800 {"hmset",hmsetCommand,-4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
09aeb579 801 {"hmget",hmgetCommand,-3,REDIS_CMD_BULK,NULL,1,1,1},
01426b05 802 {"hincrby",hincrbyCommand,4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
76583ea4
PN
803 {"hdel",hdelCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
804 {"hlen",hlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
805 {"hkeys",hkeysCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
806 {"hvals",hvalsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
807 {"hgetall",hgetallCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
4583c4f0 808 {"hexists",hexistsCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
76583ea4
PN
809 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
810 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
811 {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
812 {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
813 {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
814 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
815 {"select",selectCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
816 {"move",moveCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
817 {"rename",renameCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
818 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
819 {"expire",expireCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
820 {"expireat",expireatCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
821 {"keys",keysCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
822 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
823 {"auth",authCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
824 {"ping",pingCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
825 {"echo",echoCommand,2,REDIS_CMD_BULK,NULL,0,0,0},
826 {"save",saveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
827 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
828 {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
829 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
830 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
831 {"type",typeCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
832 {"multi",multiCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
3805e04f 833 {"exec",execCommand,1,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0},
76583ea4
PN
834 {"discard",discardCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
835 {"sync",syncCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
836 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
837 {"flushall",flushallCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
838 {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
839 {"info",infoCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
840 {"monitor",monitorCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
841 {"ttl",ttlCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
842 {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
843 {"debug",debugCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
500ece7c 844 {"config",configCommand,-2,REDIS_CMD_BULK,NULL,0,0,0},
befec3cd 845 {"subscribe",subscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
846 {"unsubscribe",unsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
ffc6b7f8 847 {"psubscribe",psubscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
848 {"punsubscribe",punsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
4005fef1 849 {"publish",publishCommand,3,REDIS_CMD_BULK|REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0},
76583ea4 850 {NULL,NULL,0,0,NULL,0,0,0}
ed9b544e 851};
bcfc686d 852
ed9b544e 853/*============================ Utility functions ============================ */
854
855/* Glob-style pattern matching. */
500ece7c 856static int stringmatchlen(const char *pattern, int patternLen,
ed9b544e 857 const char *string, int stringLen, int nocase)
858{
859 while(patternLen) {
860 switch(pattern[0]) {
861 case '*':
862 while (pattern[1] == '*') {
863 pattern++;
864 patternLen--;
865 }
866 if (patternLen == 1)
867 return 1; /* match */
868 while(stringLen) {
869 if (stringmatchlen(pattern+1, patternLen-1,
870 string, stringLen, nocase))
871 return 1; /* match */
872 string++;
873 stringLen--;
874 }
875 return 0; /* no match */
876 break;
877 case '?':
878 if (stringLen == 0)
879 return 0; /* no match */
880 string++;
881 stringLen--;
882 break;
883 case '[':
884 {
885 int not, match;
886
887 pattern++;
888 patternLen--;
889 not = pattern[0] == '^';
890 if (not) {
891 pattern++;
892 patternLen--;
893 }
894 match = 0;
895 while(1) {
896 if (pattern[0] == '\\') {
897 pattern++;
898 patternLen--;
899 if (pattern[0] == string[0])
900 match = 1;
901 } else if (pattern[0] == ']') {
902 break;
903 } else if (patternLen == 0) {
904 pattern--;
905 patternLen++;
906 break;
907 } else if (pattern[1] == '-' && patternLen >= 3) {
908 int start = pattern[0];
909 int end = pattern[2];
910 int c = string[0];
911 if (start > end) {
912 int t = start;
913 start = end;
914 end = t;
915 }
916 if (nocase) {
917 start = tolower(start);
918 end = tolower(end);
919 c = tolower(c);
920 }
921 pattern += 2;
922 patternLen -= 2;
923 if (c >= start && c <= end)
924 match = 1;
925 } else {
926 if (!nocase) {
927 if (pattern[0] == string[0])
928 match = 1;
929 } else {
930 if (tolower((int)pattern[0]) == tolower((int)string[0]))
931 match = 1;
932 }
933 }
934 pattern++;
935 patternLen--;
936 }
937 if (not)
938 match = !match;
939 if (!match)
940 return 0; /* no match */
941 string++;
942 stringLen--;
943 break;
944 }
945 case '\\':
946 if (patternLen >= 2) {
947 pattern++;
948 patternLen--;
949 }
950 /* fall through */
951 default:
952 if (!nocase) {
953 if (pattern[0] != string[0])
954 return 0; /* no match */
955 } else {
956 if (tolower((int)pattern[0]) != tolower((int)string[0]))
957 return 0; /* no match */
958 }
959 string++;
960 stringLen--;
961 break;
962 }
963 pattern++;
964 patternLen--;
965 if (stringLen == 0) {
966 while(*pattern == '*') {
967 pattern++;
968 patternLen--;
969 }
970 break;
971 }
972 }
973 if (patternLen == 0 && stringLen == 0)
974 return 1;
975 return 0;
976}
977
500ece7c 978static int stringmatch(const char *pattern, const char *string, int nocase) {
979 return stringmatchlen(pattern,strlen(pattern),string,strlen(string),nocase);
980}
981
2b619329 982/* Convert a string representing an amount of memory into the number of
983 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
984 * (1024*1024*1024).
985 *
986 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
987 * set to 0 */
988static long long memtoll(const char *p, int *err) {
989 const char *u;
990 char buf[128];
991 long mul; /* unit multiplier */
992 long long val;
993 unsigned int digits;
994
995 if (err) *err = 0;
996 /* Search the first non digit character. */
997 u = p;
998 if (*u == '-') u++;
999 while(*u && isdigit(*u)) u++;
1000 if (*u == '\0' || !strcasecmp(u,"b")) {
1001 mul = 1;
72324005 1002 } else if (!strcasecmp(u,"k")) {
2b619329 1003 mul = 1000;
72324005 1004 } else if (!strcasecmp(u,"kb")) {
2b619329 1005 mul = 1024;
72324005 1006 } else if (!strcasecmp(u,"m")) {
2b619329 1007 mul = 1000*1000;
72324005 1008 } else if (!strcasecmp(u,"mb")) {
2b619329 1009 mul = 1024*1024;
72324005 1010 } else if (!strcasecmp(u,"g")) {
2b619329 1011 mul = 1000L*1000*1000;
72324005 1012 } else if (!strcasecmp(u,"gb")) {
2b619329 1013 mul = 1024L*1024*1024;
1014 } else {
1015 if (err) *err = 1;
1016 mul = 1;
1017 }
1018 digits = u-p;
1019 if (digits >= sizeof(buf)) {
1020 if (err) *err = 1;
1021 return LLONG_MAX;
1022 }
1023 memcpy(buf,p,digits);
1024 buf[digits] = '\0';
1025 val = strtoll(buf,NULL,10);
1026 return val*mul;
1027}
1028
ee14da56 1029/* Convert a long long into a string. Returns the number of
1030 * characters needed to represent the number, that can be shorter if passed
1031 * buffer length is not enough to store the whole number. */
1032static int ll2string(char *s, size_t len, long long value) {
1033 char buf[32], *p;
1034 unsigned long long v;
1035 size_t l;
1036
1037 if (len == 0) return 0;
1038 v = (value < 0) ? -value : value;
1039 p = buf+31; /* point to the last character */
1040 do {
1041 *p-- = '0'+(v%10);
1042 v /= 10;
1043 } while(v);
1044 if (value < 0) *p-- = '-';
1045 p++;
1046 l = 32-(p-buf);
1047 if (l+1 > len) l = len-1; /* Make sure it fits, including the nul term */
1048 memcpy(s,p,l);
1049 s[l] = '\0';
1050 return l;
1051}
1052
56906eef 1053static void redisLog(int level, const char *fmt, ...) {
ed9b544e 1054 va_list ap;
1055 FILE *fp;
1056
1057 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
1058 if (!fp) return;
1059
1060 va_start(ap, fmt);
1061 if (level >= server.verbosity) {
6766f45e 1062 char *c = ".-*#";
1904ecc1 1063 char buf[64];
1064 time_t now;
1065
1066 now = time(NULL);
6c9385e0 1067 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
054e426d 1068 fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
ed9b544e 1069 vfprintf(fp, fmt, ap);
1070 fprintf(fp,"\n");
1071 fflush(fp);
1072 }
1073 va_end(ap);
1074
1075 if (server.logfile) fclose(fp);
1076}
1077
1078/*====================== Hash table type implementation ==================== */
1079
1080/* This is an hash table type that uses the SDS dynamic strings libary as
1081 * keys and radis objects as values (objects can hold SDS strings,
1082 * lists, sets). */
1083
1812e024 1084static void dictVanillaFree(void *privdata, void *val)
1085{
1086 DICT_NOTUSED(privdata);
1087 zfree(val);
1088}
1089
4409877e 1090static void dictListDestructor(void *privdata, void *val)
1091{
1092 DICT_NOTUSED(privdata);
1093 listRelease((list*)val);
1094}
1095
ed9b544e 1096static int sdsDictKeyCompare(void *privdata, const void *key1,
1097 const void *key2)
1098{
1099 int l1,l2;
1100 DICT_NOTUSED(privdata);
1101
1102 l1 = sdslen((sds)key1);
1103 l2 = sdslen((sds)key2);
1104 if (l1 != l2) return 0;
1105 return memcmp(key1, key2, l1) == 0;
1106}
1107
1108static void dictRedisObjectDestructor(void *privdata, void *val)
1109{
1110 DICT_NOTUSED(privdata);
1111
a35ddf12 1112 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
ed9b544e 1113 decrRefCount(val);
1114}
1115
942a3961 1116static int dictObjKeyCompare(void *privdata, const void *key1,
ed9b544e 1117 const void *key2)
1118{
1119 const robj *o1 = key1, *o2 = key2;
1120 return sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1121}
1122
942a3961 1123static unsigned int dictObjHash(const void *key) {
ed9b544e 1124 const robj *o = key;
1125 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1126}
1127
942a3961 1128static int dictEncObjKeyCompare(void *privdata, const void *key1,
1129 const void *key2)
1130{
9d65a1bb 1131 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
1132 int cmp;
942a3961 1133
2a1198b4 1134 if (o1->encoding == REDIS_ENCODING_INT &&
dc05abde 1135 o2->encoding == REDIS_ENCODING_INT)
1136 return o1->ptr == o2->ptr;
2a1198b4 1137
9d65a1bb 1138 o1 = getDecodedObject(o1);
1139 o2 = getDecodedObject(o2);
1140 cmp = sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1141 decrRefCount(o1);
1142 decrRefCount(o2);
1143 return cmp;
942a3961 1144}
1145
1146static unsigned int dictEncObjHash(const void *key) {
9d65a1bb 1147 robj *o = (robj*) key;
942a3961 1148
ed9e4966 1149 if (o->encoding == REDIS_ENCODING_RAW) {
1150 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1151 } else {
1152 if (o->encoding == REDIS_ENCODING_INT) {
1153 char buf[32];
1154 int len;
1155
ee14da56 1156 len = ll2string(buf,32,(long)o->ptr);
ed9e4966 1157 return dictGenHashFunction((unsigned char*)buf, len);
1158 } else {
1159 unsigned int hash;
1160
1161 o = getDecodedObject(o);
1162 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1163 decrRefCount(o);
1164 return hash;
1165 }
1166 }
942a3961 1167}
1168
f2d9f50f 1169/* Sets type and expires */
ed9b544e 1170static dictType setDictType = {
942a3961 1171 dictEncObjHash, /* hash function */
ed9b544e 1172 NULL, /* key dup */
1173 NULL, /* val dup */
942a3961 1174 dictEncObjKeyCompare, /* key compare */
ed9b544e 1175 dictRedisObjectDestructor, /* key destructor */
1176 NULL /* val destructor */
1177};
1178
f2d9f50f 1179/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1812e024 1180static dictType zsetDictType = {
1181 dictEncObjHash, /* hash function */
1182 NULL, /* key dup */
1183 NULL, /* val dup */
1184 dictEncObjKeyCompare, /* key compare */
1185 dictRedisObjectDestructor, /* key destructor */
da0a1620 1186 dictVanillaFree /* val destructor of malloc(sizeof(double)) */
1812e024 1187};
1188
f2d9f50f 1189/* Db->dict */
5234952b 1190static dictType dbDictType = {
942a3961 1191 dictObjHash, /* hash function */
ed9b544e 1192 NULL, /* key dup */
1193 NULL, /* val dup */
942a3961 1194 dictObjKeyCompare, /* key compare */
ed9b544e 1195 dictRedisObjectDestructor, /* key destructor */
1196 dictRedisObjectDestructor /* val destructor */
1197};
1198
f2d9f50f 1199/* Db->expires */
1200static dictType keyptrDictType = {
1201 dictObjHash, /* hash function */
1202 NULL, /* key dup */
1203 NULL, /* val dup */
1204 dictObjKeyCompare, /* key compare */
1205 dictRedisObjectDestructor, /* key destructor */
1206 NULL /* val destructor */
1207};
1208
5234952b 1209/* Hash type hash table (note that small hashes are represented with zimpaps) */
1210static dictType hashDictType = {
1211 dictEncObjHash, /* hash function */
1212 NULL, /* key dup */
1213 NULL, /* val dup */
1214 dictEncObjKeyCompare, /* key compare */
1215 dictRedisObjectDestructor, /* key destructor */
1216 dictRedisObjectDestructor /* val destructor */
1217};
1218
4409877e 1219/* Keylist hash table type has unencoded redis objects as keys and
d5d55fc3 1220 * lists as values. It's used for blocking operations (BLPOP) and to
1221 * map swapped keys to a list of clients waiting for this keys to be loaded. */
4409877e 1222static dictType keylistDictType = {
1223 dictObjHash, /* hash function */
1224 NULL, /* key dup */
1225 NULL, /* val dup */
1226 dictObjKeyCompare, /* key compare */
1227 dictRedisObjectDestructor, /* key destructor */
1228 dictListDestructor /* val destructor */
1229};
1230
42ab0172
AO
1231static void version();
1232
ed9b544e 1233/* ========================= Random utility functions ======================= */
1234
1235/* Redis generally does not try to recover from out of memory conditions
1236 * when allocating objects or strings, it is not clear if it will be possible
1237 * to report this condition to the client since the networking layer itself
1238 * is based on heap allocation for send buffers, so we simply abort.
1239 * At least the code will be simpler to read... */
1240static void oom(const char *msg) {
71c54b21 1241 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
ed9b544e 1242 sleep(1);
1243 abort();
1244}
1245
1246/* ====================== Redis server networking stuff ===================== */
56906eef 1247static void closeTimedoutClients(void) {
ed9b544e 1248 redisClient *c;
ed9b544e 1249 listNode *ln;
1250 time_t now = time(NULL);
c7df85a4 1251 listIter li;
ed9b544e 1252
c7df85a4 1253 listRewind(server.clients,&li);
1254 while ((ln = listNext(&li)) != NULL) {
ed9b544e 1255 c = listNodeValue(ln);
f86a74e9 1256 if (server.maxidletime &&
1257 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
c7cf2ec9 1258 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
ffc6b7f8 1259 dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
1260 listLength(c->pubsub_patterns) == 0 &&
d6cc8867 1261 (now - c->lastinteraction > server.maxidletime))
f86a74e9 1262 {
f870935d 1263 redisLog(REDIS_VERBOSE,"Closing idle client");
ed9b544e 1264 freeClient(c);
f86a74e9 1265 } else if (c->flags & REDIS_BLOCKED) {
58d976b8 1266 if (c->blockingto != 0 && c->blockingto < now) {
b177fd30 1267 addReply(c,shared.nullmultibulk);
b0d8747d 1268 unblockClientWaitingData(c);
f86a74e9 1269 }
ed9b544e 1270 }
1271 }
ed9b544e 1272}
1273
12fea928 1274static int htNeedsResize(dict *dict) {
1275 long long size, used;
1276
1277 size = dictSlots(dict);
1278 used = dictSize(dict);
1279 return (size && used && size > DICT_HT_INITIAL_SIZE &&
1280 (used*100/size < REDIS_HT_MINFILL));
1281}
1282
0bc03378 1283/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1284 * we resize the hash table to save memory */
56906eef 1285static void tryResizeHashTables(void) {
0bc03378 1286 int j;
1287
1288 for (j = 0; j < server.dbnum; j++) {
5413c40d 1289 if (htNeedsResize(server.db[j].dict))
0bc03378 1290 dictResize(server.db[j].dict);
12fea928 1291 if (htNeedsResize(server.db[j].expires))
1292 dictResize(server.db[j].expires);
0bc03378 1293 }
1294}
1295
8ca3e9d1 1296/* Our hash table implementation performs rehashing incrementally while
1297 * we write/read from the hash table. Still if the server is idle, the hash
1298 * table will use two tables for a long time. So we try to use 1 millisecond
1299 * of CPU time at every serverCron() loop in order to rehash some key. */
1300static void incrementallyRehash(void) {
1301 int j;
1302
1303 for (j = 0; j < server.dbnum; j++) {
1304 if (dictIsRehashing(server.db[j].dict)) {
1305 dictRehashMilliseconds(server.db[j].dict,1);
1306 break; /* already used our millisecond for this loop... */
1307 }
1308 }
1309}
1310
9d65a1bb 1311/* A background saving child (BGSAVE) terminated its work. Handle this. */
1312void backgroundSaveDoneHandler(int statloc) {
1313 int exitcode = WEXITSTATUS(statloc);
1314 int bysignal = WIFSIGNALED(statloc);
1315
1316 if (!bysignal && exitcode == 0) {
1317 redisLog(REDIS_NOTICE,
1318 "Background saving terminated with success");
1319 server.dirty = 0;
1320 server.lastsave = time(NULL);
1321 } else if (!bysignal && exitcode != 0) {
1322 redisLog(REDIS_WARNING, "Background saving error");
1323 } else {
1324 redisLog(REDIS_WARNING,
454eea7c 1325 "Background saving terminated by signal %d", WTERMSIG(statloc));
9d65a1bb 1326 rdbRemoveTempFile(server.bgsavechildpid);
1327 }
1328 server.bgsavechildpid = -1;
1329 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1330 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1331 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1332}
1333
1334/* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1335 * Handle this. */
1336void backgroundRewriteDoneHandler(int statloc) {
1337 int exitcode = WEXITSTATUS(statloc);
1338 int bysignal = WIFSIGNALED(statloc);
1339
1340 if (!bysignal && exitcode == 0) {
1341 int fd;
1342 char tmpfile[256];
1343
1344 redisLog(REDIS_NOTICE,
1345 "Background append only file rewriting terminated with success");
1346 /* Now it's time to flush the differences accumulated by the parent */
1347 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
1348 fd = open(tmpfile,O_WRONLY|O_APPEND);
1349 if (fd == -1) {
1350 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
1351 goto cleanup;
1352 }
1353 /* Flush our data... */
1354 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
1355 (signed) sdslen(server.bgrewritebuf)) {
1356 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));
1357 close(fd);
1358 goto cleanup;
1359 }
b32627cd 1360 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
9d65a1bb 1361 /* Now our work is to rename the temp file into the stable file. And
1362 * switch the file descriptor used by the server for append only. */
1363 if (rename(tmpfile,server.appendfilename) == -1) {
1364 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
1365 close(fd);
1366 goto cleanup;
1367 }
1368 /* Mission completed... almost */
1369 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
1370 if (server.appendfd != -1) {
1371 /* If append only is actually enabled... */
1372 close(server.appendfd);
1373 server.appendfd = fd;
1374 fsync(fd);
85a83172 1375 server.appendseldb = -1; /* Make sure it will issue SELECT */
9d65a1bb 1376 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
1377 } else {
1378 /* If append only is disabled we just generate a dump in this
1379 * format. Why not? */
1380 close(fd);
1381 }
1382 } else if (!bysignal && exitcode != 0) {
1383 redisLog(REDIS_WARNING, "Background append only file rewriting error");
1384 } else {
1385 redisLog(REDIS_WARNING,
454eea7c 1386 "Background append only file rewriting terminated by signal %d",
1387 WTERMSIG(statloc));
9d65a1bb 1388 }
1389cleanup:
1390 sdsfree(server.bgrewritebuf);
1391 server.bgrewritebuf = sdsempty();
1392 aofRemoveTempFile(server.bgrewritechildpid);
1393 server.bgrewritechildpid = -1;
1394}
1395
884d4b39 1396/* This function is called once a background process of some kind terminates,
1397 * as we want to avoid resizing the hash tables when there is a child in order
1398 * to play well with copy-on-write (otherwise when a resize happens lots of
1399 * memory pages are copied). The goal of this function is to update the ability
1400 * for dict.c to resize the hash tables accordingly to the fact we have o not
1401 * running childs. */
1402static void updateDictResizePolicy(void) {
1403 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
1404 dictEnableResize();
1405 else
1406 dictDisableResize();
1407}
1408
56906eef 1409static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
94754ccc 1410 int j, loops = server.cronloops++;
ed9b544e 1411 REDIS_NOTUSED(eventLoop);
1412 REDIS_NOTUSED(id);
1413 REDIS_NOTUSED(clientData);
1414
3a66edc7 1415 /* We take a cached value of the unix time in the global state because
1416 * with virtual memory and aging there is to store the current time
1417 * in objects at every object access, and accuracy is not needed.
1418 * To access a global var is faster than calling time(NULL) */
1419 server.unixtime = time(NULL);
1420
0bc03378 1421 /* Show some info about non-empty databases */
ed9b544e 1422 for (j = 0; j < server.dbnum; j++) {
dec423d9 1423 long long size, used, vkeys;
94754ccc 1424
3305306f 1425 size = dictSlots(server.db[j].dict);
1426 used = dictSize(server.db[j].dict);
94754ccc 1427 vkeys = dictSize(server.db[j].expires);
1763929f 1428 if (!(loops % 50) && (used || vkeys)) {
f870935d 1429 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
a4d1ba9a 1430 /* dictPrintStats(server.dict); */
ed9b544e 1431 }
ed9b544e 1432 }
1433
0bc03378 1434 /* We don't want to resize the hash tables while a bacground saving
1435 * is in progress: the saving child is created using fork() that is
1436 * implemented with a copy-on-write semantic in most modern systems, so
1437 * if we resize the HT while there is the saving child at work actually
1438 * a lot of memory movements in the parent will cause a lot of pages
1439 * copied. */
8ca3e9d1 1440 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
1441 if (!(loops % 10)) tryResizeHashTables();
1442 if (server.activerehashing) incrementallyRehash();
884d4b39 1443 }
0bc03378 1444
ed9b544e 1445 /* Show information about connected clients */
1763929f 1446 if (!(loops % 50)) {
bdcb92f2 1447 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
ed9b544e 1448 listLength(server.clients)-listLength(server.slaves),
1449 listLength(server.slaves),
bdcb92f2 1450 zmalloc_used_memory());
ed9b544e 1451 }
1452
1453 /* Close connections of timedout clients */
1763929f 1454 if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients)
ed9b544e 1455 closeTimedoutClients();
1456
9d65a1bb 1457 /* Check if a background saving or AOF rewrite in progress terminated */
1458 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
ed9b544e 1459 int statloc;
9d65a1bb 1460 pid_t pid;
1461
1462 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
1463 if (pid == server.bgsavechildpid) {
1464 backgroundSaveDoneHandler(statloc);
ed9b544e 1465 } else {
9d65a1bb 1466 backgroundRewriteDoneHandler(statloc);
ed9b544e 1467 }
884d4b39 1468 updateDictResizePolicy();
ed9b544e 1469 }
1470 } else {
1471 /* If there is not a background saving in progress check if
1472 * we have to save now */
1473 time_t now = time(NULL);
1474 for (j = 0; j < server.saveparamslen; j++) {
1475 struct saveparam *sp = server.saveparams+j;
1476
1477 if (server.dirty >= sp->changes &&
1478 now-server.lastsave > sp->seconds) {
1479 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
1480 sp->changes, sp->seconds);
f78fd11b 1481 rdbSaveBackground(server.dbfilename);
ed9b544e 1482 break;
1483 }
1484 }
1485 }
94754ccc 1486
f2324293 1487 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1488 * will use few CPU cycles if there are few expiring keys, otherwise
1489 * it will get more aggressive to avoid that too much memory is used by
1490 * keys that can be removed from the keyspace. */
94754ccc 1491 for (j = 0; j < server.dbnum; j++) {
f2324293 1492 int expired;
94754ccc 1493 redisDb *db = server.db+j;
94754ccc 1494
f2324293 1495 /* Continue to expire if at the end of the cycle more than 25%
1496 * of the keys were expired. */
1497 do {
4ef8de8a 1498 long num = dictSize(db->expires);
94754ccc 1499 time_t now = time(NULL);
1500
f2324293 1501 expired = 0;
94754ccc 1502 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
1503 num = REDIS_EXPIRELOOKUPS_PER_CRON;
1504 while (num--) {
1505 dictEntry *de;
1506 time_t t;
1507
1508 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
1509 t = (time_t) dictGetEntryVal(de);
1510 if (now > t) {
1511 deleteKey(db,dictGetEntryKey(de));
f2324293 1512 expired++;
2a6a2ed1 1513 server.stat_expiredkeys++;
94754ccc 1514 }
1515 }
f2324293 1516 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
94754ccc 1517 }
1518
4ef8de8a 1519 /* Swap a few keys on disk if we are over the memory limit and VM
f870935d 1520 * is enbled. Try to free objects from the free list first. */
7e69548d 1521 if (vmCanSwapOut()) {
1522 while (server.vm_enabled && zmalloc_used_memory() >
f870935d 1523 server.vm_max_memory)
1524 {
72e9fd40 1525 int retval;
1526
a5819310 1527 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
72e9fd40 1528 retval = (server.vm_max_threads == 0) ?
1529 vmSwapOneObjectBlocking() :
1530 vmSwapOneObjectThreaded();
1763929f 1531 if (retval == REDIS_ERR && !(loops % 300) &&
72e9fd40 1532 zmalloc_used_memory() >
1533 (server.vm_max_memory+server.vm_max_memory/10))
1534 {
1535 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
7e69548d 1536 }
72e9fd40 1537 /* Note that when using threade I/O we free just one object,
1538 * because anyway when the I/O thread in charge to swap this
1539 * object out will finish, the handler of completed jobs
1540 * will try to swap more objects if we are still out of memory. */
1541 if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
4ef8de8a 1542 }
1543 }
1544
ed9b544e 1545 /* Check if we should connect to a MASTER */
1763929f 1546 if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) {
ed9b544e 1547 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
1548 if (syncWithMaster() == REDIS_OK) {
1549 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
8f63ddca 1550 if (server.appendonly) rewriteAppendOnlyFileBackground();
ed9b544e 1551 }
1552 }
1763929f 1553 return 100;
ed9b544e 1554}
1555
d5d55fc3 1556/* This function gets called every time Redis is entering the
1557 * main loop of the event driven library, that is, before to sleep
1558 * for ready file descriptors. */
1559static void beforeSleep(struct aeEventLoop *eventLoop) {
1560 REDIS_NOTUSED(eventLoop);
1561
28ed1f33 1562 /* Awake clients that got all the swapped keys they requested */
d5d55fc3 1563 if (server.vm_enabled && listLength(server.io_ready_clients)) {
1564 listIter li;
1565 listNode *ln;
1566
1567 listRewind(server.io_ready_clients,&li);
1568 while((ln = listNext(&li))) {
1569 redisClient *c = ln->value;
1570 struct redisCommand *cmd;
1571
1572 /* Resume the client. */
1573 listDelNode(server.io_ready_clients,ln);
1574 c->flags &= (~REDIS_IO_WAIT);
1575 server.vm_blocked_clients--;
1576 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1577 readQueryFromClient, c);
1578 cmd = lookupCommand(c->argv[0]->ptr);
1579 assert(cmd != NULL);
1580 call(c,cmd);
1581 resetClient(c);
1582 /* There may be more data to process in the input buffer. */
1583 if (c->querybuf && sdslen(c->querybuf) > 0)
1584 processInputBuffer(c);
1585 }
1586 }
28ed1f33 1587 /* Write the AOF buffer on disk */
1588 flushAppendOnlyFile();
d5d55fc3 1589}
1590
ed9b544e 1591static void createSharedObjects(void) {
05df7621 1592 int j;
1593
ed9b544e 1594 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
1595 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
1596 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
c937aa89 1597 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
1598 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
1599 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
1600 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
1601 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
1602 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
ed9b544e 1603 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
6e469882 1604 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
ed9b544e 1605 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
1606 "-ERR Operation against a key holding the wrong kind of value\r\n"));
ed9b544e 1607 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
1608 "-ERR no such key\r\n"));
ed9b544e 1609 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
1610 "-ERR syntax error\r\n"));
c937aa89 1611 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
1612 "-ERR source and destination objects are the same\r\n"));
1613 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
1614 "-ERR index out of range\r\n"));
ed9b544e 1615 shared.space = createObject(REDIS_STRING,sdsnew(" "));
c937aa89 1616 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
1617 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
ed9b544e 1618 shared.select0 = createStringObject("select 0\r\n",10);
1619 shared.select1 = createStringObject("select 1\r\n",10);
1620 shared.select2 = createStringObject("select 2\r\n",10);
1621 shared.select3 = createStringObject("select 3\r\n",10);
1622 shared.select4 = createStringObject("select 4\r\n",10);
1623 shared.select5 = createStringObject("select 5\r\n",10);
1624 shared.select6 = createStringObject("select 6\r\n",10);
1625 shared.select7 = createStringObject("select 7\r\n",10);
1626 shared.select8 = createStringObject("select 8\r\n",10);
1627 shared.select9 = createStringObject("select 9\r\n",10);
befec3cd 1628 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
c8d0ea0e 1629 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
befec3cd 1630 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
fc46bb71 1631 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
ffc6b7f8 1632 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
1633 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
befec3cd 1634 shared.mbulk3 = createStringObject("*3\r\n",4);
c8d0ea0e 1635 shared.mbulk4 = createStringObject("*4\r\n",4);
05df7621 1636 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
1637 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
1638 shared.integers[j]->encoding = REDIS_ENCODING_INT;
1639 }
ed9b544e 1640}
1641
1642static void appendServerSaveParams(time_t seconds, int changes) {
1643 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
ed9b544e 1644 server.saveparams[server.saveparamslen].seconds = seconds;
1645 server.saveparams[server.saveparamslen].changes = changes;
1646 server.saveparamslen++;
1647}
1648
bcfc686d 1649static void resetServerSaveParams() {
ed9b544e 1650 zfree(server.saveparams);
1651 server.saveparams = NULL;
1652 server.saveparamslen = 0;
1653}
1654
1655static void initServerConfig() {
1656 server.dbnum = REDIS_DEFAULT_DBNUM;
1657 server.port = REDIS_SERVERPORT;
f870935d 1658 server.verbosity = REDIS_VERBOSE;
ed9b544e 1659 server.maxidletime = REDIS_MAXIDLETIME;
1660 server.saveparams = NULL;
1661 server.logfile = NULL; /* NULL = log on standard output */
1662 server.bindaddr = NULL;
1663 server.glueoutputbuf = 1;
1664 server.daemonize = 0;
44b38ef4 1665 server.appendonly = 0;
1b677732 1666 server.appendfsync = APPENDFSYNC_EVERYSEC;
48f0308a 1667 server.lastfsync = time(NULL);
44b38ef4 1668 server.appendfd = -1;
1669 server.appendseldb = -1; /* Make sure the first time will not match */
500ece7c 1670 server.pidfile = zstrdup("/var/run/redis.pid");
1671 server.dbfilename = zstrdup("dump.rdb");
1672 server.appendfilename = zstrdup("appendonly.aof");
abcb223e 1673 server.requirepass = NULL;
b0553789 1674 server.rdbcompression = 1;
8ca3e9d1 1675 server.activerehashing = 1;
285add55 1676 server.maxclients = 0;
d5d55fc3 1677 server.blpop_blocked_clients = 0;
3fd78bcd 1678 server.maxmemory = 0;
75680a3c 1679 server.vm_enabled = 0;
054e426d 1680 server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
75680a3c 1681 server.vm_page_size = 256; /* 256 bytes per page */
1682 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
1683 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
92f8e882 1684 server.vm_max_threads = 4;
d5d55fc3 1685 server.vm_blocked_clients = 0;
cbba7dd7 1686 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
1687 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
75680a3c 1688
bcfc686d 1689 resetServerSaveParams();
ed9b544e 1690
1691 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1692 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1693 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1694 /* Replication related */
1695 server.isslave = 0;
d0ccebcf 1696 server.masterauth = NULL;
ed9b544e 1697 server.masterhost = NULL;
1698 server.masterport = 6379;
1699 server.master = NULL;
1700 server.replstate = REDIS_REPL_NONE;
a7866db6 1701
1702 /* Double constants initialization */
1703 R_Zero = 0.0;
1704 R_PosInf = 1.0/R_Zero;
1705 R_NegInf = -1.0/R_Zero;
1706 R_Nan = R_Zero/R_Zero;
ed9b544e 1707}
1708
1709static void initServer() {
1710 int j;
1711
1712 signal(SIGHUP, SIG_IGN);
1713 signal(SIGPIPE, SIG_IGN);
fe3bbfbe 1714 setupSigSegvAction();
ed9b544e 1715
b9bc0eef 1716 server.devnull = fopen("/dev/null","w");
1717 if (server.devnull == NULL) {
1718 redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr);
1719 exit(1);
1720 }
ed9b544e 1721 server.clients = listCreate();
1722 server.slaves = listCreate();
87eca727 1723 server.monitors = listCreate();
ed9b544e 1724 server.objfreelist = listCreate();
1725 createSharedObjects();
1726 server.el = aeCreateEventLoop();
3305306f 1727 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
ed9b544e 1728 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
1729 if (server.fd == -1) {
1730 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
1731 exit(1);
1732 }
3305306f 1733 for (j = 0; j < server.dbnum; j++) {
5234952b 1734 server.db[j].dict = dictCreate(&dbDictType,NULL);
f2d9f50f 1735 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
4409877e 1736 server.db[j].blockingkeys = dictCreate(&keylistDictType,NULL);
d5d55fc3 1737 if (server.vm_enabled)
1738 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
3305306f 1739 server.db[j].id = j;
1740 }
ffc6b7f8 1741 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1742 server.pubsub_patterns = listCreate();
1743 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1744 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
ed9b544e 1745 server.cronloops = 0;
9f3c422c 1746 server.bgsavechildpid = -1;
9d65a1bb 1747 server.bgrewritechildpid = -1;
1748 server.bgrewritebuf = sdsempty();
28ed1f33 1749 server.aofbuf = sdsempty();
ed9b544e 1750 server.lastsave = time(NULL);
1751 server.dirty = 0;
ed9b544e 1752 server.stat_numcommands = 0;
1753 server.stat_numconnections = 0;
2a6a2ed1 1754 server.stat_expiredkeys = 0;
ed9b544e 1755 server.stat_starttime = time(NULL);
3a66edc7 1756 server.unixtime = time(NULL);
d8f8b666 1757 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
996cb5f7 1758 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
1759 acceptHandler, NULL) == AE_ERR) oom("creating file event");
44b38ef4 1760
1761 if (server.appendonly) {
3bb225d6 1762 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
44b38ef4 1763 if (server.appendfd == -1) {
1764 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1765 strerror(errno));
1766 exit(1);
1767 }
1768 }
75680a3c 1769
1770 if (server.vm_enabled) vmInit();
ed9b544e 1771}
1772
1773/* Empty the whole database */
ca37e9cd 1774static long long emptyDb() {
ed9b544e 1775 int j;
ca37e9cd 1776 long long removed = 0;
ed9b544e 1777
3305306f 1778 for (j = 0; j < server.dbnum; j++) {
ca37e9cd 1779 removed += dictSize(server.db[j].dict);
3305306f 1780 dictEmpty(server.db[j].dict);
1781 dictEmpty(server.db[j].expires);
1782 }
ca37e9cd 1783 return removed;
ed9b544e 1784}
1785
85dd2f3a 1786static int yesnotoi(char *s) {
1787 if (!strcasecmp(s,"yes")) return 1;
1788 else if (!strcasecmp(s,"no")) return 0;
1789 else return -1;
1790}
1791
ed9b544e 1792/* I agree, this is a very rudimental way to load a configuration...
1793 will improve later if the config gets more complex */
1794static void loadServerConfig(char *filename) {
c9a111ac 1795 FILE *fp;
ed9b544e 1796 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
1797 int linenum = 0;
1798 sds line = NULL;
c9a111ac 1799
1800 if (filename[0] == '-' && filename[1] == '\0')
1801 fp = stdin;
1802 else {
1803 if ((fp = fopen(filename,"r")) == NULL) {
9a22de82 1804 redisLog(REDIS_WARNING, "Fatal error, can't open config file '%s'", filename);
c9a111ac 1805 exit(1);
1806 }
ed9b544e 1807 }
c9a111ac 1808
ed9b544e 1809 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1810 sds *argv;
1811 int argc, j;
1812
1813 linenum++;
1814 line = sdsnew(buf);
1815 line = sdstrim(line," \t\r\n");
1816
1817 /* Skip comments and blank lines*/
1818 if (line[0] == '#' || line[0] == '\0') {
1819 sdsfree(line);
1820 continue;
1821 }
1822
1823 /* Split into arguments */
1824 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
1825 sdstolower(argv[0]);
1826
1827 /* Execute config directives */
bb0b03a3 1828 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
ed9b544e 1829 server.maxidletime = atoi(argv[1]);
0150db36 1830 if (server.maxidletime < 0) {
ed9b544e 1831 err = "Invalid timeout value"; goto loaderr;
1832 }
bb0b03a3 1833 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
ed9b544e 1834 server.port = atoi(argv[1]);
1835 if (server.port < 1 || server.port > 65535) {
1836 err = "Invalid port"; goto loaderr;
1837 }
bb0b03a3 1838 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
ed9b544e 1839 server.bindaddr = zstrdup(argv[1]);
bb0b03a3 1840 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
ed9b544e 1841 int seconds = atoi(argv[1]);
1842 int changes = atoi(argv[2]);
1843 if (seconds < 1 || changes < 0) {
1844 err = "Invalid save parameters"; goto loaderr;
1845 }
1846 appendServerSaveParams(seconds,changes);
bb0b03a3 1847 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
ed9b544e 1848 if (chdir(argv[1]) == -1) {
1849 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
1850 argv[1], strerror(errno));
1851 exit(1);
1852 }
bb0b03a3 1853 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
1854 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
f870935d 1855 else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
bb0b03a3 1856 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
1857 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
ed9b544e 1858 else {
1859 err = "Invalid log level. Must be one of debug, notice, warning";
1860 goto loaderr;
1861 }
bb0b03a3 1862 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
c9a111ac 1863 FILE *logfp;
ed9b544e 1864
1865 server.logfile = zstrdup(argv[1]);
bb0b03a3 1866 if (!strcasecmp(server.logfile,"stdout")) {
ed9b544e 1867 zfree(server.logfile);
1868 server.logfile = NULL;
1869 }
1870 if (server.logfile) {
1871 /* Test if we are able to open the file. The server will not
1872 * be able to abort just for this problem later... */
c9a111ac 1873 logfp = fopen(server.logfile,"a");
1874 if (logfp == NULL) {
ed9b544e 1875 err = sdscatprintf(sdsempty(),
1876 "Can't open the log file: %s", strerror(errno));
1877 goto loaderr;
1878 }
c9a111ac 1879 fclose(logfp);
ed9b544e 1880 }
bb0b03a3 1881 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
ed9b544e 1882 server.dbnum = atoi(argv[1]);
1883 if (server.dbnum < 1) {
1884 err = "Invalid number of databases"; goto loaderr;
1885 }
b3f83f12
JZ
1886 } else if (!strcasecmp(argv[0],"include") && argc == 2) {
1887 loadServerConfig(argv[1]);
285add55 1888 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
1889 server.maxclients = atoi(argv[1]);
3fd78bcd 1890 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
2b619329 1891 server.maxmemory = memtoll(argv[1],NULL);
bb0b03a3 1892 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
ed9b544e 1893 server.masterhost = sdsnew(argv[1]);
1894 server.masterport = atoi(argv[2]);
1895 server.replstate = REDIS_REPL_CONNECT;
d0ccebcf 1896 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
1897 server.masterauth = zstrdup(argv[1]);
bb0b03a3 1898 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
85dd2f3a 1899 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
ed9b544e 1900 err = "argument must be 'yes' or 'no'"; goto loaderr;
1901 }
121f70cf 1902 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
1903 if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
8ca3e9d1 1904 err = "argument must be 'yes' or 'no'"; goto loaderr;
1905 }
1906 } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
1907 if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
121f70cf 1908 err = "argument must be 'yes' or 'no'"; goto loaderr;
1909 }
bb0b03a3 1910 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
85dd2f3a 1911 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
ed9b544e 1912 err = "argument must be 'yes' or 'no'"; goto loaderr;
1913 }
44b38ef4 1914 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
1915 if ((server.appendonly = yesnotoi(argv[1])) == -1) {
1916 err = "argument must be 'yes' or 'no'"; goto loaderr;
1917 }
f3b52411
PN
1918 } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
1919 zfree(server.appendfilename);
1920 server.appendfilename = zstrdup(argv[1]);
48f0308a 1921 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
1766c6da 1922 if (!strcasecmp(argv[1],"no")) {
48f0308a 1923 server.appendfsync = APPENDFSYNC_NO;
1766c6da 1924 } else if (!strcasecmp(argv[1],"always")) {
48f0308a 1925 server.appendfsync = APPENDFSYNC_ALWAYS;
1766c6da 1926 } else if (!strcasecmp(argv[1],"everysec")) {
48f0308a 1927 server.appendfsync = APPENDFSYNC_EVERYSEC;
1928 } else {
1929 err = "argument must be 'no', 'always' or 'everysec'";
1930 goto loaderr;
1931 }
bb0b03a3 1932 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
054e426d 1933 server.requirepass = zstrdup(argv[1]);
bb0b03a3 1934 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
500ece7c 1935 zfree(server.pidfile);
054e426d 1936 server.pidfile = zstrdup(argv[1]);
bb0b03a3 1937 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
500ece7c 1938 zfree(server.dbfilename);
054e426d 1939 server.dbfilename = zstrdup(argv[1]);
75680a3c 1940 } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
1941 if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
1942 err = "argument must be 'yes' or 'no'"; goto loaderr;
1943 }
054e426d 1944 } else if (!strcasecmp(argv[0],"vm-swap-file") && argc == 2) {
fefed597 1945 zfree(server.vm_swap_file);
054e426d 1946 server.vm_swap_file = zstrdup(argv[1]);
4ef8de8a 1947 } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
2b619329 1948 server.vm_max_memory = memtoll(argv[1],NULL);
4ef8de8a 1949 } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
2b619329 1950 server.vm_page_size = memtoll(argv[1], NULL);
4ef8de8a 1951 } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
2b619329 1952 server.vm_pages = memtoll(argv[1], NULL);
92f8e882 1953 } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
1954 server.vm_max_threads = strtoll(argv[1], NULL, 10);
cbba7dd7 1955 } else if (!strcasecmp(argv[0],"hash-max-zipmap-entries") && argc == 2){
2b619329 1956 server.hash_max_zipmap_entries = memtoll(argv[1], NULL);
cbba7dd7 1957 } else if (!strcasecmp(argv[0],"hash-max-zipmap-value") && argc == 2){
2b619329 1958 server.hash_max_zipmap_value = memtoll(argv[1], NULL);
ed9b544e 1959 } else {
1960 err = "Bad directive or wrong number of arguments"; goto loaderr;
1961 }
1962 for (j = 0; j < argc; j++)
1963 sdsfree(argv[j]);
1964 zfree(argv);
1965 sdsfree(line);
1966 }
c9a111ac 1967 if (fp != stdin) fclose(fp);
ed9b544e 1968 return;
1969
1970loaderr:
1971 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
1972 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
1973 fprintf(stderr, ">>> '%s'\n", line);
1974 fprintf(stderr, "%s\n", err);
1975 exit(1);
1976}
1977
1978static void freeClientArgv(redisClient *c) {
1979 int j;
1980
1981 for (j = 0; j < c->argc; j++)
1982 decrRefCount(c->argv[j]);
e8a74421 1983 for (j = 0; j < c->mbargc; j++)
1984 decrRefCount(c->mbargv[j]);
ed9b544e 1985 c->argc = 0;
e8a74421 1986 c->mbargc = 0;
ed9b544e 1987}
1988
1989static void freeClient(redisClient *c) {
1990 listNode *ln;
1991
4409877e 1992 /* Note that if the client we are freeing is blocked into a blocking
b0d8747d 1993 * call, we have to set querybuf to NULL *before* to call
1994 * unblockClientWaitingData() to avoid processInputBuffer() will get
1995 * called. Also it is important to remove the file events after
1996 * this, because this call adds the READABLE event. */
4409877e 1997 sdsfree(c->querybuf);
1998 c->querybuf = NULL;
1999 if (c->flags & REDIS_BLOCKED)
b0d8747d 2000 unblockClientWaitingData(c);
4409877e 2001
ffc6b7f8 2002 /* Unsubscribe from all the pubsub channels */
2003 pubsubUnsubscribeAllChannels(c,0);
2004 pubsubUnsubscribeAllPatterns(c,0);
2005 dictRelease(c->pubsub_channels);
2006 listRelease(c->pubsub_patterns);
befec3cd 2007 /* Obvious cleanup */
ed9b544e 2008 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
2009 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
ed9b544e 2010 listRelease(c->reply);
2011 freeClientArgv(c);
2012 close(c->fd);
92f8e882 2013 /* Remove from the list of clients */
ed9b544e 2014 ln = listSearchKey(server.clients,c);
dfc5e96c 2015 redisAssert(ln != NULL);
ed9b544e 2016 listDelNode(server.clients,ln);
d5d55fc3 2017 /* Remove from the list of clients waiting for swapped keys */
2018 if (c->flags & REDIS_IO_WAIT && listLength(c->io_keys) == 0) {
2019 ln = listSearchKey(server.io_ready_clients,c);
2020 if (ln) {
2021 listDelNode(server.io_ready_clients,ln);
2022 server.vm_blocked_clients--;
2023 }
2024 }
2025 while (server.vm_enabled && listLength(c->io_keys)) {
2026 ln = listFirst(c->io_keys);
2027 dontWaitForSwappedKey(c,ln->value);
92f8e882 2028 }
b3e3d0d7 2029 listRelease(c->io_keys);
befec3cd 2030 /* Master/slave cleanup */
ed9b544e 2031 if (c->flags & REDIS_SLAVE) {
6208b3a7 2032 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
2033 close(c->repldbfd);
87eca727 2034 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
2035 ln = listSearchKey(l,c);
dfc5e96c 2036 redisAssert(ln != NULL);
87eca727 2037 listDelNode(l,ln);
ed9b544e 2038 }
2039 if (c->flags & REDIS_MASTER) {
2040 server.master = NULL;
2041 server.replstate = REDIS_REPL_CONNECT;
2042 }
befec3cd 2043 /* Release memory */
93ea3759 2044 zfree(c->argv);
e8a74421 2045 zfree(c->mbargv);
6e469882 2046 freeClientMultiState(c);
ed9b544e 2047 zfree(c);
2048}
2049
cc30e368 2050#define GLUEREPLY_UP_TO (1024)
ed9b544e 2051static void glueReplyBuffersIfNeeded(redisClient *c) {
c28b42ac 2052 int copylen = 0;
2053 char buf[GLUEREPLY_UP_TO];
6208b3a7 2054 listNode *ln;
c7df85a4 2055 listIter li;
ed9b544e 2056 robj *o;
2057
c7df85a4 2058 listRewind(c->reply,&li);
2059 while((ln = listNext(&li))) {
c28b42ac 2060 int objlen;
2061
ed9b544e 2062 o = ln->value;
c28b42ac 2063 objlen = sdslen(o->ptr);
2064 if (copylen + objlen <= GLUEREPLY_UP_TO) {
2065 memcpy(buf+copylen,o->ptr,objlen);
2066 copylen += objlen;
ed9b544e 2067 listDelNode(c->reply,ln);
c28b42ac 2068 } else {
2069 if (copylen == 0) return;
2070 break;
ed9b544e 2071 }
ed9b544e 2072 }
c28b42ac 2073 /* Now the output buffer is empty, add the new single element */
2074 o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
2075 listAddNodeHead(c->reply,o);
ed9b544e 2076}
2077
2078static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2079 redisClient *c = privdata;
2080 int nwritten = 0, totwritten = 0, objlen;
2081 robj *o;
2082 REDIS_NOTUSED(el);
2083 REDIS_NOTUSED(mask);
2084
2895e862 2085 /* Use writev() if we have enough buffers to send */
7ea870c0 2086 if (!server.glueoutputbuf &&
e0a62c7f 2087 listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
7ea870c0 2088 !(c->flags & REDIS_MASTER))
2895e862 2089 {
2090 sendReplyToClientWritev(el, fd, privdata, mask);
2091 return;
2092 }
2895e862 2093
ed9b544e 2094 while(listLength(c->reply)) {
c28b42ac 2095 if (server.glueoutputbuf && listLength(c->reply) > 1)
2096 glueReplyBuffersIfNeeded(c);
2097
ed9b544e 2098 o = listNodeValue(listFirst(c->reply));
2099 objlen = sdslen(o->ptr);
2100
2101 if (objlen == 0) {
2102 listDelNode(c->reply,listFirst(c->reply));
2103 continue;
2104 }
2105
2106 if (c->flags & REDIS_MASTER) {
6f376729 2107 /* Don't reply to a master */
ed9b544e 2108 nwritten = objlen - c->sentlen;
2109 } else {
a4d1ba9a 2110 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
ed9b544e 2111 if (nwritten <= 0) break;
2112 }
2113 c->sentlen += nwritten;
2114 totwritten += nwritten;
2115 /* If we fully sent the object on head go to the next one */
2116 if (c->sentlen == objlen) {
2117 listDelNode(c->reply,listFirst(c->reply));
2118 c->sentlen = 0;
2119 }
6f376729 2120 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
12f9d551 2121 * bytes, in a single threaded server it's a good idea to serve
6f376729 2122 * other clients as well, even if a very large request comes from
2123 * super fast link that is always able to accept data (in real world
12f9d551 2124 * scenario think about 'KEYS *' against the loopback interfae) */
6f376729 2125 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
ed9b544e 2126 }
2127 if (nwritten == -1) {
2128 if (errno == EAGAIN) {
2129 nwritten = 0;
2130 } else {
f870935d 2131 redisLog(REDIS_VERBOSE,
ed9b544e 2132 "Error writing to client: %s", strerror(errno));
2133 freeClient(c);
2134 return;
2135 }
2136 }
2137 if (totwritten > 0) c->lastinteraction = time(NULL);
2138 if (listLength(c->reply) == 0) {
2139 c->sentlen = 0;
2140 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2141 }
2142}
2143
2895e862 2144static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
2145{
2146 redisClient *c = privdata;
2147 int nwritten = 0, totwritten = 0, objlen, willwrite;
2148 robj *o;
2149 struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
2150 int offset, ion = 0;
2151 REDIS_NOTUSED(el);
2152 REDIS_NOTUSED(mask);
2153
2154 listNode *node;
2155 while (listLength(c->reply)) {
2156 offset = c->sentlen;
2157 ion = 0;
2158 willwrite = 0;
2159
2160 /* fill-in the iov[] array */
2161 for(node = listFirst(c->reply); node; node = listNextNode(node)) {
2162 o = listNodeValue(node);
2163 objlen = sdslen(o->ptr);
2164
e0a62c7f 2165 if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
2895e862 2166 break;
2167
2168 if(ion == REDIS_WRITEV_IOVEC_COUNT)
2169 break; /* no more iovecs */
2170
2171 iov[ion].iov_base = ((char*)o->ptr) + offset;
2172 iov[ion].iov_len = objlen - offset;
2173 willwrite += objlen - offset;
2174 offset = 0; /* just for the first item */
2175 ion++;
2176 }
2177
2178 if(willwrite == 0)
2179 break;
2180
2181 /* write all collected blocks at once */
2182 if((nwritten = writev(fd, iov, ion)) < 0) {
2183 if (errno != EAGAIN) {
f870935d 2184 redisLog(REDIS_VERBOSE,
2895e862 2185 "Error writing to client: %s", strerror(errno));
2186 freeClient(c);
2187 return;
2188 }
2189 break;
2190 }
2191
2192 totwritten += nwritten;
2193 offset = c->sentlen;
2194
2195 /* remove written robjs from c->reply */
2196 while (nwritten && listLength(c->reply)) {
2197 o = listNodeValue(listFirst(c->reply));
2198 objlen = sdslen(o->ptr);
2199
2200 if(nwritten >= objlen - offset) {
2201 listDelNode(c->reply, listFirst(c->reply));
2202 nwritten -= objlen - offset;
2203 c->sentlen = 0;
2204 } else {
2205 /* partial write */
2206 c->sentlen += nwritten;
2207 break;
2208 }
2209 offset = 0;
2210 }
2211 }
2212
e0a62c7f 2213 if (totwritten > 0)
2895e862 2214 c->lastinteraction = time(NULL);
2215
2216 if (listLength(c->reply) == 0) {
2217 c->sentlen = 0;
2218 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2219 }
2220}
2221
ed9b544e 2222static struct redisCommand *lookupCommand(char *name) {
2223 int j = 0;
2224 while(cmdTable[j].name != NULL) {
bb0b03a3 2225 if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];
ed9b544e 2226 j++;
2227 }
2228 return NULL;
2229}
2230
2231/* resetClient prepare the client to process the next command */
2232static void resetClient(redisClient *c) {
2233 freeClientArgv(c);
2234 c->bulklen = -1;
e8a74421 2235 c->multibulk = 0;
ed9b544e 2236}
2237
6e469882 2238/* Call() is the core of Redis execution of a command */
2239static void call(redisClient *c, struct redisCommand *cmd) {
2240 long long dirty;
2241
2242 dirty = server.dirty;
2243 cmd->proc(c);
4005fef1 2244 dirty = server.dirty-dirty;
2245
2246 if (server.appendonly && dirty)
6e469882 2247 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
4005fef1 2248 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
2249 listLength(server.slaves))
248ea310 2250 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
6e469882 2251 if (listLength(server.monitors))
dd142b9c 2252 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
6e469882 2253 server.stat_numcommands++;
2254}
2255
ed9b544e 2256/* If this function gets called we already read a whole
2257 * command, argments are in the client argv/argc fields.
2258 * processCommand() execute the command or prepare the
2259 * server for a bulk read from the client.
2260 *
2261 * If 1 is returned the client is still alive and valid and
2262 * and other operations can be performed by the caller. Otherwise
2263 * if 0 is returned the client was destroied (i.e. after QUIT). */
2264static int processCommand(redisClient *c) {
2265 struct redisCommand *cmd;
ed9b544e 2266
3fd78bcd 2267 /* Free some memory if needed (maxmemory setting) */
2268 if (server.maxmemory) freeMemoryIfNeeded();
2269
e8a74421 2270 /* Handle the multi bulk command type. This is an alternative protocol
2271 * supported by Redis in order to receive commands that are composed of
2272 * multiple binary-safe "bulk" arguments. The latency of processing is
2273 * a bit higher but this allows things like multi-sets, so if this
2274 * protocol is used only for MSET and similar commands this is a big win. */
2275 if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
2276 c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
2277 if (c->multibulk <= 0) {
2278 resetClient(c);
2279 return 1;
2280 } else {
2281 decrRefCount(c->argv[c->argc-1]);
2282 c->argc--;
2283 return 1;
2284 }
2285 } else if (c->multibulk) {
2286 if (c->bulklen == -1) {
2287 if (((char*)c->argv[0]->ptr)[0] != '$') {
2288 addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
2289 resetClient(c);
2290 return 1;
2291 } else {
2292 int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
2293 decrRefCount(c->argv[0]);
2294 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2295 c->argc--;
2296 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2297 resetClient(c);
2298 return 1;
2299 }
2300 c->argc--;
2301 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2302 return 1;
2303 }
2304 } else {
2305 c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
2306 c->mbargv[c->mbargc] = c->argv[0];
2307 c->mbargc++;
2308 c->argc--;
2309 c->multibulk--;
2310 if (c->multibulk == 0) {
2311 robj **auxargv;
2312 int auxargc;
2313
2314 /* Here we need to swap the multi-bulk argc/argv with the
2315 * normal argc/argv of the client structure. */
2316 auxargv = c->argv;
2317 c->argv = c->mbargv;
2318 c->mbargv = auxargv;
2319
2320 auxargc = c->argc;
2321 c->argc = c->mbargc;
2322 c->mbargc = auxargc;
2323
2324 /* We need to set bulklen to something different than -1
2325 * in order for the code below to process the command without
2326 * to try to read the last argument of a bulk command as
2327 * a special argument. */
2328 c->bulklen = 0;
2329 /* continue below and process the command */
2330 } else {
2331 c->bulklen = -1;
2332 return 1;
2333 }
2334 }
2335 }
2336 /* -- end of multi bulk commands processing -- */
2337
ed9b544e 2338 /* The QUIT command is handled as a special case. Normal command
2339 * procs are unable to close the client connection safely */
bb0b03a3 2340 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
ed9b544e 2341 freeClient(c);
2342 return 0;
2343 }
d5d55fc3 2344
2345 /* Now lookup the command and check ASAP about trivial error conditions
2346 * such wrong arity, bad command name and so forth. */
ed9b544e 2347 cmd = lookupCommand(c->argv[0]->ptr);
2348 if (!cmd) {
2c14807b 2349 addReplySds(c,
2350 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2351 (char*)c->argv[0]->ptr));
ed9b544e 2352 resetClient(c);
2353 return 1;
2354 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
2355 (c->argc < -cmd->arity)) {
454d4e43 2356 addReplySds(c,
2357 sdscatprintf(sdsempty(),
2358 "-ERR wrong number of arguments for '%s' command\r\n",
2359 cmd->name));
ed9b544e 2360 resetClient(c);
2361 return 1;
2362 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
d5d55fc3 2363 /* This is a bulk command, we have to read the last argument yet. */
ed9b544e 2364 int bulklen = atoi(c->argv[c->argc-1]->ptr);
2365
2366 decrRefCount(c->argv[c->argc-1]);
2367 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2368 c->argc--;
2369 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2370 resetClient(c);
2371 return 1;
2372 }
2373 c->argc--;
2374 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2375 /* It is possible that the bulk read is already in the
8d0490e7 2376 * buffer. Check this condition and handle it accordingly.
2377 * This is just a fast path, alternative to call processInputBuffer().
2378 * It's a good idea since the code is small and this condition
2379 * happens most of the times. */
ed9b544e 2380 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
2381 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2382 c->argc++;
2383 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2384 } else {
d5d55fc3 2385 /* Otherwise return... there is to read the last argument
2386 * from the socket. */
ed9b544e 2387 return 1;
2388 }
2389 }
942a3961 2390 /* Let's try to encode the bulk object to save space. */
2391 if (cmd->flags & REDIS_CMD_BULK)
05df7621 2392 c->argv[c->argc-1] = tryObjectEncoding(c->argv[c->argc-1]);
942a3961 2393
e63943a4 2394 /* Check if the user is authenticated */
2395 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
2396 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
2397 resetClient(c);
2398 return 1;
2399 }
2400
b61a28fe 2401 /* Handle the maxmemory directive */
2402 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
2403 zmalloc_used_memory() > server.maxmemory)
2404 {
2405 addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2406 resetClient(c);
2407 return 1;
2408 }
2409
d6cc8867 2410 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
e6cca5db 2411 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
2412 &&
ffc6b7f8 2413 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
2414 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
2415 addReplySds(c,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
d6cc8867 2416 resetClient(c);
2417 return 1;
2418 }
2419
ed9b544e 2420 /* Exec the command */
18b6cb76 2421 if (c->flags & REDIS_MULTI && cmd->proc != execCommand && cmd->proc != discardCommand) {
6e469882 2422 queueMultiCommand(c,cmd);
2423 addReply(c,shared.queued);
2424 } else {
d5d55fc3 2425 if (server.vm_enabled && server.vm_max_threads > 0 &&
0a6f3f0f 2426 blockClientOnSwappedKeys(c,cmd)) return 1;
6e469882 2427 call(c,cmd);
2428 }
ed9b544e 2429
2430 /* Prepare the client for the next command */
ed9b544e 2431 resetClient(c);
2432 return 1;
2433}
2434
248ea310 2435static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
6208b3a7 2436 listNode *ln;
c7df85a4 2437 listIter li;
ed9b544e 2438 int outc = 0, j;
93ea3759 2439 robj **outv;
248ea310 2440 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2441 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2442 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2443 robj *static_outv[REDIS_STATIC_ARGS*3+1];
2444 robj *lenobj;
93ea3759 2445
2446 if (argc <= REDIS_STATIC_ARGS) {
2447 outv = static_outv;
2448 } else {
248ea310 2449 outv = zmalloc(sizeof(robj*)*(argc*3+1));
93ea3759 2450 }
248ea310 2451
2452 lenobj = createObject(REDIS_STRING,
2453 sdscatprintf(sdsempty(), "*%d\r\n", argc));
2454 lenobj->refcount = 0;
2455 outv[outc++] = lenobj;
ed9b544e 2456 for (j = 0; j < argc; j++) {
248ea310 2457 lenobj = createObject(REDIS_STRING,
2458 sdscatprintf(sdsempty(),"$%lu\r\n",
2459 (unsigned long) stringObjectLen(argv[j])));
2460 lenobj->refcount = 0;
2461 outv[outc++] = lenobj;
ed9b544e 2462 outv[outc++] = argv[j];
248ea310 2463 outv[outc++] = shared.crlf;
ed9b544e 2464 }
ed9b544e 2465
40d224a9 2466 /* Increment all the refcounts at start and decrement at end in order to
2467 * be sure to free objects if there is no slave in a replication state
2468 * able to be feed with commands */
2469 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
c7df85a4 2470 listRewind(slaves,&li);
2471 while((ln = listNext(&li))) {
ed9b544e 2472 redisClient *slave = ln->value;
40d224a9 2473
2474 /* Don't feed slaves that are still waiting for BGSAVE to start */
6208b3a7 2475 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
40d224a9 2476
2477 /* Feed all the other slaves, MONITORs and so on */
ed9b544e 2478 if (slave->slaveseldb != dictid) {
2479 robj *selectcmd;
2480
2481 switch(dictid) {
2482 case 0: selectcmd = shared.select0; break;
2483 case 1: selectcmd = shared.select1; break;
2484 case 2: selectcmd = shared.select2; break;
2485 case 3: selectcmd = shared.select3; break;
2486 case 4: selectcmd = shared.select4; break;
2487 case 5: selectcmd = shared.select5; break;
2488 case 6: selectcmd = shared.select6; break;
2489 case 7: selectcmd = shared.select7; break;
2490 case 8: selectcmd = shared.select8; break;
2491 case 9: selectcmd = shared.select9; break;
2492 default:
2493 selectcmd = createObject(REDIS_STRING,
2494 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
2495 selectcmd->refcount = 0;
2496 break;
2497 }
2498 addReply(slave,selectcmd);
2499 slave->slaveseldb = dictid;
2500 }
2501 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
ed9b544e 2502 }
40d224a9 2503 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
93ea3759 2504 if (outv != static_outv) zfree(outv);
ed9b544e 2505}
2506
dd142b9c 2507static sds sdscatrepr(sds s, char *p, size_t len) {
2508 s = sdscatlen(s,"\"",1);
2509 while(len--) {
2510 switch(*p) {
2511 case '\\':
2512 case '"':
2513 s = sdscatprintf(s,"\\%c",*p);
2514 break;
2515 case '\n': s = sdscatlen(s,"\\n",1); break;
2516 case '\r': s = sdscatlen(s,"\\r",1); break;
2517 case '\t': s = sdscatlen(s,"\\t",1); break;
2518 case '\a': s = sdscatlen(s,"\\a",1); break;
2519 case '\b': s = sdscatlen(s,"\\b",1); break;
2520 default:
2521 if (isprint(*p))
2522 s = sdscatprintf(s,"%c",*p);
2523 else
2524 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
2525 break;
2526 }
2527 p++;
2528 }
2529 return sdscatlen(s,"\"",1);
2530}
2531
2532static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc) {
2533 listNode *ln;
2534 listIter li;
2535 int j;
2536 sds cmdrepr = sdsnew("+");
2537 robj *cmdobj;
2538 struct timeval tv;
2539
2540 gettimeofday(&tv,NULL);
2541 cmdrepr = sdscatprintf(cmdrepr,"%ld.%ld ",(long)tv.tv_sec,(long)tv.tv_usec);
2542 if (dictid != 0) cmdrepr = sdscatprintf(cmdrepr,"(db %d) ", dictid);
2543
2544 for (j = 0; j < argc; j++) {
2545 if (argv[j]->encoding == REDIS_ENCODING_INT) {
2546 cmdrepr = sdscatprintf(cmdrepr, "%ld", (long)argv[j]->ptr);
2547 } else {
2548 cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
2549 sdslen(argv[j]->ptr));
2550 }
2551 if (j != argc-1)
2552 cmdrepr = sdscatlen(cmdrepr," ",1);
2553 }
2554 cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
2555 cmdobj = createObject(REDIS_STRING,cmdrepr);
2556
2557 listRewind(monitors,&li);
2558 while((ln = listNext(&li))) {
2559 redisClient *monitor = ln->value;
2560 addReply(monitor,cmdobj);
2561 }
2562 decrRefCount(cmdobj);
2563}
2564
638e42ac 2565static void processInputBuffer(redisClient *c) {
ed9b544e 2566again:
4409877e 2567 /* Before to process the input buffer, make sure the client is not
2568 * waitig for a blocking operation such as BLPOP. Note that the first
2569 * iteration the client is never blocked, otherwise the processInputBuffer
2570 * would not be called at all, but after the execution of the first commands
2571 * in the input buffer the client may be blocked, and the "goto again"
2572 * will try to reiterate. The following line will make it return asap. */
92f8e882 2573 if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
ed9b544e 2574 if (c->bulklen == -1) {
2575 /* Read the first line of the query */
2576 char *p = strchr(c->querybuf,'\n');
2577 size_t querylen;
644fafa3 2578
ed9b544e 2579 if (p) {
2580 sds query, *argv;
2581 int argc, j;
e0a62c7f 2582
ed9b544e 2583 query = c->querybuf;
2584 c->querybuf = sdsempty();
2585 querylen = 1+(p-(query));
2586 if (sdslen(query) > querylen) {
2587 /* leave data after the first line of the query in the buffer */
2588 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
2589 }
2590 *p = '\0'; /* remove "\n" */
2591 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
2592 sdsupdatelen(query);
2593
2594 /* Now we can split the query in arguments */
ed9b544e 2595 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
93ea3759 2596 sdsfree(query);
2597
2598 if (c->argv) zfree(c->argv);
2599 c->argv = zmalloc(sizeof(robj*)*argc);
93ea3759 2600
2601 for (j = 0; j < argc; j++) {
ed9b544e 2602 if (sdslen(argv[j])) {
2603 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
2604 c->argc++;
2605 } else {
2606 sdsfree(argv[j]);
2607 }
2608 }
2609 zfree(argv);
7c49733c 2610 if (c->argc) {
2611 /* Execute the command. If the client is still valid
2612 * after processCommand() return and there is something
2613 * on the query buffer try to process the next command. */
2614 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2615 } else {
2616 /* Nothing to process, argc == 0. Just process the query
2617 * buffer if it's not empty or return to the caller */
2618 if (sdslen(c->querybuf)) goto again;
2619 }
ed9b544e 2620 return;
644fafa3 2621 } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
f870935d 2622 redisLog(REDIS_VERBOSE, "Client protocol error");
ed9b544e 2623 freeClient(c);
2624 return;
2625 }
2626 } else {
2627 /* Bulk read handling. Note that if we are at this point
2628 the client already sent a command terminated with a newline,
2629 we are reading the bulk data that is actually the last
2630 argument of the command. */
2631 int qbl = sdslen(c->querybuf);
2632
2633 if (c->bulklen <= qbl) {
2634 /* Copy everything but the final CRLF as final argument */
2635 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2636 c->argc++;
2637 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
638e42ac 2638 /* Process the command. If the client is still valid after
2639 * the processing and there is more data in the buffer
2640 * try to parse it. */
2641 if (processCommand(c) && sdslen(c->querybuf)) goto again;
ed9b544e 2642 return;
2643 }
2644 }
2645}
2646
638e42ac 2647static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2648 redisClient *c = (redisClient*) privdata;
2649 char buf[REDIS_IOBUF_LEN];
2650 int nread;
2651 REDIS_NOTUSED(el);
2652 REDIS_NOTUSED(mask);
2653
2654 nread = read(fd, buf, REDIS_IOBUF_LEN);
2655 if (nread == -1) {
2656 if (errno == EAGAIN) {
2657 nread = 0;
2658 } else {
f870935d 2659 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
638e42ac 2660 freeClient(c);
2661 return;
2662 }
2663 } else if (nread == 0) {
f870935d 2664 redisLog(REDIS_VERBOSE, "Client closed connection");
638e42ac 2665 freeClient(c);
2666 return;
2667 }
2668 if (nread) {
2669 c->querybuf = sdscatlen(c->querybuf, buf, nread);
2670 c->lastinteraction = time(NULL);
2671 } else {
2672 return;
2673 }
168ac5c6 2674 processInputBuffer(c);
638e42ac 2675}
2676
ed9b544e 2677static int selectDb(redisClient *c, int id) {
2678 if (id < 0 || id >= server.dbnum)
2679 return REDIS_ERR;
3305306f 2680 c->db = &server.db[id];
ed9b544e 2681 return REDIS_OK;
2682}
2683
40d224a9 2684static void *dupClientReplyValue(void *o) {
2685 incrRefCount((robj*)o);
12d090d2 2686 return o;
40d224a9 2687}
2688
ffc6b7f8 2689static int listMatchObjects(void *a, void *b) {
bf028098 2690 return equalStringObjects(a,b);
ffc6b7f8 2691}
2692
ed9b544e 2693static redisClient *createClient(int fd) {
2694 redisClient *c = zmalloc(sizeof(*c));
2695
2696 anetNonBlock(NULL,fd);
2697 anetTcpNoDelay(NULL,fd);
2698 if (!c) return NULL;
2699 selectDb(c,0);
2700 c->fd = fd;
2701 c->querybuf = sdsempty();
2702 c->argc = 0;
93ea3759 2703 c->argv = NULL;
ed9b544e 2704 c->bulklen = -1;
e8a74421 2705 c->multibulk = 0;
2706 c->mbargc = 0;
2707 c->mbargv = NULL;
ed9b544e 2708 c->sentlen = 0;
2709 c->flags = 0;
2710 c->lastinteraction = time(NULL);
abcb223e 2711 c->authenticated = 0;
40d224a9 2712 c->replstate = REDIS_REPL_NONE;
6b47e12e 2713 c->reply = listCreate();
ed9b544e 2714 listSetFreeMethod(c->reply,decrRefCount);
40d224a9 2715 listSetDupMethod(c->reply,dupClientReplyValue);
92f8e882 2716 c->blockingkeys = NULL;
2717 c->blockingkeysnum = 0;
2718 c->io_keys = listCreate();
2719 listSetFreeMethod(c->io_keys,decrRefCount);
ffc6b7f8 2720 c->pubsub_channels = dictCreate(&setDictType,NULL);
2721 c->pubsub_patterns = listCreate();
2722 listSetFreeMethod(c->pubsub_patterns,decrRefCount);
2723 listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
ed9b544e 2724 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
266373b2 2725 readQueryFromClient, c) == AE_ERR) {
ed9b544e 2726 freeClient(c);
2727 return NULL;
2728 }
6b47e12e 2729 listAddNodeTail(server.clients,c);
6e469882 2730 initClientMultiState(c);
ed9b544e 2731 return c;
2732}
2733
2734static void addReply(redisClient *c, robj *obj) {
2735 if (listLength(c->reply) == 0 &&
6208b3a7 2736 (c->replstate == REDIS_REPL_NONE ||
2737 c->replstate == REDIS_REPL_ONLINE) &&
ed9b544e 2738 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
266373b2 2739 sendReplyToClient, c) == AE_ERR) return;
e3cadb8a 2740
2741 if (server.vm_enabled && obj->storage != REDIS_VM_MEMORY) {
2742 obj = dupStringObject(obj);
2743 obj->refcount = 0; /* getDecodedObject() will increment the refcount */
2744 }
9d65a1bb 2745 listAddNodeTail(c->reply,getDecodedObject(obj));
ed9b544e 2746}
2747
2748static void addReplySds(redisClient *c, sds s) {
2749 robj *o = createObject(REDIS_STRING,s);
2750 addReply(c,o);
2751 decrRefCount(o);
2752}
2753
e2665397 2754static void addReplyDouble(redisClient *c, double d) {
2755 char buf[128];
2756
2757 snprintf(buf,sizeof(buf),"%.17g",d);
682ac724 2758 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
83c6a618 2759 (unsigned long) strlen(buf),buf));
e2665397 2760}
2761
f44dd428 2762static void addReplyLong(redisClient *c, long l) {
2763 char buf[128];
2764 size_t len;
2765
dd88747b 2766 if (l == 0) {
2767 addReply(c,shared.czero);
2768 return;
2769 } else if (l == 1) {
2770 addReply(c,shared.cone);
2771 return;
2772 }
f44dd428 2773 len = snprintf(buf,sizeof(buf),":%ld\r\n",l);
2774 addReplySds(c,sdsnewlen(buf,len));
2775}
2776
aa7c2934
PN
2777static void addReplyLongLong(redisClient *c, long long ll) {
2778 char buf[128];
2779 size_t len;
2780
2781 if (ll == 0) {
2782 addReply(c,shared.czero);
2783 return;
2784 } else if (ll == 1) {
2785 addReply(c,shared.cone);
2786 return;
2787 }
2788 len = snprintf(buf,sizeof(buf),":%lld\r\n",ll);
2789 addReplySds(c,sdsnewlen(buf,len));
2790}
2791
92b27fe9 2792static void addReplyUlong(redisClient *c, unsigned long ul) {
2793 char buf[128];
2794 size_t len;
2795
dd88747b 2796 if (ul == 0) {
2797 addReply(c,shared.czero);
2798 return;
2799 } else if (ul == 1) {
2800 addReply(c,shared.cone);
2801 return;
2802 }
92b27fe9 2803 len = snprintf(buf,sizeof(buf),":%lu\r\n",ul);
2804 addReplySds(c,sdsnewlen(buf,len));
2805}
2806
942a3961 2807static void addReplyBulkLen(redisClient *c, robj *obj) {
2808 size_t len;
2809
2810 if (obj->encoding == REDIS_ENCODING_RAW) {
2811 len = sdslen(obj->ptr);
2812 } else {
2813 long n = (long)obj->ptr;
2814
e054afda 2815 /* Compute how many bytes will take this integer as a radix 10 string */
942a3961 2816 len = 1;
2817 if (n < 0) {
2818 len++;
2819 n = -n;
2820 }
2821 while((n = n/10) != 0) {
2822 len++;
2823 }
2824 }
83c6a618 2825 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len));
942a3961 2826}
2827
dd88747b 2828static void addReplyBulk(redisClient *c, robj *obj) {
2829 addReplyBulkLen(c,obj);
2830 addReply(c,obj);
2831 addReply(c,shared.crlf);
2832}
2833
500ece7c 2834/* In the CONFIG command we need to add vanilla C string as bulk replies */
2835static void addReplyBulkCString(redisClient *c, char *s) {
2836 if (s == NULL) {
2837 addReply(c,shared.nullbulk);
2838 } else {
2839 robj *o = createStringObject(s,strlen(s));
2840 addReplyBulk(c,o);
2841 decrRefCount(o);
2842 }
2843}
2844
ed9b544e 2845static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2846 int cport, cfd;
2847 char cip[128];
285add55 2848 redisClient *c;
ed9b544e 2849 REDIS_NOTUSED(el);
2850 REDIS_NOTUSED(mask);
2851 REDIS_NOTUSED(privdata);
2852
2853 cfd = anetAccept(server.neterr, fd, cip, &cport);
2854 if (cfd == AE_ERR) {
f870935d 2855 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
ed9b544e 2856 return;
2857 }
f870935d 2858 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
285add55 2859 if ((c = createClient(cfd)) == NULL) {
ed9b544e 2860 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2861 close(cfd); /* May be already closed, just ingore errors */
2862 return;
2863 }
285add55 2864 /* If maxclient directive is set and this is one client more... close the
2865 * connection. Note that we create the client instead to check before
2866 * for this condition, since now the socket is already set in nonblocking
2867 * mode and we can send an error for free using the Kernel I/O */
2868 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2869 char *err = "-ERR max number of clients reached\r\n";
2870
2871 /* That's a best effort error message, don't check write errors */
fee803ba 2872 if (write(c->fd,err,strlen(err)) == -1) {
2873 /* Nothing to do, Just to avoid the warning... */
2874 }
285add55 2875 freeClient(c);
2876 return;
2877 }
ed9b544e 2878 server.stat_numconnections++;
2879}
2880
2881/* ======================= Redis objects implementation ===================== */
2882
2883static robj *createObject(int type, void *ptr) {
2884 robj *o;
2885
a5819310 2886 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
ed9b544e 2887 if (listLength(server.objfreelist)) {
2888 listNode *head = listFirst(server.objfreelist);
2889 o = listNodeValue(head);
2890 listDelNode(server.objfreelist,head);
a5819310 2891 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
ed9b544e 2892 } else {
75680a3c 2893 if (server.vm_enabled) {
a5819310 2894 pthread_mutex_unlock(&server.obj_freelist_mutex);
75680a3c 2895 o = zmalloc(sizeof(*o));
2896 } else {
2897 o = zmalloc(sizeof(*o)-sizeof(struct redisObjectVM));
2898 }
ed9b544e 2899 }
ed9b544e 2900 o->type = type;
942a3961 2901 o->encoding = REDIS_ENCODING_RAW;
ed9b544e 2902 o->ptr = ptr;
2903 o->refcount = 1;
3a66edc7 2904 if (server.vm_enabled) {
1064ef87 2905 /* Note that this code may run in the context of an I/O thread
2906 * and accessing to server.unixtime in theory is an error
2907 * (no locks). But in practice this is safe, and even if we read
2908 * garbage Redis will not fail, as it's just a statistical info */
3a66edc7 2909 o->vm.atime = server.unixtime;
2910 o->storage = REDIS_VM_MEMORY;
2911 }
ed9b544e 2912 return o;
2913}
2914
2915static robj *createStringObject(char *ptr, size_t len) {
2916 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
2917}
2918
3f973463
PN
2919static robj *createStringObjectFromLongLong(long long value) {
2920 robj *o;
2921 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
2922 incrRefCount(shared.integers[value]);
2923 o = shared.integers[value];
2924 } else {
2925 o = createObject(REDIS_STRING, NULL);
2926 if (value >= LONG_MIN && value <= LONG_MAX) {
2927 o->encoding = REDIS_ENCODING_INT;
2928 o->ptr = (void*)((long)value);
2929 } else {
ee14da56 2930 o = createObject(REDIS_STRING,sdsfromlonglong(value));
3f973463
PN
2931 }
2932 }
2933 return o;
2934}
2935
4ef8de8a 2936static robj *dupStringObject(robj *o) {
b9bc0eef 2937 assert(o->encoding == REDIS_ENCODING_RAW);
4ef8de8a 2938 return createStringObject(o->ptr,sdslen(o->ptr));
2939}
2940
ed9b544e 2941static robj *createListObject(void) {
2942 list *l = listCreate();
2943
ed9b544e 2944 listSetFreeMethod(l,decrRefCount);
2945 return createObject(REDIS_LIST,l);
2946}
2947
2948static robj *createSetObject(void) {
2949 dict *d = dictCreate(&setDictType,NULL);
ed9b544e 2950 return createObject(REDIS_SET,d);
2951}
2952
5234952b 2953static robj *createHashObject(void) {
2954 /* All the Hashes start as zipmaps. Will be automatically converted
2955 * into hash tables if there are enough elements or big elements
2956 * inside. */
2957 unsigned char *zm = zipmapNew();
2958 robj *o = createObject(REDIS_HASH,zm);
2959 o->encoding = REDIS_ENCODING_ZIPMAP;
2960 return o;
2961}
2962
1812e024 2963static robj *createZsetObject(void) {
6b47e12e 2964 zset *zs = zmalloc(sizeof(*zs));
2965
2966 zs->dict = dictCreate(&zsetDictType,NULL);
2967 zs->zsl = zslCreate();
2968 return createObject(REDIS_ZSET,zs);
1812e024 2969}
2970
ed9b544e 2971static void freeStringObject(robj *o) {
942a3961 2972 if (o->encoding == REDIS_ENCODING_RAW) {
2973 sdsfree(o->ptr);
2974 }
ed9b544e 2975}
2976
2977static void freeListObject(robj *o) {
2978 listRelease((list*) o->ptr);
2979}
2980
2981static void freeSetObject(robj *o) {
2982 dictRelease((dict*) o->ptr);
2983}
2984
fd8ccf44 2985static void freeZsetObject(robj *o) {
2986 zset *zs = o->ptr;
2987
2988 dictRelease(zs->dict);
2989 zslFree(zs->zsl);
2990 zfree(zs);
2991}
2992
ed9b544e 2993static void freeHashObject(robj *o) {
cbba7dd7 2994 switch (o->encoding) {
2995 case REDIS_ENCODING_HT:
2996 dictRelease((dict*) o->ptr);
2997 break;
2998 case REDIS_ENCODING_ZIPMAP:
2999 zfree(o->ptr);
3000 break;
3001 default:
f83c6cb5 3002 redisPanic("Unknown hash encoding type");
cbba7dd7 3003 break;
3004 }
ed9b544e 3005}
3006
3007static void incrRefCount(robj *o) {
3008 o->refcount++;
3009}
3010
3011static void decrRefCount(void *obj) {
3012 robj *o = obj;
94754ccc 3013
c651fd9e 3014 if (o->refcount <= 0) redisPanic("decrRefCount against refcount <= 0");
970e10bb 3015 /* Object is a key of a swapped out value, or in the process of being
3016 * loaded. */
996cb5f7 3017 if (server.vm_enabled &&
3018 (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
3019 {
996cb5f7 3020 if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(obj);
f2b8ab34 3021 redisAssert(o->type == REDIS_STRING);
a35ddf12 3022 freeStringObject(o);
3023 vmMarkPagesFree(o->vm.page,o->vm.usedpages);
a5819310 3024 pthread_mutex_lock(&server.obj_freelist_mutex);
a35ddf12 3025 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3026 !listAddNodeHead(server.objfreelist,o))
3027 zfree(o);
a5819310 3028 pthread_mutex_unlock(&server.obj_freelist_mutex);
7d98e08c 3029 server.vm_stats_swapped_objects--;
a35ddf12 3030 return;
3031 }
996cb5f7 3032 /* Object is in memory, or in the process of being swapped out. */
ed9b544e 3033 if (--(o->refcount) == 0) {
996cb5f7 3034 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
3035 vmCancelThreadedIOJob(obj);
ed9b544e 3036 switch(o->type) {
3037 case REDIS_STRING: freeStringObject(o); break;
3038 case REDIS_LIST: freeListObject(o); break;
3039 case REDIS_SET: freeSetObject(o); break;
fd8ccf44 3040 case REDIS_ZSET: freeZsetObject(o); break;
ed9b544e 3041 case REDIS_HASH: freeHashObject(o); break;
f83c6cb5 3042 default: redisPanic("Unknown object type"); break;
ed9b544e 3043 }
a5819310 3044 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
ed9b544e 3045 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3046 !listAddNodeHead(server.objfreelist,o))
3047 zfree(o);
a5819310 3048 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
ed9b544e 3049 }
3050}
3051
942a3961 3052static robj *lookupKey(redisDb *db, robj *key) {
3053 dictEntry *de = dictFind(db->dict,key);
3a66edc7 3054 if (de) {
55cf8433 3055 robj *key = dictGetEntryKey(de);
3056 robj *val = dictGetEntryVal(de);
3a66edc7 3057
55cf8433 3058 if (server.vm_enabled) {
996cb5f7 3059 if (key->storage == REDIS_VM_MEMORY ||
3060 key->storage == REDIS_VM_SWAPPING)
3061 {
3062 /* If we were swapping the object out, stop it, this key
3063 * was requested. */
3064 if (key->storage == REDIS_VM_SWAPPING)
3065 vmCancelThreadedIOJob(key);
55cf8433 3066 /* Update the access time of the key for the aging algorithm. */
3067 key->vm.atime = server.unixtime;
3068 } else {
d5d55fc3 3069 int notify = (key->storage == REDIS_VM_LOADING);
3070
55cf8433 3071 /* Our value was swapped on disk. Bring it at home. */
f2b8ab34 3072 redisAssert(val == NULL);
55cf8433 3073 val = vmLoadObject(key);
3074 dictGetEntryVal(de) = val;
d5d55fc3 3075
3076 /* Clients blocked by the VM subsystem may be waiting for
3077 * this key... */
3078 if (notify) handleClientsBlockedOnSwappedKey(db,key);
55cf8433 3079 }
3080 }
3081 return val;
3a66edc7 3082 } else {
3083 return NULL;
3084 }
942a3961 3085}
3086
3087static robj *lookupKeyRead(redisDb *db, robj *key) {
3088 expireIfNeeded(db,key);
3089 return lookupKey(db,key);
3090}
3091
3092static robj *lookupKeyWrite(redisDb *db, robj *key) {
3093 deleteIfVolatile(db,key);
3094 return lookupKey(db,key);
3095}
3096
92b27fe9 3097static robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
3098 robj *o = lookupKeyRead(c->db, key);
3099 if (!o) addReply(c,reply);
3100 return o;
3101}
3102
3103static robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
3104 robj *o = lookupKeyWrite(c->db, key);
3105 if (!o) addReply(c,reply);
3106 return o;
3107}
3108
3109static int checkType(redisClient *c, robj *o, int type) {
3110 if (o->type != type) {
3111 addReply(c,shared.wrongtypeerr);
3112 return 1;
3113 }
3114 return 0;
3115}
3116
942a3961 3117static int deleteKey(redisDb *db, robj *key) {
3118 int retval;
3119
3120 /* We need to protect key from destruction: after the first dictDelete()
3121 * it may happen that 'key' is no longer valid if we don't increment
3122 * it's count. This may happen when we get the object reference directly
3123 * from the hash table with dictRandomKey() or dict iterators */
3124 incrRefCount(key);
3125 if (dictSize(db->expires)) dictDelete(db->expires,key);
3126 retval = dictDelete(db->dict,key);
3127 decrRefCount(key);
3128
3129 return retval == DICT_OK;
3130}
3131
724a51b1 3132/* Check if the nul-terminated string 's' can be represented by a long
3133 * (that is, is a number that fits into long without any other space or
3134 * character before or after the digits).
3135 *
3136 * If so, the function returns REDIS_OK and *longval is set to the value
3137 * of the number. Otherwise REDIS_ERR is returned */
f69f2cba 3138static int isStringRepresentableAsLong(sds s, long *longval) {
724a51b1 3139 char buf[32], *endptr;
3140 long value;
3141 int slen;
e0a62c7f 3142
724a51b1 3143 value = strtol(s, &endptr, 10);
3144 if (endptr[0] != '\0') return REDIS_ERR;
ee14da56 3145 slen = ll2string(buf,32,value);
724a51b1 3146
3147 /* If the number converted back into a string is not identical
3148 * then it's not possible to encode the string as integer */
f69f2cba 3149 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
724a51b1 3150 if (longval) *longval = value;
3151 return REDIS_OK;
3152}
3153
942a3961 3154/* Try to encode a string object in order to save space */
05df7621 3155static robj *tryObjectEncoding(robj *o) {
942a3961 3156 long value;
942a3961 3157 sds s = o->ptr;
3305306f 3158
942a3961 3159 if (o->encoding != REDIS_ENCODING_RAW)
05df7621 3160 return o; /* Already encoded */
3305306f 3161
05df7621 3162 /* It's not safe to encode shared objects: shared objects can be shared
942a3961 3163 * everywhere in the "object space" of Redis. Encoded objects can only
3164 * appear as "values" (and not, for instance, as keys) */
05df7621 3165 if (o->refcount > 1) return o;
3305306f 3166
942a3961 3167 /* Currently we try to encode only strings */
dfc5e96c 3168 redisAssert(o->type == REDIS_STRING);
94754ccc 3169
724a51b1 3170 /* Check if we can represent this string as a long integer */
05df7621 3171 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return o;
942a3961 3172
3173 /* Ok, this object can be encoded */
05df7621 3174 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3175 decrRefCount(o);
3176 incrRefCount(shared.integers[value]);
3177 return shared.integers[value];
3178 } else {
3179 o->encoding = REDIS_ENCODING_INT;
3180 sdsfree(o->ptr);
3181 o->ptr = (void*) value;
3182 return o;
3183 }
942a3961 3184}
3185
9d65a1bb 3186/* Get a decoded version of an encoded object (returned as a new object).
3187 * If the object is already raw-encoded just increment the ref count. */
3188static robj *getDecodedObject(robj *o) {
942a3961 3189 robj *dec;
e0a62c7f 3190
9d65a1bb 3191 if (o->encoding == REDIS_ENCODING_RAW) {
3192 incrRefCount(o);
3193 return o;
3194 }
942a3961 3195 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
3196 char buf[32];
3197
ee14da56 3198 ll2string(buf,32,(long)o->ptr);
942a3961 3199 dec = createStringObject(buf,strlen(buf));
3200 return dec;
3201 } else {
08ee9b57 3202 redisPanic("Unknown encoding type");
942a3961 3203 }
3305306f 3204}
3205
d7f43c08 3206/* Compare two string objects via strcmp() or alike.
3207 * Note that the objects may be integer-encoded. In such a case we
ee14da56 3208 * use ll2string() to get a string representation of the numbers on the stack
1fd9bc8a 3209 * and compare the strings, it's much faster than calling getDecodedObject().
3210 *
3211 * Important note: if objects are not integer encoded, but binary-safe strings,
3212 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3213 * binary safe. */
724a51b1 3214static int compareStringObjects(robj *a, robj *b) {
dfc5e96c 3215 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
d7f43c08 3216 char bufa[128], bufb[128], *astr, *bstr;
3217 int bothsds = 1;
724a51b1 3218
e197b441 3219 if (a == b) return 0;
d7f43c08 3220 if (a->encoding != REDIS_ENCODING_RAW) {
ee14da56 3221 ll2string(bufa,sizeof(bufa),(long) a->ptr);
d7f43c08 3222 astr = bufa;
3223 bothsds = 0;
724a51b1 3224 } else {
d7f43c08 3225 astr = a->ptr;
724a51b1 3226 }
d7f43c08 3227 if (b->encoding != REDIS_ENCODING_RAW) {
ee14da56 3228 ll2string(bufb,sizeof(bufb),(long) b->ptr);
d7f43c08 3229 bstr = bufb;
3230 bothsds = 0;
3231 } else {
3232 bstr = b->ptr;
3233 }
3234 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
724a51b1 3235}
3236
bf028098 3237/* Equal string objects return 1 if the two objects are the same from the
3238 * point of view of a string comparison, otherwise 0 is returned. Note that
3239 * this function is faster then checking for (compareStringObject(a,b) == 0)
3240 * because it can perform some more optimization. */
3241static int equalStringObjects(robj *a, robj *b) {
3242 if (a->encoding != REDIS_ENCODING_RAW && b->encoding != REDIS_ENCODING_RAW){
3243 return a->ptr == b->ptr;
3244 } else {
3245 return compareStringObjects(a,b) == 0;
3246 }
3247}
3248
0ea663ea 3249static size_t stringObjectLen(robj *o) {
dfc5e96c 3250 redisAssert(o->type == REDIS_STRING);
0ea663ea 3251 if (o->encoding == REDIS_ENCODING_RAW) {
3252 return sdslen(o->ptr);
3253 } else {
3254 char buf[32];
3255
ee14da56 3256 return ll2string(buf,32,(long)o->ptr);
0ea663ea 3257 }
3258}
3259
bd79a6bd
PN
3260static int getDoubleFromObject(robj *o, double *target) {
3261 double value;
682c73e8 3262 char *eptr;
bbe025e0 3263
bd79a6bd
PN
3264 if (o == NULL) {
3265 value = 0;
3266 } else {
3267 redisAssert(o->type == REDIS_STRING);
3268 if (o->encoding == REDIS_ENCODING_RAW) {
3269 value = strtod(o->ptr, &eptr);
682c73e8 3270 if (eptr[0] != '\0') return REDIS_ERR;
bd79a6bd
PN
3271 } else if (o->encoding == REDIS_ENCODING_INT) {
3272 value = (long)o->ptr;
3273 } else {
946342c1 3274 redisPanic("Unknown string encoding");
bd79a6bd
PN
3275 }
3276 }
3277
bd79a6bd
PN
3278 *target = value;
3279 return REDIS_OK;
3280}
bbe025e0 3281
bd79a6bd
PN
3282static int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg) {
3283 double value;
3284 if (getDoubleFromObject(o, &value) != REDIS_OK) {
3285 if (msg != NULL) {
3286 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3287 } else {
3288 addReplySds(c, sdsnew("-ERR value is not a double\r\n"));
3289 }
bbe025e0
AM
3290 return REDIS_ERR;
3291 }
3292
bd79a6bd 3293 *target = value;
bbe025e0
AM
3294 return REDIS_OK;
3295}
3296
bd79a6bd
PN
3297static int getLongLongFromObject(robj *o, long long *target) {
3298 long long value;
682c73e8 3299 char *eptr;
bbe025e0 3300
bd79a6bd
PN
3301 if (o == NULL) {
3302 value = 0;
3303 } else {
3304 redisAssert(o->type == REDIS_STRING);
3305 if (o->encoding == REDIS_ENCODING_RAW) {
3306 value = strtoll(o->ptr, &eptr, 10);
682c73e8 3307 if (eptr[0] != '\0') return REDIS_ERR;
bd79a6bd
PN
3308 } else if (o->encoding == REDIS_ENCODING_INT) {
3309 value = (long)o->ptr;
3310 } else {
946342c1 3311 redisPanic("Unknown string encoding");
bd79a6bd
PN
3312 }
3313 }
3314
bd79a6bd
PN
3315 *target = value;
3316 return REDIS_OK;
3317}
bbe025e0 3318
bd79a6bd
PN
3319static int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg) {
3320 long long value;
3321 if (getLongLongFromObject(o, &value) != REDIS_OK) {
3322 if (msg != NULL) {
3323 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3324 } else {
3325 addReplySds(c, sdsnew("-ERR value is not an integer\r\n"));
3326 }
bbe025e0
AM
3327 return REDIS_ERR;
3328 }
3329
bd79a6bd 3330 *target = value;
bbe025e0
AM
3331 return REDIS_OK;
3332}
3333
bd79a6bd
PN
3334static int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg) {
3335 long long value;
bbe025e0 3336
bd79a6bd
PN
3337 if (getLongLongFromObjectOrReply(c, o, &value, msg) != REDIS_OK) return REDIS_ERR;
3338 if (value < LONG_MIN || value > LONG_MAX) {
3339 if (msg != NULL) {
3340 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3341 } else {
3342 addReplySds(c, sdsnew("-ERR value is out of range\r\n"));
3343 }
bbe025e0
AM
3344 return REDIS_ERR;
3345 }
3346
bd79a6bd 3347 *target = value;
bbe025e0
AM
3348 return REDIS_OK;
3349}
3350
06233c45 3351/*============================ RDB saving/loading =========================== */
ed9b544e 3352
f78fd11b 3353static int rdbSaveType(FILE *fp, unsigned char type) {
3354 if (fwrite(&type,1,1,fp) == 0) return -1;
3355 return 0;
3356}
3357
bb32ede5 3358static int rdbSaveTime(FILE *fp, time_t t) {
3359 int32_t t32 = (int32_t) t;
3360 if (fwrite(&t32,4,1,fp) == 0) return -1;
3361 return 0;
3362}
3363
e3566d4b 3364/* check rdbLoadLen() comments for more info */
f78fd11b 3365static int rdbSaveLen(FILE *fp, uint32_t len) {
3366 unsigned char buf[2];
3367
3368 if (len < (1<<6)) {
3369 /* Save a 6 bit len */
10c43610 3370 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
f78fd11b 3371 if (fwrite(buf,1,1,fp) == 0) return -1;
3372 } else if (len < (1<<14)) {
3373 /* Save a 14 bit len */
10c43610 3374 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
f78fd11b 3375 buf[1] = len&0xFF;
17be1a4a 3376 if (fwrite(buf,2,1,fp) == 0) return -1;
f78fd11b 3377 } else {
3378 /* Save a 32 bit len */
10c43610 3379 buf[0] = (REDIS_RDB_32BITLEN<<6);
f78fd11b 3380 if (fwrite(buf,1,1,fp) == 0) return -1;
3381 len = htonl(len);
3382 if (fwrite(&len,4,1,fp) == 0) return -1;
3383 }
3384 return 0;
3385}
3386
32a66513 3387/* Encode 'value' as an integer if possible (if integer will fit the
3388 * supported range). If the function sucessful encoded the integer
3389 * then the (up to 5 bytes) encoded representation is written in the
3390 * string pointed by 'enc' and the length is returned. Otherwise
3391 * 0 is returned. */
3392static int rdbEncodeInteger(long long value, unsigned char *enc) {
e3566d4b 3393 /* Finally check if it fits in our ranges */
3394 if (value >= -(1<<7) && value <= (1<<7)-1) {
3395 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
3396 enc[1] = value&0xFF;
3397 return 2;
3398 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
3399 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
3400 enc[1] = value&0xFF;
3401 enc[2] = (value>>8)&0xFF;
3402 return 3;
3403 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
3404 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
3405 enc[1] = value&0xFF;
3406 enc[2] = (value>>8)&0xFF;
3407 enc[3] = (value>>16)&0xFF;
3408 enc[4] = (value>>24)&0xFF;
3409 return 5;
3410 } else {
3411 return 0;
3412 }
3413}
3414
32a66513 3415/* String objects in the form "2391" "-100" without any space and with a
3416 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3417 * encoded as integers to save space */
3418static int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
3419 long long value;
3420 char *endptr, buf[32];
3421
3422 /* Check if it's possible to encode this value as a number */
3423 value = strtoll(s, &endptr, 10);
3424 if (endptr[0] != '\0') return 0;
3425 ll2string(buf,32,value);
3426
3427 /* If the number converted back into a string is not identical
3428 * then it's not possible to encode the string as integer */
3429 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
3430
3431 return rdbEncodeInteger(value,enc);
3432}
3433
b1befe6a 3434static int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
3435 size_t comprlen, outlen;
774e3047 3436 unsigned char byte;
3437 void *out;
3438
3439 /* We require at least four bytes compression for this to be worth it */
b1befe6a 3440 if (len <= 4) return 0;
3441 outlen = len-4;
3a2694c4 3442 if ((out = zmalloc(outlen+1)) == NULL) return 0;
b1befe6a 3443 comprlen = lzf_compress(s, len, out, outlen);
774e3047 3444 if (comprlen == 0) {
88e85998 3445 zfree(out);
774e3047 3446 return 0;
3447 }
3448 /* Data compressed! Let's save it on disk */
3449 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
3450 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
3451 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
b1befe6a 3452 if (rdbSaveLen(fp,len) == -1) goto writeerr;
774e3047 3453 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
88e85998 3454 zfree(out);
774e3047 3455 return comprlen;
3456
3457writeerr:
88e85998 3458 zfree(out);
774e3047 3459 return -1;
3460}
3461
e3566d4b 3462/* Save a string objet as [len][data] on disk. If the object is a string
3463 * representation of an integer value we try to safe it in a special form */
b1befe6a 3464static int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
e3566d4b 3465 int enclen;
10c43610 3466
774e3047 3467 /* Try integer encoding */
e3566d4b 3468 if (len <= 11) {
3469 unsigned char buf[5];
b1befe6a 3470 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
e3566d4b 3471 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3472 return 0;
3473 }
3474 }
774e3047 3475
3476 /* Try LZF compression - under 20 bytes it's unable to compress even
88e85998 3477 * aaaaaaaaaaaaaaaaaa so skip it */
121f70cf 3478 if (server.rdbcompression && len > 20) {
774e3047 3479 int retval;
3480
b1befe6a 3481 retval = rdbSaveLzfStringObject(fp,s,len);
774e3047 3482 if (retval == -1) return -1;
3483 if (retval > 0) return 0;
3484 /* retval == 0 means data can't be compressed, save the old way */
3485 }
3486
3487 /* Store verbatim */
10c43610 3488 if (rdbSaveLen(fp,len) == -1) return -1;
b1befe6a 3489 if (len && fwrite(s,len,1,fp) == 0) return -1;
10c43610 3490 return 0;
3491}
3492
942a3961 3493/* Like rdbSaveStringObjectRaw() but handle encoded objects */
3494static int rdbSaveStringObject(FILE *fp, robj *obj) {
3495 int retval;
942a3961 3496
32a66513 3497 /* Avoid to decode the object, then encode it again, if the
3498 * object is alrady integer encoded. */
3499 if (obj->encoding == REDIS_ENCODING_INT) {
3500 long val = (long) obj->ptr;
3501 unsigned char buf[5];
3502 int enclen;
3503
3504 if ((enclen = rdbEncodeInteger(val,buf)) > 0) {
3505 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3506 return 0;
3507 }
3508 /* otherwise... fall throught and continue with the usual
3509 * code path. */
3510 }
3511
f2d9f50f 3512 /* Avoid incr/decr ref count business when possible.
3513 * This plays well with copy-on-write given that we are probably
3514 * in a child process (BGSAVE). Also this makes sure key objects
3515 * of swapped objects are not incRefCount-ed (an assert does not allow
3516 * this in order to avoid bugs) */
3517 if (obj->encoding != REDIS_ENCODING_RAW) {
996cb5f7 3518 obj = getDecodedObject(obj);
b1befe6a 3519 retval = rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
996cb5f7 3520 decrRefCount(obj);
3521 } else {
b1befe6a 3522 retval = rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
996cb5f7 3523 }
9d65a1bb 3524 return retval;
942a3961 3525}
3526
a7866db6 3527/* Save a double value. Doubles are saved as strings prefixed by an unsigned
3528 * 8 bit integer specifing the length of the representation.
3529 * This 8 bit integer has special values in order to specify the following
3530 * conditions:
3531 * 253: not a number
3532 * 254: + inf
3533 * 255: - inf
3534 */
3535static int rdbSaveDoubleValue(FILE *fp, double val) {
3536 unsigned char buf[128];
3537 int len;
3538
3539 if (isnan(val)) {
3540 buf[0] = 253;
3541 len = 1;
3542 } else if (!isfinite(val)) {
3543 len = 1;
3544 buf[0] = (val < 0) ? 255 : 254;
3545 } else {
88e8d89f 3546#if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
fe244589 3547 /* Check if the float is in a safe range to be casted into a
3548 * long long. We are assuming that long long is 64 bit here.
3549 * Also we are assuming that there are no implementations around where
3550 * double has precision < 52 bit.
3551 *
3552 * Under this assumptions we test if a double is inside an interval
3553 * where casting to long long is safe. Then using two castings we
3554 * make sure the decimal part is zero. If all this is true we use
3555 * integer printing function that is much faster. */
fb82e75c 3556 double min = -4503599627370495; /* (2^52)-1 */
3557 double max = 4503599627370496; /* -(2^52) */
fe244589 3558 if (val > min && val < max && val == ((double)((long long)val)))
8c096b16 3559 ll2string((char*)buf+1,sizeof(buf),(long long)val);
3560 else
88e8d89f 3561#endif
8c096b16 3562 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
6c446631 3563 buf[0] = strlen((char*)buf+1);
a7866db6 3564 len = buf[0]+1;
3565 }
3566 if (fwrite(buf,len,1,fp) == 0) return -1;
3567 return 0;
3568}
3569
06233c45 3570/* Save a Redis object. */
3571static int rdbSaveObject(FILE *fp, robj *o) {
3572 if (o->type == REDIS_STRING) {
3573 /* Save a string value */
3574 if (rdbSaveStringObject(fp,o) == -1) return -1;
3575 } else if (o->type == REDIS_LIST) {
3576 /* Save a list value */
3577 list *list = o->ptr;
c7df85a4 3578 listIter li;
06233c45 3579 listNode *ln;
3580
06233c45 3581 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
c7df85a4 3582 listRewind(list,&li);
3583 while((ln = listNext(&li))) {
06233c45 3584 robj *eleobj = listNodeValue(ln);
3585
3586 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3587 }
3588 } else if (o->type == REDIS_SET) {
3589 /* Save a set value */
3590 dict *set = o->ptr;
3591 dictIterator *di = dictGetIterator(set);
3592 dictEntry *de;
3593
3594 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
3595 while((de = dictNext(di)) != NULL) {
3596 robj *eleobj = dictGetEntryKey(de);
3597
3598 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3599 }
3600 dictReleaseIterator(di);
3601 } else if (o->type == REDIS_ZSET) {
3602 /* Save a set value */
3603 zset *zs = o->ptr;
3604 dictIterator *di = dictGetIterator(zs->dict);
3605 dictEntry *de;
3606
3607 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
3608 while((de = dictNext(di)) != NULL) {
3609 robj *eleobj = dictGetEntryKey(de);
3610 double *score = dictGetEntryVal(de);
3611
3612 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3613 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
3614 }
3615 dictReleaseIterator(di);
b1befe6a 3616 } else if (o->type == REDIS_HASH) {
3617 /* Save a hash value */
3618 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3619 unsigned char *p = zipmapRewind(o->ptr);
3620 unsigned int count = zipmapLen(o->ptr);
3621 unsigned char *key, *val;
3622 unsigned int klen, vlen;
3623
3624 if (rdbSaveLen(fp,count) == -1) return -1;
3625 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
3626 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
3627 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
3628 }
3629 } else {
3630 dictIterator *di = dictGetIterator(o->ptr);
3631 dictEntry *de;
3632
3633 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
3634 while((de = dictNext(di)) != NULL) {
3635 robj *key = dictGetEntryKey(de);
3636 robj *val = dictGetEntryVal(de);
3637
3638 if (rdbSaveStringObject(fp,key) == -1) return -1;
3639 if (rdbSaveStringObject(fp,val) == -1) return -1;
3640 }
3641 dictReleaseIterator(di);
3642 }
06233c45 3643 } else {
f83c6cb5 3644 redisPanic("Unknown object type");
06233c45 3645 }
3646 return 0;
3647}
3648
3649/* Return the length the object will have on disk if saved with
3650 * the rdbSaveObject() function. Currently we use a trick to get
3651 * this length with very little changes to the code. In the future
3652 * we could switch to a faster solution. */
b9bc0eef 3653static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
3654 if (fp == NULL) fp = server.devnull;
06233c45 3655 rewind(fp);
3656 assert(rdbSaveObject(fp,o) != 1);
3657 return ftello(fp);
3658}
3659
06224fec 3660/* Return the number of pages required to save this object in the swap file */
b9bc0eef 3661static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
3662 off_t bytes = rdbSavedObjectLen(o,fp);
e0a62c7f 3663
06224fec 3664 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
3665}
3666
ed9b544e 3667/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
f78fd11b 3668static int rdbSave(char *filename) {
ed9b544e 3669 dictIterator *di = NULL;
3670 dictEntry *de;
ed9b544e 3671 FILE *fp;
3672 char tmpfile[256];
3673 int j;
bb32ede5 3674 time_t now = time(NULL);
ed9b544e 3675
2316bb3b 3676 /* Wait for I/O therads to terminate, just in case this is a
3677 * foreground-saving, to avoid seeking the swap file descriptor at the
3678 * same time. */
3679 if (server.vm_enabled)
3680 waitEmptyIOJobsQueue();
3681
a3b21203 3682 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
ed9b544e 3683 fp = fopen(tmpfile,"w");
3684 if (!fp) {
3685 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
3686 return REDIS_ERR;
3687 }
f78fd11b 3688 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
ed9b544e 3689 for (j = 0; j < server.dbnum; j++) {
bb32ede5 3690 redisDb *db = server.db+j;
3691 dict *d = db->dict;
3305306f 3692 if (dictSize(d) == 0) continue;
ed9b544e 3693 di = dictGetIterator(d);
3694 if (!di) {
3695 fclose(fp);
3696 return REDIS_ERR;
3697 }
3698
3699 /* Write the SELECT DB opcode */
f78fd11b 3700 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
3701 if (rdbSaveLen(fp,j) == -1) goto werr;
ed9b544e 3702
3703 /* Iterate this DB writing every entry */
3704 while((de = dictNext(di)) != NULL) {
3705 robj *key = dictGetEntryKey(de);
3706 robj *o = dictGetEntryVal(de);
bb32ede5 3707 time_t expiretime = getExpire(db,key);
3708
3709 /* Save the expire time */
3710 if (expiretime != -1) {
3711 /* If this key is already expired skip it */
3712 if (expiretime < now) continue;
3713 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
3714 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
3715 }
7e69548d 3716 /* Save the key and associated value. This requires special
3717 * handling if the value is swapped out. */
996cb5f7 3718 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
3719 key->storage == REDIS_VM_SWAPPING) {
7e69548d 3720 /* Save type, key, value */
3721 if (rdbSaveType(fp,o->type) == -1) goto werr;
3722 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3723 if (rdbSaveObject(fp,o) == -1) goto werr;
3724 } else {
996cb5f7 3725 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
b9bc0eef 3726 robj *po;
7e69548d 3727 /* Get a preview of the object in memory */
3728 po = vmPreviewObject(key);
7e69548d 3729 /* Save type, key, value */
3730 if (rdbSaveType(fp,key->vtype) == -1) goto werr;
b9bc0eef 3731 if (rdbSaveStringObject(fp,key) == -1) goto werr;
7e69548d 3732 if (rdbSaveObject(fp,po) == -1) goto werr;
3733 /* Remove the loaded object from memory */
3734 decrRefCount(po);
7e69548d 3735 }
ed9b544e 3736 }
3737 dictReleaseIterator(di);
3738 }
3739 /* EOF opcode */
f78fd11b 3740 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
3741
3742 /* Make sure data will not remain on the OS's output buffers */
ed9b544e 3743 fflush(fp);
3744 fsync(fileno(fp));
3745 fclose(fp);
e0a62c7f 3746
ed9b544e 3747 /* Use RENAME to make sure the DB file is changed atomically only
3748 * if the generate DB file is ok. */
3749 if (rename(tmpfile,filename) == -1) {
325d1eb4 3750 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
ed9b544e 3751 unlink(tmpfile);
3752 return REDIS_ERR;
3753 }
3754 redisLog(REDIS_NOTICE,"DB saved on disk");
3755 server.dirty = 0;
3756 server.lastsave = time(NULL);
3757 return REDIS_OK;
3758
3759werr:
3760 fclose(fp);
3761 unlink(tmpfile);
3762 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
3763 if (di) dictReleaseIterator(di);
3764 return REDIS_ERR;
3765}
3766
f78fd11b 3767static int rdbSaveBackground(char *filename) {
ed9b544e 3768 pid_t childpid;
3769
9d65a1bb 3770 if (server.bgsavechildpid != -1) return REDIS_ERR;
054e426d 3771 if (server.vm_enabled) waitEmptyIOJobsQueue();
ed9b544e 3772 if ((childpid = fork()) == 0) {
3773 /* Child */
054e426d 3774 if (server.vm_enabled) vmReopenSwapFile();
ed9b544e 3775 close(server.fd);
f78fd11b 3776 if (rdbSave(filename) == REDIS_OK) {
478c2c6f 3777 _exit(0);
ed9b544e 3778 } else {
478c2c6f 3779 _exit(1);
ed9b544e 3780 }
3781 } else {
3782 /* Parent */
5a7c647e 3783 if (childpid == -1) {
3784 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
3785 strerror(errno));
3786 return REDIS_ERR;
3787 }
ed9b544e 3788 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
9f3c422c 3789 server.bgsavechildpid = childpid;
884d4b39 3790 updateDictResizePolicy();
ed9b544e 3791 return REDIS_OK;
3792 }
3793 return REDIS_OK; /* unreached */
3794}
3795
a3b21203 3796static void rdbRemoveTempFile(pid_t childpid) {
3797 char tmpfile[256];
3798
3799 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
3800 unlink(tmpfile);
3801}
3802
f78fd11b 3803static int rdbLoadType(FILE *fp) {
3804 unsigned char type;
7b45bfb2 3805 if (fread(&type,1,1,fp) == 0) return -1;
3806 return type;
3807}
3808
bb32ede5 3809static time_t rdbLoadTime(FILE *fp) {
3810 int32_t t32;
3811 if (fread(&t32,4,1,fp) == 0) return -1;
3812 return (time_t) t32;
3813}
3814
e3566d4b 3815/* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3816 * of this file for a description of how this are stored on disk.
3817 *
3818 * isencoded is set to 1 if the readed length is not actually a length but
3819 * an "encoding type", check the above comments for more info */
c78a8ccc 3820static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
f78fd11b 3821 unsigned char buf[2];
3822 uint32_t len;
c78a8ccc 3823 int type;
f78fd11b 3824
e3566d4b 3825 if (isencoded) *isencoded = 0;
c78a8ccc 3826 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
3827 type = (buf[0]&0xC0)>>6;
3828 if (type == REDIS_RDB_6BITLEN) {
3829 /* Read a 6 bit len */
3830 return buf[0]&0x3F;
3831 } else if (type == REDIS_RDB_ENCVAL) {
3832 /* Read a 6 bit len encoding type */
3833 if (isencoded) *isencoded = 1;
3834 return buf[0]&0x3F;
3835 } else if (type == REDIS_RDB_14BITLEN) {
3836 /* Read a 14 bit len */
3837 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
3838 return ((buf[0]&0x3F)<<8)|buf[1];
3839 } else {
3840 /* Read a 32 bit len */
f78fd11b 3841 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
3842 return ntohl(len);
f78fd11b 3843 }
f78fd11b 3844}
3845
ad30aa60 3846/* Load an integer-encoded object from file 'fp', with the specified
3847 * encoding type 'enctype'. If encode is true the function may return
3848 * an integer-encoded object as reply, otherwise the returned object
3849 * will always be encoded as a raw string. */
3850static robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
e3566d4b 3851 unsigned char enc[4];
3852 long long val;
3853
3854 if (enctype == REDIS_RDB_ENC_INT8) {
3855 if (fread(enc,1,1,fp) == 0) return NULL;
3856 val = (signed char)enc[0];
3857 } else if (enctype == REDIS_RDB_ENC_INT16) {
3858 uint16_t v;
3859 if (fread(enc,2,1,fp) == 0) return NULL;
3860 v = enc[0]|(enc[1]<<8);
3861 val = (int16_t)v;
3862 } else if (enctype == REDIS_RDB_ENC_INT32) {
3863 uint32_t v;
3864 if (fread(enc,4,1,fp) == 0) return NULL;
3865 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
3866 val = (int32_t)v;
3867 } else {
3868 val = 0; /* anti-warning */
f83c6cb5 3869 redisPanic("Unknown RDB integer encoding type");
e3566d4b 3870 }
ad30aa60 3871 if (encode)
3872 return createStringObjectFromLongLong(val);
3873 else
3874 return createObject(REDIS_STRING,sdsfromlonglong(val));
e3566d4b 3875}
3876
c78a8ccc 3877static robj *rdbLoadLzfStringObject(FILE*fp) {
88e85998 3878 unsigned int len, clen;
3879 unsigned char *c = NULL;
3880 sds val = NULL;
3881
c78a8ccc 3882 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3883 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
88e85998 3884 if ((c = zmalloc(clen)) == NULL) goto err;
3885 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
3886 if (fread(c,clen,1,fp) == 0) goto err;
3887 if (lzf_decompress(c,clen,val,len) == 0) goto err;
5109cdff 3888 zfree(c);
88e85998 3889 return createObject(REDIS_STRING,val);
3890err:
3891 zfree(c);
3892 sdsfree(val);
3893 return NULL;
3894}
3895
ad30aa60 3896static robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
e3566d4b 3897 int isencoded;
3898 uint32_t len;
f78fd11b 3899 sds val;
3900
c78a8ccc 3901 len = rdbLoadLen(fp,&isencoded);
e3566d4b 3902 if (isencoded) {
3903 switch(len) {
3904 case REDIS_RDB_ENC_INT8:
3905 case REDIS_RDB_ENC_INT16:
3906 case REDIS_RDB_ENC_INT32:
ad30aa60 3907 return rdbLoadIntegerObject(fp,len,encode);
88e85998 3908 case REDIS_RDB_ENC_LZF:
bdcb92f2 3909 return rdbLoadLzfStringObject(fp);
e3566d4b 3910 default:
f83c6cb5 3911 redisPanic("Unknown RDB encoding type");
e3566d4b 3912 }
3913 }
3914
f78fd11b 3915 if (len == REDIS_RDB_LENERR) return NULL;
3916 val = sdsnewlen(NULL,len);
3917 if (len && fread(val,len,1,fp) == 0) {
3918 sdsfree(val);
3919 return NULL;
3920 }
bdcb92f2 3921 return createObject(REDIS_STRING,val);
f78fd11b 3922}
3923
ad30aa60 3924static robj *rdbLoadStringObject(FILE *fp) {
3925 return rdbGenericLoadStringObject(fp,0);
3926}
3927
3928static robj *rdbLoadEncodedStringObject(FILE *fp) {
3929 return rdbGenericLoadStringObject(fp,1);
3930}
3931
a7866db6 3932/* For information about double serialization check rdbSaveDoubleValue() */
3933static int rdbLoadDoubleValue(FILE *fp, double *val) {
3934 char buf[128];
3935 unsigned char len;
3936
3937 if (fread(&len,1,1,fp) == 0) return -1;
3938 switch(len) {
3939 case 255: *val = R_NegInf; return 0;
3940 case 254: *val = R_PosInf; return 0;
3941 case 253: *val = R_Nan; return 0;
3942 default:
3943 if (fread(buf,len,1,fp) == 0) return -1;
231d758e 3944 buf[len] = '\0';
a7866db6 3945 sscanf(buf, "%lg", val);
3946 return 0;
3947 }
3948}
3949
c78a8ccc 3950/* Load a Redis object of the specified type from the specified file.
3951 * On success a newly allocated object is returned, otherwise NULL. */
3952static robj *rdbLoadObject(int type, FILE *fp) {
3953 robj *o;
3954
bcd11906 3955 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
c78a8ccc 3956 if (type == REDIS_STRING) {
3957 /* Read string value */
ad30aa60 3958 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 3959 o = tryObjectEncoding(o);
c78a8ccc 3960 } else if (type == REDIS_LIST || type == REDIS_SET) {
3961 /* Read list/set value */
3962 uint32_t listlen;
3963
3964 if ((listlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3965 o = (type == REDIS_LIST) ? createListObject() : createSetObject();
3c68de9b 3966 /* It's faster to expand the dict to the right size asap in order
3967 * to avoid rehashing */
3968 if (type == REDIS_SET && listlen > DICT_HT_INITIAL_SIZE)
3969 dictExpand(o->ptr,listlen);
c78a8ccc 3970 /* Load every single element of the list/set */
3971 while(listlen--) {
3972 robj *ele;
3973
ad30aa60 3974 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 3975 ele = tryObjectEncoding(ele);
c78a8ccc 3976 if (type == REDIS_LIST) {
3977 listAddNodeTail((list*)o->ptr,ele);
3978 } else {
3979 dictAdd((dict*)o->ptr,ele,NULL);
3980 }
3981 }
3982 } else if (type == REDIS_ZSET) {
3983 /* Read list/set value */
ada386b2 3984 size_t zsetlen;
c78a8ccc 3985 zset *zs;
3986
3987 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3988 o = createZsetObject();
3989 zs = o->ptr;
3990 /* Load every single element of the list/set */
3991 while(zsetlen--) {
3992 robj *ele;
3993 double *score = zmalloc(sizeof(double));
3994
ad30aa60 3995 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 3996 ele = tryObjectEncoding(ele);
c78a8ccc 3997 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
3998 dictAdd(zs->dict,ele,score);
3999 zslInsert(zs->zsl,*score,ele);
4000 incrRefCount(ele); /* added to skiplist */
4001 }
ada386b2 4002 } else if (type == REDIS_HASH) {
4003 size_t hashlen;
4004
4005 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4006 o = createHashObject();
4007 /* Too many entries? Use an hash table. */
4008 if (hashlen > server.hash_max_zipmap_entries)
4009 convertToRealHash(o);
4010 /* Load every key/value, then set it into the zipmap or hash
4011 * table, as needed. */
4012 while(hashlen--) {
4013 robj *key, *val;
4014
4015 if ((key = rdbLoadStringObject(fp)) == NULL) return NULL;
4016 if ((val = rdbLoadStringObject(fp)) == NULL) return NULL;
4017 /* If we are using a zipmap and there are too big values
4018 * the object is converted to real hash table encoding. */
4019 if (o->encoding != REDIS_ENCODING_HT &&
4020 (sdslen(key->ptr) > server.hash_max_zipmap_value ||
4021 sdslen(val->ptr) > server.hash_max_zipmap_value))
4022 {
4023 convertToRealHash(o);
4024 }
4025
4026 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
4027 unsigned char *zm = o->ptr;
4028
4029 zm = zipmapSet(zm,key->ptr,sdslen(key->ptr),
4030 val->ptr,sdslen(val->ptr),NULL);
4031 o->ptr = zm;
4032 decrRefCount(key);
4033 decrRefCount(val);
4034 } else {
05df7621 4035 key = tryObjectEncoding(key);
4036 val = tryObjectEncoding(val);
ada386b2 4037 dictAdd((dict*)o->ptr,key,val);
ada386b2 4038 }
4039 }
c78a8ccc 4040 } else {
f83c6cb5 4041 redisPanic("Unknown object type");
c78a8ccc 4042 }
4043 return o;
4044}
4045
f78fd11b 4046static int rdbLoad(char *filename) {
ed9b544e 4047 FILE *fp;
f78fd11b 4048 uint32_t dbid;
bb32ede5 4049 int type, retval, rdbver;
585af7e2 4050 int swap_all_values = 0;
3305306f 4051 dict *d = server.db[0].dict;
bb32ede5 4052 redisDb *db = server.db+0;
f78fd11b 4053 char buf[1024];
242a64f3 4054 time_t expiretime, now = time(NULL);
b492cf00 4055 long long loadedkeys = 0;
bb32ede5 4056
ed9b544e 4057 fp = fopen(filename,"r");
4058 if (!fp) return REDIS_ERR;
4059 if (fread(buf,9,1,fp) == 0) goto eoferr;
f78fd11b 4060 buf[9] = '\0';
4061 if (memcmp(buf,"REDIS",5) != 0) {
ed9b544e 4062 fclose(fp);
4063 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
4064 return REDIS_ERR;
4065 }
f78fd11b 4066 rdbver = atoi(buf+5);
c78a8ccc 4067 if (rdbver != 1) {
f78fd11b 4068 fclose(fp);
4069 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
4070 return REDIS_ERR;
4071 }
ed9b544e 4072 while(1) {
585af7e2 4073 robj *key, *val;
ed9b544e 4074
585af7e2 4075 expiretime = -1;
ed9b544e 4076 /* Read type. */
f78fd11b 4077 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
bb32ede5 4078 if (type == REDIS_EXPIRETIME) {
4079 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
4080 /* We read the time so we need to read the object type again */
4081 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4082 }
ed9b544e 4083 if (type == REDIS_EOF) break;
4084 /* Handle SELECT DB opcode as a special case */
4085 if (type == REDIS_SELECTDB) {
c78a8ccc 4086 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
e3566d4b 4087 goto eoferr;
ed9b544e 4088 if (dbid >= (unsigned)server.dbnum) {
f78fd11b 4089 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
ed9b544e 4090 exit(1);
4091 }
bb32ede5 4092 db = server.db+dbid;
4093 d = db->dict;
ed9b544e 4094 continue;
4095 }
4096 /* Read key */
585af7e2 4097 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
c78a8ccc 4098 /* Read value */
585af7e2 4099 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
89e689c5 4100 /* Check if the key already expired */
4101 if (expiretime != -1 && expiretime < now) {
4102 decrRefCount(key);
4103 decrRefCount(val);
4104 continue;
4105 }
ed9b544e 4106 /* Add the new object in the hash table */
585af7e2 4107 retval = dictAdd(d,key,val);
ed9b544e 4108 if (retval == DICT_ERR) {
585af7e2 4109 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
ed9b544e 4110 exit(1);
4111 }
242a64f3 4112 loadedkeys++;
bb32ede5 4113 /* Set the expire time if needed */
89e689c5 4114 if (expiretime != -1) setExpire(db,key,expiretime);
242a64f3 4115
b492cf00 4116 /* Handle swapping while loading big datasets when VM is on */
242a64f3 4117
4118 /* If we detecter we are hopeless about fitting something in memory
4119 * we just swap every new key on disk. Directly...
4120 * Note that's important to check for this condition before resorting
4121 * to random sampling, otherwise we may try to swap already
4122 * swapped keys. */
585af7e2 4123 if (swap_all_values) {
4124 dictEntry *de = dictFind(d,key);
242a64f3 4125
4126 /* de may be NULL since the key already expired */
4127 if (de) {
585af7e2 4128 key = dictGetEntryKey(de);
4129 val = dictGetEntryVal(de);
242a64f3 4130
585af7e2 4131 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
242a64f3 4132 dictGetEntryVal(de) = NULL;
4133 }
4134 }
4135 continue;
4136 }
4137
4138 /* If we have still some hope of having some value fitting memory
4139 * then we try random sampling. */
585af7e2 4140 if (!swap_all_values && server.vm_enabled && (loadedkeys % 5000) == 0) {
b492cf00 4141 while (zmalloc_used_memory() > server.vm_max_memory) {
a69a0c9c 4142 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
b492cf00 4143 }
242a64f3 4144 if (zmalloc_used_memory() > server.vm_max_memory)
585af7e2 4145 swap_all_values = 1; /* We are already using too much mem */
b492cf00 4146 }
ed9b544e 4147 }
4148 fclose(fp);
4149 return REDIS_OK;
4150
4151eoferr: /* unexpected end of file is handled here with a fatal exit */
f80dff62 4152 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
ed9b544e 4153 exit(1);
4154 return REDIS_ERR; /* Just to avoid warning */
4155}
4156
4157/*================================== Commands =============================== */
4158
abcb223e 4159static void authCommand(redisClient *c) {
2e77c2ee 4160 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
abcb223e
BH
4161 c->authenticated = 1;
4162 addReply(c,shared.ok);
4163 } else {
4164 c->authenticated = 0;
fa4c0aba 4165 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
abcb223e
BH
4166 }
4167}
4168
ed9b544e 4169static void pingCommand(redisClient *c) {
4170 addReply(c,shared.pong);
4171}
4172
4173static void echoCommand(redisClient *c) {
dd88747b 4174 addReplyBulk(c,c->argv[1]);
ed9b544e 4175}
4176
4177/*=================================== Strings =============================== */
4178
526d00a5 4179static void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
ed9b544e 4180 int retval;
10ce1276 4181 long seconds = 0; /* initialized to avoid an harmness warning */
ed9b544e 4182
526d00a5 4183 if (expire) {
4184 if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
4185 return;
4186 if (seconds <= 0) {
4187 addReplySds(c,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4188 return;
4189 }
4190 }
4191
4192 if (nx) deleteIfVolatile(c->db,key);
4193 retval = dictAdd(c->db->dict,key,val);
ed9b544e 4194 if (retval == DICT_ERR) {
4195 if (!nx) {
1b03836c 4196 /* If the key is about a swapped value, we want a new key object
4197 * to overwrite the old. So we delete the old key in the database.
4198 * This will also make sure that swap pages about the old object
4199 * will be marked as free. */
526d00a5 4200 if (server.vm_enabled && deleteIfSwapped(c->db,key))
4201 incrRefCount(key);
4202 dictReplace(c->db->dict,key,val);
4203 incrRefCount(val);
ed9b544e 4204 } else {
c937aa89 4205 addReply(c,shared.czero);
ed9b544e 4206 return;
4207 }
4208 } else {
526d00a5 4209 incrRefCount(key);
4210 incrRefCount(val);
ed9b544e 4211 }
4212 server.dirty++;
526d00a5 4213 removeExpire(c->db,key);
4214 if (expire) setExpire(c->db,key,time(NULL)+seconds);
c937aa89 4215 addReply(c, nx ? shared.cone : shared.ok);
ed9b544e 4216}
4217
4218static void setCommand(redisClient *c) {
526d00a5 4219 setGenericCommand(c,0,c->argv[1],c->argv[2],NULL);
ed9b544e 4220}
4221
4222static void setnxCommand(redisClient *c) {
526d00a5 4223 setGenericCommand(c,1,c->argv[1],c->argv[2],NULL);
4224}
4225
4226static void setexCommand(redisClient *c) {
4227 setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
ed9b544e 4228}
4229
322fc7d8 4230static int getGenericCommand(redisClient *c) {
dd88747b 4231 robj *o;
e0a62c7f 4232
dd88747b 4233 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
322fc7d8 4234 return REDIS_OK;
dd88747b 4235
4236 if (o->type != REDIS_STRING) {
4237 addReply(c,shared.wrongtypeerr);
4238 return REDIS_ERR;
ed9b544e 4239 } else {
dd88747b 4240 addReplyBulk(c,o);
4241 return REDIS_OK;
ed9b544e 4242 }
4243}
4244
322fc7d8 4245static void getCommand(redisClient *c) {
4246 getGenericCommand(c);
4247}
4248
f6b141c5 4249static void getsetCommand(redisClient *c) {
322fc7d8 4250 if (getGenericCommand(c) == REDIS_ERR) return;
a431eb74 4251 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
4252 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
4253 } else {
4254 incrRefCount(c->argv[1]);
4255 }
4256 incrRefCount(c->argv[2]);
4257 server.dirty++;
4258 removeExpire(c->db,c->argv[1]);
4259}
4260
70003d28 4261static void mgetCommand(redisClient *c) {
70003d28 4262 int j;
e0a62c7f 4263
c937aa89 4264 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
70003d28 4265 for (j = 1; j < c->argc; j++) {
3305306f 4266 robj *o = lookupKeyRead(c->db,c->argv[j]);
4267 if (o == NULL) {
c937aa89 4268 addReply(c,shared.nullbulk);
70003d28 4269 } else {
70003d28 4270 if (o->type != REDIS_STRING) {
c937aa89 4271 addReply(c,shared.nullbulk);
70003d28 4272 } else {
dd88747b 4273 addReplyBulk(c,o);
70003d28 4274 }
4275 }
4276 }
4277}
4278
6c446631 4279static void msetGenericCommand(redisClient *c, int nx) {
906573e7 4280 int j, busykeys = 0;
6c446631 4281
4282 if ((c->argc % 2) == 0) {
454d4e43 4283 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
6c446631 4284 return;
4285 }
4286 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4287 * set nothing at all if at least one already key exists. */
4288 if (nx) {
4289 for (j = 1; j < c->argc; j += 2) {
906573e7 4290 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
4291 busykeys++;
6c446631 4292 }
4293 }
4294 }
906573e7 4295 if (busykeys) {
4296 addReply(c, shared.czero);
4297 return;
4298 }
6c446631 4299
4300 for (j = 1; j < c->argc; j += 2) {
4301 int retval;
4302
05df7621 4303 c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
6c446631 4304 retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
4305 if (retval == DICT_ERR) {
4306 dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
4307 incrRefCount(c->argv[j+1]);
4308 } else {
4309 incrRefCount(c->argv[j]);
4310 incrRefCount(c->argv[j+1]);
4311 }
4312 removeExpire(c->db,c->argv[j]);
4313 }
4314 server.dirty += (c->argc-1)/2;
4315 addReply(c, nx ? shared.cone : shared.ok);
4316}
4317
4318static void msetCommand(redisClient *c) {
4319 msetGenericCommand(c,0);
4320}
4321
4322static void msetnxCommand(redisClient *c) {
4323 msetGenericCommand(c,1);
4324}
4325
d68ed120 4326static void incrDecrCommand(redisClient *c, long long incr) {
ed9b544e 4327 long long value;
4328 int retval;
4329 robj *o;
e0a62c7f 4330
3305306f 4331 o = lookupKeyWrite(c->db,c->argv[1]);
6485f293
PN
4332 if (o != NULL && checkType(c,o,REDIS_STRING)) return;
4333 if (getLongLongFromObjectOrReply(c,o,&value,NULL) != REDIS_OK) return;
ed9b544e 4334
4335 value += incr;
4336 o = createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",value));
05df7621 4337 o = tryObjectEncoding(o);
3305306f 4338 retval = dictAdd(c->db->dict,c->argv[1],o);
ed9b544e 4339 if (retval == DICT_ERR) {
3305306f 4340 dictReplace(c->db->dict,c->argv[1],o);
4341 removeExpire(c->db,c->argv[1]);
ed9b544e 4342 } else {
4343 incrRefCount(c->argv[1]);
4344 }
4345 server.dirty++;
c937aa89 4346 addReply(c,shared.colon);
ed9b544e 4347 addReply(c,o);
4348 addReply(c,shared.crlf);
4349}
4350
4351static void incrCommand(redisClient *c) {
a4d1ba9a 4352 incrDecrCommand(c,1);
ed9b544e 4353}
4354
4355static void decrCommand(redisClient *c) {
a4d1ba9a 4356 incrDecrCommand(c,-1);
ed9b544e 4357}
4358
4359static void incrbyCommand(redisClient *c) {
bbe025e0
AM
4360 long long incr;
4361
bd79a6bd 4362 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
a4d1ba9a 4363 incrDecrCommand(c,incr);
ed9b544e 4364}
4365
4366static void decrbyCommand(redisClient *c) {
bbe025e0
AM
4367 long long incr;
4368
bd79a6bd 4369 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
a4d1ba9a 4370 incrDecrCommand(c,-incr);
ed9b544e 4371}
4372
4b00bebd 4373static void appendCommand(redisClient *c) {
4374 int retval;
4375 size_t totlen;
4376 robj *o;
4377
4378 o = lookupKeyWrite(c->db,c->argv[1]);
4379 if (o == NULL) {
4380 /* Create the key */
4381 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
4382 incrRefCount(c->argv[1]);
4383 incrRefCount(c->argv[2]);
4384 totlen = stringObjectLen(c->argv[2]);
4385 } else {
4386 dictEntry *de;
e0a62c7f 4387
4b00bebd 4388 de = dictFind(c->db->dict,c->argv[1]);
4389 assert(de != NULL);
4390
4391 o = dictGetEntryVal(de);
4392 if (o->type != REDIS_STRING) {
4393 addReply(c,shared.wrongtypeerr);
4394 return;
4395 }
4396 /* If the object is specially encoded or shared we have to make
4397 * a copy */
4398 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
4399 robj *decoded = getDecodedObject(o);
4400
4401 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
4402 decrRefCount(decoded);
4403 dictReplace(c->db->dict,c->argv[1],o);
4404 }
4405 /* APPEND! */
4406 if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
4407 o->ptr = sdscatlen(o->ptr,
4408 c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
4409 } else {
4410 o->ptr = sdscatprintf(o->ptr, "%ld",
4411 (unsigned long) c->argv[2]->ptr);
4412 }
4413 totlen = sdslen(o->ptr);
4414 }
4415 server.dirty++;
4416 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
4417}
4418
39191553 4419static void substrCommand(redisClient *c) {
4420 robj *o;
4421 long start = atoi(c->argv[2]->ptr);
4422 long end = atoi(c->argv[3]->ptr);
dd88747b 4423 size_t rangelen, strlen;
4424 sds range;
39191553 4425
dd88747b 4426 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4427 checkType(c,o,REDIS_STRING)) return;
39191553 4428
dd88747b 4429 o = getDecodedObject(o);
4430 strlen = sdslen(o->ptr);
8fe7fad7 4431
dd88747b 4432 /* convert negative indexes */
4433 if (start < 0) start = strlen+start;
4434 if (end < 0) end = strlen+end;
4435 if (start < 0) start = 0;
4436 if (end < 0) end = 0;
39191553 4437
dd88747b 4438 /* indexes sanity checks */
4439 if (start > end || (size_t)start >= strlen) {
4440 /* Out of range start or start > end result in null reply */
4441 addReply(c,shared.nullbulk);
4442 decrRefCount(o);
4443 return;
39191553 4444 }
dd88747b 4445 if ((size_t)end >= strlen) end = strlen-1;
4446 rangelen = (end-start)+1;
4447
4448 /* Return the result */
4449 addReplySds(c,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen));
4450 range = sdsnewlen((char*)o->ptr+start,rangelen);
4451 addReplySds(c,range);
4452 addReply(c,shared.crlf);
4453 decrRefCount(o);
39191553 4454}
4455
ed9b544e 4456/* ========================= Type agnostic commands ========================= */
4457
4458static void delCommand(redisClient *c) {
5109cdff 4459 int deleted = 0, j;
4460
4461 for (j = 1; j < c->argc; j++) {
4462 if (deleteKey(c->db,c->argv[j])) {
4463 server.dirty++;
4464 deleted++;
4465 }
4466 }
dd88747b 4467 addReplyLong(c,deleted);
ed9b544e 4468}
4469
4470static void existsCommand(redisClient *c) {
f4f06efc
PN
4471 expireIfNeeded(c->db,c->argv[1]);
4472 if (dictFind(c->db->dict,c->argv[1])) {
4473 addReply(c, shared.cone);
4474 } else {
4475 addReply(c, shared.czero);
4476 }
ed9b544e 4477}
4478
4479static void selectCommand(redisClient *c) {
4480 int id = atoi(c->argv[1]->ptr);
e0a62c7f 4481
ed9b544e 4482 if (selectDb(c,id) == REDIS_ERR) {
774e3047 4483 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
ed9b544e 4484 } else {
4485 addReply(c,shared.ok);
4486 }
4487}
4488
4489static void randomkeyCommand(redisClient *c) {
4490 dictEntry *de;
dc4be23e 4491 robj *key;
e0a62c7f 4492
3305306f 4493 while(1) {
4494 de = dictGetRandomKey(c->db->dict);
ce7bef07 4495 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
3305306f 4496 }
2b619329 4497
ed9b544e 4498 if (de == NULL) {
dc4be23e 4499 addReply(c,shared.nullbulk);
4500 return;
4501 }
4502
4503 key = dictGetEntryKey(de);
4504 if (server.vm_enabled) {
4505 key = dupStringObject(key);
4506 addReplyBulk(c,key);
4507 decrRefCount(key);
ed9b544e 4508 } else {
dc4be23e 4509 addReplyBulk(c,key);
ed9b544e 4510 }
4511}
4512
4513static void keysCommand(redisClient *c) {
4514 dictIterator *di;
4515 dictEntry *de;
4516 sds pattern = c->argv[1]->ptr;
4517 int plen = sdslen(pattern);
a3f9eec2 4518 unsigned long numkeys = 0;
ed9b544e 4519 robj *lenobj = createObject(REDIS_STRING,NULL);
4520
3305306f 4521 di = dictGetIterator(c->db->dict);
ed9b544e 4522 addReply(c,lenobj);
4523 decrRefCount(lenobj);
4524 while((de = dictNext(di)) != NULL) {
4525 robj *keyobj = dictGetEntryKey(de);
3305306f 4526
ed9b544e 4527 sds key = keyobj->ptr;
4528 if ((pattern[0] == '*' && pattern[1] == '\0') ||
4529 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
3305306f 4530 if (expireIfNeeded(c->db,keyobj) == 0) {
dd88747b 4531 addReplyBulk(c,keyobj);
3305306f 4532 numkeys++;
3305306f 4533 }
ed9b544e 4534 }
4535 }
4536 dictReleaseIterator(di);
a3f9eec2 4537 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
ed9b544e 4538}
4539
4540static void dbsizeCommand(redisClient *c) {
4541 addReplySds(c,
3305306f 4542 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
ed9b544e 4543}
4544
4545static void lastsaveCommand(redisClient *c) {
4546 addReplySds(c,
c937aa89 4547 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
ed9b544e 4548}
4549
4550static void typeCommand(redisClient *c) {
3305306f 4551 robj *o;
ed9b544e 4552 char *type;
3305306f 4553
4554 o = lookupKeyRead(c->db,c->argv[1]);
4555 if (o == NULL) {
c937aa89 4556 type = "+none";
ed9b544e 4557 } else {
ed9b544e 4558 switch(o->type) {
c937aa89 4559 case REDIS_STRING: type = "+string"; break;
4560 case REDIS_LIST: type = "+list"; break;
4561 case REDIS_SET: type = "+set"; break;
412a8bce 4562 case REDIS_ZSET: type = "+zset"; break;
ada386b2 4563 case REDIS_HASH: type = "+hash"; break;
4564 default: type = "+unknown"; break;
ed9b544e 4565 }
4566 }
4567 addReplySds(c,sdsnew(type));
4568 addReply(c,shared.crlf);
4569}
4570
4571static void saveCommand(redisClient *c) {
9d65a1bb 4572 if (server.bgsavechildpid != -1) {
05557f6d 4573 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
4574 return;
4575 }
f78fd11b 4576 if (rdbSave(server.dbfilename) == REDIS_OK) {
ed9b544e 4577 addReply(c,shared.ok);
4578 } else {
4579 addReply(c,shared.err);
4580 }
4581}
4582
4583static void bgsaveCommand(redisClient *c) {
9d65a1bb 4584 if (server.bgsavechildpid != -1) {
ed9b544e 4585 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
4586 return;
4587 }
f78fd11b 4588 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
49b99ab4 4589 char *status = "+Background saving started\r\n";
4590 addReplySds(c,sdsnew(status));
ed9b544e 4591 } else {
4592 addReply(c,shared.err);
4593 }
4594}
4595
4596static void shutdownCommand(redisClient *c) {
4597 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
a3b21203 4598 /* Kill the saving child if there is a background saving in progress.
4599 We want to avoid race conditions, for instance our saving child may
4600 overwrite the synchronous saving did by SHUTDOWN. */
9d65a1bb 4601 if (server.bgsavechildpid != -1) {
9f3c422c 4602 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
4603 kill(server.bgsavechildpid,SIGKILL);
a3b21203 4604 rdbRemoveTempFile(server.bgsavechildpid);
9f3c422c 4605 }
ac945e2d 4606 if (server.appendonly) {
4607 /* Append only file: fsync() the AOF and exit */
4608 fsync(server.appendfd);
054e426d 4609 if (server.vm_enabled) unlink(server.vm_swap_file);
ac945e2d 4610 exit(0);
ed9b544e 4611 } else {
ac945e2d 4612 /* Snapshotting. Perform a SYNC SAVE and exit */
4613 if (rdbSave(server.dbfilename) == REDIS_OK) {
4614 if (server.daemonize)
4615 unlink(server.pidfile);
4616 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
4617 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
4618 exit(0);
4619 } else {
dd88747b 4620 /* Ooops.. error saving! The best we can do is to continue
4621 * operating. Note that if there was a background saving process,
4622 * in the next cron() Redis will be notified that the background
4623 * saving aborted, handling special stuff like slaves pending for
4624 * synchronization... */
e0a62c7f 4625 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
dd88747b 4626 addReplySds(c,
4627 sdsnew("-ERR can't quit, problems saving the DB\r\n"));
ac945e2d 4628 }
ed9b544e 4629 }
4630}
4631
4632static void renameGenericCommand(redisClient *c, int nx) {
ed9b544e 4633 robj *o;
4634
4635 /* To use the same key as src and dst is probably an error */
4636 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
c937aa89 4637 addReply(c,shared.sameobjecterr);
ed9b544e 4638 return;
4639 }
4640
dd88747b 4641 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
ed9b544e 4642 return;
dd88747b 4643
ed9b544e 4644 incrRefCount(o);
3305306f 4645 deleteIfVolatile(c->db,c->argv[2]);
4646 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
ed9b544e 4647 if (nx) {
4648 decrRefCount(o);
c937aa89 4649 addReply(c,shared.czero);
ed9b544e 4650 return;
4651 }
3305306f 4652 dictReplace(c->db->dict,c->argv[2],o);
ed9b544e 4653 } else {
4654 incrRefCount(c->argv[2]);
4655 }
3305306f 4656 deleteKey(c->db,c->argv[1]);
ed9b544e 4657 server.dirty++;
c937aa89 4658 addReply(c,nx ? shared.cone : shared.ok);
ed9b544e 4659}
4660
4661static void renameCommand(redisClient *c) {
4662 renameGenericCommand(c,0);
4663}
4664
4665static void renamenxCommand(redisClient *c) {
4666 renameGenericCommand(c,1);
4667}
4668
4669static void moveCommand(redisClient *c) {
3305306f 4670 robj *o;
4671 redisDb *src, *dst;
ed9b544e 4672 int srcid;
4673
4674 /* Obtain source and target DB pointers */
3305306f 4675 src = c->db;
4676 srcid = c->db->id;
ed9b544e 4677 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
c937aa89 4678 addReply(c,shared.outofrangeerr);
ed9b544e 4679 return;
4680 }
3305306f 4681 dst = c->db;
4682 selectDb(c,srcid); /* Back to the source DB */
ed9b544e 4683
4684 /* If the user is moving using as target the same
4685 * DB as the source DB it is probably an error. */
4686 if (src == dst) {
c937aa89 4687 addReply(c,shared.sameobjecterr);
ed9b544e 4688 return;
4689 }
4690
4691 /* Check if the element exists and get a reference */
3305306f 4692 o = lookupKeyWrite(c->db,c->argv[1]);
4693 if (!o) {
c937aa89 4694 addReply(c,shared.czero);
ed9b544e 4695 return;
4696 }
4697
4698 /* Try to add the element to the target DB */
3305306f 4699 deleteIfVolatile(dst,c->argv[1]);
4700 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
c937aa89 4701 addReply(c,shared.czero);
ed9b544e 4702 return;
4703 }
3305306f 4704 incrRefCount(c->argv[1]);
ed9b544e 4705 incrRefCount(o);
4706
4707 /* OK! key moved, free the entry in the source DB */
3305306f 4708 deleteKey(src,c->argv[1]);
ed9b544e 4709 server.dirty++;
c937aa89 4710 addReply(c,shared.cone);
ed9b544e 4711}
4712
4713/* =================================== Lists ================================ */
4714static void pushGenericCommand(redisClient *c, int where) {
4715 robj *lobj;
ed9b544e 4716 list *list;
3305306f 4717
4718 lobj = lookupKeyWrite(c->db,c->argv[1]);
4719 if (lobj == NULL) {
95242ab5 4720 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
520b5a33 4721 addReply(c,shared.cone);
95242ab5 4722 return;
4723 }
ed9b544e 4724 lobj = createListObject();
4725 list = lobj->ptr;
4726 if (where == REDIS_HEAD) {
6b47e12e 4727 listAddNodeHead(list,c->argv[2]);
ed9b544e 4728 } else {
6b47e12e 4729 listAddNodeTail(list,c->argv[2]);
ed9b544e 4730 }
3305306f 4731 dictAdd(c->db->dict,c->argv[1],lobj);
ed9b544e 4732 incrRefCount(c->argv[1]);
4733 incrRefCount(c->argv[2]);
4734 } else {
ed9b544e 4735 if (lobj->type != REDIS_LIST) {
4736 addReply(c,shared.wrongtypeerr);
4737 return;
4738 }
95242ab5 4739 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
520b5a33 4740 addReply(c,shared.cone);
95242ab5 4741 return;
4742 }
ed9b544e 4743 list = lobj->ptr;
4744 if (where == REDIS_HEAD) {
6b47e12e 4745 listAddNodeHead(list,c->argv[2]);
ed9b544e 4746 } else {
6b47e12e 4747 listAddNodeTail(list,c->argv[2]);
ed9b544e 4748 }
4749 incrRefCount(c->argv[2]);
4750 }
4751 server.dirty++;
520b5a33 4752 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",listLength(list)));
ed9b544e 4753}
4754
4755static void lpushCommand(redisClient *c) {
4756 pushGenericCommand(c,REDIS_HEAD);
4757}
4758
4759static void rpushCommand(redisClient *c) {
4760 pushGenericCommand(c,REDIS_TAIL);
4761}
4762
4763static void llenCommand(redisClient *c) {
3305306f 4764 robj *o;
ed9b544e 4765 list *l;
dd88747b 4766
4767 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
4768 checkType(c,o,REDIS_LIST)) return;
e0a62c7f 4769
dd88747b 4770 l = o->ptr;
4771 addReplyUlong(c,listLength(l));
ed9b544e 4772}
4773
4774static void lindexCommand(redisClient *c) {
3305306f 4775 robj *o;
ed9b544e 4776 int index = atoi(c->argv[2]->ptr);
dd88747b 4777 list *list;
4778 listNode *ln;
4779
4780 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4781 checkType(c,o,REDIS_LIST)) return;
4782 list = o->ptr;
4783
4784 ln = listIndex(list, index);
4785 if (ln == NULL) {
c937aa89 4786 addReply(c,shared.nullbulk);
ed9b544e 4787 } else {
dd88747b 4788 robj *ele = listNodeValue(ln);
4789 addReplyBulk(c,ele);
ed9b544e 4790 }
4791}
4792
4793static void lsetCommand(redisClient *c) {
3305306f 4794 robj *o;
ed9b544e 4795 int index = atoi(c->argv[2]->ptr);
dd88747b 4796 list *list;
4797 listNode *ln;
4798
4799 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL ||
4800 checkType(c,o,REDIS_LIST)) return;
4801 list = o->ptr;
4802
4803 ln = listIndex(list, index);
4804 if (ln == NULL) {
4805 addReply(c,shared.outofrangeerr);
ed9b544e 4806 } else {
dd88747b 4807 robj *ele = listNodeValue(ln);
ed9b544e 4808
dd88747b 4809 decrRefCount(ele);
4810 listNodeValue(ln) = c->argv[3];
4811 incrRefCount(c->argv[3]);
4812 addReply(c,shared.ok);
4813 server.dirty++;
ed9b544e 4814 }
4815}
4816
4817static void popGenericCommand(redisClient *c, int where) {
3305306f 4818 robj *o;
dd88747b 4819 list *list;
4820 listNode *ln;
3305306f 4821
dd88747b 4822 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4823 checkType(c,o,REDIS_LIST)) return;
4824 list = o->ptr;
ed9b544e 4825
dd88747b 4826 if (where == REDIS_HEAD)
4827 ln = listFirst(list);
4828 else
4829 ln = listLast(list);
ed9b544e 4830
dd88747b 4831 if (ln == NULL) {
4832 addReply(c,shared.nullbulk);
4833 } else {
4834 robj *ele = listNodeValue(ln);
4835 addReplyBulk(c,ele);
4836 listDelNode(list,ln);
3ea27d37 4837 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 4838 server.dirty++;
ed9b544e 4839 }
4840}
4841
4842static void lpopCommand(redisClient *c) {
4843 popGenericCommand(c,REDIS_HEAD);
4844}
4845
4846static void rpopCommand(redisClient *c) {
4847 popGenericCommand(c,REDIS_TAIL);
4848}
4849
4850static void lrangeCommand(redisClient *c) {
3305306f 4851 robj *o;
ed9b544e 4852 int start = atoi(c->argv[2]->ptr);
4853 int end = atoi(c->argv[3]->ptr);
dd88747b 4854 int llen;
4855 int rangelen, j;
4856 list *list;
4857 listNode *ln;
4858 robj *ele;
4859
4e27f268 4860 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
4861 || checkType(c,o,REDIS_LIST)) return;
dd88747b 4862 list = o->ptr;
4863 llen = listLength(list);
4864
4865 /* convert negative indexes */
4866 if (start < 0) start = llen+start;
4867 if (end < 0) end = llen+end;
4868 if (start < 0) start = 0;
4869 if (end < 0) end = 0;
4870
4871 /* indexes sanity checks */
4872 if (start > end || start >= llen) {
4873 /* Out of range start or start > end result in empty list */
4874 addReply(c,shared.emptymultibulk);
4875 return;
4876 }
4877 if (end >= llen) end = llen-1;
4878 rangelen = (end-start)+1;
3305306f 4879
dd88747b 4880 /* Return the result in form of a multi-bulk reply */
4881 ln = listIndex(list, start);
4882 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
4883 for (j = 0; j < rangelen; j++) {
4884 ele = listNodeValue(ln);
4885 addReplyBulk(c,ele);
4886 ln = ln->next;
ed9b544e 4887 }
4888}
4889
4890static void ltrimCommand(redisClient *c) {
3305306f 4891 robj *o;
ed9b544e 4892 int start = atoi(c->argv[2]->ptr);
4893 int end = atoi(c->argv[3]->ptr);
dd88747b 4894 int llen;
4895 int j, ltrim, rtrim;
4896 list *list;
4897 listNode *ln;
4898
4899 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
4900 checkType(c,o,REDIS_LIST)) return;
4901 list = o->ptr;
4902 llen = listLength(list);
4903
4904 /* convert negative indexes */
4905 if (start < 0) start = llen+start;
4906 if (end < 0) end = llen+end;
4907 if (start < 0) start = 0;
4908 if (end < 0) end = 0;
4909
4910 /* indexes sanity checks */
4911 if (start > end || start >= llen) {
4912 /* Out of range start or start > end result in empty list */
4913 ltrim = llen;
4914 rtrim = 0;
ed9b544e 4915 } else {
dd88747b 4916 if (end >= llen) end = llen-1;
4917 ltrim = start;
4918 rtrim = llen-end-1;
4919 }
ed9b544e 4920
dd88747b 4921 /* Remove list elements to perform the trim */
4922 for (j = 0; j < ltrim; j++) {
4923 ln = listFirst(list);
4924 listDelNode(list,ln);
4925 }
4926 for (j = 0; j < rtrim; j++) {
4927 ln = listLast(list);
4928 listDelNode(list,ln);
ed9b544e 4929 }
3ea27d37 4930 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 4931 server.dirty++;
4932 addReply(c,shared.ok);
ed9b544e 4933}
4934
4935static void lremCommand(redisClient *c) {
3305306f 4936 robj *o;
dd88747b 4937 list *list;
4938 listNode *ln, *next;
4939 int toremove = atoi(c->argv[2]->ptr);
4940 int removed = 0;
4941 int fromtail = 0;
a4d1ba9a 4942
dd88747b 4943 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
4944 checkType(c,o,REDIS_LIST)) return;
4945 list = o->ptr;
4946
4947 if (toremove < 0) {
4948 toremove = -toremove;
4949 fromtail = 1;
4950 }
4951 ln = fromtail ? list->tail : list->head;
4952 while (ln) {
4953 robj *ele = listNodeValue(ln);
4954
4955 next = fromtail ? ln->prev : ln->next;
bf028098 4956 if (equalStringObjects(ele,c->argv[3])) {
dd88747b 4957 listDelNode(list,ln);
4958 server.dirty++;
4959 removed++;
4960 if (toremove && removed == toremove) break;
ed9b544e 4961 }
dd88747b 4962 ln = next;
ed9b544e 4963 }
3ea27d37 4964 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 4965 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
ed9b544e 4966}
4967
12f9d551 4968/* This is the semantic of this command:
0f5f7e9a 4969 * RPOPLPUSH srclist dstlist:
12f9d551 4970 * IF LLEN(srclist) > 0
4971 * element = RPOP srclist
4972 * LPUSH dstlist element
4973 * RETURN element
4974 * ELSE
4975 * RETURN nil
4976 * END
4977 * END
4978 *
4979 * The idea is to be able to get an element from a list in a reliable way
4980 * since the element is not just returned but pushed against another list
4981 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4982 */
0f5f7e9a 4983static void rpoplpushcommand(redisClient *c) {
12f9d551 4984 robj *sobj;
dd88747b 4985 list *srclist;
4986 listNode *ln;
4987
4988 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4989 checkType(c,sobj,REDIS_LIST)) return;
4990 srclist = sobj->ptr;
4991 ln = listLast(srclist);
12f9d551 4992
dd88747b 4993 if (ln == NULL) {
12f9d551 4994 addReply(c,shared.nullbulk);
4995 } else {
dd88747b 4996 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
4997 robj *ele = listNodeValue(ln);
4998 list *dstlist;
e20fb74f 4999
dd88747b 5000 if (dobj && dobj->type != REDIS_LIST) {
5001 addReply(c,shared.wrongtypeerr);
5002 return;
5003 }
12f9d551 5004
dd88747b 5005 /* Add the element to the target list (unless it's directly
5006 * passed to some BLPOP-ing client */
5007 if (!handleClientsWaitingListPush(c,c->argv[2],ele)) {
5008 if (dobj == NULL) {
5009 /* Create the list if the key does not exist */
5010 dobj = createListObject();
5011 dictAdd(c->db->dict,c->argv[2],dobj);
5012 incrRefCount(c->argv[2]);
12f9d551 5013 }
dd88747b 5014 dstlist = dobj->ptr;
5015 listAddNodeHead(dstlist,ele);
5016 incrRefCount(ele);
12f9d551 5017 }
dd88747b 5018
5019 /* Send the element to the client as reply as well */
5020 addReplyBulk(c,ele);
5021
5022 /* Finally remove the element from the source list */
5023 listDelNode(srclist,ln);
3ea27d37 5024 if (listLength(srclist) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5025 server.dirty++;
12f9d551 5026 }
5027}
5028
ed9b544e 5029/* ==================================== Sets ================================ */
5030
5031static void saddCommand(redisClient *c) {
ed9b544e 5032 robj *set;
5033
3305306f 5034 set = lookupKeyWrite(c->db,c->argv[1]);
5035 if (set == NULL) {
ed9b544e 5036 set = createSetObject();
3305306f 5037 dictAdd(c->db->dict,c->argv[1],set);
ed9b544e 5038 incrRefCount(c->argv[1]);
5039 } else {
ed9b544e 5040 if (set->type != REDIS_SET) {
c937aa89 5041 addReply(c,shared.wrongtypeerr);
ed9b544e 5042 return;
5043 }
5044 }
5045 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
5046 incrRefCount(c->argv[2]);
5047 server.dirty++;
c937aa89 5048 addReply(c,shared.cone);
ed9b544e 5049 } else {
c937aa89 5050 addReply(c,shared.czero);
ed9b544e 5051 }
5052}
5053
5054static void sremCommand(redisClient *c) {
3305306f 5055 robj *set;
ed9b544e 5056
dd88747b 5057 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5058 checkType(c,set,REDIS_SET)) return;
5059
5060 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
5061 server.dirty++;
5062 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
3ea27d37 5063 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5064 addReply(c,shared.cone);
ed9b544e 5065 } else {
dd88747b 5066 addReply(c,shared.czero);
ed9b544e 5067 }
5068}
5069
a4460ef4 5070static void smoveCommand(redisClient *c) {
5071 robj *srcset, *dstset;
5072
5073 srcset = lookupKeyWrite(c->db,c->argv[1]);
5074 dstset = lookupKeyWrite(c->db,c->argv[2]);
5075
5076 /* If the source key does not exist return 0, if it's of the wrong type
5077 * raise an error */
5078 if (srcset == NULL || srcset->type != REDIS_SET) {
5079 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
5080 return;
5081 }
5082 /* Error if the destination key is not a set as well */
5083 if (dstset && dstset->type != REDIS_SET) {
5084 addReply(c,shared.wrongtypeerr);
5085 return;
5086 }
5087 /* Remove the element from the source set */
5088 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
5089 /* Key not found in the src set! return zero */
5090 addReply(c,shared.czero);
5091 return;
5092 }
3ea27d37 5093 if (dictSize((dict*)srcset->ptr) == 0 && srcset != dstset)
5094 deleteKey(c->db,c->argv[1]);
a4460ef4 5095 server.dirty++;
5096 /* Add the element to the destination set */
5097 if (!dstset) {
5098 dstset = createSetObject();
5099 dictAdd(c->db->dict,c->argv[2],dstset);
5100 incrRefCount(c->argv[2]);
5101 }
5102 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
5103 incrRefCount(c->argv[3]);
5104 addReply(c,shared.cone);
5105}
5106
ed9b544e 5107static void sismemberCommand(redisClient *c) {
3305306f 5108 robj *set;
ed9b544e 5109
dd88747b 5110 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5111 checkType(c,set,REDIS_SET)) return;
5112
5113 if (dictFind(set->ptr,c->argv[2]))
5114 addReply(c,shared.cone);
5115 else
c937aa89 5116 addReply(c,shared.czero);
ed9b544e 5117}
5118
5119static void scardCommand(redisClient *c) {
3305306f 5120 robj *o;
ed9b544e 5121 dict *s;
dd88747b 5122
5123 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5124 checkType(c,o,REDIS_SET)) return;
e0a62c7f 5125
dd88747b 5126 s = o->ptr;
5127 addReplyUlong(c,dictSize(s));
ed9b544e 5128}
5129
12fea928 5130static void spopCommand(redisClient *c) {
5131 robj *set;
5132 dictEntry *de;
5133
dd88747b 5134 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5135 checkType(c,set,REDIS_SET)) return;
5136
5137 de = dictGetRandomKey(set->ptr);
5138 if (de == NULL) {
12fea928 5139 addReply(c,shared.nullbulk);
5140 } else {
dd88747b 5141 robj *ele = dictGetEntryKey(de);
12fea928 5142
dd88747b 5143 addReplyBulk(c,ele);
5144 dictDelete(set->ptr,ele);
5145 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
3ea27d37 5146 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5147 server.dirty++;
12fea928 5148 }
5149}
5150
2abb95a9 5151static void srandmemberCommand(redisClient *c) {
5152 robj *set;
5153 dictEntry *de;
5154
dd88747b 5155 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5156 checkType(c,set,REDIS_SET)) return;
5157
5158 de = dictGetRandomKey(set->ptr);
5159 if (de == NULL) {
2abb95a9 5160 addReply(c,shared.nullbulk);
5161 } else {
dd88747b 5162 robj *ele = dictGetEntryKey(de);
2abb95a9 5163
dd88747b 5164 addReplyBulk(c,ele);
2abb95a9 5165 }
5166}
5167
ed9b544e 5168static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
5169 dict **d1 = (void*) s1, **d2 = (void*) s2;
5170
3305306f 5171 return dictSize(*d1)-dictSize(*d2);
ed9b544e 5172}
5173
682ac724 5174static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
ed9b544e 5175 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5176 dictIterator *di;
5177 dictEntry *de;
5178 robj *lenobj = NULL, *dstset = NULL;
682ac724 5179 unsigned long j, cardinality = 0;
ed9b544e 5180
ed9b544e 5181 for (j = 0; j < setsnum; j++) {
5182 robj *setobj;
3305306f 5183
5184 setobj = dstkey ?
5185 lookupKeyWrite(c->db,setskeys[j]) :
5186 lookupKeyRead(c->db,setskeys[j]);
5187 if (!setobj) {
ed9b544e 5188 zfree(dv);
5faa6025 5189 if (dstkey) {
fdcaae84 5190 if (deleteKey(c->db,dstkey))
5191 server.dirty++;
0d36ded0 5192 addReply(c,shared.czero);
5faa6025 5193 } else {
4e27f268 5194 addReply(c,shared.emptymultibulk);
5faa6025 5195 }
ed9b544e 5196 return;
5197 }
ed9b544e 5198 if (setobj->type != REDIS_SET) {
5199 zfree(dv);
c937aa89 5200 addReply(c,shared.wrongtypeerr);
ed9b544e 5201 return;
5202 }
5203 dv[j] = setobj->ptr;
5204 }
5205 /* Sort sets from the smallest to largest, this will improve our
5206 * algorithm's performace */
5207 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
5208
5209 /* The first thing we should output is the total number of elements...
5210 * since this is a multi-bulk write, but at this stage we don't know
5211 * the intersection set size, so we use a trick, append an empty object
5212 * to the output list and save the pointer to later modify it with the
5213 * right length */
5214 if (!dstkey) {
5215 lenobj = createObject(REDIS_STRING,NULL);
5216 addReply(c,lenobj);
5217 decrRefCount(lenobj);
5218 } else {
5219 /* If we have a target key where to store the resulting set
5220 * create this key with an empty set inside */
5221 dstset = createSetObject();
ed9b544e 5222 }
5223
5224 /* Iterate all the elements of the first (smallest) set, and test
5225 * the element against all the other sets, if at least one set does
5226 * not include the element it is discarded */
5227 di = dictGetIterator(dv[0]);
ed9b544e 5228
5229 while((de = dictNext(di)) != NULL) {
5230 robj *ele;
5231
5232 for (j = 1; j < setsnum; j++)
5233 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
5234 if (j != setsnum)
5235 continue; /* at least one set does not contain the member */
5236 ele = dictGetEntryKey(de);
5237 if (!dstkey) {
dd88747b 5238 addReplyBulk(c,ele);
ed9b544e 5239 cardinality++;
5240 } else {
5241 dictAdd(dstset->ptr,ele,NULL);
5242 incrRefCount(ele);
5243 }
5244 }
5245 dictReleaseIterator(di);
5246
83cdfe18 5247 if (dstkey) {
3ea27d37 5248 /* Store the resulting set into the target, if the intersection
5249 * is not an empty set. */
83cdfe18 5250 deleteKey(c->db,dstkey);
3ea27d37 5251 if (dictSize((dict*)dstset->ptr) > 0) {
5252 dictAdd(c->db->dict,dstkey,dstset);
5253 incrRefCount(dstkey);
d36c4e97 5254 addReplyLong(c,dictSize((dict*)dstset->ptr));
3ea27d37 5255 } else {
5256 decrRefCount(dstset);
d36c4e97 5257 addReply(c,shared.czero);
3ea27d37 5258 }
40d224a9 5259 server.dirty++;
d36c4e97 5260 } else {
5261 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
40d224a9 5262 }
ed9b544e 5263 zfree(dv);
5264}
5265
5266static void sinterCommand(redisClient *c) {
5267 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
5268}
5269
5270static void sinterstoreCommand(redisClient *c) {
5271 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
5272}
5273
f4f56e1d 5274#define REDIS_OP_UNION 0
5275#define REDIS_OP_DIFF 1
2830ca53 5276#define REDIS_OP_INTER 2
f4f56e1d 5277
5278static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
40d224a9 5279 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5280 dictIterator *di;
5281 dictEntry *de;
f4f56e1d 5282 robj *dstset = NULL;
40d224a9 5283 int j, cardinality = 0;
5284
40d224a9 5285 for (j = 0; j < setsnum; j++) {
5286 robj *setobj;
5287
5288 setobj = dstkey ?
5289 lookupKeyWrite(c->db,setskeys[j]) :
5290 lookupKeyRead(c->db,setskeys[j]);
5291 if (!setobj) {
5292 dv[j] = NULL;
5293 continue;
5294 }
5295 if (setobj->type != REDIS_SET) {
5296 zfree(dv);
5297 addReply(c,shared.wrongtypeerr);
5298 return;
5299 }
5300 dv[j] = setobj->ptr;
5301 }
5302
5303 /* We need a temp set object to store our union. If the dstkey
5304 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5305 * this set object will be the resulting object to set into the target key*/
5306 dstset = createSetObject();
5307
40d224a9 5308 /* Iterate all the elements of all the sets, add every element a single
5309 * time to the result set */
5310 for (j = 0; j < setsnum; j++) {
51829ed3 5311 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
40d224a9 5312 if (!dv[j]) continue; /* non existing keys are like empty sets */
5313
5314 di = dictGetIterator(dv[j]);
40d224a9 5315
5316 while((de = dictNext(di)) != NULL) {
5317 robj *ele;
5318
5319 /* dictAdd will not add the same element multiple times */
5320 ele = dictGetEntryKey(de);
f4f56e1d 5321 if (op == REDIS_OP_UNION || j == 0) {
5322 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
5323 incrRefCount(ele);
40d224a9 5324 cardinality++;
5325 }
f4f56e1d 5326 } else if (op == REDIS_OP_DIFF) {
5327 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
5328 cardinality--;
5329 }
40d224a9 5330 }
5331 }
5332 dictReleaseIterator(di);
51829ed3 5333
d36c4e97 5334 /* result set is empty? Exit asap. */
5335 if (op == REDIS_OP_DIFF && cardinality == 0) break;
40d224a9 5336 }
5337
f4f56e1d 5338 /* Output the content of the resulting set, if not in STORE mode */
5339 if (!dstkey) {
5340 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
5341 di = dictGetIterator(dstset->ptr);
f4f56e1d 5342 while((de = dictNext(di)) != NULL) {
5343 robj *ele;
5344
5345 ele = dictGetEntryKey(de);
dd88747b 5346 addReplyBulk(c,ele);
f4f56e1d 5347 }
5348 dictReleaseIterator(di);
d36c4e97 5349 decrRefCount(dstset);
83cdfe18
AG
5350 } else {
5351 /* If we have a target key where to store the resulting set
5352 * create this key with the result set inside */
5353 deleteKey(c->db,dstkey);
3ea27d37 5354 if (dictSize((dict*)dstset->ptr) > 0) {
5355 dictAdd(c->db->dict,dstkey,dstset);
5356 incrRefCount(dstkey);
d36c4e97 5357 addReplyLong(c,dictSize((dict*)dstset->ptr));
3ea27d37 5358 } else {
5359 decrRefCount(dstset);
d36c4e97 5360 addReply(c,shared.czero);
3ea27d37 5361 }
40d224a9 5362 server.dirty++;
5363 }
5364 zfree(dv);
5365}
5366
5367static void sunionCommand(redisClient *c) {
f4f56e1d 5368 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
40d224a9 5369}
5370
5371static void sunionstoreCommand(redisClient *c) {
f4f56e1d 5372 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
5373}
5374
5375static void sdiffCommand(redisClient *c) {
5376 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
5377}
5378
5379static void sdiffstoreCommand(redisClient *c) {
5380 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
40d224a9 5381}
5382
6b47e12e 5383/* ==================================== ZSets =============================== */
5384
5385/* ZSETs are ordered sets using two data structures to hold the same elements
5386 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5387 * data structure.
5388 *
5389 * The elements are added to an hash table mapping Redis objects to scores.
5390 * At the same time the elements are added to a skip list mapping scores
5391 * to Redis objects (so objects are sorted by scores in this "view"). */
5392
5393/* This skiplist implementation is almost a C translation of the original
5394 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5395 * Alternative to Balanced Trees", modified in three ways:
5396 * a) this implementation allows for repeated values.
5397 * b) the comparison is not just by key (our 'score') but by satellite data.
5398 * c) there is a back pointer, so it's a doubly linked list with the back
5399 * pointers being only at "level 1". This allows to traverse the list
5400 * from tail to head, useful for ZREVRANGE. */
5401
5402static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
5403 zskiplistNode *zn = zmalloc(sizeof(*zn));
5404
5405 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
2b37892e
PN
5406 if (level > 0)
5407 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
6b47e12e 5408 zn->score = score;
5409 zn->obj = obj;
5410 return zn;
5411}
5412
5413static zskiplist *zslCreate(void) {
5414 int j;
5415 zskiplist *zsl;
e0a62c7f 5416
6b47e12e 5417 zsl = zmalloc(sizeof(*zsl));
5418 zsl->level = 1;
cc812361 5419 zsl->length = 0;
6b47e12e 5420 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
69d95c3e 5421 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
6b47e12e 5422 zsl->header->forward[j] = NULL;
94e543b5 5423
5424 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5425 if (j < ZSKIPLIST_MAXLEVEL-1)
5426 zsl->header->span[j] = 0;
69d95c3e 5427 }
e3870fab 5428 zsl->header->backward = NULL;
5429 zsl->tail = NULL;
6b47e12e 5430 return zsl;
5431}
5432
fd8ccf44 5433static void zslFreeNode(zskiplistNode *node) {
5434 decrRefCount(node->obj);
ad807e6f 5435 zfree(node->forward);
69d95c3e 5436 zfree(node->span);
fd8ccf44 5437 zfree(node);
5438}
5439
5440static void zslFree(zskiplist *zsl) {
ad807e6f 5441 zskiplistNode *node = zsl->header->forward[0], *next;
fd8ccf44 5442
ad807e6f 5443 zfree(zsl->header->forward);
69d95c3e 5444 zfree(zsl->header->span);
ad807e6f 5445 zfree(zsl->header);
fd8ccf44 5446 while(node) {
599379dd 5447 next = node->forward[0];
fd8ccf44 5448 zslFreeNode(node);
5449 node = next;
5450 }
ad807e6f 5451 zfree(zsl);
fd8ccf44 5452}
5453
6b47e12e 5454static int zslRandomLevel(void) {
5455 int level = 1;
5456 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
5457 level += 1;
10c2baa5 5458 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
6b47e12e 5459}
5460
5461static void zslInsert(zskiplist *zsl, double score, robj *obj) {
5462 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
2b37892e 5463 unsigned int rank[ZSKIPLIST_MAXLEVEL];
6b47e12e 5464 int i, level;
5465
5466 x = zsl->header;
5467 for (i = zsl->level-1; i >= 0; i--) {
2b37892e
PN
5468 /* store rank that is crossed to reach the insert position */
5469 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
69d95c3e 5470
9d60e6e4 5471 while (x->forward[i] &&
5472 (x->forward[i]->score < score ||
5473 (x->forward[i]->score == score &&
69d95c3e 5474 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
a50ea45c 5475 rank[i] += i > 0 ? x->span[i-1] : 1;
6b47e12e 5476 x = x->forward[i];
69d95c3e 5477 }
6b47e12e 5478 update[i] = x;
5479 }
6b47e12e 5480 /* we assume the key is not already inside, since we allow duplicated
5481 * scores, and the re-insertion of score and redis object should never
5482 * happpen since the caller of zslInsert() should test in the hash table
5483 * if the element is already inside or not. */
5484 level = zslRandomLevel();
5485 if (level > zsl->level) {
69d95c3e 5486 for (i = zsl->level; i < level; i++) {
2b37892e 5487 rank[i] = 0;
6b47e12e 5488 update[i] = zsl->header;
2b37892e 5489 update[i]->span[i-1] = zsl->length;
69d95c3e 5490 }
6b47e12e 5491 zsl->level = level;
5492 }
5493 x = zslCreateNode(level,score,obj);
5494 for (i = 0; i < level; i++) {
5495 x->forward[i] = update[i]->forward[i];
5496 update[i]->forward[i] = x;
69d95c3e
PN
5497
5498 /* update span covered by update[i] as x is inserted here */
2b37892e
PN
5499 if (i > 0) {
5500 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
5501 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
5502 }
6b47e12e 5503 }
69d95c3e
PN
5504
5505 /* increment span for untouched levels */
5506 for (i = level; i < zsl->level; i++) {
2b37892e 5507 update[i]->span[i-1]++;
69d95c3e
PN
5508 }
5509
bb975144 5510 x->backward = (update[0] == zsl->header) ? NULL : update[0];
e3870fab 5511 if (x->forward[0])
5512 x->forward[0]->backward = x;
5513 else
5514 zsl->tail = x;
cc812361 5515 zsl->length++;
6b47e12e 5516}
5517
84105336
PN
5518/* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5519void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
5520 int i;
5521 for (i = 0; i < zsl->level; i++) {
5522 if (update[i]->forward[i] == x) {
5523 if (i > 0) {
5524 update[i]->span[i-1] += x->span[i-1] - 1;
5525 }
5526 update[i]->forward[i] = x->forward[i];
5527 } else {
5528 /* invariant: i > 0, because update[0]->forward[0]
5529 * is always equal to x */
5530 update[i]->span[i-1] -= 1;
5531 }
5532 }
5533 if (x->forward[0]) {
5534 x->forward[0]->backward = x->backward;
5535 } else {
5536 zsl->tail = x->backward;
5537 }
5538 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
5539 zsl->level--;
5540 zsl->length--;
5541}
5542
50c55df5 5543/* Delete an element with matching score/object from the skiplist. */
fd8ccf44 5544static int zslDelete(zskiplist *zsl, double score, robj *obj) {
e197b441 5545 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5546 int i;
5547
5548 x = zsl->header;
5549 for (i = zsl->level-1; i >= 0; i--) {
9d60e6e4 5550 while (x->forward[i] &&
5551 (x->forward[i]->score < score ||
5552 (x->forward[i]->score == score &&
5553 compareStringObjects(x->forward[i]->obj,obj) < 0)))
e197b441 5554 x = x->forward[i];
5555 update[i] = x;
5556 }
5557 /* We may have multiple elements with the same score, what we need
5558 * is to find the element with both the right score and object. */
5559 x = x->forward[0];
bf028098 5560 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
84105336 5561 zslDeleteNode(zsl, x, update);
9d60e6e4 5562 zslFreeNode(x);
9d60e6e4 5563 return 1;
5564 } else {
5565 return 0; /* not found */
e197b441 5566 }
5567 return 0; /* not found */
fd8ccf44 5568}
5569
1807985b 5570/* Delete all the elements with score between min and max from the skiplist.
5571 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5572 * Note that this function takes the reference to the hash table view of the
5573 * sorted set, in order to remove the elements from the hash table too. */
f84d3933 5574static unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
1807985b 5575 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5576 unsigned long removed = 0;
5577 int i;
5578
5579 x = zsl->header;
5580 for (i = zsl->level-1; i >= 0; i--) {
5581 while (x->forward[i] && x->forward[i]->score < min)
5582 x = x->forward[i];
5583 update[i] = x;
5584 }
5585 /* We may have multiple elements with the same score, what we need
5586 * is to find the element with both the right score and object. */
5587 x = x->forward[0];
5588 while (x && x->score <= max) {
84105336
PN
5589 zskiplistNode *next = x->forward[0];
5590 zslDeleteNode(zsl, x, update);
1807985b 5591 dictDelete(dict,x->obj);
5592 zslFreeNode(x);
1807985b 5593 removed++;
5594 x = next;
5595 }
5596 return removed; /* not found */
5597}
1807985b 5598
9212eafd 5599/* Delete all the elements with rank between start and end from the skiplist.
2424490f 5600 * Start and end are inclusive. Note that start and end need to be 1-based */
9212eafd
PN
5601static unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
5602 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5603 unsigned long traversed = 0, removed = 0;
5604 int i;
5605
9212eafd
PN
5606 x = zsl->header;
5607 for (i = zsl->level-1; i >= 0; i--) {
5608 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
5609 traversed += i > 0 ? x->span[i-1] : 1;
5610 x = x->forward[i];
1807985b 5611 }
9212eafd
PN
5612 update[i] = x;
5613 }
5614
5615 traversed++;
5616 x = x->forward[0];
5617 while (x && traversed <= end) {
84105336
PN
5618 zskiplistNode *next = x->forward[0];
5619 zslDeleteNode(zsl, x, update);
1807985b 5620 dictDelete(dict,x->obj);
5621 zslFreeNode(x);
1807985b 5622 removed++;
9212eafd 5623 traversed++;
1807985b 5624 x = next;
5625 }
9212eafd 5626 return removed;
1807985b 5627}
5628
50c55df5 5629/* Find the first node having a score equal or greater than the specified one.
5630 * Returns NULL if there is no match. */
5631static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
5632 zskiplistNode *x;
5633 int i;
5634
5635 x = zsl->header;
5636 for (i = zsl->level-1; i >= 0; i--) {
5637 while (x->forward[i] && x->forward[i]->score < score)
5638 x = x->forward[i];
5639 }
5640 /* We may have multiple elements with the same score, what we need
5641 * is to find the element with both the right score and object. */
5642 return x->forward[0];
5643}
5644
27b0ccca
PN
5645/* Find the rank for an element by both score and key.
5646 * Returns 0 when the element cannot be found, rank otherwise.
5647 * Note that the rank is 1-based due to the span of zsl->header to the
5648 * first element. */
5649static unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
5650 zskiplistNode *x;
5651 unsigned long rank = 0;
5652 int i;
5653
5654 x = zsl->header;
5655 for (i = zsl->level-1; i >= 0; i--) {
5656 while (x->forward[i] &&
5657 (x->forward[i]->score < score ||
5658 (x->forward[i]->score == score &&
5659 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
a50ea45c 5660 rank += i > 0 ? x->span[i-1] : 1;
27b0ccca
PN
5661 x = x->forward[i];
5662 }
5663
5664 /* x might be equal to zsl->header, so test if obj is non-NULL */
bf028098 5665 if (x->obj && equalStringObjects(x->obj,o)) {
27b0ccca
PN
5666 return rank;
5667 }
5668 }
5669 return 0;
5670}
5671
e74825c2
PN
5672/* Finds an element by its rank. The rank argument needs to be 1-based. */
5673zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
5674 zskiplistNode *x;
5675 unsigned long traversed = 0;
5676 int i;
5677
5678 x = zsl->header;
5679 for (i = zsl->level-1; i >= 0; i--) {
dd88747b 5680 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
5681 {
a50ea45c 5682 traversed += i > 0 ? x->span[i-1] : 1;
e74825c2
PN
5683 x = x->forward[i];
5684 }
e74825c2
PN
5685 if (traversed == rank) {
5686 return x;
5687 }
5688 }
5689 return NULL;
5690}
5691
fd8ccf44 5692/* The actual Z-commands implementations */
5693
7db723ad 5694/* This generic command implements both ZADD and ZINCRBY.
e2665397 5695 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
7db723ad 5696 * the increment if the operation is a ZINCRBY (doincrement == 1). */
e2665397 5697static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
fd8ccf44 5698 robj *zsetobj;
5699 zset *zs;
5700 double *score;
5701
e2665397 5702 zsetobj = lookupKeyWrite(c->db,key);
fd8ccf44 5703 if (zsetobj == NULL) {
5704 zsetobj = createZsetObject();
e2665397 5705 dictAdd(c->db->dict,key,zsetobj);
5706 incrRefCount(key);
fd8ccf44 5707 } else {
5708 if (zsetobj->type != REDIS_ZSET) {
5709 addReply(c,shared.wrongtypeerr);
5710 return;
5711 }
5712 }
fd8ccf44 5713 zs = zsetobj->ptr;
e2665397 5714
7db723ad 5715 /* Ok now since we implement both ZADD and ZINCRBY here the code
e2665397 5716 * needs to handle the two different conditions. It's all about setting
5717 * '*score', that is, the new score to set, to the right value. */
5718 score = zmalloc(sizeof(double));
5719 if (doincrement) {
5720 dictEntry *de;
5721
5722 /* Read the old score. If the element was not present starts from 0 */
5723 de = dictFind(zs->dict,ele);
5724 if (de) {
5725 double *oldscore = dictGetEntryVal(de);
5726 *score = *oldscore + scoreval;
5727 } else {
5728 *score = scoreval;
5729 }
5730 } else {
5731 *score = scoreval;
5732 }
5733
5734 /* What follows is a simple remove and re-insert operation that is common
7db723ad 5735 * to both ZADD and ZINCRBY... */
e2665397 5736 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
fd8ccf44 5737 /* case 1: New element */
e2665397 5738 incrRefCount(ele); /* added to hash */
5739 zslInsert(zs->zsl,*score,ele);
5740 incrRefCount(ele); /* added to skiplist */
fd8ccf44 5741 server.dirty++;
e2665397 5742 if (doincrement)
e2665397 5743 addReplyDouble(c,*score);
91d71bfc 5744 else
5745 addReply(c,shared.cone);
fd8ccf44 5746 } else {
5747 dictEntry *de;
5748 double *oldscore;
e0a62c7f 5749
fd8ccf44 5750 /* case 2: Score update operation */
e2665397 5751 de = dictFind(zs->dict,ele);
dfc5e96c 5752 redisAssert(de != NULL);
fd8ccf44 5753 oldscore = dictGetEntryVal(de);
5754 if (*score != *oldscore) {
5755 int deleted;
5756
e2665397 5757 /* Remove and insert the element in the skip list with new score */
5758 deleted = zslDelete(zs->zsl,*oldscore,ele);
dfc5e96c 5759 redisAssert(deleted != 0);
e2665397 5760 zslInsert(zs->zsl,*score,ele);
5761 incrRefCount(ele);
5762 /* Update the score in the hash table */
5763 dictReplace(zs->dict,ele,score);
fd8ccf44 5764 server.dirty++;
2161a965 5765 } else {
5766 zfree(score);
fd8ccf44 5767 }
e2665397 5768 if (doincrement)
5769 addReplyDouble(c,*score);
5770 else
5771 addReply(c,shared.czero);
fd8ccf44 5772 }
5773}
5774
e2665397 5775static void zaddCommand(redisClient *c) {
5776 double scoreval;
5777
bd79a6bd 5778 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
e2665397 5779 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
5780}
5781
7db723ad 5782static void zincrbyCommand(redisClient *c) {
e2665397 5783 double scoreval;
5784
bd79a6bd 5785 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
e2665397 5786 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
5787}
5788
1b7106e7 5789static void zremCommand(redisClient *c) {
5790 robj *zsetobj;
5791 zset *zs;
dd88747b 5792 dictEntry *de;
5793 double *oldscore;
5794 int deleted;
1b7106e7 5795
dd88747b 5796 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5797 checkType(c,zsetobj,REDIS_ZSET)) return;
1b7106e7 5798
dd88747b 5799 zs = zsetobj->ptr;
5800 de = dictFind(zs->dict,c->argv[2]);
5801 if (de == NULL) {
5802 addReply(c,shared.czero);
5803 return;
1b7106e7 5804 }
dd88747b 5805 /* Delete from the skiplist */
5806 oldscore = dictGetEntryVal(de);
5807 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
5808 redisAssert(deleted != 0);
5809
5810 /* Delete from the hash table */
5811 dictDelete(zs->dict,c->argv[2]);
5812 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
3ea27d37 5813 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5814 server.dirty++;
5815 addReply(c,shared.cone);
1b7106e7 5816}
5817
1807985b 5818static void zremrangebyscoreCommand(redisClient *c) {
bbe025e0
AM
5819 double min;
5820 double max;
dd88747b 5821 long deleted;
1807985b 5822 robj *zsetobj;
5823 zset *zs;
5824
bd79a6bd
PN
5825 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
5826 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
bbe025e0 5827
dd88747b 5828 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5829 checkType(c,zsetobj,REDIS_ZSET)) return;
1807985b 5830
dd88747b 5831 zs = zsetobj->ptr;
5832 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
5833 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
3ea27d37 5834 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5835 server.dirty += deleted;
5836 addReplyLong(c,deleted);
1807985b 5837}
5838
9212eafd 5839static void zremrangebyrankCommand(redisClient *c) {
bbe025e0
AM
5840 long start;
5841 long end;
dd88747b 5842 int llen;
5843 long deleted;
9212eafd
PN
5844 robj *zsetobj;
5845 zset *zs;
5846
bd79a6bd
PN
5847 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
5848 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
bbe025e0 5849
dd88747b 5850 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5851 checkType(c,zsetobj,REDIS_ZSET)) return;
5852 zs = zsetobj->ptr;
5853 llen = zs->zsl->length;
9212eafd 5854
dd88747b 5855 /* convert negative indexes */
5856 if (start < 0) start = llen+start;
5857 if (end < 0) end = llen+end;
5858 if (start < 0) start = 0;
5859 if (end < 0) end = 0;
9212eafd 5860
dd88747b 5861 /* indexes sanity checks */
5862 if (start > end || start >= llen) {
5863 addReply(c,shared.czero);
5864 return;
9212eafd 5865 }
dd88747b 5866 if (end >= llen) end = llen-1;
5867
5868 /* increment start and end because zsl*Rank functions
5869 * use 1-based rank */
5870 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
5871 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
3ea27d37 5872 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5873 server.dirty += deleted;
5874 addReplyLong(c, deleted);
9212eafd
PN
5875}
5876
8f92e768
PN
5877typedef struct {
5878 dict *dict;
5879 double weight;
5880} zsetopsrc;
5881
5882static int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
5883 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
5884 unsigned long size1, size2;
5885 size1 = d1->dict ? dictSize(d1->dict) : 0;
5886 size2 = d2->dict ? dictSize(d2->dict) : 0;
5887 return size1 - size2;
5888}
5889
d2764cd6
PN
5890#define REDIS_AGGR_SUM 1
5891#define REDIS_AGGR_MIN 2
5892#define REDIS_AGGR_MAX 3
5893
5894inline static void zunionInterAggregate(double *target, double val, int aggregate) {
5895 if (aggregate == REDIS_AGGR_SUM) {
5896 *target = *target + val;
5897 } else if (aggregate == REDIS_AGGR_MIN) {
5898 *target = val < *target ? val : *target;
5899 } else if (aggregate == REDIS_AGGR_MAX) {
5900 *target = val > *target ? val : *target;
5901 } else {
5902 /* safety net */
f83c6cb5 5903 redisPanic("Unknown ZUNION/INTER aggregate type");
d2764cd6
PN
5904 }
5905}
5906
2830ca53 5907static void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
8f92e768 5908 int i, j, zsetnum;
d2764cd6 5909 int aggregate = REDIS_AGGR_SUM;
8f92e768 5910 zsetopsrc *src;
2830ca53
PN
5911 robj *dstobj;
5912 zset *dstzset;
b287c9bb
PN
5913 dictIterator *di;
5914 dictEntry *de;
5915
2830ca53
PN
5916 /* expect zsetnum input keys to be given */
5917 zsetnum = atoi(c->argv[2]->ptr);
5918 if (zsetnum < 1) {
5919 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNION/ZINTER\r\n"));
5920 return;
b287c9bb 5921 }
2830ca53
PN
5922
5923 /* test if the expected number of keys would overflow */
5924 if (3+zsetnum > c->argc) {
b287c9bb
PN
5925 addReply(c,shared.syntaxerr);
5926 return;
5927 }
5928
2830ca53 5929 /* read keys to be used for input */
b9eed483 5930 src = zmalloc(sizeof(zsetopsrc) * zsetnum);
2830ca53 5931 for (i = 0, j = 3; i < zsetnum; i++, j++) {
b287c9bb
PN
5932 robj *zsetobj = lookupKeyWrite(c->db,c->argv[j]);
5933 if (!zsetobj) {
8f92e768 5934 src[i].dict = NULL;
b287c9bb
PN
5935 } else {
5936 if (zsetobj->type != REDIS_ZSET) {
8f92e768 5937 zfree(src);
b287c9bb
PN
5938 addReply(c,shared.wrongtypeerr);
5939 return;
5940 }
8f92e768 5941 src[i].dict = ((zset*)zsetobj->ptr)->dict;
b287c9bb 5942 }
2830ca53
PN
5943
5944 /* default all weights to 1 */
8f92e768 5945 src[i].weight = 1.0;
b287c9bb
PN
5946 }
5947
2830ca53
PN
5948 /* parse optional extra arguments */
5949 if (j < c->argc) {
d2764cd6 5950 int remaining = c->argc - j;
b287c9bb 5951
2830ca53 5952 while (remaining) {
d2764cd6 5953 if (remaining >= (zsetnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
2830ca53 5954 j++; remaining--;
2830ca53 5955 for (i = 0; i < zsetnum; i++, j++, remaining--) {
bd79a6bd 5956 if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK)
bbe025e0 5957 return;
2830ca53 5958 }
d2764cd6
PN
5959 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
5960 j++; remaining--;
5961 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
5962 aggregate = REDIS_AGGR_SUM;
5963 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
5964 aggregate = REDIS_AGGR_MIN;
5965 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
5966 aggregate = REDIS_AGGR_MAX;
5967 } else {
5968 zfree(src);
5969 addReply(c,shared.syntaxerr);
5970 return;
5971 }
5972 j++; remaining--;
2830ca53 5973 } else {
8f92e768 5974 zfree(src);
2830ca53
PN
5975 addReply(c,shared.syntaxerr);
5976 return;
5977 }
5978 }
5979 }
b287c9bb 5980
d2764cd6
PN
5981 /* sort sets from the smallest to largest, this will improve our
5982 * algorithm's performance */
5983 qsort(src,zsetnum,sizeof(zsetopsrc), qsortCompareZsetopsrcByCardinality);
5984
2830ca53
PN
5985 dstobj = createZsetObject();
5986 dstzset = dstobj->ptr;
5987
5988 if (op == REDIS_OP_INTER) {
8f92e768
PN
5989 /* skip going over all entries if the smallest zset is NULL or empty */
5990 if (src[0].dict && dictSize(src[0].dict) > 0) {
5991 /* precondition: as src[0].dict is non-empty and the zsets are ordered
5992 * from small to large, all src[i > 0].dict are non-empty too */
5993 di = dictGetIterator(src[0].dict);
2830ca53 5994 while((de = dictNext(di)) != NULL) {
d2764cd6
PN
5995 double *score = zmalloc(sizeof(double)), value;
5996 *score = src[0].weight * (*(double*)dictGetEntryVal(de));
2830ca53 5997
d2764cd6
PN
5998 for (j = 1; j < zsetnum; j++) {
5999 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
2830ca53 6000 if (other) {
d2764cd6
PN
6001 value = src[j].weight * (*(double*)dictGetEntryVal(other));
6002 zunionInterAggregate(score, value, aggregate);
2830ca53
PN
6003 } else {
6004 break;
6005 }
6006 }
b287c9bb 6007
2830ca53 6008 /* skip entry when not present in every source dict */
8f92e768 6009 if (j != zsetnum) {
2830ca53
PN
6010 zfree(score);
6011 } else {
6012 robj *o = dictGetEntryKey(de);
6013 dictAdd(dstzset->dict,o,score);
6014 incrRefCount(o); /* added to dictionary */
6015 zslInsert(dstzset->zsl,*score,o);
6016 incrRefCount(o); /* added to skiplist */
b287c9bb
PN
6017 }
6018 }
2830ca53
PN
6019 dictReleaseIterator(di);
6020 }
6021 } else if (op == REDIS_OP_UNION) {
6022 for (i = 0; i < zsetnum; i++) {
8f92e768 6023 if (!src[i].dict) continue;
2830ca53 6024
8f92e768 6025 di = dictGetIterator(src[i].dict);
2830ca53
PN
6026 while((de = dictNext(di)) != NULL) {
6027 /* skip key when already processed */
6028 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
6029
d2764cd6
PN
6030 double *score = zmalloc(sizeof(double)), value;
6031 *score = src[i].weight * (*(double*)dictGetEntryVal(de));
2830ca53 6032
d2764cd6
PN
6033 /* because the zsets are sorted by size, its only possible
6034 * for sets at larger indices to hold this entry */
6035 for (j = (i+1); j < zsetnum; j++) {
6036 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
2830ca53 6037 if (other) {
d2764cd6
PN
6038 value = src[j].weight * (*(double*)dictGetEntryVal(other));
6039 zunionInterAggregate(score, value, aggregate);
2830ca53
PN
6040 }
6041 }
b287c9bb 6042
2830ca53
PN
6043 robj *o = dictGetEntryKey(de);
6044 dictAdd(dstzset->dict,o,score);
6045 incrRefCount(o); /* added to dictionary */
6046 zslInsert(dstzset->zsl,*score,o);
6047 incrRefCount(o); /* added to skiplist */
6048 }
6049 dictReleaseIterator(di);
b287c9bb 6050 }
2830ca53
PN
6051 } else {
6052 /* unknown operator */
6053 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
b287c9bb
PN
6054 }
6055
6056 deleteKey(c->db,dstkey);
3ea27d37 6057 if (dstzset->zsl->length) {
6058 dictAdd(c->db->dict,dstkey,dstobj);
6059 incrRefCount(dstkey);
6060 addReplyLong(c, dstzset->zsl->length);
6061 server.dirty++;
6062 } else {
8bca8773 6063 decrRefCount(dstobj);
3ea27d37 6064 addReply(c, shared.czero);
6065 }
8f92e768 6066 zfree(src);
b287c9bb
PN
6067}
6068
2830ca53
PN
6069static void zunionCommand(redisClient *c) {
6070 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
b287c9bb
PN
6071}
6072
2830ca53
PN
6073static void zinterCommand(redisClient *c) {
6074 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
b287c9bb
PN
6075}
6076
e3870fab 6077static void zrangeGenericCommand(redisClient *c, int reverse) {
cc812361 6078 robj *o;
bbe025e0
AM
6079 long start;
6080 long end;
752da584 6081 int withscores = 0;
dd88747b 6082 int llen;
6083 int rangelen, j;
6084 zset *zsetobj;
6085 zskiplist *zsl;
6086 zskiplistNode *ln;
6087 robj *ele;
752da584 6088
bd79a6bd
PN
6089 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6090 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
bbe025e0 6091
752da584 6092 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
6093 withscores = 1;
6094 } else if (c->argc >= 5) {
6095 addReply(c,shared.syntaxerr);
6096 return;
6097 }
cc812361 6098
4e27f268 6099 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6100 || checkType(c,o,REDIS_ZSET)) return;
dd88747b 6101 zsetobj = o->ptr;
6102 zsl = zsetobj->zsl;
6103 llen = zsl->length;
cc812361 6104
dd88747b 6105 /* convert negative indexes */
6106 if (start < 0) start = llen+start;
6107 if (end < 0) end = llen+end;
6108 if (start < 0) start = 0;
6109 if (end < 0) end = 0;
cc812361 6110
dd88747b 6111 /* indexes sanity checks */
6112 if (start > end || start >= llen) {
6113 /* Out of range start or start > end result in empty list */
6114 addReply(c,shared.emptymultibulk);
6115 return;
6116 }
6117 if (end >= llen) end = llen-1;
6118 rangelen = (end-start)+1;
cc812361 6119
dd88747b 6120 /* check if starting point is trivial, before searching
6121 * the element in log(N) time */
6122 if (reverse) {
6123 ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start);
6124 } else {
6125 ln = start == 0 ?
6126 zsl->header->forward[0] : zslGetElementByRank(zsl, start+1);
6127 }
cc812361 6128
dd88747b 6129 /* Return the result in form of a multi-bulk reply */
6130 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
6131 withscores ? (rangelen*2) : rangelen));
6132 for (j = 0; j < rangelen; j++) {
6133 ele = ln->obj;
6134 addReplyBulk(c,ele);
6135 if (withscores)
6136 addReplyDouble(c,ln->score);
6137 ln = reverse ? ln->backward : ln->forward[0];
cc812361 6138 }
6139}
6140
e3870fab 6141static void zrangeCommand(redisClient *c) {
6142 zrangeGenericCommand(c,0);
6143}
6144
6145static void zrevrangeCommand(redisClient *c) {
6146 zrangeGenericCommand(c,1);
6147}
6148
f44dd428 6149/* This command implements both ZRANGEBYSCORE and ZCOUNT.
6150 * If justcount is non-zero, just the count is returned. */
6151static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
50c55df5 6152 robj *o;
f44dd428 6153 double min, max;
6154 int minex = 0, maxex = 0; /* are min or max exclusive? */
80181f78 6155 int offset = 0, limit = -1;
0500ef27
SH
6156 int withscores = 0;
6157 int badsyntax = 0;
6158
f44dd428 6159 /* Parse the min-max interval. If one of the values is prefixed
6160 * by the "(" character, it's considered "open". For instance
6161 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6162 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6163 if (((char*)c->argv[2]->ptr)[0] == '(') {
6164 min = strtod((char*)c->argv[2]->ptr+1,NULL);
6165 minex = 1;
6166 } else {
6167 min = strtod(c->argv[2]->ptr,NULL);
6168 }
6169 if (((char*)c->argv[3]->ptr)[0] == '(') {
6170 max = strtod((char*)c->argv[3]->ptr+1,NULL);
6171 maxex = 1;
6172 } else {
6173 max = strtod(c->argv[3]->ptr,NULL);
6174 }
6175
6176 /* Parse "WITHSCORES": note that if the command was called with
6177 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6178 * enter the following paths to parse WITHSCORES and LIMIT. */
0500ef27 6179 if (c->argc == 5 || c->argc == 8) {
3a3978b1 6180 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
6181 withscores = 1;
6182 else
6183 badsyntax = 1;
0500ef27 6184 }
3a3978b1 6185 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
0500ef27 6186 badsyntax = 1;
0500ef27 6187 if (badsyntax) {
454d4e43 6188 addReplySds(c,
6189 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
80181f78 6190 return;
0500ef27
SH
6191 }
6192
f44dd428 6193 /* Parse "LIMIT" */
0500ef27 6194 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
80181f78 6195 addReply(c,shared.syntaxerr);
6196 return;
0500ef27 6197 } else if (c->argc == (7 + withscores)) {
80181f78 6198 offset = atoi(c->argv[5]->ptr);
6199 limit = atoi(c->argv[6]->ptr);
0b13687c 6200 if (offset < 0) offset = 0;
80181f78 6201 }
50c55df5 6202
f44dd428 6203 /* Ok, lookup the key and get the range */
50c55df5 6204 o = lookupKeyRead(c->db,c->argv[1]);
6205 if (o == NULL) {
4e27f268 6206 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
50c55df5 6207 } else {
6208 if (o->type != REDIS_ZSET) {
6209 addReply(c,shared.wrongtypeerr);
6210 } else {
6211 zset *zsetobj = o->ptr;
6212 zskiplist *zsl = zsetobj->zsl;
6213 zskiplistNode *ln;
f44dd428 6214 robj *ele, *lenobj = NULL;
6215 unsigned long rangelen = 0;
50c55df5 6216
f44dd428 6217 /* Get the first node with the score >= min, or with
6218 * score > min if 'minex' is true. */
50c55df5 6219 ln = zslFirstWithScore(zsl,min);
f44dd428 6220 while (minex && ln && ln->score == min) ln = ln->forward[0];
6221
50c55df5 6222 if (ln == NULL) {
6223 /* No element matching the speciifed interval */
f44dd428 6224 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
50c55df5 6225 return;
6226 }
6227
6228 /* We don't know in advance how many matching elements there
6229 * are in the list, so we push this object that will represent
6230 * the multi-bulk length in the output buffer, and will "fix"
6231 * it later */
f44dd428 6232 if (!justcount) {
6233 lenobj = createObject(REDIS_STRING,NULL);
6234 addReply(c,lenobj);
6235 decrRefCount(lenobj);
6236 }
50c55df5 6237
f44dd428 6238 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
80181f78 6239 if (offset) {
6240 offset--;
6241 ln = ln->forward[0];
6242 continue;
6243 }
6244 if (limit == 0) break;
f44dd428 6245 if (!justcount) {
6246 ele = ln->obj;
dd88747b 6247 addReplyBulk(c,ele);
f44dd428 6248 if (withscores)
6249 addReplyDouble(c,ln->score);
6250 }
50c55df5 6251 ln = ln->forward[0];
6252 rangelen++;
80181f78 6253 if (limit > 0) limit--;
50c55df5 6254 }
f44dd428 6255 if (justcount) {
6256 addReplyLong(c,(long)rangelen);
6257 } else {
6258 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
6259 withscores ? (rangelen*2) : rangelen);
6260 }
50c55df5 6261 }
6262 }
6263}
6264
f44dd428 6265static void zrangebyscoreCommand(redisClient *c) {
6266 genericZrangebyscoreCommand(c,0);
6267}
6268
6269static void zcountCommand(redisClient *c) {
6270 genericZrangebyscoreCommand(c,1);
6271}
6272
3c41331e 6273static void zcardCommand(redisClient *c) {
e197b441 6274 robj *o;
6275 zset *zs;
dd88747b 6276
6277 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6278 checkType(c,o,REDIS_ZSET)) return;
6279
6280 zs = o->ptr;
6281 addReplyUlong(c,zs->zsl->length);
e197b441 6282}
6283
6e333bbe 6284static void zscoreCommand(redisClient *c) {
6285 robj *o;
6286 zset *zs;
dd88747b 6287 dictEntry *de;
6288
6289 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6290 checkType(c,o,REDIS_ZSET)) return;
6291
6292 zs = o->ptr;
6293 de = dictFind(zs->dict,c->argv[2]);
6294 if (!de) {
96d8b4ee 6295 addReply(c,shared.nullbulk);
6e333bbe 6296 } else {
dd88747b 6297 double *score = dictGetEntryVal(de);
6e333bbe 6298
dd88747b 6299 addReplyDouble(c,*score);
6e333bbe 6300 }
6301}
6302
798d9e55 6303static void zrankGenericCommand(redisClient *c, int reverse) {
69d95c3e 6304 robj *o;
dd88747b 6305 zset *zs;
6306 zskiplist *zsl;
6307 dictEntry *de;
6308 unsigned long rank;
6309 double *score;
6310
6311 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6312 checkType(c,o,REDIS_ZSET)) return;
6313
6314 zs = o->ptr;
6315 zsl = zs->zsl;
6316 de = dictFind(zs->dict,c->argv[2]);
6317 if (!de) {
69d95c3e
PN
6318 addReply(c,shared.nullbulk);
6319 return;
6320 }
69d95c3e 6321
dd88747b 6322 score = dictGetEntryVal(de);
6323 rank = zslGetRank(zsl, *score, c->argv[2]);
6324 if (rank) {
6325 if (reverse) {
6326 addReplyLong(c, zsl->length - rank);
27b0ccca 6327 } else {
dd88747b 6328 addReplyLong(c, rank-1);
69d95c3e 6329 }
dd88747b 6330 } else {
6331 addReply(c,shared.nullbulk);
978c2c94 6332 }
6333}
6334
798d9e55
PN
6335static void zrankCommand(redisClient *c) {
6336 zrankGenericCommand(c, 0);
6337}
6338
6339static void zrevrankCommand(redisClient *c) {
6340 zrankGenericCommand(c, 1);
6341}
6342
7fb16bac
PN
6343/* ========================= Hashes utility functions ======================= */
6344#define REDIS_HASH_KEY 1
6345#define REDIS_HASH_VALUE 2
978c2c94 6346
7fb16bac
PN
6347/* Check the length of a number of objects to see if we need to convert a
6348 * zipmap to a real hash. Note that we only check string encoded objects
6349 * as their string length can be queried in constant time. */
6350static void hashTryConversion(robj *subject, robj **argv, int start, int end) {
6351 int i;
6352 if (subject->encoding != REDIS_ENCODING_ZIPMAP) return;
978c2c94 6353
7fb16bac
PN
6354 for (i = start; i <= end; i++) {
6355 if (argv[i]->encoding == REDIS_ENCODING_RAW &&
6356 sdslen(argv[i]->ptr) > server.hash_max_zipmap_value)
6357 {
6358 convertToRealHash(subject);
978c2c94 6359 return;
6360 }
6361 }
7fb16bac 6362}
bae2c7ec 6363
97224de7
PN
6364/* Encode given objects in-place when the hash uses a dict. */
6365static void hashTryObjectEncoding(robj *subject, robj **o1, robj **o2) {
6366 if (subject->encoding == REDIS_ENCODING_HT) {
3f973463
PN
6367 if (o1) *o1 = tryObjectEncoding(*o1);
6368 if (o2) *o2 = tryObjectEncoding(*o2);
97224de7
PN
6369 }
6370}
6371
7fb16bac 6372/* Get the value from a hash identified by key. Returns either a string
a3f3af86
PN
6373 * object or NULL if the value cannot be found. The refcount of the object
6374 * is always increased by 1 when the value was found. */
7fb16bac
PN
6375static robj *hashGet(robj *o, robj *key) {
6376 robj *value = NULL;
978c2c94 6377 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
7fb16bac
PN
6378 unsigned char *v;
6379 unsigned int vlen;
6380 key = getDecodedObject(key);
6381 if (zipmapGet(o->ptr,key->ptr,sdslen(key->ptr),&v,&vlen)) {
6382 value = createStringObject((char*)v,vlen);
6383 }
6384 decrRefCount(key);
6385 } else {
6386 dictEntry *de = dictFind(o->ptr,key);
6387 if (de != NULL) {
6388 value = dictGetEntryVal(de);
a3f3af86 6389 incrRefCount(value);
7fb16bac
PN
6390 }
6391 }
6392 return value;
6393}
978c2c94 6394
7fb16bac
PN
6395/* Test if the key exists in the given hash. Returns 1 if the key
6396 * exists and 0 when it doesn't. */
6397static int hashExists(robj *o, robj *key) {
6398 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6399 key = getDecodedObject(key);
6400 if (zipmapExists(o->ptr,key->ptr,sdslen(key->ptr))) {
6401 decrRefCount(key);
6402 return 1;
6403 }
6404 decrRefCount(key);
6405 } else {
6406 if (dictFind(o->ptr,key) != NULL) {
6407 return 1;
6408 }
6409 }
6410 return 0;
6411}
bae2c7ec 6412
7fb16bac
PN
6413/* Add an element, discard the old if the key already exists.
6414 * Return 0 on insert and 1 on update. */
feb8d7e6 6415static int hashSet(robj *o, robj *key, robj *value) {
7fb16bac
PN
6416 int update = 0;
6417 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6418 key = getDecodedObject(key);
6419 value = getDecodedObject(value);
6420 o->ptr = zipmapSet(o->ptr,
6421 key->ptr,sdslen(key->ptr),
6422 value->ptr,sdslen(value->ptr), &update);
6423 decrRefCount(key);
6424 decrRefCount(value);
6425
6426 /* Check if the zipmap needs to be upgraded to a real hash table */
6427 if (zipmapLen(o->ptr) > server.hash_max_zipmap_entries)
bae2c7ec 6428 convertToRealHash(o);
978c2c94 6429 } else {
7fb16bac
PN
6430 if (dictReplace(o->ptr,key,value)) {
6431 /* Insert */
6432 incrRefCount(key);
978c2c94 6433 } else {
7fb16bac 6434 /* Update */
978c2c94 6435 update = 1;
6436 }
7fb16bac 6437 incrRefCount(value);
978c2c94 6438 }
7fb16bac 6439 return update;
978c2c94 6440}
6441
7fb16bac
PN
6442/* Delete an element from a hash.
6443 * Return 1 on deleted and 0 on not found. */
6444static int hashDelete(robj *o, robj *key) {
6445 int deleted = 0;
6446 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6447 key = getDecodedObject(key);
6448 o->ptr = zipmapDel(o->ptr,key->ptr,sdslen(key->ptr), &deleted);
6449 decrRefCount(key);
6450 } else {
6451 deleted = dictDelete((dict*)o->ptr,key) == DICT_OK;
6452 /* Always check if the dictionary needs a resize after a delete. */
6453 if (deleted && htNeedsResize(o->ptr)) dictResize(o->ptr);
d33278d1 6454 }
7fb16bac
PN
6455 return deleted;
6456}
d33278d1 6457
7fb16bac 6458/* Return the number of elements in a hash. */
c811bb38 6459static unsigned long hashLength(robj *o) {
7fb16bac
PN
6460 return (o->encoding == REDIS_ENCODING_ZIPMAP) ?
6461 zipmapLen((unsigned char*)o->ptr) : dictSize((dict*)o->ptr);
6462}
6463
6464/* Structure to hold hash iteration abstration. Note that iteration over
6465 * hashes involves both fields and values. Because it is possible that
6466 * not both are required, store pointers in the iterator to avoid
6467 * unnecessary memory allocation for fields/values. */
6468typedef struct {
6469 int encoding;
6470 unsigned char *zi;
6471 unsigned char *zk, *zv;
6472 unsigned int zklen, zvlen;
6473
6474 dictIterator *di;
6475 dictEntry *de;
6476} hashIterator;
6477
c44d3b56
PN
6478static hashIterator *hashInitIterator(robj *subject) {
6479 hashIterator *hi = zmalloc(sizeof(hashIterator));
7fb16bac
PN
6480 hi->encoding = subject->encoding;
6481 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6482 hi->zi = zipmapRewind(subject->ptr);
6483 } else if (hi->encoding == REDIS_ENCODING_HT) {
6484 hi->di = dictGetIterator(subject->ptr);
d33278d1 6485 } else {
7fb16bac 6486 redisAssert(NULL);
d33278d1 6487 }
c44d3b56 6488 return hi;
7fb16bac 6489}
d33278d1 6490
7fb16bac
PN
6491static void hashReleaseIterator(hashIterator *hi) {
6492 if (hi->encoding == REDIS_ENCODING_HT) {
6493 dictReleaseIterator(hi->di);
d33278d1 6494 }
c44d3b56 6495 zfree(hi);
7fb16bac 6496}
d33278d1 6497
7fb16bac
PN
6498/* Move to the next entry in the hash. Return REDIS_OK when the next entry
6499 * could be found and REDIS_ERR when the iterator reaches the end. */
c811bb38 6500static int hashNext(hashIterator *hi) {
7fb16bac
PN
6501 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6502 if ((hi->zi = zipmapNext(hi->zi, &hi->zk, &hi->zklen,
6503 &hi->zv, &hi->zvlen)) == NULL) return REDIS_ERR;
6504 } else {
6505 if ((hi->de = dictNext(hi->di)) == NULL) return REDIS_ERR;
6506 }
6507 return REDIS_OK;
6508}
d33278d1 6509
0c390abc 6510/* Get key or value object at current iteration position.
a3f3af86 6511 * This increases the refcount of the field object by 1. */
c811bb38 6512static robj *hashCurrent(hashIterator *hi, int what) {
7fb16bac
PN
6513 robj *o;
6514 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6515 if (what & REDIS_HASH_KEY) {
6516 o = createStringObject((char*)hi->zk,hi->zklen);
6517 } else {
6518 o = createStringObject((char*)hi->zv,hi->zvlen);
d33278d1 6519 }
d33278d1 6520 } else {
7fb16bac
PN
6521 if (what & REDIS_HASH_KEY) {
6522 o = dictGetEntryKey(hi->de);
6523 } else {
6524 o = dictGetEntryVal(hi->de);
d33278d1 6525 }
a3f3af86 6526 incrRefCount(o);
d33278d1 6527 }
7fb16bac 6528 return o;
d33278d1
PN
6529}
6530
7fb16bac
PN
6531static robj *hashLookupWriteOrCreate(redisClient *c, robj *key) {
6532 robj *o = lookupKeyWrite(c->db,key);
01426b05
PN
6533 if (o == NULL) {
6534 o = createHashObject();
7fb16bac
PN
6535 dictAdd(c->db->dict,key,o);
6536 incrRefCount(key);
01426b05
PN
6537 } else {
6538 if (o->type != REDIS_HASH) {
6539 addReply(c,shared.wrongtypeerr);
7fb16bac 6540 return NULL;
01426b05
PN
6541 }
6542 }
7fb16bac
PN
6543 return o;
6544}
01426b05 6545
7fb16bac
PN
6546/* ============================= Hash commands ============================== */
6547static void hsetCommand(redisClient *c) {
6e9e463f 6548 int update;
7fb16bac 6549 robj *o;
bbe025e0 6550
7fb16bac
PN
6551 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6552 hashTryConversion(o,c->argv,2,3);
97224de7 6553 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
feb8d7e6 6554 update = hashSet(o,c->argv[2],c->argv[3]);
6e9e463f 6555 addReply(c, update ? shared.czero : shared.cone);
7fb16bac
PN
6556 server.dirty++;
6557}
01426b05 6558
1f1c7695
PN
6559static void hsetnxCommand(redisClient *c) {
6560 robj *o;
6561 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6562 hashTryConversion(o,c->argv,2,3);
6563
6564 if (hashExists(o, c->argv[2])) {
6565 addReply(c, shared.czero);
01426b05 6566 } else {
97224de7 6567 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
feb8d7e6 6568 hashSet(o,c->argv[2],c->argv[3]);
1f1c7695
PN
6569 addReply(c, shared.cone);
6570 server.dirty++;
6571 }
6572}
01426b05 6573
7fb16bac
PN
6574static void hmsetCommand(redisClient *c) {
6575 int i;
6576 robj *o;
01426b05 6577
7fb16bac
PN
6578 if ((c->argc % 2) == 1) {
6579 addReplySds(c,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6580 return;
6581 }
01426b05 6582
7fb16bac
PN
6583 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6584 hashTryConversion(o,c->argv,2,c->argc-1);
6585 for (i = 2; i < c->argc; i += 2) {
97224de7 6586 hashTryObjectEncoding(o,&c->argv[i], &c->argv[i+1]);
feb8d7e6 6587 hashSet(o,c->argv[i],c->argv[i+1]);
7fb16bac
PN
6588 }
6589 addReply(c, shared.ok);
edc2f63a 6590 server.dirty++;
7fb16bac
PN
6591}
6592
6593static void hincrbyCommand(redisClient *c) {
6594 long long value, incr;
6595 robj *o, *current, *new;
6596
bd79a6bd 6597 if (getLongLongFromObjectOrReply(c,c->argv[3],&incr,NULL) != REDIS_OK) return;
7fb16bac
PN
6598 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6599 if ((current = hashGet(o,c->argv[2])) != NULL) {
946342c1
PN
6600 if (getLongLongFromObjectOrReply(c,current,&value,
6601 "hash value is not an integer") != REDIS_OK) {
6602 decrRefCount(current);
6603 return;
6604 }
a3f3af86 6605 decrRefCount(current);
7fb16bac
PN
6606 } else {
6607 value = 0;
01426b05
PN
6608 }
6609
7fb16bac 6610 value += incr;
3f973463
PN
6611 new = createStringObjectFromLongLong(value);
6612 hashTryObjectEncoding(o,&c->argv[2],NULL);
feb8d7e6 6613 hashSet(o,c->argv[2],new);
7fb16bac
PN
6614 decrRefCount(new);
6615 addReplyLongLong(c,value);
01426b05 6616 server.dirty++;
01426b05
PN
6617}
6618
978c2c94 6619static void hgetCommand(redisClient *c) {
7fb16bac 6620 robj *o, *value;
dd88747b 6621 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6622 checkType(c,o,REDIS_HASH)) return;
6623
7fb16bac
PN
6624 if ((value = hashGet(o,c->argv[2])) != NULL) {
6625 addReplyBulk(c,value);
a3f3af86 6626 decrRefCount(value);
dd88747b 6627 } else {
7fb16bac 6628 addReply(c,shared.nullbulk);
69d95c3e 6629 }
69d95c3e
PN
6630}
6631
09aeb579
PN
6632static void hmgetCommand(redisClient *c) {
6633 int i;
7fb16bac
PN
6634 robj *o, *value;
6635 o = lookupKeyRead(c->db,c->argv[1]);
6636 if (o != NULL && o->type != REDIS_HASH) {
6637 addReply(c,shared.wrongtypeerr);
09aeb579
PN
6638 }
6639
7fb16bac
PN
6640 /* Note the check for o != NULL happens inside the loop. This is
6641 * done because objects that cannot be found are considered to be
6642 * an empty hash. The reply should then be a series of NULLs. */
09aeb579 6643 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-2));
7fb16bac
PN
6644 for (i = 2; i < c->argc; i++) {
6645 if (o != NULL && (value = hashGet(o,c->argv[i])) != NULL) {
6646 addReplyBulk(c,value);
a3f3af86 6647 decrRefCount(value);
7fb16bac
PN
6648 } else {
6649 addReply(c,shared.nullbulk);
09aeb579
PN
6650 }
6651 }
6652}
6653
07efaf74 6654static void hdelCommand(redisClient *c) {
dd88747b 6655 robj *o;
dd88747b 6656 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6657 checkType(c,o,REDIS_HASH)) return;
07efaf74 6658
7fb16bac
PN
6659 if (hashDelete(o,c->argv[2])) {
6660 if (hashLength(o) == 0) deleteKey(c->db,c->argv[1]);
6661 addReply(c,shared.cone);
6662 server.dirty++;
dd88747b 6663 } else {
7fb16bac 6664 addReply(c,shared.czero);
07efaf74 6665 }
6666}
6667
92b27fe9 6668static void hlenCommand(redisClient *c) {
6669 robj *o;
dd88747b 6670 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
92b27fe9 6671 checkType(c,o,REDIS_HASH)) return;
6672
7fb16bac 6673 addReplyUlong(c,hashLength(o));
92b27fe9 6674}
6675
78409a0f 6676static void genericHgetallCommand(redisClient *c, int flags) {
7fb16bac 6677 robj *o, *lenobj, *obj;
78409a0f 6678 unsigned long count = 0;
c44d3b56 6679 hashIterator *hi;
78409a0f 6680
4e27f268 6681 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
78409a0f 6682 || checkType(c,o,REDIS_HASH)) return;
6683
6684 lenobj = createObject(REDIS_STRING,NULL);
6685 addReply(c,lenobj);
6686 decrRefCount(lenobj);
6687
c44d3b56
PN
6688 hi = hashInitIterator(o);
6689 while (hashNext(hi) != REDIS_ERR) {
7fb16bac 6690 if (flags & REDIS_HASH_KEY) {
c44d3b56 6691 obj = hashCurrent(hi,REDIS_HASH_KEY);
7fb16bac 6692 addReplyBulk(c,obj);
a3f3af86 6693 decrRefCount(obj);
7fb16bac 6694 count++;
78409a0f 6695 }
7fb16bac 6696 if (flags & REDIS_HASH_VALUE) {
c44d3b56 6697 obj = hashCurrent(hi,REDIS_HASH_VALUE);
7fb16bac 6698 addReplyBulk(c,obj);
a3f3af86 6699 decrRefCount(obj);
7fb16bac 6700 count++;
78409a0f 6701 }
78409a0f 6702 }
c44d3b56 6703 hashReleaseIterator(hi);
7fb16bac 6704
78409a0f 6705 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",count);
6706}
6707
6708static void hkeysCommand(redisClient *c) {
7fb16bac 6709 genericHgetallCommand(c,REDIS_HASH_KEY);
78409a0f 6710}
6711
6712static void hvalsCommand(redisClient *c) {
7fb16bac 6713 genericHgetallCommand(c,REDIS_HASH_VALUE);
78409a0f 6714}
6715
6716static void hgetallCommand(redisClient *c) {
7fb16bac 6717 genericHgetallCommand(c,REDIS_HASH_KEY|REDIS_HASH_VALUE);
78409a0f 6718}
6719
a86f14b1 6720static void hexistsCommand(redisClient *c) {
6721 robj *o;
a86f14b1 6722 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6723 checkType(c,o,REDIS_HASH)) return;
6724
7fb16bac 6725 addReply(c, hashExists(o,c->argv[2]) ? shared.cone : shared.czero);
a86f14b1 6726}
6727
ada386b2 6728static void convertToRealHash(robj *o) {
6729 unsigned char *key, *val, *p, *zm = o->ptr;
6730 unsigned int klen, vlen;
6731 dict *dict = dictCreate(&hashDictType,NULL);
6732
6733 assert(o->type == REDIS_HASH && o->encoding != REDIS_ENCODING_HT);
6734 p = zipmapRewind(zm);
6735 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
6736 robj *keyobj, *valobj;
6737
6738 keyobj = createStringObject((char*)key,klen);
6739 valobj = createStringObject((char*)val,vlen);
05df7621 6740 keyobj = tryObjectEncoding(keyobj);
6741 valobj = tryObjectEncoding(valobj);
ada386b2 6742 dictAdd(dict,keyobj,valobj);
6743 }
6744 o->encoding = REDIS_ENCODING_HT;
6745 o->ptr = dict;
6746 zfree(zm);
6747}
6748
6b47e12e 6749/* ========================= Non type-specific commands ==================== */
6750
ed9b544e 6751static void flushdbCommand(redisClient *c) {
ca37e9cd 6752 server.dirty += dictSize(c->db->dict);
3305306f 6753 dictEmpty(c->db->dict);
6754 dictEmpty(c->db->expires);
ed9b544e 6755 addReply(c,shared.ok);
ed9b544e 6756}
6757
6758static void flushallCommand(redisClient *c) {
ca37e9cd 6759 server.dirty += emptyDb();
ed9b544e 6760 addReply(c,shared.ok);
500ece7c 6761 if (server.bgsavechildpid != -1) {
6762 kill(server.bgsavechildpid,SIGKILL);
6763 rdbRemoveTempFile(server.bgsavechildpid);
6764 }
f78fd11b 6765 rdbSave(server.dbfilename);
ca37e9cd 6766 server.dirty++;
ed9b544e 6767}
6768
56906eef 6769static redisSortOperation *createSortOperation(int type, robj *pattern) {
ed9b544e 6770 redisSortOperation *so = zmalloc(sizeof(*so));
ed9b544e 6771 so->type = type;
6772 so->pattern = pattern;
6773 return so;
6774}
6775
6776/* Return the value associated to the key with a name obtained
55017f9d
PN
6777 * substituting the first occurence of '*' in 'pattern' with 'subst'.
6778 * The returned object will always have its refcount increased by 1
6779 * when it is non-NULL. */
56906eef 6780static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
6d7d1370 6781 char *p, *f;
ed9b544e 6782 sds spat, ssub;
6d7d1370
PN
6783 robj keyobj, fieldobj, *o;
6784 int prefixlen, sublen, postfixlen, fieldlen;
ed9b544e 6785 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6786 struct {
f1017b3f 6787 long len;
6788 long free;
ed9b544e 6789 char buf[REDIS_SORTKEY_MAX+1];
6d7d1370 6790 } keyname, fieldname;
ed9b544e 6791
28173a49 6792 /* If the pattern is "#" return the substitution object itself in order
6793 * to implement the "SORT ... GET #" feature. */
6794 spat = pattern->ptr;
6795 if (spat[0] == '#' && spat[1] == '\0') {
55017f9d 6796 incrRefCount(subst);
28173a49 6797 return subst;
6798 }
6799
6800 /* The substitution object may be specially encoded. If so we create
9d65a1bb 6801 * a decoded object on the fly. Otherwise getDecodedObject will just
6802 * increment the ref count, that we'll decrement later. */
6803 subst = getDecodedObject(subst);
942a3961 6804
ed9b544e 6805 ssub = subst->ptr;
6806 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
6807 p = strchr(spat,'*');
ed5a857a 6808 if (!p) {
6809 decrRefCount(subst);
6810 return NULL;
6811 }
ed9b544e 6812
6d7d1370
PN
6813 /* Find out if we're dealing with a hash dereference. */
6814 if ((f = strstr(p+1, "->")) != NULL) {
6815 fieldlen = sdslen(spat)-(f-spat);
6816 /* this also copies \0 character */
6817 memcpy(fieldname.buf,f+2,fieldlen-1);
6818 fieldname.len = fieldlen-2;
6819 } else {
6820 fieldlen = 0;
6821 }
6822
ed9b544e 6823 prefixlen = p-spat;
6824 sublen = sdslen(ssub);
6d7d1370 6825 postfixlen = sdslen(spat)-(prefixlen+1)-fieldlen;
ed9b544e 6826 memcpy(keyname.buf,spat,prefixlen);
6827 memcpy(keyname.buf+prefixlen,ssub,sublen);
6828 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
6829 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
6830 keyname.len = prefixlen+sublen+postfixlen;
942a3961 6831 decrRefCount(subst);
6832
6d7d1370
PN
6833 /* Lookup substituted key */
6834 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2));
6835 o = lookupKeyRead(db,&keyobj);
55017f9d
PN
6836 if (o == NULL) return NULL;
6837
6838 if (fieldlen > 0) {
6839 if (o->type != REDIS_HASH || fieldname.len < 1) return NULL;
6d7d1370 6840
705dad38
PN
6841 /* Retrieve value from hash by the field name. This operation
6842 * already increases the refcount of the returned object. */
6d7d1370
PN
6843 initStaticStringObject(fieldobj,((char*)&fieldname)+(sizeof(long)*2));
6844 o = hashGet(o, &fieldobj);
705dad38 6845 } else {
55017f9d 6846 if (o->type != REDIS_STRING) return NULL;
b6f07345 6847
705dad38
PN
6848 /* Every object that this function returns needs to have its refcount
6849 * increased. sortCommand decreases it again. */
6850 incrRefCount(o);
6d7d1370
PN
6851 }
6852
6853 return o;
ed9b544e 6854}
6855
6856/* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6857 * the additional parameter is not standard but a BSD-specific we have to
6858 * pass sorting parameters via the global 'server' structure */
6859static int sortCompare(const void *s1, const void *s2) {
6860 const redisSortObject *so1 = s1, *so2 = s2;
6861 int cmp;
6862
6863 if (!server.sort_alpha) {
6864 /* Numeric sorting. Here it's trivial as we precomputed scores */
6865 if (so1->u.score > so2->u.score) {
6866 cmp = 1;
6867 } else if (so1->u.score < so2->u.score) {
6868 cmp = -1;
6869 } else {
6870 cmp = 0;
6871 }
6872 } else {
6873 /* Alphanumeric sorting */
6874 if (server.sort_bypattern) {
6875 if (!so1->u.cmpobj || !so2->u.cmpobj) {
6876 /* At least one compare object is NULL */
6877 if (so1->u.cmpobj == so2->u.cmpobj)
6878 cmp = 0;
6879 else if (so1->u.cmpobj == NULL)
6880 cmp = -1;
6881 else
6882 cmp = 1;
6883 } else {
6884 /* We have both the objects, use strcoll */
6885 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
6886 }
6887 } else {
08ee9b57 6888 /* Compare elements directly. */
6889 cmp = compareStringObjects(so1->obj,so2->obj);
ed9b544e 6890 }
6891 }
6892 return server.sort_desc ? -cmp : cmp;
6893}
6894
6895/* The SORT command is the most complex command in Redis. Warning: this code
6896 * is optimized for speed and a bit less for readability */
6897static void sortCommand(redisClient *c) {
ed9b544e 6898 list *operations;
6899 int outputlen = 0;
6900 int desc = 0, alpha = 0;
6901 int limit_start = 0, limit_count = -1, start, end;
6902 int j, dontsort = 0, vectorlen;
6903 int getop = 0; /* GET operation counter */
443c6409 6904 robj *sortval, *sortby = NULL, *storekey = NULL;
ed9b544e 6905 redisSortObject *vector; /* Resulting vector to sort */
6906
6907 /* Lookup the key to sort. It must be of the right types */
3305306f 6908 sortval = lookupKeyRead(c->db,c->argv[1]);
6909 if (sortval == NULL) {
4e27f268 6910 addReply(c,shared.emptymultibulk);
ed9b544e 6911 return;
6912 }
a5eb649b 6913 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
6914 sortval->type != REDIS_ZSET)
6915 {
c937aa89 6916 addReply(c,shared.wrongtypeerr);
ed9b544e 6917 return;
6918 }
6919
6920 /* Create a list of operations to perform for every sorted element.
6921 * Operations can be GET/DEL/INCR/DECR */
6922 operations = listCreate();
092dac2a 6923 listSetFreeMethod(operations,zfree);
ed9b544e 6924 j = 2;
6925
6926 /* Now we need to protect sortval incrementing its count, in the future
6927 * SORT may have options able to overwrite/delete keys during the sorting
6928 * and the sorted key itself may get destroied */
6929 incrRefCount(sortval);
6930
6931 /* The SORT command has an SQL-alike syntax, parse it */
6932 while(j < c->argc) {
6933 int leftargs = c->argc-j-1;
6934 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
6935 desc = 0;
6936 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
6937 desc = 1;
6938 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
6939 alpha = 1;
6940 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
6941 limit_start = atoi(c->argv[j+1]->ptr);
6942 limit_count = atoi(c->argv[j+2]->ptr);
6943 j+=2;
443c6409 6944 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
6945 storekey = c->argv[j+1];
6946 j++;
ed9b544e 6947 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
6948 sortby = c->argv[j+1];
6949 /* If the BY pattern does not contain '*', i.e. it is constant,
6950 * we don't need to sort nor to lookup the weight keys. */
6951 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
6952 j++;
6953 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
6954 listAddNodeTail(operations,createSortOperation(
6955 REDIS_SORT_GET,c->argv[j+1]));
6956 getop++;
6957 j++;
ed9b544e 6958 } else {
6959 decrRefCount(sortval);
6960 listRelease(operations);
c937aa89 6961 addReply(c,shared.syntaxerr);
ed9b544e 6962 return;
6963 }
6964 j++;
6965 }
6966
6967 /* Load the sorting vector with all the objects to sort */
a5eb649b 6968 switch(sortval->type) {
6969 case REDIS_LIST: vectorlen = listLength((list*)sortval->ptr); break;
6970 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
6971 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
f83c6cb5 6972 default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
a5eb649b 6973 }
ed9b544e 6974 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
ed9b544e 6975 j = 0;
a5eb649b 6976
ed9b544e 6977 if (sortval->type == REDIS_LIST) {
6978 list *list = sortval->ptr;
6208b3a7 6979 listNode *ln;
c7df85a4 6980 listIter li;
6208b3a7 6981
c7df85a4 6982 listRewind(list,&li);
6983 while((ln = listNext(&li))) {
ed9b544e 6984 robj *ele = ln->value;
6985 vector[j].obj = ele;
6986 vector[j].u.score = 0;
6987 vector[j].u.cmpobj = NULL;
ed9b544e 6988 j++;
6989 }
6990 } else {
a5eb649b 6991 dict *set;
ed9b544e 6992 dictIterator *di;
6993 dictEntry *setele;
6994
a5eb649b 6995 if (sortval->type == REDIS_SET) {
6996 set = sortval->ptr;
6997 } else {
6998 zset *zs = sortval->ptr;
6999 set = zs->dict;
7000 }
7001
ed9b544e 7002 di = dictGetIterator(set);
ed9b544e 7003 while((setele = dictNext(di)) != NULL) {
7004 vector[j].obj = dictGetEntryKey(setele);
7005 vector[j].u.score = 0;
7006 vector[j].u.cmpobj = NULL;
7007 j++;
7008 }
7009 dictReleaseIterator(di);
7010 }
dfc5e96c 7011 redisAssert(j == vectorlen);
ed9b544e 7012
7013 /* Now it's time to load the right scores in the sorting vector */
7014 if (dontsort == 0) {
7015 for (j = 0; j < vectorlen; j++) {
6d7d1370 7016 robj *byval;
ed9b544e 7017 if (sortby) {
6d7d1370 7018 /* lookup value to sort by */
3305306f 7019 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
705dad38 7020 if (!byval) continue;
ed9b544e 7021 } else {
6d7d1370
PN
7022 /* use object itself to sort by */
7023 byval = vector[j].obj;
7024 }
7025
7026 if (alpha) {
08ee9b57 7027 if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
6d7d1370
PN
7028 } else {
7029 if (byval->encoding == REDIS_ENCODING_RAW) {
7030 vector[j].u.score = strtod(byval->ptr,NULL);
16fa22f1 7031 } else if (byval->encoding == REDIS_ENCODING_INT) {
6d7d1370
PN
7032 /* Don't need to decode the object if it's
7033 * integer-encoded (the only encoding supported) so
7034 * far. We can just cast it */
16fa22f1
PN
7035 vector[j].u.score = (long)byval->ptr;
7036 } else {
7037 redisAssert(1 != 1);
942a3961 7038 }
ed9b544e 7039 }
6d7d1370 7040
705dad38
PN
7041 /* when the object was retrieved using lookupKeyByPattern,
7042 * its refcount needs to be decreased. */
7043 if (sortby) {
7044 decrRefCount(byval);
ed9b544e 7045 }
7046 }
7047 }
7048
7049 /* We are ready to sort the vector... perform a bit of sanity check
7050 * on the LIMIT option too. We'll use a partial version of quicksort. */
7051 start = (limit_start < 0) ? 0 : limit_start;
7052 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
7053 if (start >= vectorlen) {
7054 start = vectorlen-1;
7055 end = vectorlen-2;
7056 }
7057 if (end >= vectorlen) end = vectorlen-1;
7058
7059 if (dontsort == 0) {
7060 server.sort_desc = desc;
7061 server.sort_alpha = alpha;
7062 server.sort_bypattern = sortby ? 1 : 0;
5f5b9840 7063 if (sortby && (start != 0 || end != vectorlen-1))
7064 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
7065 else
7066 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
ed9b544e 7067 }
7068
7069 /* Send command output to the output buffer, performing the specified
7070 * GET/DEL/INCR/DECR operations if any. */
7071 outputlen = getop ? getop*(end-start+1) : end-start+1;
443c6409 7072 if (storekey == NULL) {
7073 /* STORE option not specified, sent the sorting result to client */
7074 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
7075 for (j = start; j <= end; j++) {
7076 listNode *ln;
c7df85a4 7077 listIter li;
7078
dd88747b 7079 if (!getop) addReplyBulk(c,vector[j].obj);
c7df85a4 7080 listRewind(operations,&li);
7081 while((ln = listNext(&li))) {
443c6409 7082 redisSortOperation *sop = ln->value;
7083 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7084 vector[j].obj);
7085
7086 if (sop->type == REDIS_SORT_GET) {
55017f9d 7087 if (!val) {
443c6409 7088 addReply(c,shared.nullbulk);
7089 } else {
dd88747b 7090 addReplyBulk(c,val);
55017f9d 7091 decrRefCount(val);
443c6409 7092 }
7093 } else {
dfc5e96c 7094 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
443c6409 7095 }
7096 }
ed9b544e 7097 }
443c6409 7098 } else {
7099 robj *listObject = createListObject();
7100 list *listPtr = (list*) listObject->ptr;
7101
7102 /* STORE option specified, set the sorting result as a List object */
7103 for (j = start; j <= end; j++) {
7104 listNode *ln;
c7df85a4 7105 listIter li;
7106
443c6409 7107 if (!getop) {
7108 listAddNodeTail(listPtr,vector[j].obj);
7109 incrRefCount(vector[j].obj);
7110 }
c7df85a4 7111 listRewind(operations,&li);
7112 while((ln = listNext(&li))) {
443c6409 7113 redisSortOperation *sop = ln->value;
7114 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7115 vector[j].obj);
7116
7117 if (sop->type == REDIS_SORT_GET) {
55017f9d 7118 if (!val) {
443c6409 7119 listAddNodeTail(listPtr,createStringObject("",0));
7120 } else {
55017f9d
PN
7121 /* We should do a incrRefCount on val because it is
7122 * added to the list, but also a decrRefCount because
7123 * it is returned by lookupKeyByPattern. This results
7124 * in doing nothing at all. */
443c6409 7125 listAddNodeTail(listPtr,val);
443c6409 7126 }
ed9b544e 7127 } else {
dfc5e96c 7128 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
ed9b544e 7129 }
ed9b544e 7130 }
ed9b544e 7131 }
121796f7 7132 if (dictReplace(c->db->dict,storekey,listObject)) {
7133 incrRefCount(storekey);
7134 }
443c6409 7135 /* Note: we add 1 because the DB is dirty anyway since even if the
7136 * SORT result is empty a new key is set and maybe the old content
7137 * replaced. */
7138 server.dirty += 1+outputlen;
7139 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
ed9b544e 7140 }
7141
7142 /* Cleanup */
7143 decrRefCount(sortval);
7144 listRelease(operations);
7145 for (j = 0; j < vectorlen; j++) {
16fa22f1 7146 if (alpha && vector[j].u.cmpobj)
ed9b544e 7147 decrRefCount(vector[j].u.cmpobj);
7148 }
7149 zfree(vector);
7150}
7151
ec6c7a1d 7152/* Convert an amount of bytes into a human readable string in the form
7153 * of 100B, 2G, 100M, 4K, and so forth. */
7154static void bytesToHuman(char *s, unsigned long long n) {
7155 double d;
7156
7157 if (n < 1024) {
7158 /* Bytes */
7159 sprintf(s,"%lluB",n);
7160 return;
7161 } else if (n < (1024*1024)) {
7162 d = (double)n/(1024);
7163 sprintf(s,"%.2fK",d);
7164 } else if (n < (1024LL*1024*1024)) {
7165 d = (double)n/(1024*1024);
7166 sprintf(s,"%.2fM",d);
7167 } else if (n < (1024LL*1024*1024*1024)) {
7168 d = (double)n/(1024LL*1024*1024);
b72f6a4b 7169 sprintf(s,"%.2fG",d);
ec6c7a1d 7170 }
7171}
7172
1c85b79f 7173/* Create the string returned by the INFO command. This is decoupled
7174 * by the INFO command itself as we need to report the same information
7175 * on memory corruption problems. */
7176static sds genRedisInfoString(void) {
ed9b544e 7177 sds info;
7178 time_t uptime = time(NULL)-server.stat_starttime;
c3cb078d 7179 int j;
ec6c7a1d 7180 char hmem[64];
55a8298f 7181
b72f6a4b 7182 bytesToHuman(hmem,zmalloc_used_memory());
ed9b544e 7183 info = sdscatprintf(sdsempty(),
7184 "redis_version:%s\r\n"
f1017b3f 7185 "arch_bits:%s\r\n"
7a932b74 7186 "multiplexing_api:%s\r\n"
0d7170a4 7187 "process_id:%ld\r\n"
682ac724 7188 "uptime_in_seconds:%ld\r\n"
7189 "uptime_in_days:%ld\r\n"
ed9b544e 7190 "connected_clients:%d\r\n"
7191 "connected_slaves:%d\r\n"
f86a74e9 7192 "blocked_clients:%d\r\n"
5fba9f71 7193 "used_memory:%zu\r\n"
ec6c7a1d 7194 "used_memory_human:%s\r\n"
ed9b544e 7195 "changes_since_last_save:%lld\r\n"
be2bb6b0 7196 "bgsave_in_progress:%d\r\n"
682ac724 7197 "last_save_time:%ld\r\n"
b3fad521 7198 "bgrewriteaof_in_progress:%d\r\n"
ed9b544e 7199 "total_connections_received:%lld\r\n"
7200 "total_commands_processed:%lld\r\n"
2a6a2ed1 7201 "expired_keys:%lld\r\n"
55a8298f 7202 "hash_max_zipmap_entries:%ld\r\n"
7203 "hash_max_zipmap_value:%ld\r\n"
ffc6b7f8 7204 "pubsub_channels:%ld\r\n"
7205 "pubsub_patterns:%u\r\n"
7d98e08c 7206 "vm_enabled:%d\r\n"
a0f643ea 7207 "role:%s\r\n"
ed9b544e 7208 ,REDIS_VERSION,
f1017b3f 7209 (sizeof(long) == 8) ? "64" : "32",
7a932b74 7210 aeGetApiName(),
0d7170a4 7211 (long) getpid(),
a0f643ea 7212 uptime,
7213 uptime/(3600*24),
ed9b544e 7214 listLength(server.clients)-listLength(server.slaves),
7215 listLength(server.slaves),
d5d55fc3 7216 server.blpop_blocked_clients,
b72f6a4b 7217 zmalloc_used_memory(),
ec6c7a1d 7218 hmem,
ed9b544e 7219 server.dirty,
9d65a1bb 7220 server.bgsavechildpid != -1,
ed9b544e 7221 server.lastsave,
b3fad521 7222 server.bgrewritechildpid != -1,
ed9b544e 7223 server.stat_numconnections,
7224 server.stat_numcommands,
2a6a2ed1 7225 server.stat_expiredkeys,
55a8298f 7226 server.hash_max_zipmap_entries,
7227 server.hash_max_zipmap_value,
ffc6b7f8 7228 dictSize(server.pubsub_channels),
7229 listLength(server.pubsub_patterns),
7d98e08c 7230 server.vm_enabled != 0,
a0f643ea 7231 server.masterhost == NULL ? "master" : "slave"
ed9b544e 7232 );
a0f643ea 7233 if (server.masterhost) {
7234 info = sdscatprintf(info,
7235 "master_host:%s\r\n"
7236 "master_port:%d\r\n"
7237 "master_link_status:%s\r\n"
7238 "master_last_io_seconds_ago:%d\r\n"
7239 ,server.masterhost,
7240 server.masterport,
7241 (server.replstate == REDIS_REPL_CONNECTED) ?
7242 "up" : "down",
f72b934d 7243 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
a0f643ea 7244 );
7245 }
7d98e08c 7246 if (server.vm_enabled) {
1064ef87 7247 lockThreadedIO();
7d98e08c 7248 info = sdscatprintf(info,
7249 "vm_conf_max_memory:%llu\r\n"
7250 "vm_conf_page_size:%llu\r\n"
7251 "vm_conf_pages:%llu\r\n"
7252 "vm_stats_used_pages:%llu\r\n"
7253 "vm_stats_swapped_objects:%llu\r\n"
7254 "vm_stats_swappin_count:%llu\r\n"
7255 "vm_stats_swappout_count:%llu\r\n"
b9bc0eef 7256 "vm_stats_io_newjobs_len:%lu\r\n"
7257 "vm_stats_io_processing_len:%lu\r\n"
7258 "vm_stats_io_processed_len:%lu\r\n"
25fd2cb2 7259 "vm_stats_io_active_threads:%lu\r\n"
d5d55fc3 7260 "vm_stats_blocked_clients:%lu\r\n"
7d98e08c 7261 ,(unsigned long long) server.vm_max_memory,
7262 (unsigned long long) server.vm_page_size,
7263 (unsigned long long) server.vm_pages,
7264 (unsigned long long) server.vm_stats_used_pages,
7265 (unsigned long long) server.vm_stats_swapped_objects,
7266 (unsigned long long) server.vm_stats_swapins,
b9bc0eef 7267 (unsigned long long) server.vm_stats_swapouts,
7268 (unsigned long) listLength(server.io_newjobs),
7269 (unsigned long) listLength(server.io_processing),
7270 (unsigned long) listLength(server.io_processed),
d5d55fc3 7271 (unsigned long) server.io_active_threads,
7272 (unsigned long) server.vm_blocked_clients
7d98e08c 7273 );
1064ef87 7274 unlockThreadedIO();
7d98e08c 7275 }
c3cb078d 7276 for (j = 0; j < server.dbnum; j++) {
7277 long long keys, vkeys;
7278
7279 keys = dictSize(server.db[j].dict);
7280 vkeys = dictSize(server.db[j].expires);
7281 if (keys || vkeys) {
9d65a1bb 7282 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
c3cb078d 7283 j, keys, vkeys);
7284 }
7285 }
1c85b79f 7286 return info;
7287}
7288
7289static void infoCommand(redisClient *c) {
7290 sds info = genRedisInfoString();
83c6a618 7291 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
7292 (unsigned long)sdslen(info)));
ed9b544e 7293 addReplySds(c,info);
70003d28 7294 addReply(c,shared.crlf);
ed9b544e 7295}
7296
3305306f 7297static void monitorCommand(redisClient *c) {
7298 /* ignore MONITOR if aleady slave or in monitor mode */
7299 if (c->flags & REDIS_SLAVE) return;
7300
7301 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
7302 c->slaveseldb = 0;
6b47e12e 7303 listAddNodeTail(server.monitors,c);
3305306f 7304 addReply(c,shared.ok);
7305}
7306
7307/* ================================= Expire ================================= */
7308static int removeExpire(redisDb *db, robj *key) {
7309 if (dictDelete(db->expires,key) == DICT_OK) {
7310 return 1;
7311 } else {
7312 return 0;
7313 }
7314}
7315
7316static int setExpire(redisDb *db, robj *key, time_t when) {
7317 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
7318 return 0;
7319 } else {
7320 incrRefCount(key);
7321 return 1;
7322 }
7323}
7324
bb32ede5 7325/* Return the expire time of the specified key, or -1 if no expire
7326 * is associated with this key (i.e. the key is non volatile) */
7327static time_t getExpire(redisDb *db, robj *key) {
7328 dictEntry *de;
7329
7330 /* No expire? return ASAP */
7331 if (dictSize(db->expires) == 0 ||
7332 (de = dictFind(db->expires,key)) == NULL) return -1;
7333
7334 return (time_t) dictGetEntryVal(de);
7335}
7336
3305306f 7337static int expireIfNeeded(redisDb *db, robj *key) {
7338 time_t when;
7339 dictEntry *de;
7340
7341 /* No expire? return ASAP */
7342 if (dictSize(db->expires) == 0 ||
7343 (de = dictFind(db->expires,key)) == NULL) return 0;
7344
7345 /* Lookup the expire */
7346 when = (time_t) dictGetEntryVal(de);
7347 if (time(NULL) <= when) return 0;
7348
7349 /* Delete the key */
7350 dictDelete(db->expires,key);
2a6a2ed1 7351 server.stat_expiredkeys++;
3305306f 7352 return dictDelete(db->dict,key) == DICT_OK;
7353}
7354
7355static int deleteIfVolatile(redisDb *db, robj *key) {
7356 dictEntry *de;
7357
7358 /* No expire? return ASAP */
7359 if (dictSize(db->expires) == 0 ||
7360 (de = dictFind(db->expires,key)) == NULL) return 0;
7361
7362 /* Delete the key */
0c66a471 7363 server.dirty++;
2a6a2ed1 7364 server.stat_expiredkeys++;
3305306f 7365 dictDelete(db->expires,key);
7366 return dictDelete(db->dict,key) == DICT_OK;
7367}
7368
bbe025e0 7369static void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
3305306f 7370 dictEntry *de;
bbe025e0
AM
7371 time_t seconds;
7372
bd79a6bd 7373 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
bbe025e0
AM
7374
7375 seconds -= offset;
3305306f 7376
802e8373 7377 de = dictFind(c->db->dict,key);
3305306f 7378 if (de == NULL) {
7379 addReply(c,shared.czero);
7380 return;
7381 }
d4dd6556 7382 if (seconds <= 0) {
43e5ccdf 7383 if (deleteKey(c->db,key)) server.dirty++;
7384 addReply(c, shared.cone);
3305306f 7385 return;
7386 } else {
7387 time_t when = time(NULL)+seconds;
802e8373 7388 if (setExpire(c->db,key,when)) {
3305306f 7389 addReply(c,shared.cone);
77423026 7390 server.dirty++;
7391 } else {
3305306f 7392 addReply(c,shared.czero);
77423026 7393 }
3305306f 7394 return;
7395 }
7396}
7397
802e8373 7398static void expireCommand(redisClient *c) {
bbe025e0 7399 expireGenericCommand(c,c->argv[1],c->argv[2],0);
802e8373 7400}
7401
7402static void expireatCommand(redisClient *c) {
bbe025e0 7403 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
802e8373 7404}
7405
fd88489a 7406static void ttlCommand(redisClient *c) {
7407 time_t expire;
7408 int ttl = -1;
7409
7410 expire = getExpire(c->db,c->argv[1]);
7411 if (expire != -1) {
7412 ttl = (int) (expire-time(NULL));
7413 if (ttl < 0) ttl = -1;
7414 }
7415 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
7416}
7417
6e469882 7418/* ================================ MULTI/EXEC ============================== */
7419
7420/* Client state initialization for MULTI/EXEC */
7421static void initClientMultiState(redisClient *c) {
7422 c->mstate.commands = NULL;
7423 c->mstate.count = 0;
7424}
7425
7426/* Release all the resources associated with MULTI/EXEC state */
7427static void freeClientMultiState(redisClient *c) {
7428 int j;
7429
7430 for (j = 0; j < c->mstate.count; j++) {
7431 int i;
7432 multiCmd *mc = c->mstate.commands+j;
7433
7434 for (i = 0; i < mc->argc; i++)
7435 decrRefCount(mc->argv[i]);
7436 zfree(mc->argv);
7437 }
7438 zfree(c->mstate.commands);
7439}
7440
7441/* Add a new command into the MULTI commands queue */
7442static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
7443 multiCmd *mc;
7444 int j;
7445
7446 c->mstate.commands = zrealloc(c->mstate.commands,
7447 sizeof(multiCmd)*(c->mstate.count+1));
7448 mc = c->mstate.commands+c->mstate.count;
7449 mc->cmd = cmd;
7450 mc->argc = c->argc;
7451 mc->argv = zmalloc(sizeof(robj*)*c->argc);
7452 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
7453 for (j = 0; j < c->argc; j++)
7454 incrRefCount(mc->argv[j]);
7455 c->mstate.count++;
7456}
7457
7458static void multiCommand(redisClient *c) {
7459 c->flags |= REDIS_MULTI;
36c548f0 7460 addReply(c,shared.ok);
6e469882 7461}
7462
18b6cb76
DJ
7463static void discardCommand(redisClient *c) {
7464 if (!(c->flags & REDIS_MULTI)) {
7465 addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
7466 return;
7467 }
7468
7469 freeClientMultiState(c);
7470 initClientMultiState(c);
7471 c->flags &= (~REDIS_MULTI);
7472 addReply(c,shared.ok);
7473}
7474
66c8853f 7475/* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7476 * implememntation for more information. */
7477static void execCommandReplicateMulti(redisClient *c) {
7478 struct redisCommand *cmd;
7479 robj *multistring = createStringObject("MULTI",5);
7480
7481 cmd = lookupCommand("multi");
7482 if (server.appendonly)
7483 feedAppendOnlyFile(cmd,c->db->id,&multistring,1);
7484 if (listLength(server.slaves))
7485 replicationFeedSlaves(server.slaves,c->db->id,&multistring,1);
7486 decrRefCount(multistring);
7487}
7488
6e469882 7489static void execCommand(redisClient *c) {
7490 int j;
7491 robj **orig_argv;
7492 int orig_argc;
7493
7494 if (!(c->flags & REDIS_MULTI)) {
7495 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
7496 return;
7497 }
7498
66c8853f 7499 /* Replicate a MULTI request now that we are sure the block is executed.
7500 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7501 * both the AOF and the replication link will have the same consistency
7502 * and atomicity guarantees. */
7503 execCommandReplicateMulti(c);
7504
7505 /* Exec all the queued commands */
6e469882 7506 orig_argv = c->argv;
7507 orig_argc = c->argc;
7508 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
7509 for (j = 0; j < c->mstate.count; j++) {
7510 c->argc = c->mstate.commands[j].argc;
7511 c->argv = c->mstate.commands[j].argv;
7512 call(c,c->mstate.commands[j].cmd);
7513 }
7514 c->argv = orig_argv;
7515 c->argc = orig_argc;
7516 freeClientMultiState(c);
7517 initClientMultiState(c);
7518 c->flags &= (~REDIS_MULTI);
66c8853f 7519 /* Make sure the EXEC command is always replicated / AOF, since we
7520 * always send the MULTI command (we can't know beforehand if the
7521 * next operations will contain at least a modification to the DB). */
7522 server.dirty++;
6e469882 7523}
7524
4409877e 7525/* =========================== Blocking Operations ========================= */
7526
7527/* Currently Redis blocking operations support is limited to list POP ops,
7528 * so the current implementation is not fully generic, but it is also not
7529 * completely specific so it will not require a rewrite to support new
7530 * kind of blocking operations in the future.
7531 *
7532 * Still it's important to note that list blocking operations can be already
7533 * used as a notification mechanism in order to implement other blocking
7534 * operations at application level, so there must be a very strong evidence
7535 * of usefulness and generality before new blocking operations are implemented.
7536 *
7537 * This is how the current blocking POP works, we use BLPOP as example:
7538 * - If the user calls BLPOP and the key exists and contains a non empty list
7539 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7540 * if there is not to block.
7541 * - If instead BLPOP is called and the key does not exists or the list is
7542 * empty we need to block. In order to do so we remove the notification for
7543 * new data to read in the client socket (so that we'll not serve new
7544 * requests if the blocking request is not served). Also we put the client
95242ab5 7545 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
4409877e 7546 * blocking for this keys.
7547 * - If a PUSH operation against a key with blocked clients waiting is
7548 * performed, we serve the first in the list: basically instead to push
7549 * the new element inside the list we return it to the (first / oldest)
7550 * blocking client, unblock the client, and remove it form the list.
7551 *
7552 * The above comment and the source code should be enough in order to understand
7553 * the implementation and modify / fix it later.
7554 */
7555
7556/* Set a client in blocking mode for the specified key, with the specified
7557 * timeout */
b177fd30 7558static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
4409877e 7559 dictEntry *de;
7560 list *l;
b177fd30 7561 int j;
4409877e 7562
b177fd30 7563 c->blockingkeys = zmalloc(sizeof(robj*)*numkeys);
7564 c->blockingkeysnum = numkeys;
4409877e 7565 c->blockingto = timeout;
b177fd30 7566 for (j = 0; j < numkeys; j++) {
7567 /* Add the key in the client structure, to map clients -> keys */
7568 c->blockingkeys[j] = keys[j];
7569 incrRefCount(keys[j]);
4409877e 7570
b177fd30 7571 /* And in the other "side", to map keys -> clients */
7572 de = dictFind(c->db->blockingkeys,keys[j]);
7573 if (de == NULL) {
7574 int retval;
7575
7576 /* For every key we take a list of clients blocked for it */
7577 l = listCreate();
7578 retval = dictAdd(c->db->blockingkeys,keys[j],l);
7579 incrRefCount(keys[j]);
7580 assert(retval == DICT_OK);
7581 } else {
7582 l = dictGetEntryVal(de);
7583 }
7584 listAddNodeTail(l,c);
4409877e 7585 }
b177fd30 7586 /* Mark the client as a blocked client */
4409877e 7587 c->flags |= REDIS_BLOCKED;
d5d55fc3 7588 server.blpop_blocked_clients++;
4409877e 7589}
7590
7591/* Unblock a client that's waiting in a blocking operation such as BLPOP */
b0d8747d 7592static void unblockClientWaitingData(redisClient *c) {
4409877e 7593 dictEntry *de;
7594 list *l;
b177fd30 7595 int j;
4409877e 7596
b177fd30 7597 assert(c->blockingkeys != NULL);
7598 /* The client may wait for multiple keys, so unblock it for every key. */
7599 for (j = 0; j < c->blockingkeysnum; j++) {
7600 /* Remove this client from the list of clients waiting for this key. */
7601 de = dictFind(c->db->blockingkeys,c->blockingkeys[j]);
7602 assert(de != NULL);
7603 l = dictGetEntryVal(de);
7604 listDelNode(l,listSearchKey(l,c));
7605 /* If the list is empty we need to remove it to avoid wasting memory */
7606 if (listLength(l) == 0)
7607 dictDelete(c->db->blockingkeys,c->blockingkeys[j]);
7608 decrRefCount(c->blockingkeys[j]);
7609 }
7610 /* Cleanup the client structure */
7611 zfree(c->blockingkeys);
7612 c->blockingkeys = NULL;
4409877e 7613 c->flags &= (~REDIS_BLOCKED);
d5d55fc3 7614 server.blpop_blocked_clients--;
5921aa36 7615 /* We want to process data if there is some command waiting
b0d8747d 7616 * in the input buffer. Note that this is safe even if
7617 * unblockClientWaitingData() gets called from freeClient() because
7618 * freeClient() will be smart enough to call this function
7619 * *after* c->querybuf was set to NULL. */
4409877e 7620 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
7621}
7622
7623/* This should be called from any function PUSHing into lists.
7624 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7625 * 'ele' is the element pushed.
7626 *
7627 * If the function returns 0 there was no client waiting for a list push
7628 * against this key.
7629 *
7630 * If the function returns 1 there was a client waiting for a list push
7631 * against this key, the element was passed to this client thus it's not
7632 * needed to actually add it to the list and the caller should return asap. */
7633static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
7634 struct dictEntry *de;
7635 redisClient *receiver;
7636 list *l;
7637 listNode *ln;
7638
7639 de = dictFind(c->db->blockingkeys,key);
7640 if (de == NULL) return 0;
7641 l = dictGetEntryVal(de);
7642 ln = listFirst(l);
7643 assert(ln != NULL);
7644 receiver = ln->value;
4409877e 7645
b177fd30 7646 addReplySds(receiver,sdsnew("*2\r\n"));
dd88747b 7647 addReplyBulk(receiver,key);
7648 addReplyBulk(receiver,ele);
b0d8747d 7649 unblockClientWaitingData(receiver);
4409877e 7650 return 1;
7651}
7652
7653/* Blocking RPOP/LPOP */
7654static void blockingPopGenericCommand(redisClient *c, int where) {
7655 robj *o;
7656 time_t timeout;
b177fd30 7657 int j;
4409877e 7658
b177fd30 7659 for (j = 1; j < c->argc-1; j++) {
7660 o = lookupKeyWrite(c->db,c->argv[j]);
7661 if (o != NULL) {
7662 if (o->type != REDIS_LIST) {
7663 addReply(c,shared.wrongtypeerr);
4409877e 7664 return;
b177fd30 7665 } else {
7666 list *list = o->ptr;
7667 if (listLength(list) != 0) {
7668 /* If the list contains elements fall back to the usual
7669 * non-blocking POP operation */
7670 robj *argv[2], **orig_argv;
7671 int orig_argc;
e0a62c7f 7672
b177fd30 7673 /* We need to alter the command arguments before to call
7674 * popGenericCommand() as the command takes a single key. */
7675 orig_argv = c->argv;
7676 orig_argc = c->argc;
7677 argv[1] = c->argv[j];
7678 c->argv = argv;
7679 c->argc = 2;
7680
7681 /* Also the return value is different, we need to output
7682 * the multi bulk reply header and the key name. The
7683 * "real" command will add the last element (the value)
7684 * for us. If this souds like an hack to you it's just
7685 * because it is... */
7686 addReplySds(c,sdsnew("*2\r\n"));
dd88747b 7687 addReplyBulk(c,argv[1]);
b177fd30 7688 popGenericCommand(c,where);
7689
7690 /* Fix the client structure with the original stuff */
7691 c->argv = orig_argv;
7692 c->argc = orig_argc;
7693 return;
7694 }
4409877e 7695 }
7696 }
7697 }
7698 /* If the list is empty or the key does not exists we must block */
b177fd30 7699 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
4409877e 7700 if (timeout > 0) timeout += time(NULL);
b177fd30 7701 blockForKeys(c,c->argv+1,c->argc-2,timeout);
4409877e 7702}
7703
7704static void blpopCommand(redisClient *c) {
7705 blockingPopGenericCommand(c,REDIS_HEAD);
7706}
7707
7708static void brpopCommand(redisClient *c) {
7709 blockingPopGenericCommand(c,REDIS_TAIL);
7710}
7711
ed9b544e 7712/* =============================== Replication ============================= */
7713
a4d1ba9a 7714static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 7715 ssize_t nwritten, ret = size;
7716 time_t start = time(NULL);
7717
7718 timeout++;
7719 while(size) {
7720 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
7721 nwritten = write(fd,ptr,size);
7722 if (nwritten == -1) return -1;
7723 ptr += nwritten;
7724 size -= nwritten;
7725 }
7726 if ((time(NULL)-start) > timeout) {
7727 errno = ETIMEDOUT;
7728 return -1;
7729 }
7730 }
7731 return ret;
7732}
7733
a4d1ba9a 7734static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 7735 ssize_t nread, totread = 0;
7736 time_t start = time(NULL);
7737
7738 timeout++;
7739 while(size) {
7740 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
7741 nread = read(fd,ptr,size);
7742 if (nread == -1) return -1;
7743 ptr += nread;
7744 size -= nread;
7745 totread += nread;
7746 }
7747 if ((time(NULL)-start) > timeout) {
7748 errno = ETIMEDOUT;
7749 return -1;
7750 }
7751 }
7752 return totread;
7753}
7754
7755static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
7756 ssize_t nread = 0;
7757
7758 size--;
7759 while(size) {
7760 char c;
7761
7762 if (syncRead(fd,&c,1,timeout) == -1) return -1;
7763 if (c == '\n') {
7764 *ptr = '\0';
7765 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
7766 return nread;
7767 } else {
7768 *ptr++ = c;
7769 *ptr = '\0';
7770 nread++;
7771 }
7772 }
7773 return nread;
7774}
7775
7776static void syncCommand(redisClient *c) {
40d224a9 7777 /* ignore SYNC if aleady slave or in monitor mode */
7778 if (c->flags & REDIS_SLAVE) return;
7779
7780 /* SYNC can't be issued when the server has pending data to send to
7781 * the client about already issued commands. We need a fresh reply
7782 * buffer registering the differences between the BGSAVE and the current
7783 * dataset, so that we can copy to other slaves if needed. */
7784 if (listLength(c->reply) != 0) {
7785 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7786 return;
7787 }
7788
7789 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
7790 /* Here we need to check if there is a background saving operation
7791 * in progress, or if it is required to start one */
9d65a1bb 7792 if (server.bgsavechildpid != -1) {
40d224a9 7793 /* Ok a background save is in progress. Let's check if it is a good
7794 * one for replication, i.e. if there is another slave that is
7795 * registering differences since the server forked to save */
7796 redisClient *slave;
7797 listNode *ln;
c7df85a4 7798 listIter li;
40d224a9 7799
c7df85a4 7800 listRewind(server.slaves,&li);
7801 while((ln = listNext(&li))) {
40d224a9 7802 slave = ln->value;
7803 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
40d224a9 7804 }
7805 if (ln) {
7806 /* Perfect, the server is already registering differences for
7807 * another slave. Set the right state, and copy the buffer. */
7808 listRelease(c->reply);
7809 c->reply = listDup(slave->reply);
40d224a9 7810 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7811 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
7812 } else {
7813 /* No way, we need to wait for the next BGSAVE in order to
7814 * register differences */
7815 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
7816 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
7817 }
7818 } else {
7819 /* Ok we don't have a BGSAVE in progress, let's start one */
7820 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
7821 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
7822 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
7823 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
7824 return;
7825 }
7826 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7827 }
6208b3a7 7828 c->repldbfd = -1;
40d224a9 7829 c->flags |= REDIS_SLAVE;
7830 c->slaveseldb = 0;
6b47e12e 7831 listAddNodeTail(server.slaves,c);
40d224a9 7832 return;
7833}
7834
6208b3a7 7835static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
7836 redisClient *slave = privdata;
7837 REDIS_NOTUSED(el);
7838 REDIS_NOTUSED(mask);
7839 char buf[REDIS_IOBUF_LEN];
7840 ssize_t nwritten, buflen;
7841
7842 if (slave->repldboff == 0) {
7843 /* Write the bulk write count before to transfer the DB. In theory here
7844 * we don't know how much room there is in the output buffer of the
7845 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7846 * operations) will never be smaller than the few bytes we need. */
7847 sds bulkcount;
7848
7849 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7850 slave->repldbsize);
7851 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
7852 {
7853 sdsfree(bulkcount);
7854 freeClient(slave);
7855 return;
7856 }
7857 sdsfree(bulkcount);
7858 }
7859 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
7860 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
7861 if (buflen <= 0) {
7862 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
7863 (buflen == 0) ? "premature EOF" : strerror(errno));
7864 freeClient(slave);
7865 return;
7866 }
7867 if ((nwritten = write(fd,buf,buflen)) == -1) {
f870935d 7868 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
6208b3a7 7869 strerror(errno));
7870 freeClient(slave);
7871 return;
7872 }
7873 slave->repldboff += nwritten;
7874 if (slave->repldboff == slave->repldbsize) {
7875 close(slave->repldbfd);
7876 slave->repldbfd = -1;
7877 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
7878 slave->replstate = REDIS_REPL_ONLINE;
7879 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
266373b2 7880 sendReplyToClient, slave) == AE_ERR) {
6208b3a7 7881 freeClient(slave);
7882 return;
7883 }
7884 addReplySds(slave,sdsempty());
7885 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
7886 }
7887}
ed9b544e 7888
a3b21203 7889/* This function is called at the end of every backgrond saving.
7890 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
7891 * otherwise REDIS_ERR is passed to the function.
7892 *
7893 * The goal of this function is to handle slaves waiting for a successful
7894 * background saving in order to perform non-blocking synchronization. */
7895static void updateSlavesWaitingBgsave(int bgsaveerr) {
6208b3a7 7896 listNode *ln;
7897 int startbgsave = 0;
c7df85a4 7898 listIter li;
ed9b544e 7899
c7df85a4 7900 listRewind(server.slaves,&li);
7901 while((ln = listNext(&li))) {
6208b3a7 7902 redisClient *slave = ln->value;
ed9b544e 7903
6208b3a7 7904 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
7905 startbgsave = 1;
7906 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7907 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
dde65f3f 7908 struct redis_stat buf;
e0a62c7f 7909
6208b3a7 7910 if (bgsaveerr != REDIS_OK) {
7911 freeClient(slave);
7912 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
7913 continue;
7914 }
7915 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
dde65f3f 7916 redis_fstat(slave->repldbfd,&buf) == -1) {
6208b3a7 7917 freeClient(slave);
7918 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
7919 continue;
7920 }
7921 slave->repldboff = 0;
7922 slave->repldbsize = buf.st_size;
7923 slave->replstate = REDIS_REPL_SEND_BULK;
7924 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
266373b2 7925 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
6208b3a7 7926 freeClient(slave);
7927 continue;
7928 }
7929 }
ed9b544e 7930 }
6208b3a7 7931 if (startbgsave) {
7932 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
c7df85a4 7933 listIter li;
7934
7935 listRewind(server.slaves,&li);
6208b3a7 7936 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
c7df85a4 7937 while((ln = listNext(&li))) {
6208b3a7 7938 redisClient *slave = ln->value;
ed9b544e 7939
6208b3a7 7940 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
7941 freeClient(slave);
7942 }
7943 }
7944 }
ed9b544e 7945}
7946
7947static int syncWithMaster(void) {
d0ccebcf 7948 char buf[1024], tmpfile[256], authcmd[1024];
18e61fa2 7949 long dumpsize;
ed9b544e 7950 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
8c5abee8 7951 int dfd, maxtries = 5;
ed9b544e 7952
7953 if (fd == -1) {
7954 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
7955 strerror(errno));
7956 return REDIS_ERR;
7957 }
d0ccebcf 7958
7959 /* AUTH with the master if required. */
7960 if(server.masterauth) {
7961 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
7962 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
7963 close(fd);
7964 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
7965 strerror(errno));
7966 return REDIS_ERR;
7967 }
7968 /* Read the AUTH result. */
7969 if (syncReadLine(fd,buf,1024,3600) == -1) {
7970 close(fd);
7971 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
7972 strerror(errno));
7973 return REDIS_ERR;
7974 }
7975 if (buf[0] != '+') {
7976 close(fd);
7977 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
7978 return REDIS_ERR;
7979 }
7980 }
7981
ed9b544e 7982 /* Issue the SYNC command */
7983 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
7984 close(fd);
7985 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
7986 strerror(errno));
7987 return REDIS_ERR;
7988 }
7989 /* Read the bulk write count */
8c4d91fc 7990 if (syncReadLine(fd,buf,1024,3600) == -1) {
ed9b544e 7991 close(fd);
7992 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
7993 strerror(errno));
7994 return REDIS_ERR;
7995 }
4aa701c1 7996 if (buf[0] != '$') {
7997 close(fd);
7998 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
7999 return REDIS_ERR;
8000 }
18e61fa2 8001 dumpsize = strtol(buf+1,NULL,10);
8002 redisLog(REDIS_NOTICE,"Receiving %ld bytes data dump from MASTER",dumpsize);
ed9b544e 8003 /* Read the bulk write data on a temp file */
8c5abee8 8004 while(maxtries--) {
8005 snprintf(tmpfile,256,
8006 "temp-%d.%ld.rdb",(int)time(NULL),(long int)getpid());
8007 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
8008 if (dfd != -1) break;
5de9ad7c 8009 sleep(1);
8c5abee8 8010 }
ed9b544e 8011 if (dfd == -1) {
8012 close(fd);
8013 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
8014 return REDIS_ERR;
8015 }
8016 while(dumpsize) {
8017 int nread, nwritten;
8018
8019 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
8020 if (nread == -1) {
8021 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
8022 strerror(errno));
8023 close(fd);
8024 close(dfd);
8025 return REDIS_ERR;
8026 }
8027 nwritten = write(dfd,buf,nread);
8028 if (nwritten == -1) {
8029 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
8030 close(fd);
8031 close(dfd);
8032 return REDIS_ERR;
8033 }
8034 dumpsize -= nread;
8035 }
8036 close(dfd);
8037 if (rename(tmpfile,server.dbfilename) == -1) {
8038 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
8039 unlink(tmpfile);
8040 close(fd);
8041 return REDIS_ERR;
8042 }
8043 emptyDb();
f78fd11b 8044 if (rdbLoad(server.dbfilename) != REDIS_OK) {
ed9b544e 8045 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
8046 close(fd);
8047 return REDIS_ERR;
8048 }
8049 server.master = createClient(fd);
8050 server.master->flags |= REDIS_MASTER;
179b3952 8051 server.master->authenticated = 1;
ed9b544e 8052 server.replstate = REDIS_REPL_CONNECTED;
8053 return REDIS_OK;
8054}
8055
321b0e13 8056static void slaveofCommand(redisClient *c) {
8057 if (!strcasecmp(c->argv[1]->ptr,"no") &&
8058 !strcasecmp(c->argv[2]->ptr,"one")) {
8059 if (server.masterhost) {
8060 sdsfree(server.masterhost);
8061 server.masterhost = NULL;
8062 if (server.master) freeClient(server.master);
8063 server.replstate = REDIS_REPL_NONE;
8064 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
8065 }
8066 } else {
8067 sdsfree(server.masterhost);
8068 server.masterhost = sdsdup(c->argv[1]->ptr);
8069 server.masterport = atoi(c->argv[2]->ptr);
8070 if (server.master) freeClient(server.master);
8071 server.replstate = REDIS_REPL_CONNECT;
8072 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
8073 server.masterhost, server.masterport);
8074 }
8075 addReply(c,shared.ok);
8076}
8077
3fd78bcd 8078/* ============================ Maxmemory directive ======================== */
8079
a5819310 8080/* Try to free one object form the pre-allocated objects free list.
8081 * This is useful under low mem conditions as by default we take 1 million
8082 * free objects allocated. On success REDIS_OK is returned, otherwise
8083 * REDIS_ERR. */
8084static int tryFreeOneObjectFromFreelist(void) {
f870935d 8085 robj *o;
8086
a5819310 8087 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
8088 if (listLength(server.objfreelist)) {
8089 listNode *head = listFirst(server.objfreelist);
8090 o = listNodeValue(head);
8091 listDelNode(server.objfreelist,head);
8092 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8093 zfree(o);
8094 return REDIS_OK;
8095 } else {
8096 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8097 return REDIS_ERR;
8098 }
f870935d 8099}
8100
3fd78bcd 8101/* This function gets called when 'maxmemory' is set on the config file to limit
8102 * the max memory used by the server, and we are out of memory.
8103 * This function will try to, in order:
8104 *
8105 * - Free objects from the free list
8106 * - Try to remove keys with an EXPIRE set
8107 *
8108 * It is not possible to free enough memory to reach used-memory < maxmemory
8109 * the server will start refusing commands that will enlarge even more the
8110 * memory usage.
8111 */
8112static void freeMemoryIfNeeded(void) {
8113 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
a5819310 8114 int j, k, freed = 0;
8115
8116 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
8117 for (j = 0; j < server.dbnum; j++) {
8118 int minttl = -1;
8119 robj *minkey = NULL;
8120 struct dictEntry *de;
8121
8122 if (dictSize(server.db[j].expires)) {
8123 freed = 1;
8124 /* From a sample of three keys drop the one nearest to
8125 * the natural expire */
8126 for (k = 0; k < 3; k++) {
8127 time_t t;
8128
8129 de = dictGetRandomKey(server.db[j].expires);
8130 t = (time_t) dictGetEntryVal(de);
8131 if (minttl == -1 || t < minttl) {
8132 minkey = dictGetEntryKey(de);
8133 minttl = t;
3fd78bcd 8134 }
3fd78bcd 8135 }
a5819310 8136 deleteKey(server.db+j,minkey);
3fd78bcd 8137 }
3fd78bcd 8138 }
a5819310 8139 if (!freed) return; /* nothing to free... */
3fd78bcd 8140 }
8141}
8142
f80dff62 8143/* ============================== Append Only file ========================== */
8144
28ed1f33 8145/* Write the append only file buffer on disk.
8146 *
8147 * Since we are required to write the AOF before replying to the client,
8148 * and the only way the client socket can get a write is entering when the
8149 * the event loop, we accumulate all the AOF writes in a memory
8150 * buffer and write it on disk using this function just before entering
8151 * the event loop again. */
8152static void flushAppendOnlyFile(void) {
8153 time_t now;
8154 ssize_t nwritten;
8155
8156 if (sdslen(server.aofbuf) == 0) return;
8157
8158 /* We want to perform a single write. This should be guaranteed atomic
8159 * at least if the filesystem we are writing is a real physical one.
8160 * While this will save us against the server being killed I don't think
8161 * there is much to do about the whole server stopping for power problems
8162 * or alike */
8163 nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf));
8164 if (nwritten != (signed)sdslen(server.aofbuf)) {
8165 /* Ooops, we are in troubles. The best thing to do for now is
8166 * aborting instead of giving the illusion that everything is
8167 * working as expected. */
8168 if (nwritten == -1) {
8169 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
8170 } else {
8171 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
8172 }
8173 exit(1);
8174 }
8175 sdsfree(server.aofbuf);
8176 server.aofbuf = sdsempty();
8177
8178 /* Fsync if needed */
8179 now = time(NULL);
8180 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
8181 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
8182 now-server.lastfsync > 1))
8183 {
8184 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8185 * flushing metadata. */
8186 aof_fsync(server.appendfd); /* Let's try to get this data on the disk */
8187 server.lastfsync = now;
8188 }
8189}
8190
9376e434
PN
8191static sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) {
8192 int j;
8193 buf = sdscatprintf(buf,"*%d\r\n",argc);
8194 for (j = 0; j < argc; j++) {
8195 robj *o = getDecodedObject(argv[j]);
8196 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
8197 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
8198 buf = sdscatlen(buf,"\r\n",2);
8199 decrRefCount(o);
8200 }
8201 return buf;
8202}
8203
8204static sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) {
8205 int argc = 3;
8206 long when;
8207 robj *argv[3];
8208
8209 /* Make sure we can use strtol */
8210 seconds = getDecodedObject(seconds);
8211 when = time(NULL)+strtol(seconds->ptr,NULL,10);
8212 decrRefCount(seconds);
8213
8214 argv[0] = createStringObject("EXPIREAT",8);
8215 argv[1] = key;
8216 argv[2] = createObject(REDIS_STRING,
8217 sdscatprintf(sdsempty(),"%ld",when));
8218 buf = catAppendOnlyGenericCommand(buf, argc, argv);
8219 decrRefCount(argv[0]);
8220 decrRefCount(argv[2]);
8221 return buf;
8222}
8223
f80dff62 8224static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
8225 sds buf = sdsempty();
f80dff62 8226 robj *tmpargv[3];
8227
8228 /* The DB this command was targetting is not the same as the last command
8229 * we appendend. To issue a SELECT command is needed. */
8230 if (dictid != server.appendseldb) {
8231 char seldb[64];
8232
8233 snprintf(seldb,sizeof(seldb),"%d",dictid);
682ac724 8234 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
83c6a618 8235 (unsigned long)strlen(seldb),seldb);
f80dff62 8236 server.appendseldb = dictid;
8237 }
8238
f80dff62 8239 if (cmd->proc == expireCommand) {
9376e434
PN
8240 /* Translate EXPIRE into EXPIREAT */
8241 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8242 } else if (cmd->proc == setexCommand) {
8243 /* Translate SETEX to SET and EXPIREAT */
8244 tmpargv[0] = createStringObject("SET",3);
f80dff62 8245 tmpargv[1] = argv[1];
9376e434
PN
8246 tmpargv[2] = argv[3];
8247 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
8248 decrRefCount(tmpargv[0]);
8249 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8250 } else {
8251 buf = catAppendOnlyGenericCommand(buf,argc,argv);
f80dff62 8252 }
8253
28ed1f33 8254 /* Append to the AOF buffer. This will be flushed on disk just before
8255 * of re-entering the event loop, so before the client will get a
8256 * positive reply about the operation performed. */
8257 server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf));
8258
85a83172 8259 /* If a background append only file rewriting is in progress we want to
8260 * accumulate the differences between the child DB and the current one
8261 * in a buffer, so that when the child process will do its work we
8262 * can append the differences to the new append only file. */
8263 if (server.bgrewritechildpid != -1)
8264 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
8265
8266 sdsfree(buf);
f80dff62 8267}
8268
8269/* In Redis commands are always executed in the context of a client, so in
8270 * order to load the append only file we need to create a fake client. */
8271static struct redisClient *createFakeClient(void) {
8272 struct redisClient *c = zmalloc(sizeof(*c));
8273
8274 selectDb(c,0);
8275 c->fd = -1;
8276 c->querybuf = sdsempty();
8277 c->argc = 0;
8278 c->argv = NULL;
8279 c->flags = 0;
9387d17d 8280 /* We set the fake client as a slave waiting for the synchronization
8281 * so that Redis will not try to send replies to this client. */
8282 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
f80dff62 8283 c->reply = listCreate();
8284 listSetFreeMethod(c->reply,decrRefCount);
8285 listSetDupMethod(c->reply,dupClientReplyValue);
4132ad8d 8286 initClientMultiState(c);
f80dff62 8287 return c;
8288}
8289
8290static void freeFakeClient(struct redisClient *c) {
8291 sdsfree(c->querybuf);
8292 listRelease(c->reply);
4132ad8d 8293 freeClientMultiState(c);
f80dff62 8294 zfree(c);
8295}
8296
8297/* Replay the append log file. On error REDIS_OK is returned. On non fatal
8298 * error (the append only file is zero-length) REDIS_ERR is returned. On
8299 * fatal error an error message is logged and the program exists. */
8300int loadAppendOnlyFile(char *filename) {
8301 struct redisClient *fakeClient;
8302 FILE *fp = fopen(filename,"r");
8303 struct redis_stat sb;
b492cf00 8304 unsigned long long loadedkeys = 0;
4132ad8d 8305 int appendonly = server.appendonly;
f80dff62 8306
8307 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
8308 return REDIS_ERR;
8309
8310 if (fp == NULL) {
8311 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
8312 exit(1);
8313 }
8314
4132ad8d
PN
8315 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8316 * to the same file we're about to read. */
8317 server.appendonly = 0;
8318
f80dff62 8319 fakeClient = createFakeClient();
8320 while(1) {
8321 int argc, j;
8322 unsigned long len;
8323 robj **argv;
8324 char buf[128];
8325 sds argsds;
8326 struct redisCommand *cmd;
8327
8328 if (fgets(buf,sizeof(buf),fp) == NULL) {
8329 if (feof(fp))
8330 break;
8331 else
8332 goto readerr;
8333 }
8334 if (buf[0] != '*') goto fmterr;
8335 argc = atoi(buf+1);
8336 argv = zmalloc(sizeof(robj*)*argc);
8337 for (j = 0; j < argc; j++) {
8338 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
8339 if (buf[0] != '$') goto fmterr;
8340 len = strtol(buf+1,NULL,10);
8341 argsds = sdsnewlen(NULL,len);
0f151ef1 8342 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
f80dff62 8343 argv[j] = createObject(REDIS_STRING,argsds);
8344 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
8345 }
8346
8347 /* Command lookup */
8348 cmd = lookupCommand(argv[0]->ptr);
8349 if (!cmd) {
8350 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
8351 exit(1);
8352 }
bdcb92f2 8353 /* Try object encoding */
f80dff62 8354 if (cmd->flags & REDIS_CMD_BULK)
05df7621 8355 argv[argc-1] = tryObjectEncoding(argv[argc-1]);
f80dff62 8356 /* Run the command in the context of a fake client */
8357 fakeClient->argc = argc;
8358 fakeClient->argv = argv;
8359 cmd->proc(fakeClient);
8360 /* Discard the reply objects list from the fake client */
8361 while(listLength(fakeClient->reply))
8362 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
8363 /* Clean up, ready for the next command */
8364 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
8365 zfree(argv);
b492cf00 8366 /* Handle swapping while loading big datasets when VM is on */
8367 loadedkeys++;
8368 if (server.vm_enabled && (loadedkeys % 5000) == 0) {
8369 while (zmalloc_used_memory() > server.vm_max_memory) {
a69a0c9c 8370 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
b492cf00 8371 }
8372 }
f80dff62 8373 }
4132ad8d
PN
8374
8375 /* This point can only be reached when EOF is reached without errors.
8376 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8377 if (fakeClient->flags & REDIS_MULTI) goto readerr;
8378
f80dff62 8379 fclose(fp);
8380 freeFakeClient(fakeClient);
4132ad8d 8381 server.appendonly = appendonly;
f80dff62 8382 return REDIS_OK;
8383
8384readerr:
8385 if (feof(fp)) {
8386 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
8387 } else {
8388 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
8389 }
8390 exit(1);
8391fmterr:
8392 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
8393 exit(1);
8394}
8395
9d65a1bb 8396/* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
9c8e3cee 8397static int fwriteBulkObject(FILE *fp, robj *obj) {
9d65a1bb 8398 char buf[128];
b9bc0eef 8399 int decrrc = 0;
8400
f2d9f50f 8401 /* Avoid the incr/decr ref count business if possible to help
8402 * copy-on-write (we are often in a child process when this function
8403 * is called).
8404 * Also makes sure that key objects don't get incrRefCount-ed when VM
8405 * is enabled */
8406 if (obj->encoding != REDIS_ENCODING_RAW) {
b9bc0eef 8407 obj = getDecodedObject(obj);
8408 decrrc = 1;
8409 }
9d65a1bb 8410 snprintf(buf,sizeof(buf),"$%ld\r\n",(long)sdslen(obj->ptr));
8411 if (fwrite(buf,strlen(buf),1,fp) == 0) goto err;
e96e4fbf 8412 if (sdslen(obj->ptr) && fwrite(obj->ptr,sdslen(obj->ptr),1,fp) == 0)
8413 goto err;
9d65a1bb 8414 if (fwrite("\r\n",2,1,fp) == 0) goto err;
b9bc0eef 8415 if (decrrc) decrRefCount(obj);
9d65a1bb 8416 return 1;
8417err:
b9bc0eef 8418 if (decrrc) decrRefCount(obj);
9d65a1bb 8419 return 0;
8420}
8421
9c8e3cee 8422/* Write binary-safe string into a file in the bulkformat
8423 * $<count>\r\n<payload>\r\n */
8424static int fwriteBulkString(FILE *fp, char *s, unsigned long len) {
8425 char buf[128];
8426
8427 snprintf(buf,sizeof(buf),"$%ld\r\n",(unsigned long)len);
8428 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8429 if (len && fwrite(s,len,1,fp) == 0) return 0;
8430 if (fwrite("\r\n",2,1,fp) == 0) return 0;
8431 return 1;
8432}
8433
9d65a1bb 8434/* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8435static int fwriteBulkDouble(FILE *fp, double d) {
8436 char buf[128], dbuf[128];
8437
8438 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
8439 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
8440 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8441 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
8442 return 1;
8443}
8444
8445/* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8446static int fwriteBulkLong(FILE *fp, long l) {
8447 char buf[128], lbuf[128];
8448
8449 snprintf(lbuf,sizeof(lbuf),"%ld\r\n",l);
8450 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(lbuf)-2);
8451 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8452 if (fwrite(lbuf,strlen(lbuf),1,fp) == 0) return 0;
8453 return 1;
8454}
8455
8456/* Write a sequence of commands able to fully rebuild the dataset into
8457 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8458static int rewriteAppendOnlyFile(char *filename) {
8459 dictIterator *di = NULL;
8460 dictEntry *de;
8461 FILE *fp;
8462 char tmpfile[256];
8463 int j;
8464 time_t now = time(NULL);
8465
8466 /* Note that we have to use a different temp name here compared to the
8467 * one used by rewriteAppendOnlyFileBackground() function. */
8468 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
8469 fp = fopen(tmpfile,"w");
8470 if (!fp) {
8471 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
8472 return REDIS_ERR;
8473 }
8474 for (j = 0; j < server.dbnum; j++) {
8475 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
8476 redisDb *db = server.db+j;
8477 dict *d = db->dict;
8478 if (dictSize(d) == 0) continue;
8479 di = dictGetIterator(d);
8480 if (!di) {
8481 fclose(fp);
8482 return REDIS_ERR;
8483 }
8484
8485 /* SELECT the new DB */
8486 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
85a83172 8487 if (fwriteBulkLong(fp,j) == 0) goto werr;
9d65a1bb 8488
8489 /* Iterate this DB writing every entry */
8490 while((de = dictNext(di)) != NULL) {
e7546c63 8491 robj *key, *o;
8492 time_t expiretime;
8493 int swapped;
8494
8495 key = dictGetEntryKey(de);
b9bc0eef 8496 /* If the value for this key is swapped, load a preview in memory.
8497 * We use a "swapped" flag to remember if we need to free the
8498 * value object instead to just increment the ref count anyway
8499 * in order to avoid copy-on-write of pages if we are forked() */
996cb5f7 8500 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
8501 key->storage == REDIS_VM_SWAPPING) {
e7546c63 8502 o = dictGetEntryVal(de);
8503 swapped = 0;
8504 } else {
8505 o = vmPreviewObject(key);
e7546c63 8506 swapped = 1;
8507 }
8508 expiretime = getExpire(db,key);
9d65a1bb 8509
8510 /* Save the key and associated value */
9d65a1bb 8511 if (o->type == REDIS_STRING) {
8512 /* Emit a SET command */
8513 char cmd[]="*3\r\n$3\r\nSET\r\n";
8514 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8515 /* Key and value */
9c8e3cee 8516 if (fwriteBulkObject(fp,key) == 0) goto werr;
8517 if (fwriteBulkObject(fp,o) == 0) goto werr;
9d65a1bb 8518 } else if (o->type == REDIS_LIST) {
8519 /* Emit the RPUSHes needed to rebuild the list */
8520 list *list = o->ptr;
8521 listNode *ln;
c7df85a4 8522 listIter li;
9d65a1bb 8523
c7df85a4 8524 listRewind(list,&li);
8525 while((ln = listNext(&li))) {
9d65a1bb 8526 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
8527 robj *eleobj = listNodeValue(ln);
8528
8529 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8530 if (fwriteBulkObject(fp,key) == 0) goto werr;
8531 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 8532 }
8533 } else if (o->type == REDIS_SET) {
8534 /* Emit the SADDs needed to rebuild the set */
8535 dict *set = o->ptr;
8536 dictIterator *di = dictGetIterator(set);
8537 dictEntry *de;
8538
8539 while((de = dictNext(di)) != NULL) {
8540 char cmd[]="*3\r\n$4\r\nSADD\r\n";
8541 robj *eleobj = dictGetEntryKey(de);
8542
8543 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8544 if (fwriteBulkObject(fp,key) == 0) goto werr;
8545 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 8546 }
8547 dictReleaseIterator(di);
8548 } else if (o->type == REDIS_ZSET) {
8549 /* Emit the ZADDs needed to rebuild the sorted set */
8550 zset *zs = o->ptr;
8551 dictIterator *di = dictGetIterator(zs->dict);
8552 dictEntry *de;
8553
8554 while((de = dictNext(di)) != NULL) {
8555 char cmd[]="*4\r\n$4\r\nZADD\r\n";
8556 robj *eleobj = dictGetEntryKey(de);
8557 double *score = dictGetEntryVal(de);
8558
8559 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8560 if (fwriteBulkObject(fp,key) == 0) goto werr;
9d65a1bb 8561 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
9c8e3cee 8562 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 8563 }
8564 dictReleaseIterator(di);
9c8e3cee 8565 } else if (o->type == REDIS_HASH) {
8566 char cmd[]="*4\r\n$4\r\nHSET\r\n";
8567
8568 /* Emit the HSETs needed to rebuild the hash */
8569 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
8570 unsigned char *p = zipmapRewind(o->ptr);
8571 unsigned char *field, *val;
8572 unsigned int flen, vlen;
8573
8574 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
8575 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8576 if (fwriteBulkObject(fp,key) == 0) goto werr;
8577 if (fwriteBulkString(fp,(char*)field,flen) == -1)
8578 return -1;
8579 if (fwriteBulkString(fp,(char*)val,vlen) == -1)
8580 return -1;
8581 }
8582 } else {
8583 dictIterator *di = dictGetIterator(o->ptr);
8584 dictEntry *de;
8585
8586 while((de = dictNext(di)) != NULL) {
8587 robj *field = dictGetEntryKey(de);
8588 robj *val = dictGetEntryVal(de);
8589
8590 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8591 if (fwriteBulkObject(fp,key) == 0) goto werr;
8592 if (fwriteBulkObject(fp,field) == -1) return -1;
8593 if (fwriteBulkObject(fp,val) == -1) return -1;
8594 }
8595 dictReleaseIterator(di);
8596 }
9d65a1bb 8597 } else {
f83c6cb5 8598 redisPanic("Unknown object type");
9d65a1bb 8599 }
8600 /* Save the expire time */
8601 if (expiretime != -1) {
e96e4fbf 8602 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
9d65a1bb 8603 /* If this key is already expired skip it */
8604 if (expiretime < now) continue;
8605 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8606 if (fwriteBulkObject(fp,key) == 0) goto werr;
9d65a1bb 8607 if (fwriteBulkLong(fp,expiretime) == 0) goto werr;
8608 }
b9bc0eef 8609 if (swapped) decrRefCount(o);
9d65a1bb 8610 }
8611 dictReleaseIterator(di);
8612 }
8613
8614 /* Make sure data will not remain on the OS's output buffers */
8615 fflush(fp);
8616 fsync(fileno(fp));
8617 fclose(fp);
e0a62c7f 8618
9d65a1bb 8619 /* Use RENAME to make sure the DB file is changed atomically only
8620 * if the generate DB file is ok. */
8621 if (rename(tmpfile,filename) == -1) {
8622 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
8623 unlink(tmpfile);
8624 return REDIS_ERR;
8625 }
8626 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
8627 return REDIS_OK;
8628
8629werr:
8630 fclose(fp);
8631 unlink(tmpfile);
e96e4fbf 8632 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
9d65a1bb 8633 if (di) dictReleaseIterator(di);
8634 return REDIS_ERR;
8635}
8636
8637/* This is how rewriting of the append only file in background works:
8638 *
8639 * 1) The user calls BGREWRITEAOF
8640 * 2) Redis calls this function, that forks():
8641 * 2a) the child rewrite the append only file in a temp file.
8642 * 2b) the parent accumulates differences in server.bgrewritebuf.
8643 * 3) When the child finished '2a' exists.
8644 * 4) The parent will trap the exit code, if it's OK, will append the
8645 * data accumulated into server.bgrewritebuf into the temp file, and
8646 * finally will rename(2) the temp file in the actual file name.
8647 * The the new file is reopened as the new append only file. Profit!
8648 */
8649static int rewriteAppendOnlyFileBackground(void) {
8650 pid_t childpid;
8651
8652 if (server.bgrewritechildpid != -1) return REDIS_ERR;
054e426d 8653 if (server.vm_enabled) waitEmptyIOJobsQueue();
9d65a1bb 8654 if ((childpid = fork()) == 0) {
8655 /* Child */
8656 char tmpfile[256];
9d65a1bb 8657
054e426d 8658 if (server.vm_enabled) vmReopenSwapFile();
8659 close(server.fd);
9d65a1bb 8660 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
8661 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
478c2c6f 8662 _exit(0);
9d65a1bb 8663 } else {
478c2c6f 8664 _exit(1);
9d65a1bb 8665 }
8666 } else {
8667 /* Parent */
8668 if (childpid == -1) {
8669 redisLog(REDIS_WARNING,
8670 "Can't rewrite append only file in background: fork: %s",
8671 strerror(errno));
8672 return REDIS_ERR;
8673 }
8674 redisLog(REDIS_NOTICE,
8675 "Background append only file rewriting started by pid %d",childpid);
8676 server.bgrewritechildpid = childpid;
884d4b39 8677 updateDictResizePolicy();
85a83172 8678 /* We set appendseldb to -1 in order to force the next call to the
8679 * feedAppendOnlyFile() to issue a SELECT command, so the differences
8680 * accumulated by the parent into server.bgrewritebuf will start
8681 * with a SELECT statement and it will be safe to merge. */
8682 server.appendseldb = -1;
9d65a1bb 8683 return REDIS_OK;
8684 }
8685 return REDIS_OK; /* unreached */
8686}
8687
8688static void bgrewriteaofCommand(redisClient *c) {
8689 if (server.bgrewritechildpid != -1) {
8690 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
8691 return;
8692 }
8693 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
49b99ab4 8694 char *status = "+Background append only file rewriting started\r\n";
8695 addReplySds(c,sdsnew(status));
9d65a1bb 8696 } else {
8697 addReply(c,shared.err);
8698 }
8699}
8700
8701static void aofRemoveTempFile(pid_t childpid) {
8702 char tmpfile[256];
8703
8704 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
8705 unlink(tmpfile);
8706}
8707
996cb5f7 8708/* Virtual Memory is composed mainly of two subsystems:
8709 * - Blocking Virutal Memory
8710 * - Threaded Virtual Memory I/O
8711 * The two parts are not fully decoupled, but functions are split among two
8712 * different sections of the source code (delimited by comments) in order to
8713 * make more clear what functionality is about the blocking VM and what about
8714 * the threaded (not blocking) VM.
8715 *
8716 * Redis VM design:
8717 *
8718 * Redis VM is a blocking VM (one that blocks reading swapped values from
8719 * disk into memory when a value swapped out is needed in memory) that is made
8720 * unblocking by trying to examine the command argument vector in order to
8721 * load in background values that will likely be needed in order to exec
8722 * the command. The command is executed only once all the relevant keys
8723 * are loaded into memory.
8724 *
8725 * This basically is almost as simple of a blocking VM, but almost as parallel
8726 * as a fully non-blocking VM.
8727 */
8728
8729/* =================== Virtual Memory - Blocking Side ====================== */
054e426d 8730
75680a3c 8731static void vmInit(void) {
8732 off_t totsize;
996cb5f7 8733 int pipefds[2];
bcaa7a4f 8734 size_t stacksize;
8b5bb414 8735 struct flock fl;
75680a3c 8736
4ad37480 8737 if (server.vm_max_threads != 0)
8738 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
8739
054e426d 8740 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
8b5bb414 8741 /* Try to open the old swap file, otherwise create it */
6fa987e3 8742 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
8743 server.vm_fp = fopen(server.vm_swap_file,"w+b");
8744 }
75680a3c 8745 if (server.vm_fp == NULL) {
6fa987e3 8746 redisLog(REDIS_WARNING,
8b5bb414 8747 "Can't open the swap file: %s. Exiting.",
6fa987e3 8748 strerror(errno));
75680a3c 8749 exit(1);
8750 }
8751 server.vm_fd = fileno(server.vm_fp);
8b5bb414 8752 /* Lock the swap file for writing, this is useful in order to avoid
8753 * another instance to use the same swap file for a config error. */
8754 fl.l_type = F_WRLCK;
8755 fl.l_whence = SEEK_SET;
8756 fl.l_start = fl.l_len = 0;
8757 if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
8758 redisLog(REDIS_WARNING,
8759 "Can't lock the swap file at '%s': %s. Make sure it is not used by another Redis instance.", server.vm_swap_file, strerror(errno));
8760 exit(1);
8761 }
8762 /* Initialize */
75680a3c 8763 server.vm_next_page = 0;
8764 server.vm_near_pages = 0;
7d98e08c 8765 server.vm_stats_used_pages = 0;
8766 server.vm_stats_swapped_objects = 0;
8767 server.vm_stats_swapouts = 0;
8768 server.vm_stats_swapins = 0;
75680a3c 8769 totsize = server.vm_pages*server.vm_page_size;
8770 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
8771 if (ftruncate(server.vm_fd,totsize) == -1) {
8772 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
8773 strerror(errno));
8774 exit(1);
8775 } else {
8776 redisLog(REDIS_NOTICE,"Swap file allocated with success");
8777 }
7d30035d 8778 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
f870935d 8779 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
4ef8de8a 8780 (long long) (server.vm_pages+7)/8, server.vm_pages);
7d30035d 8781 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
92f8e882 8782
996cb5f7 8783 /* Initialize threaded I/O (used by Virtual Memory) */
8784 server.io_newjobs = listCreate();
8785 server.io_processing = listCreate();
8786 server.io_processed = listCreate();
d5d55fc3 8787 server.io_ready_clients = listCreate();
92f8e882 8788 pthread_mutex_init(&server.io_mutex,NULL);
a5819310 8789 pthread_mutex_init(&server.obj_freelist_mutex,NULL);
8790 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
92f8e882 8791 server.io_active_threads = 0;
996cb5f7 8792 if (pipe(pipefds) == -1) {
8793 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
8794 ,strerror(errno));
8795 exit(1);
8796 }
8797 server.io_ready_pipe_read = pipefds[0];
8798 server.io_ready_pipe_write = pipefds[1];
8799 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
bcaa7a4f 8800 /* LZF requires a lot of stack */
8801 pthread_attr_init(&server.io_threads_attr);
8802 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
8803 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
8804 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
b9bc0eef 8805 /* Listen for events in the threaded I/O pipe */
8806 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
8807 vmThreadedIOCompletedJob, NULL) == AE_ERR)
8808 oom("creating file event");
75680a3c 8809}
8810
06224fec 8811/* Mark the page as used */
8812static void vmMarkPageUsed(off_t page) {
8813 off_t byte = page/8;
8814 int bit = page&7;
970e10bb 8815 redisAssert(vmFreePage(page) == 1);
06224fec 8816 server.vm_bitmap[byte] |= 1<<bit;
8817}
8818
8819/* Mark N contiguous pages as used, with 'page' being the first. */
8820static void vmMarkPagesUsed(off_t page, off_t count) {
8821 off_t j;
8822
8823 for (j = 0; j < count; j++)
7d30035d 8824 vmMarkPageUsed(page+j);
7d98e08c 8825 server.vm_stats_used_pages += count;
7c775e09 8826 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
8827 (long long)count, (long long)page);
06224fec 8828}
8829
8830/* Mark the page as free */
8831static void vmMarkPageFree(off_t page) {
8832 off_t byte = page/8;
8833 int bit = page&7;
970e10bb 8834 redisAssert(vmFreePage(page) == 0);
06224fec 8835 server.vm_bitmap[byte] &= ~(1<<bit);
8836}
8837
8838/* Mark N contiguous pages as free, with 'page' being the first. */
8839static void vmMarkPagesFree(off_t page, off_t count) {
8840 off_t j;
8841
8842 for (j = 0; j < count; j++)
7d30035d 8843 vmMarkPageFree(page+j);
7d98e08c 8844 server.vm_stats_used_pages -= count;
7c775e09 8845 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
8846 (long long)count, (long long)page);
06224fec 8847}
8848
8849/* Test if the page is free */
8850static int vmFreePage(off_t page) {
8851 off_t byte = page/8;
8852 int bit = page&7;
7d30035d 8853 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
06224fec 8854}
8855
8856/* Find N contiguous free pages storing the first page of the cluster in *first.
e0a62c7f 8857 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
3a66edc7 8858 * REDIS_ERR is returned.
06224fec 8859 *
8860 * This function uses a simple algorithm: we try to allocate
8861 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
8862 * again from the start of the swap file searching for free spaces.
8863 *
8864 * If it looks pretty clear that there are no free pages near our offset
8865 * we try to find less populated places doing a forward jump of
8866 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
8867 * without hurry, and then we jump again and so forth...
e0a62c7f 8868 *
06224fec 8869 * This function can be improved using a free list to avoid to guess
8870 * too much, since we could collect data about freed pages.
8871 *
8872 * note: I implemented this function just after watching an episode of
8873 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
8874 */
c7df85a4 8875static int vmFindContiguousPages(off_t *first, off_t n) {
06224fec 8876 off_t base, offset = 0, since_jump = 0, numfree = 0;
8877
8878 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
8879 server.vm_near_pages = 0;
8880 server.vm_next_page = 0;
8881 }
8882 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
8883 base = server.vm_next_page;
8884
8885 while(offset < server.vm_pages) {
8886 off_t this = base+offset;
8887
8888 /* If we overflow, restart from page zero */
8889 if (this >= server.vm_pages) {
8890 this -= server.vm_pages;
8891 if (this == 0) {
8892 /* Just overflowed, what we found on tail is no longer
8893 * interesting, as it's no longer contiguous. */
8894 numfree = 0;
8895 }
8896 }
8897 if (vmFreePage(this)) {
8898 /* This is a free page */
8899 numfree++;
8900 /* Already got N free pages? Return to the caller, with success */
8901 if (numfree == n) {
7d30035d 8902 *first = this-(n-1);
8903 server.vm_next_page = this+1;
7c775e09 8904 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
3a66edc7 8905 return REDIS_OK;
06224fec 8906 }
8907 } else {
8908 /* The current one is not a free page */
8909 numfree = 0;
8910 }
8911
8912 /* Fast-forward if the current page is not free and we already
8913 * searched enough near this place. */
8914 since_jump++;
8915 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
8916 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
8917 since_jump = 0;
8918 /* Note that even if we rewind after the jump, we are don't need
8919 * to make sure numfree is set to zero as we only jump *if* it
8920 * is set to zero. */
8921 } else {
8922 /* Otherwise just check the next page */
8923 offset++;
8924 }
8925 }
3a66edc7 8926 return REDIS_ERR;
8927}
8928
a5819310 8929/* Write the specified object at the specified page of the swap file */
8930static int vmWriteObjectOnSwap(robj *o, off_t page) {
8931 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
8932 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
8933 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
8934 redisLog(REDIS_WARNING,
9ebed7cf 8935 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
a5819310 8936 strerror(errno));
8937 return REDIS_ERR;
8938 }
8939 rdbSaveObject(server.vm_fp,o);
ba76a8f9 8940 fflush(server.vm_fp);
a5819310 8941 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
8942 return REDIS_OK;
8943}
8944
3a66edc7 8945/* Swap the 'val' object relative to 'key' into disk. Store all the information
8946 * needed to later retrieve the object into the key object.
8947 * If we can't find enough contiguous empty pages to swap the object on disk
8948 * REDIS_ERR is returned. */
a69a0c9c 8949static int vmSwapObjectBlocking(robj *key, robj *val) {
b9bc0eef 8950 off_t pages = rdbSavedObjectPages(val,NULL);
3a66edc7 8951 off_t page;
8952
8953 assert(key->storage == REDIS_VM_MEMORY);
4ef8de8a 8954 assert(key->refcount == 1);
3a66edc7 8955 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return REDIS_ERR;
a5819310 8956 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return REDIS_ERR;
3a66edc7 8957 key->vm.page = page;
8958 key->vm.usedpages = pages;
8959 key->storage = REDIS_VM_SWAPPED;
d894161b 8960 key->vtype = val->type;
3a66edc7 8961 decrRefCount(val); /* Deallocate the object from memory. */
8962 vmMarkPagesUsed(page,pages);
7d30035d 8963 redisLog(REDIS_DEBUG,"VM: object %s swapped out at %lld (%lld pages)",
8964 (unsigned char*) key->ptr,
8965 (unsigned long long) page, (unsigned long long) pages);
7d98e08c 8966 server.vm_stats_swapped_objects++;
8967 server.vm_stats_swapouts++;
3a66edc7 8968 return REDIS_OK;
8969}
8970
a5819310 8971static robj *vmReadObjectFromSwap(off_t page, int type) {
8972 robj *o;
3a66edc7 8973
a5819310 8974 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
8975 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
3a66edc7 8976 redisLog(REDIS_WARNING,
d5d55fc3 8977 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
3a66edc7 8978 strerror(errno));
478c2c6f 8979 _exit(1);
3a66edc7 8980 }
a5819310 8981 o = rdbLoadObject(type,server.vm_fp);
8982 if (o == NULL) {
d5d55fc3 8983 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
478c2c6f 8984 _exit(1);
3a66edc7 8985 }
a5819310 8986 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
8987 return o;
8988}
8989
8990/* Load the value object relative to the 'key' object from swap to memory.
8991 * The newly allocated object is returned.
8992 *
8993 * If preview is true the unserialized object is returned to the caller but
8994 * no changes are made to the key object, nor the pages are marked as freed */
8995static robj *vmGenericLoadObject(robj *key, int preview) {
8996 robj *val;
8997
d5d55fc3 8998 redisAssert(key->storage == REDIS_VM_SWAPPED || key->storage == REDIS_VM_LOADING);
a5819310 8999 val = vmReadObjectFromSwap(key->vm.page,key->vtype);
7e69548d 9000 if (!preview) {
9001 key->storage = REDIS_VM_MEMORY;
9002 key->vm.atime = server.unixtime;
9003 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9004 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk",
9005 (unsigned char*) key->ptr);
7d98e08c 9006 server.vm_stats_swapped_objects--;
38aba9a1 9007 } else {
9008 redisLog(REDIS_DEBUG, "VM: object %s previewed from disk",
9009 (unsigned char*) key->ptr);
7e69548d 9010 }
7d98e08c 9011 server.vm_stats_swapins++;
3a66edc7 9012 return val;
06224fec 9013}
9014
7e69548d 9015/* Plain object loading, from swap to memory */
9016static robj *vmLoadObject(robj *key) {
996cb5f7 9017 /* If we are loading the object in background, stop it, we
9018 * need to load this object synchronously ASAP. */
9019 if (key->storage == REDIS_VM_LOADING)
9020 vmCancelThreadedIOJob(key);
7e69548d 9021 return vmGenericLoadObject(key,0);
9022}
9023
9024/* Just load the value on disk, without to modify the key.
9025 * This is useful when we want to perform some operation on the value
9026 * without to really bring it from swap to memory, like while saving the
9027 * dataset or rewriting the append only log. */
9028static robj *vmPreviewObject(robj *key) {
9029 return vmGenericLoadObject(key,1);
9030}
9031
4ef8de8a 9032/* How a good candidate is this object for swapping?
9033 * The better candidate it is, the greater the returned value.
9034 *
9035 * Currently we try to perform a fast estimation of the object size in
9036 * memory, and combine it with aging informations.
9037 *
9038 * Basically swappability = idle-time * log(estimated size)
9039 *
9040 * Bigger objects are preferred over smaller objects, but not
9041 * proportionally, this is why we use the logarithm. This algorithm is
9042 * just a first try and will probably be tuned later. */
9043static double computeObjectSwappability(robj *o) {
9044 time_t age = server.unixtime - o->vm.atime;
9045 long asize = 0;
9046 list *l;
9047 dict *d;
9048 struct dictEntry *de;
9049 int z;
9050
9051 if (age <= 0) return 0;
9052 switch(o->type) {
9053 case REDIS_STRING:
9054 if (o->encoding != REDIS_ENCODING_RAW) {
9055 asize = sizeof(*o);
9056 } else {
9057 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
9058 }
9059 break;
9060 case REDIS_LIST:
9061 l = o->ptr;
9062 listNode *ln = listFirst(l);
9063
9064 asize = sizeof(list);
9065 if (ln) {
9066 robj *ele = ln->value;
9067 long elesize;
9068
9069 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9070 (sizeof(*o)+sdslen(ele->ptr)) :
9071 sizeof(*o);
9072 asize += (sizeof(listNode)+elesize)*listLength(l);
9073 }
9074 break;
9075 case REDIS_SET:
9076 case REDIS_ZSET:
9077 z = (o->type == REDIS_ZSET);
9078 d = z ? ((zset*)o->ptr)->dict : o->ptr;
9079
9080 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9081 if (z) asize += sizeof(zset)-sizeof(dict);
9082 if (dictSize(d)) {
9083 long elesize;
9084 robj *ele;
9085
9086 de = dictGetRandomKey(d);
9087 ele = dictGetEntryKey(de);
9088 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9089 (sizeof(*o)+sdslen(ele->ptr)) :
9090 sizeof(*o);
9091 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9092 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
9093 }
9094 break;
a97b9060 9095 case REDIS_HASH:
9096 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9097 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
9098 unsigned int len = zipmapLen((unsigned char*)o->ptr);
9099 unsigned int klen, vlen;
9100 unsigned char *key, *val;
9101
9102 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
9103 klen = 0;
9104 vlen = 0;
9105 }
9106 asize = len*(klen+vlen+3);
9107 } else if (o->encoding == REDIS_ENCODING_HT) {
9108 d = o->ptr;
9109 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9110 if (dictSize(d)) {
9111 long elesize;
9112 robj *ele;
9113
9114 de = dictGetRandomKey(d);
9115 ele = dictGetEntryKey(de);
9116 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9117 (sizeof(*o)+sdslen(ele->ptr)) :
9118 sizeof(*o);
9119 ele = dictGetEntryVal(de);
9120 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9121 (sizeof(*o)+sdslen(ele->ptr)) :
9122 sizeof(*o);
9123 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9124 }
9125 }
9126 break;
4ef8de8a 9127 }
c8c72447 9128 return (double)age*log(1+asize);
4ef8de8a 9129}
9130
9131/* Try to swap an object that's a good candidate for swapping.
9132 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
a69a0c9c 9133 * to swap any object at all.
9134 *
9135 * If 'usethreaded' is true, Redis will try to swap the object in background
9136 * using I/O threads. */
9137static int vmSwapOneObject(int usethreads) {
4ef8de8a 9138 int j, i;
9139 struct dictEntry *best = NULL;
9140 double best_swappability = 0;
b9bc0eef 9141 redisDb *best_db = NULL;
4ef8de8a 9142 robj *key, *val;
9143
9144 for (j = 0; j < server.dbnum; j++) {
9145 redisDb *db = server.db+j;
b72f6a4b 9146 /* Why maxtries is set to 100?
9147 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9148 * are swappable objects */
b0d8747d 9149 int maxtries = 100;
4ef8de8a 9150
9151 if (dictSize(db->dict) == 0) continue;
9152 for (i = 0; i < 5; i++) {
9153 dictEntry *de;
9154 double swappability;
9155
e3cadb8a 9156 if (maxtries) maxtries--;
4ef8de8a 9157 de = dictGetRandomKey(db->dict);
9158 key = dictGetEntryKey(de);
9159 val = dictGetEntryVal(de);
1064ef87 9160 /* Only swap objects that are currently in memory.
9161 *
9162 * Also don't swap shared objects if threaded VM is on, as we
9163 * try to ensure that the main thread does not touch the
9164 * object while the I/O thread is using it, but we can't
9165 * control other keys without adding additional mutex. */
9166 if (key->storage != REDIS_VM_MEMORY ||
9167 (server.vm_max_threads != 0 && val->refcount != 1)) {
e3cadb8a 9168 if (maxtries) i--; /* don't count this try */
9169 continue;
9170 }
4ef8de8a 9171 swappability = computeObjectSwappability(val);
9172 if (!best || swappability > best_swappability) {
9173 best = de;
9174 best_swappability = swappability;
b9bc0eef 9175 best_db = db;
4ef8de8a 9176 }
9177 }
9178 }
7c775e09 9179 if (best == NULL) return REDIS_ERR;
4ef8de8a 9180 key = dictGetEntryKey(best);
9181 val = dictGetEntryVal(best);
9182
e3cadb8a 9183 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
4ef8de8a 9184 key->ptr, best_swappability);
9185
9186 /* Unshare the key if needed */
9187 if (key->refcount > 1) {
9188 robj *newkey = dupStringObject(key);
9189 decrRefCount(key);
9190 key = dictGetEntryKey(best) = newkey;
9191 }
9192 /* Swap it */
a69a0c9c 9193 if (usethreads) {
b9bc0eef 9194 vmSwapObjectThreaded(key,val,best_db);
4ef8de8a 9195 return REDIS_OK;
9196 } else {
a69a0c9c 9197 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
9198 dictGetEntryVal(best) = NULL;
9199 return REDIS_OK;
9200 } else {
9201 return REDIS_ERR;
9202 }
4ef8de8a 9203 }
9204}
9205
a69a0c9c 9206static int vmSwapOneObjectBlocking() {
9207 return vmSwapOneObject(0);
9208}
9209
9210static int vmSwapOneObjectThreaded() {
9211 return vmSwapOneObject(1);
9212}
9213
7e69548d 9214/* Return true if it's safe to swap out objects in a given moment.
9215 * Basically we don't want to swap objects out while there is a BGSAVE
9216 * or a BGAEOREWRITE running in backgroud. */
9217static int vmCanSwapOut(void) {
9218 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
9219}
9220
1b03836c 9221/* Delete a key if swapped. Returns 1 if the key was found, was swapped
9222 * and was deleted. Otherwise 0 is returned. */
9223static int deleteIfSwapped(redisDb *db, robj *key) {
9224 dictEntry *de;
9225 robj *foundkey;
9226
9227 if ((de = dictFind(db->dict,key)) == NULL) return 0;
9228 foundkey = dictGetEntryKey(de);
9229 if (foundkey->storage == REDIS_VM_MEMORY) return 0;
9230 deleteKey(db,key);
9231 return 1;
9232}
9233
996cb5f7 9234/* =================== Virtual Memory - Threaded I/O ======================= */
9235
b9bc0eef 9236static void freeIOJob(iojob *j) {
d5d55fc3 9237 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
9238 j->type == REDIS_IOJOB_DO_SWAP ||
9239 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
b9bc0eef 9240 decrRefCount(j->val);
78ebe4c8 9241 /* We don't decrRefCount the j->key field as we did't incremented
9242 * the count creating IO Jobs. This is because the key field here is
9243 * just used as an indentifier and if a key is removed the Job should
9244 * never be touched again. */
b9bc0eef 9245 zfree(j);
9246}
9247
996cb5f7 9248/* Every time a thread finished a Job, it writes a byte into the write side
9249 * of an unix pipe in order to "awake" the main thread, and this function
9250 * is called. */
9251static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
9252 int mask)
9253{
9254 char buf[1];
b0d8747d 9255 int retval, processed = 0, toprocess = -1, trytoswap = 1;
996cb5f7 9256 REDIS_NOTUSED(el);
9257 REDIS_NOTUSED(mask);
9258 REDIS_NOTUSED(privdata);
9259
9260 /* For every byte we read in the read side of the pipe, there is one
9261 * I/O job completed to process. */
9262 while((retval = read(fd,buf,1)) == 1) {
b9bc0eef 9263 iojob *j;
9264 listNode *ln;
9265 robj *key;
9266 struct dictEntry *de;
9267
996cb5f7 9268 redisLog(REDIS_DEBUG,"Processing I/O completed job");
b9bc0eef 9269
9270 /* Get the processed element (the oldest one) */
9271 lockThreadedIO();
1064ef87 9272 assert(listLength(server.io_processed) != 0);
f6c0bba8 9273 if (toprocess == -1) {
9274 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
9275 if (toprocess <= 0) toprocess = 1;
9276 }
b9bc0eef 9277 ln = listFirst(server.io_processed);
9278 j = ln->value;
9279 listDelNode(server.io_processed,ln);
9280 unlockThreadedIO();
9281 /* If this job is marked as canceled, just ignore it */
9282 if (j->canceled) {
9283 freeIOJob(j);
9284 continue;
9285 }
9286 /* Post process it in the main thread, as there are things we
9287 * can do just here to avoid race conditions and/or invasive locks */
6c96ba7d 9288 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 9289 de = dictFind(j->db->dict,j->key);
9290 assert(de != NULL);
9291 key = dictGetEntryKey(de);
9292 if (j->type == REDIS_IOJOB_LOAD) {
d5d55fc3 9293 redisDb *db;
9294
b9bc0eef 9295 /* Key loaded, bring it at home */
9296 key->storage = REDIS_VM_MEMORY;
9297 key->vm.atime = server.unixtime;
9298 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9299 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
9300 (unsigned char*) key->ptr);
9301 server.vm_stats_swapped_objects--;
9302 server.vm_stats_swapins++;
d5d55fc3 9303 dictGetEntryVal(de) = j->val;
9304 incrRefCount(j->val);
9305 db = j->db;
b9bc0eef 9306 freeIOJob(j);
d5d55fc3 9307 /* Handle clients waiting for this key to be loaded. */
9308 handleClientsBlockedOnSwappedKey(db,key);
b9bc0eef 9309 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9310 /* Now we know the amount of pages required to swap this object.
9311 * Let's find some space for it, and queue this task again
9312 * rebranded as REDIS_IOJOB_DO_SWAP. */
054e426d 9313 if (!vmCanSwapOut() ||
9314 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
9315 {
9316 /* Ooops... no space or we can't swap as there is
9317 * a fork()ed Redis trying to save stuff on disk. */
b9bc0eef 9318 freeIOJob(j);
054e426d 9319 key->storage = REDIS_VM_MEMORY; /* undo operation */
b9bc0eef 9320 } else {
c7df85a4 9321 /* Note that we need to mark this pages as used now,
9322 * if the job will be canceled, we'll mark them as freed
9323 * again. */
9324 vmMarkPagesUsed(j->page,j->pages);
b9bc0eef 9325 j->type = REDIS_IOJOB_DO_SWAP;
9326 lockThreadedIO();
9327 queueIOJob(j);
9328 unlockThreadedIO();
9329 }
9330 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9331 robj *val;
9332
9333 /* Key swapped. We can finally free some memory. */
6c96ba7d 9334 if (key->storage != REDIS_VM_SWAPPING) {
9335 printf("key->storage: %d\n",key->storage);
9336 printf("key->name: %s\n",(char*)key->ptr);
9337 printf("key->refcount: %d\n",key->refcount);
9338 printf("val: %p\n",(void*)j->val);
9339 printf("val->type: %d\n",j->val->type);
9340 printf("val->ptr: %s\n",(char*)j->val->ptr);
9341 }
9342 redisAssert(key->storage == REDIS_VM_SWAPPING);
b9bc0eef 9343 val = dictGetEntryVal(de);
9344 key->vm.page = j->page;
9345 key->vm.usedpages = j->pages;
9346 key->storage = REDIS_VM_SWAPPED;
9347 key->vtype = j->val->type;
9348 decrRefCount(val); /* Deallocate the object from memory. */
f11b8647 9349 dictGetEntryVal(de) = NULL;
b9bc0eef 9350 redisLog(REDIS_DEBUG,
9351 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9352 (unsigned char*) key->ptr,
9353 (unsigned long long) j->page, (unsigned long long) j->pages);
9354 server.vm_stats_swapped_objects++;
9355 server.vm_stats_swapouts++;
9356 freeIOJob(j);
f11b8647 9357 /* Put a few more swap requests in queue if we are still
9358 * out of memory */
b0d8747d 9359 if (trytoswap && vmCanSwapOut() &&
9360 zmalloc_used_memory() > server.vm_max_memory)
9361 {
f11b8647 9362 int more = 1;
9363 while(more) {
9364 lockThreadedIO();
9365 more = listLength(server.io_newjobs) <
9366 (unsigned) server.vm_max_threads;
9367 unlockThreadedIO();
9368 /* Don't waste CPU time if swappable objects are rare. */
b0d8747d 9369 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
9370 trytoswap = 0;
9371 break;
9372 }
f11b8647 9373 }
9374 }
b9bc0eef 9375 }
c953f24b 9376 processed++;
f6c0bba8 9377 if (processed == toprocess) return;
996cb5f7 9378 }
9379 if (retval < 0 && errno != EAGAIN) {
9380 redisLog(REDIS_WARNING,
9381 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9382 strerror(errno));
9383 }
9384}
9385
9386static void lockThreadedIO(void) {
9387 pthread_mutex_lock(&server.io_mutex);
9388}
9389
9390static void unlockThreadedIO(void) {
9391 pthread_mutex_unlock(&server.io_mutex);
9392}
9393
9394/* Remove the specified object from the threaded I/O queue if still not
9395 * processed, otherwise make sure to flag it as canceled. */
9396static void vmCancelThreadedIOJob(robj *o) {
9397 list *lists[3] = {
6c96ba7d 9398 server.io_newjobs, /* 0 */
9399 server.io_processing, /* 1 */
9400 server.io_processed /* 2 */
996cb5f7 9401 };
9402 int i;
9403
9404 assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
2e111efe 9405again:
996cb5f7 9406 lockThreadedIO();
9407 /* Search for a matching key in one of the queues */
9408 for (i = 0; i < 3; i++) {
9409 listNode *ln;
c7df85a4 9410 listIter li;
996cb5f7 9411
c7df85a4 9412 listRewind(lists[i],&li);
9413 while ((ln = listNext(&li)) != NULL) {
996cb5f7 9414 iojob *job = ln->value;
9415
6c96ba7d 9416 if (job->canceled) continue; /* Skip this, already canceled. */
78ebe4c8 9417 if (job->key == o) {
970e10bb 9418 redisLog(REDIS_DEBUG,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
9419 (void*)job, (char*)o->ptr, job->type, i);
427a2153 9420 /* Mark the pages as free since the swap didn't happened
9421 * or happened but is now discarded. */
970e10bb 9422 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
427a2153 9423 vmMarkPagesFree(job->page,job->pages);
9424 /* Cancel the job. It depends on the list the job is
9425 * living in. */
996cb5f7 9426 switch(i) {
9427 case 0: /* io_newjobs */
6c96ba7d 9428 /* If the job was yet not processed the best thing to do
996cb5f7 9429 * is to remove it from the queue at all */
6c96ba7d 9430 freeIOJob(job);
996cb5f7 9431 listDelNode(lists[i],ln);
9432 break;
9433 case 1: /* io_processing */
d5d55fc3 9434 /* Oh Shi- the thread is messing with the Job:
9435 *
9436 * Probably it's accessing the object if this is a
9437 * PREPARE_SWAP or DO_SWAP job.
9438 * If it's a LOAD job it may be reading from disk and
9439 * if we don't wait for the job to terminate before to
9440 * cancel it, maybe in a few microseconds data can be
9441 * corrupted in this pages. So the short story is:
9442 *
9443 * Better to wait for the job to move into the
9444 * next queue (processed)... */
9445
9446 /* We try again and again until the job is completed. */
9447 unlockThreadedIO();
9448 /* But let's wait some time for the I/O thread
9449 * to finish with this job. After all this condition
9450 * should be very rare. */
9451 usleep(1);
9452 goto again;
996cb5f7 9453 case 2: /* io_processed */
2e111efe 9454 /* The job was already processed, that's easy...
9455 * just mark it as canceled so that we'll ignore it
9456 * when processing completed jobs. */
996cb5f7 9457 job->canceled = 1;
9458 break;
9459 }
c7df85a4 9460 /* Finally we have to adjust the storage type of the object
9461 * in order to "UNDO" the operaiton. */
996cb5f7 9462 if (o->storage == REDIS_VM_LOADING)
9463 o->storage = REDIS_VM_SWAPPED;
9464 else if (o->storage == REDIS_VM_SWAPPING)
9465 o->storage = REDIS_VM_MEMORY;
9466 unlockThreadedIO();
9467 return;
9468 }
9469 }
9470 }
9471 unlockThreadedIO();
9472 assert(1 != 1); /* We should never reach this */
9473}
9474
b9bc0eef 9475static void *IOThreadEntryPoint(void *arg) {
9476 iojob *j;
9477 listNode *ln;
9478 REDIS_NOTUSED(arg);
9479
9480 pthread_detach(pthread_self());
9481 while(1) {
9482 /* Get a new job to process */
9483 lockThreadedIO();
9484 if (listLength(server.io_newjobs) == 0) {
9485 /* No new jobs in queue, exit. */
9ebed7cf 9486 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
9487 (long) pthread_self());
b9bc0eef 9488 server.io_active_threads--;
9489 unlockThreadedIO();
9490 return NULL;
9491 }
9492 ln = listFirst(server.io_newjobs);
9493 j = ln->value;
9494 listDelNode(server.io_newjobs,ln);
9495 /* Add the job in the processing queue */
9496 j->thread = pthread_self();
9497 listAddNodeTail(server.io_processing,j);
9498 ln = listLast(server.io_processing); /* We use ln later to remove it */
9499 unlockThreadedIO();
9ebed7cf 9500 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
9501 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
b9bc0eef 9502
9503 /* Process the Job */
9504 if (j->type == REDIS_IOJOB_LOAD) {
d5d55fc3 9505 j->val = vmReadObjectFromSwap(j->page,j->key->vtype);
b9bc0eef 9506 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9507 FILE *fp = fopen("/dev/null","w+");
9508 j->pages = rdbSavedObjectPages(j->val,fp);
9509 fclose(fp);
9510 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
a5819310 9511 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
9512 j->canceled = 1;
b9bc0eef 9513 }
9514
9515 /* Done: insert the job into the processed queue */
9ebed7cf 9516 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
9517 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
b9bc0eef 9518 lockThreadedIO();
9519 listDelNode(server.io_processing,ln);
9520 listAddNodeTail(server.io_processed,j);
9521 unlockThreadedIO();
e0a62c7f 9522
b9bc0eef 9523 /* Signal the main thread there is new stuff to process */
9524 assert(write(server.io_ready_pipe_write,"x",1) == 1);
9525 }
9526 return NULL; /* never reached */
9527}
9528
9529static void spawnIOThread(void) {
9530 pthread_t thread;
478c2c6f 9531 sigset_t mask, omask;
a97b9060 9532 int err;
b9bc0eef 9533
478c2c6f 9534 sigemptyset(&mask);
9535 sigaddset(&mask,SIGCHLD);
9536 sigaddset(&mask,SIGHUP);
9537 sigaddset(&mask,SIGPIPE);
9538 pthread_sigmask(SIG_SETMASK, &mask, &omask);
a97b9060 9539 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
9540 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
9541 strerror(err));
9542 usleep(1000000);
9543 }
478c2c6f 9544 pthread_sigmask(SIG_SETMASK, &omask, NULL);
b9bc0eef 9545 server.io_active_threads++;
9546}
9547
4ee9488d 9548/* We need to wait for the last thread to exit before we are able to
9549 * fork() in order to BGSAVE or BGREWRITEAOF. */
054e426d 9550static void waitEmptyIOJobsQueue(void) {
4ee9488d 9551 while(1) {
76b7233a 9552 int io_processed_len;
9553
4ee9488d 9554 lockThreadedIO();
054e426d 9555 if (listLength(server.io_newjobs) == 0 &&
9556 listLength(server.io_processing) == 0 &&
9557 server.io_active_threads == 0)
9558 {
4ee9488d 9559 unlockThreadedIO();
9560 return;
9561 }
76b7233a 9562 /* While waiting for empty jobs queue condition we post-process some
9563 * finshed job, as I/O threads may be hanging trying to write against
9564 * the io_ready_pipe_write FD but there are so much pending jobs that
9565 * it's blocking. */
9566 io_processed_len = listLength(server.io_processed);
4ee9488d 9567 unlockThreadedIO();
76b7233a 9568 if (io_processed_len) {
9569 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
9570 usleep(1000); /* 1 millisecond */
9571 } else {
9572 usleep(10000); /* 10 milliseconds */
9573 }
4ee9488d 9574 }
9575}
9576
054e426d 9577static void vmReopenSwapFile(void) {
478c2c6f 9578 /* Note: we don't close the old one as we are in the child process
9579 * and don't want to mess at all with the original file object. */
054e426d 9580 server.vm_fp = fopen(server.vm_swap_file,"r+b");
9581 if (server.vm_fp == NULL) {
9582 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
9583 server.vm_swap_file);
478c2c6f 9584 _exit(1);
054e426d 9585 }
9586 server.vm_fd = fileno(server.vm_fp);
9587}
9588
b9bc0eef 9589/* This function must be called while with threaded IO locked */
9590static void queueIOJob(iojob *j) {
6c96ba7d 9591 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
9592 (void*)j, j->type, (char*)j->key->ptr);
b9bc0eef 9593 listAddNodeTail(server.io_newjobs,j);
9594 if (server.io_active_threads < server.vm_max_threads)
9595 spawnIOThread();
9596}
9597
9598static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
9599 iojob *j;
e0a62c7f 9600
b9bc0eef 9601 assert(key->storage == REDIS_VM_MEMORY);
9602 assert(key->refcount == 1);
9603
9604 j = zmalloc(sizeof(*j));
9605 j->type = REDIS_IOJOB_PREPARE_SWAP;
9606 j->db = db;
78ebe4c8 9607 j->key = key;
b9bc0eef 9608 j->val = val;
9609 incrRefCount(val);
9610 j->canceled = 0;
9611 j->thread = (pthread_t) -1;
f11b8647 9612 key->storage = REDIS_VM_SWAPPING;
b9bc0eef 9613
9614 lockThreadedIO();
9615 queueIOJob(j);
9616 unlockThreadedIO();
9617 return REDIS_OK;
9618}
9619
b0d8747d 9620/* ============ Virtual Memory - Blocking clients on missing keys =========== */
9621
d5d55fc3 9622/* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
9623 * If there is not already a job loading the key, it is craeted.
9624 * The key is added to the io_keys list in the client structure, and also
9625 * in the hash table mapping swapped keys to waiting clients, that is,
9626 * server.io_waited_keys. */
9627static int waitForSwappedKey(redisClient *c, robj *key) {
9628 struct dictEntry *de;
9629 robj *o;
9630 list *l;
9631
9632 /* If the key does not exist or is already in RAM we don't need to
9633 * block the client at all. */
9634 de = dictFind(c->db->dict,key);
9635 if (de == NULL) return 0;
9636 o = dictGetEntryKey(de);
9637 if (o->storage == REDIS_VM_MEMORY) {
9638 return 0;
9639 } else if (o->storage == REDIS_VM_SWAPPING) {
9640 /* We were swapping the key, undo it! */
9641 vmCancelThreadedIOJob(o);
9642 return 0;
9643 }
e0a62c7f 9644
d5d55fc3 9645 /* OK: the key is either swapped, or being loaded just now. */
9646
9647 /* Add the key to the list of keys this client is waiting for.
9648 * This maps clients to keys they are waiting for. */
9649 listAddNodeTail(c->io_keys,key);
9650 incrRefCount(key);
9651
9652 /* Add the client to the swapped keys => clients waiting map. */
9653 de = dictFind(c->db->io_keys,key);
9654 if (de == NULL) {
9655 int retval;
9656
9657 /* For every key we take a list of clients blocked for it */
9658 l = listCreate();
9659 retval = dictAdd(c->db->io_keys,key,l);
9660 incrRefCount(key);
9661 assert(retval == DICT_OK);
9662 } else {
9663 l = dictGetEntryVal(de);
9664 }
9665 listAddNodeTail(l,c);
9666
9667 /* Are we already loading the key from disk? If not create a job */
9668 if (o->storage == REDIS_VM_SWAPPED) {
9669 iojob *j;
9670
9671 o->storage = REDIS_VM_LOADING;
9672 j = zmalloc(sizeof(*j));
9673 j->type = REDIS_IOJOB_LOAD;
9674 j->db = c->db;
78ebe4c8 9675 j->key = o;
d5d55fc3 9676 j->key->vtype = o->vtype;
9677 j->page = o->vm.page;
9678 j->val = NULL;
9679 j->canceled = 0;
9680 j->thread = (pthread_t) -1;
9681 lockThreadedIO();
9682 queueIOJob(j);
9683 unlockThreadedIO();
9684 }
9685 return 1;
9686}
9687
6f078746
PN
9688/* Preload keys for any command with first, last and step values for
9689 * the command keys prototype, as defined in the command table. */
9690static void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
9691 int j, last;
9692 if (cmd->vm_firstkey == 0) return;
9693 last = cmd->vm_lastkey;
9694 if (last < 0) last = argc+last;
9695 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
9696 redisAssert(j < argc);
9697 waitForSwappedKey(c,argv[j]);
9698 }
9699}
9700
739ba0d2
PN
9701/* Preload keys needed for the ZUNION and ZINTER commands.
9702 * Note that the number of keys to preload is user-defined, so we need to
9703 * apply a sanity check against argc. */
ca1788b5 9704static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
76583ea4 9705 int i, num;
ca1788b5 9706 REDIS_NOTUSED(cmd);
ca1788b5
PN
9707
9708 num = atoi(argv[2]->ptr);
739ba0d2 9709 if (num > (argc-3)) return;
76583ea4 9710 for (i = 0; i < num; i++) {
ca1788b5 9711 waitForSwappedKey(c,argv[3+i]);
76583ea4
PN
9712 }
9713}
9714
3805e04f
PN
9715/* Preload keys needed to execute the entire MULTI/EXEC block.
9716 *
9717 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
9718 * and will block the client when any command requires a swapped out value. */
9719static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
9720 int i, margc;
9721 struct redisCommand *mcmd;
9722 robj **margv;
9723 REDIS_NOTUSED(cmd);
9724 REDIS_NOTUSED(argc);
9725 REDIS_NOTUSED(argv);
9726
9727 if (!(c->flags & REDIS_MULTI)) return;
9728 for (i = 0; i < c->mstate.count; i++) {
9729 mcmd = c->mstate.commands[i].cmd;
9730 margc = c->mstate.commands[i].argc;
9731 margv = c->mstate.commands[i].argv;
9732
9733 if (mcmd->vm_preload_proc != NULL) {
9734 mcmd->vm_preload_proc(c,mcmd,margc,margv);
9735 } else {
9736 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
9737 }
76583ea4
PN
9738 }
9739}
9740
b0d8747d 9741/* Is this client attempting to run a command against swapped keys?
d5d55fc3 9742 * If so, block it ASAP, load the keys in background, then resume it.
b0d8747d 9743 *
d5d55fc3 9744 * The important idea about this function is that it can fail! If keys will
9745 * still be swapped when the client is resumed, this key lookups will
9746 * just block loading keys from disk. In practical terms this should only
9747 * happen with SORT BY command or if there is a bug in this function.
9748 *
9749 * Return 1 if the client is marked as blocked, 0 if the client can
9750 * continue as the keys it is going to access appear to be in memory. */
0a6f3f0f 9751static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
76583ea4 9752 if (cmd->vm_preload_proc != NULL) {
ca1788b5 9753 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
76583ea4 9754 } else {
6f078746 9755 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
76583ea4
PN
9756 }
9757
d5d55fc3 9758 /* If the client was blocked for at least one key, mark it as blocked. */
9759 if (listLength(c->io_keys)) {
9760 c->flags |= REDIS_IO_WAIT;
9761 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
9762 server.vm_blocked_clients++;
9763 return 1;
9764 } else {
9765 return 0;
9766 }
9767}
9768
9769/* Remove the 'key' from the list of blocked keys for a given client.
9770 *
9771 * The function returns 1 when there are no longer blocking keys after
9772 * the current one was removed (and the client can be unblocked). */
9773static int dontWaitForSwappedKey(redisClient *c, robj *key) {
9774 list *l;
9775 listNode *ln;
9776 listIter li;
9777 struct dictEntry *de;
9778
9779 /* Remove the key from the list of keys this client is waiting for. */
9780 listRewind(c->io_keys,&li);
9781 while ((ln = listNext(&li)) != NULL) {
bf028098 9782 if (equalStringObjects(ln->value,key)) {
d5d55fc3 9783 listDelNode(c->io_keys,ln);
9784 break;
9785 }
9786 }
9787 assert(ln != NULL);
9788
9789 /* Remove the client form the key => waiting clients map. */
9790 de = dictFind(c->db->io_keys,key);
9791 assert(de != NULL);
9792 l = dictGetEntryVal(de);
9793 ln = listSearchKey(l,c);
9794 assert(ln != NULL);
9795 listDelNode(l,ln);
9796 if (listLength(l) == 0)
9797 dictDelete(c->db->io_keys,key);
9798
9799 return listLength(c->io_keys) == 0;
9800}
9801
9802static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
9803 struct dictEntry *de;
9804 list *l;
9805 listNode *ln;
9806 int len;
9807
9808 de = dictFind(db->io_keys,key);
9809 if (!de) return;
9810
9811 l = dictGetEntryVal(de);
9812 len = listLength(l);
9813 /* Note: we can't use something like while(listLength(l)) as the list
9814 * can be freed by the calling function when we remove the last element. */
9815 while (len--) {
9816 ln = listFirst(l);
9817 redisClient *c = ln->value;
9818
9819 if (dontWaitForSwappedKey(c,key)) {
9820 /* Put the client in the list of clients ready to go as we
9821 * loaded all the keys about it. */
9822 listAddNodeTail(server.io_ready_clients,c);
9823 }
9824 }
b0d8747d 9825}
b0d8747d 9826
500ece7c 9827/* =========================== Remote Configuration ========================= */
9828
9829static void configSetCommand(redisClient *c) {
9830 robj *o = getDecodedObject(c->argv[3]);
9831 if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
9832 zfree(server.dbfilename);
9833 server.dbfilename = zstrdup(o->ptr);
9834 } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
9835 zfree(server.requirepass);
9836 server.requirepass = zstrdup(o->ptr);
9837 } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
9838 zfree(server.masterauth);
9839 server.masterauth = zstrdup(o->ptr);
9840 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
9841 server.maxmemory = strtoll(o->ptr, NULL, 10);
1b677732 9842 } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
9843 if (!strcasecmp(o->ptr,"no")) {
9844 server.appendfsync = APPENDFSYNC_NO;
9845 } else if (!strcasecmp(o->ptr,"everysec")) {
9846 server.appendfsync = APPENDFSYNC_EVERYSEC;
9847 } else if (!strcasecmp(o->ptr,"always")) {
9848 server.appendfsync = APPENDFSYNC_ALWAYS;
9849 } else {
9850 goto badfmt;
9851 }
a34e0a25 9852 } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
9853 int vlen, j;
9854 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
9855
9856 /* Perform sanity check before setting the new config:
9857 * - Even number of args
9858 * - Seconds >= 1, changes >= 0 */
9859 if (vlen & 1) {
9860 sdsfreesplitres(v,vlen);
9861 goto badfmt;
9862 }
9863 for (j = 0; j < vlen; j++) {
9864 char *eptr;
9865 long val;
9866
9867 val = strtoll(v[j], &eptr, 10);
9868 if (eptr[0] != '\0' ||
9869 ((j & 1) == 0 && val < 1) ||
9870 ((j & 1) == 1 && val < 0)) {
9871 sdsfreesplitres(v,vlen);
9872 goto badfmt;
9873 }
9874 }
9875 /* Finally set the new config */
9876 resetServerSaveParams();
9877 for (j = 0; j < vlen; j += 2) {
9878 time_t seconds;
9879 int changes;
9880
9881 seconds = strtoll(v[j],NULL,10);
9882 changes = strtoll(v[j+1],NULL,10);
9883 appendServerSaveParams(seconds, changes);
9884 }
9885 sdsfreesplitres(v,vlen);
500ece7c 9886 } else {
9887 addReplySds(c,sdscatprintf(sdsempty(),
9888 "-ERR not supported CONFIG parameter %s\r\n",
9889 (char*)c->argv[2]->ptr));
9890 decrRefCount(o);
9891 return;
9892 }
9893 decrRefCount(o);
9894 addReply(c,shared.ok);
a34e0a25 9895 return;
9896
9897badfmt: /* Bad format errors */
9898 addReplySds(c,sdscatprintf(sdsempty(),
9899 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
9900 (char*)o->ptr,
9901 (char*)c->argv[2]->ptr));
9902 decrRefCount(o);
500ece7c 9903}
9904
9905static void configGetCommand(redisClient *c) {
9906 robj *o = getDecodedObject(c->argv[2]);
9907 robj *lenobj = createObject(REDIS_STRING,NULL);
9908 char *pattern = o->ptr;
9909 int matches = 0;
9910
9911 addReply(c,lenobj);
9912 decrRefCount(lenobj);
9913
9914 if (stringmatch(pattern,"dbfilename",0)) {
9915 addReplyBulkCString(c,"dbfilename");
9916 addReplyBulkCString(c,server.dbfilename);
9917 matches++;
9918 }
9919 if (stringmatch(pattern,"requirepass",0)) {
9920 addReplyBulkCString(c,"requirepass");
9921 addReplyBulkCString(c,server.requirepass);
9922 matches++;
9923 }
9924 if (stringmatch(pattern,"masterauth",0)) {
9925 addReplyBulkCString(c,"masterauth");
9926 addReplyBulkCString(c,server.masterauth);
9927 matches++;
9928 }
9929 if (stringmatch(pattern,"maxmemory",0)) {
9930 char buf[128];
9931
9932 snprintf(buf,128,"%llu\n",server.maxmemory);
9933 addReplyBulkCString(c,"maxmemory");
9934 addReplyBulkCString(c,buf);
9935 matches++;
9936 }
1b677732 9937 if (stringmatch(pattern,"appendfsync",0)) {
9938 char *policy;
9939
9940 switch(server.appendfsync) {
9941 case APPENDFSYNC_NO: policy = "no"; break;
9942 case APPENDFSYNC_EVERYSEC: policy = "everysec"; break;
9943 case APPENDFSYNC_ALWAYS: policy = "always"; break;
9944 default: policy = "unknown"; break; /* too harmless to panic */
9945 }
9946 addReplyBulkCString(c,"appendfsync");
9947 addReplyBulkCString(c,policy);
9948 matches++;
9949 }
a34e0a25 9950 if (stringmatch(pattern,"save",0)) {
9951 sds buf = sdsempty();
9952 int j;
9953
9954 for (j = 0; j < server.saveparamslen; j++) {
9955 buf = sdscatprintf(buf,"%ld %d",
9956 server.saveparams[j].seconds,
9957 server.saveparams[j].changes);
9958 if (j != server.saveparamslen-1)
9959 buf = sdscatlen(buf," ",1);
9960 }
9961 addReplyBulkCString(c,"save");
9962 addReplyBulkCString(c,buf);
9963 sdsfree(buf);
9964 matches++;
9965 }
500ece7c 9966 decrRefCount(o);
9967 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",matches*2);
9968}
9969
9970static void configCommand(redisClient *c) {
9971 if (!strcasecmp(c->argv[1]->ptr,"set")) {
9972 if (c->argc != 4) goto badarity;
9973 configSetCommand(c);
9974 } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
9975 if (c->argc != 3) goto badarity;
9976 configGetCommand(c);
9977 } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
9978 if (c->argc != 2) goto badarity;
9979 server.stat_numcommands = 0;
9980 server.stat_numconnections = 0;
9981 server.stat_expiredkeys = 0;
9982 server.stat_starttime = time(NULL);
9983 addReply(c,shared.ok);
9984 } else {
9985 addReplySds(c,sdscatprintf(sdsempty(),
9986 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
9987 }
9988 return;
9989
9990badarity:
9991 addReplySds(c,sdscatprintf(sdsempty(),
9992 "-ERR Wrong number of arguments for CONFIG %s\r\n",
9993 (char*) c->argv[1]->ptr));
9994}
9995
befec3cd 9996/* =========================== Pubsub implementation ======================== */
9997
ffc6b7f8 9998static void freePubsubPattern(void *p) {
9999 pubsubPattern *pat = p;
10000
10001 decrRefCount(pat->pattern);
10002 zfree(pat);
10003}
10004
10005static int listMatchPubsubPattern(void *a, void *b) {
10006 pubsubPattern *pa = a, *pb = b;
10007
10008 return (pa->client == pb->client) &&
bf028098 10009 (equalStringObjects(pa->pattern,pb->pattern));
ffc6b7f8 10010}
10011
10012/* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10013 * 0 if the client was already subscribed to that channel. */
10014static int pubsubSubscribeChannel(redisClient *c, robj *channel) {
befec3cd 10015 struct dictEntry *de;
10016 list *clients = NULL;
10017 int retval = 0;
10018
ffc6b7f8 10019 /* Add the channel to the client -> channels hash table */
10020 if (dictAdd(c->pubsub_channels,channel,NULL) == DICT_OK) {
befec3cd 10021 retval = 1;
ffc6b7f8 10022 incrRefCount(channel);
10023 /* Add the client to the channel -> list of clients hash table */
10024 de = dictFind(server.pubsub_channels,channel);
befec3cd 10025 if (de == NULL) {
10026 clients = listCreate();
ffc6b7f8 10027 dictAdd(server.pubsub_channels,channel,clients);
10028 incrRefCount(channel);
befec3cd 10029 } else {
10030 clients = dictGetEntryVal(de);
10031 }
10032 listAddNodeTail(clients,c);
10033 }
10034 /* Notify the client */
10035 addReply(c,shared.mbulk3);
10036 addReply(c,shared.subscribebulk);
ffc6b7f8 10037 addReplyBulk(c,channel);
10038 addReplyLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
befec3cd 10039 return retval;
10040}
10041
ffc6b7f8 10042/* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10043 * 0 if the client was not subscribed to the specified channel. */
10044static int pubsubUnsubscribeChannel(redisClient *c, robj *channel, int notify) {
befec3cd 10045 struct dictEntry *de;
10046 list *clients;
10047 listNode *ln;
10048 int retval = 0;
10049
ffc6b7f8 10050 /* Remove the channel from the client -> channels hash table */
10051 incrRefCount(channel); /* channel may be just a pointer to the same object
201037f5 10052 we have in the hash tables. Protect it... */
ffc6b7f8 10053 if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
befec3cd 10054 retval = 1;
ffc6b7f8 10055 /* Remove the client from the channel -> clients list hash table */
10056 de = dictFind(server.pubsub_channels,channel);
befec3cd 10057 assert(de != NULL);
10058 clients = dictGetEntryVal(de);
10059 ln = listSearchKey(clients,c);
10060 assert(ln != NULL);
10061 listDelNode(clients,ln);
ff767a75 10062 if (listLength(clients) == 0) {
10063 /* Free the list and associated hash entry at all if this was
10064 * the latest client, so that it will be possible to abuse
ffc6b7f8 10065 * Redis PUBSUB creating millions of channels. */
10066 dictDelete(server.pubsub_channels,channel);
ff767a75 10067 }
befec3cd 10068 }
10069 /* Notify the client */
10070 if (notify) {
10071 addReply(c,shared.mbulk3);
10072 addReply(c,shared.unsubscribebulk);
ffc6b7f8 10073 addReplyBulk(c,channel);
10074 addReplyLong(c,dictSize(c->pubsub_channels)+
10075 listLength(c->pubsub_patterns));
10076
10077 }
10078 decrRefCount(channel); /* it is finally safe to release it */
10079 return retval;
10080}
10081
10082/* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10083static int pubsubSubscribePattern(redisClient *c, robj *pattern) {
10084 int retval = 0;
10085
10086 if (listSearchKey(c->pubsub_patterns,pattern) == NULL) {
10087 retval = 1;
10088 pubsubPattern *pat;
10089 listAddNodeTail(c->pubsub_patterns,pattern);
10090 incrRefCount(pattern);
10091 pat = zmalloc(sizeof(*pat));
10092 pat->pattern = getDecodedObject(pattern);
10093 pat->client = c;
10094 listAddNodeTail(server.pubsub_patterns,pat);
10095 }
10096 /* Notify the client */
10097 addReply(c,shared.mbulk3);
10098 addReply(c,shared.psubscribebulk);
10099 addReplyBulk(c,pattern);
10100 addReplyLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
10101 return retval;
10102}
10103
10104/* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10105 * 0 if the client was not subscribed to the specified channel. */
10106static int pubsubUnsubscribePattern(redisClient *c, robj *pattern, int notify) {
10107 listNode *ln;
10108 pubsubPattern pat;
10109 int retval = 0;
10110
10111 incrRefCount(pattern); /* Protect the object. May be the same we remove */
10112 if ((ln = listSearchKey(c->pubsub_patterns,pattern)) != NULL) {
10113 retval = 1;
10114 listDelNode(c->pubsub_patterns,ln);
10115 pat.client = c;
10116 pat.pattern = pattern;
10117 ln = listSearchKey(server.pubsub_patterns,&pat);
10118 listDelNode(server.pubsub_patterns,ln);
10119 }
10120 /* Notify the client */
10121 if (notify) {
10122 addReply(c,shared.mbulk3);
10123 addReply(c,shared.punsubscribebulk);
10124 addReplyBulk(c,pattern);
10125 addReplyLong(c,dictSize(c->pubsub_channels)+
10126 listLength(c->pubsub_patterns));
befec3cd 10127 }
ffc6b7f8 10128 decrRefCount(pattern);
befec3cd 10129 return retval;
10130}
10131
ffc6b7f8 10132/* Unsubscribe from all the channels. Return the number of channels the
10133 * client was subscribed from. */
10134static int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
10135 dictIterator *di = dictGetIterator(c->pubsub_channels);
befec3cd 10136 dictEntry *de;
10137 int count = 0;
10138
10139 while((de = dictNext(di)) != NULL) {
ffc6b7f8 10140 robj *channel = dictGetEntryKey(de);
befec3cd 10141
ffc6b7f8 10142 count += pubsubUnsubscribeChannel(c,channel,notify);
befec3cd 10143 }
10144 dictReleaseIterator(di);
10145 return count;
10146}
10147
ffc6b7f8 10148/* Unsubscribe from all the patterns. Return the number of patterns the
10149 * client was subscribed from. */
10150static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify) {
10151 listNode *ln;
10152 listIter li;
10153 int count = 0;
10154
10155 listRewind(c->pubsub_patterns,&li);
10156 while ((ln = listNext(&li)) != NULL) {
10157 robj *pattern = ln->value;
10158
10159 count += pubsubUnsubscribePattern(c,pattern,notify);
10160 }
10161 return count;
10162}
10163
befec3cd 10164/* Publish a message */
ffc6b7f8 10165static int pubsubPublishMessage(robj *channel, robj *message) {
befec3cd 10166 int receivers = 0;
10167 struct dictEntry *de;
ffc6b7f8 10168 listNode *ln;
10169 listIter li;
befec3cd 10170
ffc6b7f8 10171 /* Send to clients listening for that channel */
10172 de = dictFind(server.pubsub_channels,channel);
befec3cd 10173 if (de) {
10174 list *list = dictGetEntryVal(de);
10175 listNode *ln;
10176 listIter li;
10177
10178 listRewind(list,&li);
10179 while ((ln = listNext(&li)) != NULL) {
10180 redisClient *c = ln->value;
10181
10182 addReply(c,shared.mbulk3);
10183 addReply(c,shared.messagebulk);
ffc6b7f8 10184 addReplyBulk(c,channel);
befec3cd 10185 addReplyBulk(c,message);
10186 receivers++;
10187 }
10188 }
ffc6b7f8 10189 /* Send to clients listening to matching channels */
10190 if (listLength(server.pubsub_patterns)) {
10191 listRewind(server.pubsub_patterns,&li);
10192 channel = getDecodedObject(channel);
10193 while ((ln = listNext(&li)) != NULL) {
10194 pubsubPattern *pat = ln->value;
10195
10196 if (stringmatchlen((char*)pat->pattern->ptr,
10197 sdslen(pat->pattern->ptr),
10198 (char*)channel->ptr,
10199 sdslen(channel->ptr),0)) {
c8d0ea0e 10200 addReply(pat->client,shared.mbulk4);
10201 addReply(pat->client,shared.pmessagebulk);
10202 addReplyBulk(pat->client,pat->pattern);
ffc6b7f8 10203 addReplyBulk(pat->client,channel);
10204 addReplyBulk(pat->client,message);
10205 receivers++;
10206 }
10207 }
10208 decrRefCount(channel);
10209 }
befec3cd 10210 return receivers;
10211}
10212
10213static void subscribeCommand(redisClient *c) {
10214 int j;
10215
10216 for (j = 1; j < c->argc; j++)
ffc6b7f8 10217 pubsubSubscribeChannel(c,c->argv[j]);
befec3cd 10218}
10219
10220static void unsubscribeCommand(redisClient *c) {
10221 if (c->argc == 1) {
ffc6b7f8 10222 pubsubUnsubscribeAllChannels(c,1);
10223 return;
10224 } else {
10225 int j;
10226
10227 for (j = 1; j < c->argc; j++)
10228 pubsubUnsubscribeChannel(c,c->argv[j],1);
10229 }
10230}
10231
10232static void psubscribeCommand(redisClient *c) {
10233 int j;
10234
10235 for (j = 1; j < c->argc; j++)
10236 pubsubSubscribePattern(c,c->argv[j]);
10237}
10238
10239static void punsubscribeCommand(redisClient *c) {
10240 if (c->argc == 1) {
10241 pubsubUnsubscribeAllPatterns(c,1);
befec3cd 10242 return;
10243 } else {
10244 int j;
10245
10246 for (j = 1; j < c->argc; j++)
ffc6b7f8 10247 pubsubUnsubscribePattern(c,c->argv[j],1);
befec3cd 10248 }
10249}
10250
10251static void publishCommand(redisClient *c) {
10252 int receivers = pubsubPublishMessage(c->argv[1],c->argv[2]);
10253 addReplyLong(c,receivers);
10254}
10255
7f957c92 10256/* ================================= Debugging ============================== */
10257
10258static void debugCommand(redisClient *c) {
10259 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
10260 *((char*)-1) = 'x';
210e29f7 10261 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
10262 if (rdbSave(server.dbfilename) != REDIS_OK) {
10263 addReply(c,shared.err);
10264 return;
10265 }
10266 emptyDb();
10267 if (rdbLoad(server.dbfilename) != REDIS_OK) {
10268 addReply(c,shared.err);
10269 return;
10270 }
10271 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
10272 addReply(c,shared.ok);
71c2b467 10273 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
10274 emptyDb();
10275 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
10276 addReply(c,shared.err);
10277 return;
10278 }
10279 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
10280 addReply(c,shared.ok);
333298da 10281 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
10282 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
10283 robj *key, *val;
10284
10285 if (!de) {
10286 addReply(c,shared.nokeyerr);
10287 return;
10288 }
10289 key = dictGetEntryKey(de);
10290 val = dictGetEntryVal(de);
59146ef3 10291 if (!server.vm_enabled || (key->storage == REDIS_VM_MEMORY ||
10292 key->storage == REDIS_VM_SWAPPING)) {
07efaf74 10293 char *strenc;
10294 char buf[128];
10295
10296 if (val->encoding < (sizeof(strencoding)/sizeof(char*))) {
10297 strenc = strencoding[val->encoding];
10298 } else {
10299 snprintf(buf,64,"unknown encoding %d\n", val->encoding);
10300 strenc = buf;
10301 }
ace06542 10302 addReplySds(c,sdscatprintf(sdsempty(),
10303 "+Key at:%p refcount:%d, value at:%p refcount:%d "
07efaf74 10304 "encoding:%s serializedlength:%lld\r\n",
682ac724 10305 (void*)key, key->refcount, (void*)val, val->refcount,
07efaf74 10306 strenc, (long long) rdbSavedObjectLen(val,NULL)));
ace06542 10307 } else {
10308 addReplySds(c,sdscatprintf(sdsempty(),
10309 "+Key at:%p refcount:%d, value swapped at: page %llu "
10310 "using %llu pages\r\n",
10311 (void*)key, key->refcount, (unsigned long long) key->vm.page,
10312 (unsigned long long) key->vm.usedpages));
10313 }
78ebe4c8 10314 } else if (!strcasecmp(c->argv[1]->ptr,"swapin") && c->argc == 3) {
10315 lookupKeyRead(c->db,c->argv[2]);
10316 addReply(c,shared.ok);
7d30035d 10317 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
10318 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
10319 robj *key, *val;
10320
10321 if (!server.vm_enabled) {
10322 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
10323 return;
10324 }
10325 if (!de) {
10326 addReply(c,shared.nokeyerr);
10327 return;
10328 }
10329 key = dictGetEntryKey(de);
10330 val = dictGetEntryVal(de);
4ef8de8a 10331 /* If the key is shared we want to create a copy */
10332 if (key->refcount > 1) {
10333 robj *newkey = dupStringObject(key);
10334 decrRefCount(key);
10335 key = dictGetEntryKey(de) = newkey;
10336 }
10337 /* Swap it */
7d30035d 10338 if (key->storage != REDIS_VM_MEMORY) {
10339 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
a69a0c9c 10340 } else if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
7d30035d 10341 dictGetEntryVal(de) = NULL;
10342 addReply(c,shared.ok);
10343 } else {
10344 addReply(c,shared.err);
10345 }
59305dc7 10346 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
10347 long keys, j;
10348 robj *key, *val;
10349 char buf[128];
10350
10351 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
10352 return;
10353 for (j = 0; j < keys; j++) {
10354 snprintf(buf,sizeof(buf),"key:%lu",j);
10355 key = createStringObject(buf,strlen(buf));
10356 if (lookupKeyRead(c->db,key) != NULL) {
10357 decrRefCount(key);
10358 continue;
10359 }
10360 snprintf(buf,sizeof(buf),"value:%lu",j);
10361 val = createStringObject(buf,strlen(buf));
10362 dictAdd(c->db->dict,key,val);
10363 }
10364 addReply(c,shared.ok);
7f957c92 10365 } else {
333298da 10366 addReplySds(c,sdsnew(
bdcb92f2 10367 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
7f957c92 10368 }
10369}
56906eef 10370
6c96ba7d 10371static void _redisAssert(char *estr, char *file, int line) {
dfc5e96c 10372 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
6c96ba7d 10373 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true\n",file,line,estr);
dfc5e96c 10374#ifdef HAVE_BACKTRACE
10375 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
10376 *((char*)-1) = 'x';
10377#endif
10378}
10379
c651fd9e 10380static void _redisPanic(char *msg, char *file, int line) {
10381 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
17772754 10382 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
c651fd9e 10383#ifdef HAVE_BACKTRACE
10384 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
10385 *((char*)-1) = 'x';
10386#endif
10387}
10388
bcfc686d 10389/* =================================== Main! ================================ */
56906eef 10390
bcfc686d 10391#ifdef __linux__
10392int linuxOvercommitMemoryValue(void) {
10393 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
10394 char buf[64];
56906eef 10395
bcfc686d 10396 if (!fp) return -1;
10397 if (fgets(buf,64,fp) == NULL) {
10398 fclose(fp);
10399 return -1;
10400 }
10401 fclose(fp);
56906eef 10402
bcfc686d 10403 return atoi(buf);
10404}
10405
10406void linuxOvercommitMemoryWarning(void) {
10407 if (linuxOvercommitMemoryValue() == 0) {
7ccd2d0a 10408 redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. 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.");
bcfc686d 10409 }
10410}
10411#endif /* __linux__ */
10412
10413static void daemonize(void) {
10414 int fd;
10415 FILE *fp;
10416
10417 if (fork() != 0) exit(0); /* parent exits */
10418 setsid(); /* create a new session */
10419
10420 /* Every output goes to /dev/null. If Redis is daemonized but
10421 * the 'logfile' is set to 'stdout' in the configuration file
10422 * it will not log at all. */
10423 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
10424 dup2(fd, STDIN_FILENO);
10425 dup2(fd, STDOUT_FILENO);
10426 dup2(fd, STDERR_FILENO);
10427 if (fd > STDERR_FILENO) close(fd);
10428 }
10429 /* Try to write the pid file */
10430 fp = fopen(server.pidfile,"w");
10431 if (fp) {
10432 fprintf(fp,"%d\n",getpid());
10433 fclose(fp);
56906eef 10434 }
56906eef 10435}
10436
42ab0172
AO
10437static void version() {
10438 printf("Redis server version %s\n", REDIS_VERSION);
10439 exit(0);
10440}
10441
723fb69b
AO
10442static void usage() {
10443 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
e9409273 10444 fprintf(stderr," ./redis-server - (read config from stdin)\n");
723fb69b
AO
10445 exit(1);
10446}
10447
bcfc686d 10448int main(int argc, char **argv) {
9651a787 10449 time_t start;
10450
bcfc686d 10451 initServerConfig();
10452 if (argc == 2) {
44efe66e 10453 if (strcmp(argv[1], "-v") == 0 ||
10454 strcmp(argv[1], "--version") == 0) version();
10455 if (strcmp(argv[1], "--help") == 0) usage();
bcfc686d 10456 resetServerSaveParams();
10457 loadServerConfig(argv[1]);
723fb69b
AO
10458 } else if ((argc > 2)) {
10459 usage();
bcfc686d 10460 } else {
10461 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'");
10462 }
bcfc686d 10463 if (server.daemonize) daemonize();
71c54b21 10464 initServer();
bcfc686d 10465 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
10466#ifdef __linux__
10467 linuxOvercommitMemoryWarning();
10468#endif
9651a787 10469 start = time(NULL);
bcfc686d 10470 if (server.appendonly) {
10471 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
9651a787 10472 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
bcfc686d 10473 } else {
10474 if (rdbLoad(server.dbfilename) == REDIS_OK)
9651a787 10475 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
bcfc686d 10476 }
bcfc686d 10477 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
d5d55fc3 10478 aeSetBeforeSleepProc(server.el,beforeSleep);
bcfc686d 10479 aeMain(server.el);
10480 aeDeleteEventLoop(server.el);
10481 return 0;
10482}
10483
10484/* ============================= Backtrace support ========================= */
10485
10486#ifdef HAVE_BACKTRACE
10487static char *findFuncName(void *pointer, unsigned long *offset);
10488
56906eef 10489static void *getMcontextEip(ucontext_t *uc) {
10490#if defined(__FreeBSD__)
10491 return (void*) uc->uc_mcontext.mc_eip;
10492#elif defined(__dietlibc__)
10493 return (void*) uc->uc_mcontext.eip;
06db1f50 10494#elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
da0a1620 10495 #if __x86_64__
10496 return (void*) uc->uc_mcontext->__ss.__rip;
10497 #else
56906eef 10498 return (void*) uc->uc_mcontext->__ss.__eip;
da0a1620 10499 #endif
06db1f50 10500#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
cb7e07cc 10501 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
06db1f50 10502 return (void*) uc->uc_mcontext->__ss.__rip;
cbc59b38 10503 #else
10504 return (void*) uc->uc_mcontext->__ss.__eip;
e0a62c7f 10505 #endif
54bac49d 10506#elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
c04c9ac9 10507 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
b91cf5ef 10508#elif defined(__ia64__) /* Linux IA64 */
10509 return (void*) uc->uc_mcontext.sc_ip;
10510#else
10511 return NULL;
56906eef 10512#endif
10513}
10514
10515static void segvHandler(int sig, siginfo_t *info, void *secret) {
10516 void *trace[100];
10517 char **messages = NULL;
10518 int i, trace_size = 0;
10519 unsigned long offset=0;
56906eef 10520 ucontext_t *uc = (ucontext_t*) secret;
1c85b79f 10521 sds infostring;
56906eef 10522 REDIS_NOTUSED(info);
10523
10524 redisLog(REDIS_WARNING,
10525 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
1c85b79f 10526 infostring = genRedisInfoString();
10527 redisLog(REDIS_WARNING, "%s",infostring);
10528 /* It's not safe to sdsfree() the returned string under memory
10529 * corruption conditions. Let it leak as we are going to abort */
e0a62c7f 10530
56906eef 10531 trace_size = backtrace(trace, 100);
de96dbfe 10532 /* overwrite sigaction with caller's address */
b91cf5ef 10533 if (getMcontextEip(uc) != NULL) {
10534 trace[1] = getMcontextEip(uc);
10535 }
56906eef 10536 messages = backtrace_symbols(trace, trace_size);
fe3bbfbe 10537
d76412d1 10538 for (i=1; i<trace_size; ++i) {
56906eef 10539 char *fn = findFuncName(trace[i], &offset), *p;
10540
10541 p = strchr(messages[i],'+');
10542 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
10543 redisLog(REDIS_WARNING,"%s", messages[i]);
10544 } else {
10545 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
10546 }
10547 }
b177fd30 10548 /* free(messages); Don't call free() with possibly corrupted memory. */
478c2c6f 10549 _exit(0);
fe3bbfbe 10550}
56906eef 10551
10552static void setupSigSegvAction(void) {
10553 struct sigaction act;
10554
10555 sigemptyset (&act.sa_mask);
10556 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
10557 * is used. Otherwise, sa_handler is used */
10558 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
10559 act.sa_sigaction = segvHandler;
10560 sigaction (SIGSEGV, &act, NULL);
10561 sigaction (SIGBUS, &act, NULL);
12fea928 10562 sigaction (SIGFPE, &act, NULL);
10563 sigaction (SIGILL, &act, NULL);
10564 sigaction (SIGBUS, &act, NULL);
e65fdc78 10565 return;
56906eef 10566}
e65fdc78 10567
bcfc686d 10568#include "staticsymbols.h"
10569/* This function try to convert a pointer into a function name. It's used in
10570 * oreder to provide a backtrace under segmentation fault that's able to
10571 * display functions declared as static (otherwise the backtrace is useless). */
10572static char *findFuncName(void *pointer, unsigned long *offset){
10573 int i, ret = -1;
10574 unsigned long off, minoff = 0;
ed9b544e 10575
bcfc686d 10576 /* Try to match against the Symbol with the smallest offset */
10577 for (i=0; symsTable[i].pointer; i++) {
10578 unsigned long lp = (unsigned long) pointer;
0bc03378 10579
bcfc686d 10580 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
10581 off=lp-symsTable[i].pointer;
10582 if (ret < 0 || off < minoff) {
10583 minoff=off;
10584 ret=i;
10585 }
10586 }
0bc03378 10587 }
bcfc686d 10588 if (ret == -1) return NULL;
10589 *offset = minoff;
10590 return symsTable[ret].name;
0bc03378 10591}
bcfc686d 10592#else /* HAVE_BACKTRACE */
10593static void setupSigSegvAction(void) {
0bc03378 10594}
bcfc686d 10595#endif /* HAVE_BACKTRACE */
0bc03378 10596
ed9b544e 10597
ed9b544e 10598
bcfc686d 10599/* The End */
10600
10601
ed9b544e 10602