]> git.saurik.com Git - redis.git/blame - redis.c
support rdb saving/loading with dual list encoding
[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
9005896c 30#define REDIS_VERSION "2.1.1"
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 */
ba798261 77#include "zipmap.h" /* Compact dictionary-alike data structure */
c7d9d662 78#include "ziplist.h" /* Compact list data structure */
ba798261 79#include "sha1.h" /* SHA1 is used for DEBUG DIGEST */
5436146c 80#include "release.h" /* Release and/or git repository information */
ed9b544e 81
82/* Error codes */
83#define REDIS_OK 0
84#define REDIS_ERR -1
85
86/* Static server configuration */
87#define REDIS_SERVERPORT 6379 /* TCP port */
88#define REDIS_MAXIDLETIME (60*5) /* default client timeout */
6208b3a7 89#define REDIS_IOBUF_LEN 1024
ed9b544e 90#define REDIS_LOADBUF_LEN 1024
248ea310 91#define REDIS_STATIC_ARGS 8
ed9b544e 92#define REDIS_DEFAULT_DBNUM 16
93#define REDIS_CONFIGLINE_MAX 1024
94#define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
95#define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
8ca3e9d1 96#define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
6f376729 97#define REDIS_MAX_WRITE_PER_EVENT (1024*64)
2895e862 98#define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
99
100/* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
101#define REDIS_WRITEV_THRESHOLD 3
102/* Max number of iovecs used for each writev call */
103#define REDIS_WRITEV_IOVEC_COUNT 256
ed9b544e 104
105/* Hash table parameters */
106#define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
ed9b544e 107
108/* Command flags */
3fd78bcd 109#define REDIS_CMD_BULK 1 /* Bulk write command */
110#define REDIS_CMD_INLINE 2 /* Inline command */
111/* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
112 this flags will return an error when the 'maxmemory' option is set in the
113 config file and the server is using more than maxmemory bytes of memory.
114 In short this commands are denied on low memory conditions. */
115#define REDIS_CMD_DENYOOM 4
4005fef1 116#define REDIS_CMD_FORCE_REPLICATION 8 /* Force replication even if dirty is 0 */
ed9b544e 117
118/* Object types */
119#define REDIS_STRING 0
120#define REDIS_LIST 1
121#define REDIS_SET 2
1812e024 122#define REDIS_ZSET 3
123#define REDIS_HASH 4
f78fd11b 124
5234952b 125/* Objects encoding. Some kind of objects like Strings and Hashes can be
126 * internally represented in multiple ways. The 'encoding' field of the object
127 * is set to one of this fields for this object. */
c7d9d662
PN
128#define REDIS_ENCODING_RAW 0 /* Raw representation */
129#define REDIS_ENCODING_INT 1 /* Encoded as integer */
130#define REDIS_ENCODING_HT 2 /* Encoded as hash table */
131#define REDIS_ENCODING_ZIPMAP 3 /* Encoded as zipmap */
132#define REDIS_ENCODING_LIST 4 /* Encoded as zipmap */
133#define REDIS_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
942a3961 134
07efaf74 135static char* strencoding[] = {
136 "raw", "int", "zipmap", "hashtable"
137};
138
f78fd11b 139/* Object types only used for dumping to disk */
bb32ede5 140#define REDIS_EXPIRETIME 253
ed9b544e 141#define REDIS_SELECTDB 254
142#define REDIS_EOF 255
143
f78fd11b 144/* Defines related to the dump file format. To store 32 bits lengths for short
145 * keys requires a lot of space, so we check the most significant 2 bits of
146 * the first byte to interpreter the length:
147 *
148 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
149 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
150 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
a4d1ba9a 151 * 11|000000 this means: specially encoded object will follow. The six bits
152 * number specify the kind of object that follows.
153 * See the REDIS_RDB_ENC_* defines.
f78fd11b 154 *
10c43610 155 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
156 * values, will fit inside. */
f78fd11b 157#define REDIS_RDB_6BITLEN 0
158#define REDIS_RDB_14BITLEN 1
159#define REDIS_RDB_32BITLEN 2
17be1a4a 160#define REDIS_RDB_ENCVAL 3
f78fd11b 161#define REDIS_RDB_LENERR UINT_MAX
162
a4d1ba9a 163/* When a length of a string object stored on disk has the first two bits
164 * set, the remaining two bits specify a special encoding for the object
165 * accordingly to the following defines: */
166#define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
167#define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
168#define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
774e3047 169#define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
a4d1ba9a 170
75680a3c 171/* Virtual memory object->where field. */
172#define REDIS_VM_MEMORY 0 /* The object is on memory */
173#define REDIS_VM_SWAPPED 1 /* The object is on disk */
174#define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
175#define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
176
06224fec 177/* Virtual memory static configuration stuff.
178 * Check vmFindContiguousPages() to know more about this magic numbers. */
179#define REDIS_VM_MAX_NEAR_PAGES 65536
180#define REDIS_VM_MAX_RANDOM_JUMP 4096
92f8e882 181#define REDIS_VM_MAX_THREADS 32
bcaa7a4f 182#define REDIS_THREAD_STACK_SIZE (1024*1024*4)
f6c0bba8 183/* The following is the *percentage* of completed I/O jobs to process when the
184 * handelr is called. While Virtual Memory I/O operations are performed by
185 * threads, this operations must be processed by the main thread when completed
186 * in order to take effect. */
c953f24b 187#define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
06224fec 188
ed9b544e 189/* Client flags */
d5d55fc3 190#define REDIS_SLAVE 1 /* This client is a slave server */
191#define REDIS_MASTER 2 /* This client is a master server */
192#define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
193#define REDIS_MULTI 8 /* This client is in a MULTI context */
194#define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
195#define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
37ab76c9 196#define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
ed9b544e 197
40d224a9 198/* Slave replication state - slave side */
ed9b544e 199#define REDIS_REPL_NONE 0 /* No active replication */
200#define REDIS_REPL_CONNECT 1 /* Must connect to master */
201#define REDIS_REPL_CONNECTED 2 /* Connected to master */
202
40d224a9 203/* Slave replication state - from the point of view of master
204 * Note that in SEND_BULK and ONLINE state the slave receives new updates
205 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
206 * to start the next background saving in order to send updates to it. */
207#define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
208#define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
209#define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
210#define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
211
ed9b544e 212/* List related stuff */
213#define REDIS_HEAD 0
214#define REDIS_TAIL 1
215
216/* Sort operations */
217#define REDIS_SORT_GET 0
443c6409 218#define REDIS_SORT_ASC 1
219#define REDIS_SORT_DESC 2
ed9b544e 220#define REDIS_SORTKEY_MAX 1024
221
222/* Log levels */
223#define REDIS_DEBUG 0
f870935d 224#define REDIS_VERBOSE 1
225#define REDIS_NOTICE 2
226#define REDIS_WARNING 3
ed9b544e 227
228/* Anti-warning macro... */
229#define REDIS_NOTUSED(V) ((void) V)
230
6b47e12e 231#define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
232#define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
ed9b544e 233
48f0308a 234/* Append only defines */
235#define APPENDFSYNC_NO 0
236#define APPENDFSYNC_ALWAYS 1
237#define APPENDFSYNC_EVERYSEC 2
238
cbba7dd7 239/* Hashes related defaults */
240#define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
241#define REDIS_HASH_MAX_ZIPMAP_VALUE 512
242
dfc5e96c 243/* We can print the stacktrace, so our assert is defined this way: */
478c2c6f 244#define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
c651fd9e 245#define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
6c96ba7d 246static void _redisAssert(char *estr, char *file, int line);
c651fd9e 247static void _redisPanic(char *msg, char *file, int line);
dfc5e96c 248
ed9b544e 249/*================================= Data types ============================== */
250
251/* A redis object, that is a type able to hold a string / list / set */
75680a3c 252
253/* The VM object structure */
254struct redisObjectVM {
3a66edc7 255 off_t page; /* the page at witch the object is stored on disk */
256 off_t usedpages; /* number of pages used on disk */
257 time_t atime; /* Last access time */
75680a3c 258} vm;
259
260/* The actual Redis Object */
ed9b544e 261typedef struct redisObject {
ed9b544e 262 void *ptr;
942a3961 263 unsigned char type;
264 unsigned char encoding;
d894161b 265 unsigned char storage; /* If this object is a key, where is the value?
266 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
267 unsigned char vtype; /* If this object is a key, and value is swapped out,
268 * this is the type of the swapped out object. */
ed9b544e 269 int refcount;
75680a3c 270 /* VM fields, this are only allocated if VM is active, otherwise the
271 * object allocation function will just allocate
272 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
273 * Redis without VM active will not have any overhead. */
274 struct redisObjectVM vm;
ed9b544e 275} robj;
276
dfc5e96c 277/* Macro used to initalize a Redis object allocated on the stack.
278 * Note that this macro is taken near the structure definition to make sure
279 * we'll update it when the structure is changed, to avoid bugs like
280 * bug #85 introduced exactly in this way. */
281#define initStaticStringObject(_var,_ptr) do { \
282 _var.refcount = 1; \
283 _var.type = REDIS_STRING; \
284 _var.encoding = REDIS_ENCODING_RAW; \
285 _var.ptr = _ptr; \
3a66edc7 286 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
dfc5e96c 287} while(0);
288
3305306f 289typedef struct redisDb {
4409877e 290 dict *dict; /* The keyspace for this DB */
291 dict *expires; /* Timeout of keys with a timeout set */
37ab76c9 292 dict *blocking_keys; /* Keys with clients waiting for data (BLPOP) */
d5d55fc3 293 dict *io_keys; /* Keys with clients waiting for VM I/O */
37ab76c9 294 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
3305306f 295 int id;
296} redisDb;
297
6e469882 298/* Client MULTI/EXEC state */
299typedef struct multiCmd {
300 robj **argv;
301 int argc;
302 struct redisCommand *cmd;
303} multiCmd;
304
305typedef struct multiState {
306 multiCmd *commands; /* Array of MULTI commands */
307 int count; /* Total number of MULTI commands */
308} multiState;
309
ed9b544e 310/* With multiplexing we need to take per-clinet state.
311 * Clients are taken in a liked list. */
312typedef struct redisClient {
313 int fd;
3305306f 314 redisDb *db;
ed9b544e 315 int dictid;
316 sds querybuf;
e8a74421 317 robj **argv, **mbargv;
318 int argc, mbargc;
40d224a9 319 int bulklen; /* bulk read len. -1 if not in bulk read mode */
e8a74421 320 int multibulk; /* multi bulk command format active */
ed9b544e 321 list *reply;
322 int sentlen;
323 time_t lastinteraction; /* time of the last interaction, used for timeout */
d5d55fc3 324 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
40d224a9 325 int slaveseldb; /* slave selected db, if this client is a slave */
326 int authenticated; /* when requirepass is non-NULL */
327 int replstate; /* replication state if this is a slave */
328 int repldbfd; /* replication DB file descriptor */
6e469882 329 long repldboff; /* replication DB file offset */
40d224a9 330 off_t repldbsize; /* replication DB file size */
6e469882 331 multiState mstate; /* MULTI/EXEC state */
37ab76c9 332 robj **blocking_keys; /* The key we are waiting to terminate a blocking
4409877e 333 * operation such as BLPOP. Otherwise NULL. */
37ab76c9 334 int blocking_keys_num; /* Number of blocking keys */
4409877e 335 time_t blockingto; /* Blocking operation timeout. If UNIX current time
336 * is >= blockingto then the operation timed out. */
92f8e882 337 list *io_keys; /* Keys this client is waiting to be loaded from the
338 * swap file in order to continue. */
37ab76c9 339 list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */
ffc6b7f8 340 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
341 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
ed9b544e 342} redisClient;
343
344struct saveparam {
345 time_t seconds;
346 int changes;
347};
348
349/* Global server state structure */
350struct redisServer {
351 int port;
352 int fd;
3305306f 353 redisDb *db;
ed9b544e 354 long long dirty; /* changes to DB from the last save */
355 list *clients;
87eca727 356 list *slaves, *monitors;
ed9b544e 357 char neterr[ANET_ERR_LEN];
358 aeEventLoop *el;
359 int cronloops; /* number of times the cron function run */
360 list *objfreelist; /* A list of freed objects to avoid malloc() */
361 time_t lastsave; /* Unix time of last save succeeede */
ed9b544e 362 /* Fields used only for stats */
363 time_t stat_starttime; /* server start time */
364 long long stat_numcommands; /* number of processed commands */
365 long long stat_numconnections; /* number of connections received */
2a6a2ed1 366 long long stat_expiredkeys; /* number of expired keys */
ed9b544e 367 /* Configuration */
368 int verbosity;
369 int glueoutputbuf;
370 int maxidletime;
371 int dbnum;
372 int daemonize;
44b38ef4 373 int appendonly;
48f0308a 374 int appendfsync;
fab43727 375 int shutdown_asap;
48f0308a 376 time_t lastfsync;
44b38ef4 377 int appendfd;
378 int appendseldb;
ed329fcf 379 char *pidfile;
9f3c422c 380 pid_t bgsavechildpid;
9d65a1bb 381 pid_t bgrewritechildpid;
382 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
28ed1f33 383 sds aofbuf; /* AOF buffer, written before entering the event loop */
ed9b544e 384 struct saveparam *saveparams;
385 int saveparamslen;
386 char *logfile;
387 char *bindaddr;
388 char *dbfilename;
44b38ef4 389 char *appendfilename;
abcb223e 390 char *requirepass;
121f70cf 391 int rdbcompression;
8ca3e9d1 392 int activerehashing;
ed9b544e 393 /* Replication related */
394 int isslave;
d0ccebcf 395 char *masterauth;
ed9b544e 396 char *masterhost;
397 int masterport;
40d224a9 398 redisClient *master; /* client that is master for this slave */
ed9b544e 399 int replstate;
285add55 400 unsigned int maxclients;
4ef8de8a 401 unsigned long long maxmemory;
d5d55fc3 402 unsigned int blpop_blocked_clients;
403 unsigned int vm_blocked_clients;
ed9b544e 404 /* Sort parameters - qsort_r() is only available under BSD so we
405 * have to take this state global, in order to pass it to sortCompare() */
406 int sort_desc;
407 int sort_alpha;
408 int sort_bypattern;
75680a3c 409 /* Virtual memory configuration */
410 int vm_enabled;
054e426d 411 char *vm_swap_file;
75680a3c 412 off_t vm_page_size;
413 off_t vm_pages;
4ef8de8a 414 unsigned long long vm_max_memory;
cbba7dd7 415 /* Hashes config */
416 size_t hash_max_zipmap_entries;
417 size_t hash_max_zipmap_value;
75680a3c 418 /* Virtual memory state */
419 FILE *vm_fp;
420 int vm_fd;
421 off_t vm_next_page; /* Next probably empty page */
422 off_t vm_near_pages; /* Number of pages allocated sequentially */
06224fec 423 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
3a66edc7 424 time_t unixtime; /* Unix time sampled every second. */
92f8e882 425 /* Virtual memory I/O threads stuff */
92f8e882 426 /* An I/O thread process an element taken from the io_jobs queue and
996cb5f7 427 * put the result of the operation in the io_done list. While the
428 * job is being processed, it's put on io_processing queue. */
429 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
430 list *io_processing; /* List of VM I/O jobs being processed */
431 list *io_processed; /* List of VM I/O jobs already processed */
d5d55fc3 432 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
996cb5f7 433 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
a5819310 434 pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
435 pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
bcaa7a4f 436 pthread_attr_t io_threads_attr; /* attributes for threads creation */
92f8e882 437 int io_active_threads; /* Number of running I/O threads */
438 int vm_max_threads; /* Max number of I/O threads running at the same time */
996cb5f7 439 /* Our main thread is blocked on the event loop, locking for sockets ready
440 * to be read or written, so when a threaded I/O operation is ready to be
441 * processed by the main thread, the I/O thread will use a unix pipe to
442 * awake the main thread. The followings are the two pipe FDs. */
443 int io_ready_pipe_read;
444 int io_ready_pipe_write;
7d98e08c 445 /* Virtual memory stats */
446 unsigned long long vm_stats_used_pages;
447 unsigned long long vm_stats_swapped_objects;
448 unsigned long long vm_stats_swapouts;
449 unsigned long long vm_stats_swapins;
befec3cd 450 /* Pubsub */
ffc6b7f8 451 dict *pubsub_channels; /* Map channels to list of subscribed clients */
452 list *pubsub_patterns; /* A list of pubsub_patterns */
befec3cd 453 /* Misc */
b9bc0eef 454 FILE *devnull;
ed9b544e 455};
456
ffc6b7f8 457typedef struct pubsubPattern {
458 redisClient *client;
459 robj *pattern;
460} pubsubPattern;
461
ed9b544e 462typedef void redisCommandProc(redisClient *c);
ca1788b5 463typedef void redisVmPreloadProc(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
ed9b544e 464struct redisCommand {
465 char *name;
466 redisCommandProc *proc;
467 int arity;
468 int flags;
76583ea4
PN
469 /* Use a function to determine which keys need to be loaded
470 * in the background prior to executing this command. Takes precedence
471 * over vm_firstkey and others, ignored when NULL */
ca1788b5 472 redisVmPreloadProc *vm_preload_proc;
7c775e09 473 /* What keys should be loaded in background when calling this command? */
474 int vm_firstkey; /* The first argument that's a key (0 = no keys) */
475 int vm_lastkey; /* THe last argument that's a key */
476 int vm_keystep; /* The step between first and last key */
ed9b544e 477};
478
de96dbfe 479struct redisFunctionSym {
480 char *name;
56906eef 481 unsigned long pointer;
de96dbfe 482};
483
ed9b544e 484typedef struct _redisSortObject {
485 robj *obj;
486 union {
487 double score;
488 robj *cmpobj;
489 } u;
490} redisSortObject;
491
492typedef struct _redisSortOperation {
493 int type;
494 robj *pattern;
495} redisSortOperation;
496
6b47e12e 497/* ZSETs use a specialized version of Skiplists */
498
499typedef struct zskiplistNode {
500 struct zskiplistNode **forward;
e3870fab 501 struct zskiplistNode *backward;
912b9165 502 unsigned int *span;
6b47e12e 503 double score;
504 robj *obj;
505} zskiplistNode;
506
507typedef struct zskiplist {
e3870fab 508 struct zskiplistNode *header, *tail;
d13f767c 509 unsigned long length;
6b47e12e 510 int level;
511} zskiplist;
512
1812e024 513typedef struct zset {
514 dict *dict;
6b47e12e 515 zskiplist *zsl;
1812e024 516} zset;
517
6b47e12e 518/* Our shared "common" objects */
519
05df7621 520#define REDIS_SHARED_INTEGERS 10000
ed9b544e 521struct sharedObjectsStruct {
c937aa89 522 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
6e469882 523 *colon, *nullbulk, *nullmultibulk, *queued,
c937aa89 524 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
525 *outofrangeerr, *plus,
ed9b544e 526 *select0, *select1, *select2, *select3, *select4,
befec3cd 527 *select5, *select6, *select7, *select8, *select9,
c8d0ea0e 528 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk, *mbulk3,
529 *mbulk4, *psubscribebulk, *punsubscribebulk,
530 *integers[REDIS_SHARED_INTEGERS];
ed9b544e 531} shared;
532
a7866db6 533/* Global vars that are actally used as constants. The following double
534 * values are used for double on-disk serialization, and are initialized
535 * at runtime to avoid strange compiler optimizations. */
536
537static double R_Zero, R_PosInf, R_NegInf, R_Nan;
538
92f8e882 539/* VM threaded I/O request message */
b9bc0eef 540#define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
541#define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
542#define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
d5d55fc3 543typedef struct iojob {
996cb5f7 544 int type; /* Request type, REDIS_IOJOB_* */
b9bc0eef 545 redisDb *db;/* Redis database */
92f8e882 546 robj *key; /* This I/O request is about swapping this key */
b9bc0eef 547 robj *val; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
92f8e882 548 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
549 off_t page; /* Swap page where to read/write the object */
248ea310 550 off_t pages; /* Swap pages needed to save object. PREPARE_SWAP return val */
996cb5f7 551 int canceled; /* True if this command was canceled by blocking side of VM */
552 pthread_t thread; /* ID of the thread processing this entry */
553} iojob;
92f8e882 554
ed9b544e 555/*================================ Prototypes =============================== */
556
557static void freeStringObject(robj *o);
558static void freeListObject(robj *o);
559static void freeSetObject(robj *o);
560static void decrRefCount(void *o);
561static robj *createObject(int type, void *ptr);
562static void freeClient(redisClient *c);
f78fd11b 563static int rdbLoad(char *filename);
ed9b544e 564static void addReply(redisClient *c, robj *obj);
565static void addReplySds(redisClient *c, sds s);
566static void incrRefCount(robj *o);
f78fd11b 567static int rdbSaveBackground(char *filename);
ed9b544e 568static robj *createStringObject(char *ptr, size_t len);
4ef8de8a 569static robj *dupStringObject(robj *o);
248ea310 570static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
dd142b9c 571static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
28ed1f33 572static void flushAppendOnlyFile(void);
44b38ef4 573static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
ed9b544e 574static int syncWithMaster(void);
05df7621 575static robj *tryObjectEncoding(robj *o);
9d65a1bb 576static robj *getDecodedObject(robj *o);
3305306f 577static int removeExpire(redisDb *db, robj *key);
578static int expireIfNeeded(redisDb *db, robj *key);
579static int deleteIfVolatile(redisDb *db, robj *key);
1b03836c 580static int deleteIfSwapped(redisDb *db, robj *key);
94754ccc 581static int deleteKey(redisDb *db, robj *key);
bb32ede5 582static time_t getExpire(redisDb *db, robj *key);
583static int setExpire(redisDb *db, robj *key, time_t when);
a3b21203 584static void updateSlavesWaitingBgsave(int bgsaveerr);
3fd78bcd 585static void freeMemoryIfNeeded(void);
de96dbfe 586static int processCommand(redisClient *c);
56906eef 587static void setupSigSegvAction(void);
a3b21203 588static void rdbRemoveTempFile(pid_t childpid);
9d65a1bb 589static void aofRemoveTempFile(pid_t childpid);
0ea663ea 590static size_t stringObjectLen(robj *o);
638e42ac 591static void processInputBuffer(redisClient *c);
6b47e12e 592static zskiplist *zslCreate(void);
fd8ccf44 593static void zslFree(zskiplist *zsl);
2b59cfdf 594static void zslInsert(zskiplist *zsl, double score, robj *obj);
2895e862 595static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
6e469882 596static void initClientMultiState(redisClient *c);
597static void freeClientMultiState(redisClient *c);
598static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
b0d8747d 599static void unblockClientWaitingData(redisClient *c);
4409877e 600static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
75680a3c 601static void vmInit(void);
a35ddf12 602static void vmMarkPagesFree(off_t page, off_t count);
55cf8433 603static robj *vmLoadObject(robj *key);
7e69548d 604static robj *vmPreviewObject(robj *key);
a69a0c9c 605static int vmSwapOneObjectBlocking(void);
606static int vmSwapOneObjectThreaded(void);
7e69548d 607static int vmCanSwapOut(void);
a5819310 608static int tryFreeOneObjectFromFreelist(void);
996cb5f7 609static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
610static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
611static void vmCancelThreadedIOJob(robj *o);
b9bc0eef 612static void lockThreadedIO(void);
613static void unlockThreadedIO(void);
614static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
615static void freeIOJob(iojob *j);
616static void queueIOJob(iojob *j);
a5819310 617static int vmWriteObjectOnSwap(robj *o, off_t page);
618static robj *vmReadObjectFromSwap(off_t page, int type);
054e426d 619static void waitEmptyIOJobsQueue(void);
620static void vmReopenSwapFile(void);
970e10bb 621static int vmFreePage(off_t page);
ca1788b5 622static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
3805e04f 623static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
0a6f3f0f 624static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd);
d5d55fc3 625static int dontWaitForSwappedKey(redisClient *c, robj *key);
626static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
627static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
628static struct redisCommand *lookupCommand(char *name);
629static void call(redisClient *c, struct redisCommand *cmd);
630static void resetClient(redisClient *c);
ada386b2 631static void convertToRealHash(robj *o);
ffc6b7f8 632static int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
633static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
634static void freePubsubPattern(void *p);
635static int listMatchPubsubPattern(void *a, void *b);
636static int compareStringObjects(robj *a, robj *b);
bf028098 637static int equalStringObjects(robj *a, robj *b);
befec3cd 638static void usage();
8f63ddca 639static int rewriteAppendOnlyFileBackground(void);
242a64f3 640static int vmSwapObjectBlocking(robj *key, robj *val);
fab43727 641static int prepareForShutdown();
37ab76c9 642static void touchWatchedKey(redisDb *db, robj *key);
9b30e1a2 643static void touchWatchedKeysOnFlush(int dbid);
37ab76c9 644static void unwatchAllKeys(redisClient *c);
ed9b544e 645
abcb223e 646static void authCommand(redisClient *c);
ed9b544e 647static void pingCommand(redisClient *c);
648static void echoCommand(redisClient *c);
649static void setCommand(redisClient *c);
650static void setnxCommand(redisClient *c);
526d00a5 651static void setexCommand(redisClient *c);
ed9b544e 652static void getCommand(redisClient *c);
653static void delCommand(redisClient *c);
654static void existsCommand(redisClient *c);
655static void incrCommand(redisClient *c);
656static void decrCommand(redisClient *c);
657static void incrbyCommand(redisClient *c);
658static void decrbyCommand(redisClient *c);
659static void selectCommand(redisClient *c);
660static void randomkeyCommand(redisClient *c);
661static void keysCommand(redisClient *c);
662static void dbsizeCommand(redisClient *c);
663static void lastsaveCommand(redisClient *c);
664static void saveCommand(redisClient *c);
665static void bgsaveCommand(redisClient *c);
9d65a1bb 666static void bgrewriteaofCommand(redisClient *c);
ed9b544e 667static void shutdownCommand(redisClient *c);
668static void moveCommand(redisClient *c);
669static void renameCommand(redisClient *c);
670static void renamenxCommand(redisClient *c);
671static void lpushCommand(redisClient *c);
672static void rpushCommand(redisClient *c);
673static void lpopCommand(redisClient *c);
674static void rpopCommand(redisClient *c);
675static void llenCommand(redisClient *c);
676static void lindexCommand(redisClient *c);
677static void lrangeCommand(redisClient *c);
678static void ltrimCommand(redisClient *c);
679static void typeCommand(redisClient *c);
680static void lsetCommand(redisClient *c);
681static void saddCommand(redisClient *c);
682static void sremCommand(redisClient *c);
a4460ef4 683static void smoveCommand(redisClient *c);
ed9b544e 684static void sismemberCommand(redisClient *c);
685static void scardCommand(redisClient *c);
12fea928 686static void spopCommand(redisClient *c);
2abb95a9 687static void srandmemberCommand(redisClient *c);
ed9b544e 688static void sinterCommand(redisClient *c);
689static void sinterstoreCommand(redisClient *c);
40d224a9 690static void sunionCommand(redisClient *c);
691static void sunionstoreCommand(redisClient *c);
f4f56e1d 692static void sdiffCommand(redisClient *c);
693static void sdiffstoreCommand(redisClient *c);
ed9b544e 694static void syncCommand(redisClient *c);
695static void flushdbCommand(redisClient *c);
696static void flushallCommand(redisClient *c);
697static void sortCommand(redisClient *c);
698static void lremCommand(redisClient *c);
0f5f7e9a 699static void rpoplpushcommand(redisClient *c);
ed9b544e 700static void infoCommand(redisClient *c);
70003d28 701static void mgetCommand(redisClient *c);
87eca727 702static void monitorCommand(redisClient *c);
3305306f 703static void expireCommand(redisClient *c);
802e8373 704static void expireatCommand(redisClient *c);
f6b141c5 705static void getsetCommand(redisClient *c);
fd88489a 706static void ttlCommand(redisClient *c);
321b0e13 707static void slaveofCommand(redisClient *c);
7f957c92 708static void debugCommand(redisClient *c);
f6b141c5 709static void msetCommand(redisClient *c);
710static void msetnxCommand(redisClient *c);
fd8ccf44 711static void zaddCommand(redisClient *c);
7db723ad 712static void zincrbyCommand(redisClient *c);
cc812361 713static void zrangeCommand(redisClient *c);
50c55df5 714static void zrangebyscoreCommand(redisClient *c);
f44dd428 715static void zcountCommand(redisClient *c);
e3870fab 716static void zrevrangeCommand(redisClient *c);
3c41331e 717static void zcardCommand(redisClient *c);
1b7106e7 718static void zremCommand(redisClient *c);
6e333bbe 719static void zscoreCommand(redisClient *c);
1807985b 720static void zremrangebyscoreCommand(redisClient *c);
6e469882 721static void multiCommand(redisClient *c);
722static void execCommand(redisClient *c);
18b6cb76 723static void discardCommand(redisClient *c);
4409877e 724static void blpopCommand(redisClient *c);
725static void brpopCommand(redisClient *c);
4b00bebd 726static void appendCommand(redisClient *c);
39191553 727static void substrCommand(redisClient *c);
69d95c3e 728static void zrankCommand(redisClient *c);
798d9e55 729static void zrevrankCommand(redisClient *c);
978c2c94 730static void hsetCommand(redisClient *c);
1f1c7695 731static void hsetnxCommand(redisClient *c);
978c2c94 732static void hgetCommand(redisClient *c);
09aeb579
PN
733static void hmsetCommand(redisClient *c);
734static void hmgetCommand(redisClient *c);
07efaf74 735static void hdelCommand(redisClient *c);
92b27fe9 736static void hlenCommand(redisClient *c);
9212eafd 737static void zremrangebyrankCommand(redisClient *c);
5d373da9 738static void zunionstoreCommand(redisClient *c);
739static void zinterstoreCommand(redisClient *c);
78409a0f 740static void hkeysCommand(redisClient *c);
741static void hvalsCommand(redisClient *c);
742static void hgetallCommand(redisClient *c);
a86f14b1 743static void hexistsCommand(redisClient *c);
500ece7c 744static void configCommand(redisClient *c);
01426b05 745static void hincrbyCommand(redisClient *c);
befec3cd 746static void subscribeCommand(redisClient *c);
747static void unsubscribeCommand(redisClient *c);
ffc6b7f8 748static void psubscribeCommand(redisClient *c);
749static void punsubscribeCommand(redisClient *c);
befec3cd 750static void publishCommand(redisClient *c);
37ab76c9 751static void watchCommand(redisClient *c);
752static void unwatchCommand(redisClient *c);
f6b141c5 753
ed9b544e 754/*================================= Globals ================================= */
755
756/* Global vars */
757static struct redisServer server; /* server global state */
1a132bbc 758static struct redisCommand *commandTable;
1a132bbc 759static struct redisCommand readonlyCommandTable[] = {
76583ea4
PN
760 {"get",getCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
761 {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
762 {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
526d00a5 763 {"setex",setexCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
76583ea4
PN
764 {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
765 {"substr",substrCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
766 {"del",delCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
767 {"exists",existsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
768 {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
769 {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
770 {"mget",mgetCommand,-2,REDIS_CMD_INLINE,NULL,1,-1,1},
771 {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
772 {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
773 {"rpop",rpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
774 {"lpop",lpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
775 {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
776 {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
777 {"llen",llenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
778 {"lindex",lindexCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
779 {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
780 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
781 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
782 {"lrem",lremCommand,4,REDIS_CMD_BULK,NULL,1,1,1},
783 {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,2,1},
784 {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
785 {"srem",sremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
786 {"smove",smoveCommand,4,REDIS_CMD_BULK,NULL,1,2,1},
787 {"sismember",sismemberCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
788 {"scard",scardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
789 {"spop",spopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
790 {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
791 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
792 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
793 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
794 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
795 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
796 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
797 {"smembers",sinterCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
798 {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
799 {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
800 {"zrem",zremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
801 {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
802 {"zremrangebyrank",zremrangebyrankCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
5d373da9 803 {"zunionstore",zunionstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
804 {"zinterstore",zinterstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
76583ea4
PN
805 {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
806 {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
807 {"zcount",zcountCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
808 {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
809 {"zcard",zcardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
810 {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
811 {"zrank",zrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
812 {"zrevrank",zrevrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
813 {"hset",hsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
1f1c7695 814 {"hsetnx",hsetnxCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
09aeb579 815 {"hget",hgetCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
d33278d1 816 {"hmset",hmsetCommand,-4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
09aeb579 817 {"hmget",hmgetCommand,-3,REDIS_CMD_BULK,NULL,1,1,1},
01426b05 818 {"hincrby",hincrbyCommand,4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
76583ea4
PN
819 {"hdel",hdelCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
820 {"hlen",hlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
821 {"hkeys",hkeysCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
822 {"hvals",hvalsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
823 {"hgetall",hgetallCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
4583c4f0 824 {"hexists",hexistsCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
76583ea4
PN
825 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
826 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
827 {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
828 {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
829 {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
830 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
831 {"select",selectCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
832 {"move",moveCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
833 {"rename",renameCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
834 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
835 {"expire",expireCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
836 {"expireat",expireatCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
837 {"keys",keysCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
838 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
839 {"auth",authCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
840 {"ping",pingCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
841 {"echo",echoCommand,2,REDIS_CMD_BULK,NULL,0,0,0},
842 {"save",saveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
843 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
844 {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
845 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
846 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
847 {"type",typeCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
848 {"multi",multiCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
3805e04f 849 {"exec",execCommand,1,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0},
76583ea4
PN
850 {"discard",discardCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
851 {"sync",syncCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
852 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
853 {"flushall",flushallCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
854 {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
855 {"info",infoCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
856 {"monitor",monitorCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
857 {"ttl",ttlCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
858 {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
859 {"debug",debugCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
500ece7c 860 {"config",configCommand,-2,REDIS_CMD_BULK,NULL,0,0,0},
befec3cd 861 {"subscribe",subscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
862 {"unsubscribe",unsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
ffc6b7f8 863 {"psubscribe",psubscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
864 {"punsubscribe",punsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
4005fef1 865 {"publish",publishCommand,3,REDIS_CMD_BULK|REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0},
37ab76c9 866 {"watch",watchCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
d55d5c5d 867 {"unwatch",unwatchCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}
ed9b544e 868};
bcfc686d 869
ed9b544e 870/*============================ Utility functions ============================ */
871
872/* Glob-style pattern matching. */
500ece7c 873static int stringmatchlen(const char *pattern, int patternLen,
ed9b544e 874 const char *string, int stringLen, int nocase)
875{
876 while(patternLen) {
877 switch(pattern[0]) {
878 case '*':
879 while (pattern[1] == '*') {
880 pattern++;
881 patternLen--;
882 }
883 if (patternLen == 1)
884 return 1; /* match */
885 while(stringLen) {
886 if (stringmatchlen(pattern+1, patternLen-1,
887 string, stringLen, nocase))
888 return 1; /* match */
889 string++;
890 stringLen--;
891 }
892 return 0; /* no match */
893 break;
894 case '?':
895 if (stringLen == 0)
896 return 0; /* no match */
897 string++;
898 stringLen--;
899 break;
900 case '[':
901 {
902 int not, match;
903
904 pattern++;
905 patternLen--;
906 not = pattern[0] == '^';
907 if (not) {
908 pattern++;
909 patternLen--;
910 }
911 match = 0;
912 while(1) {
913 if (pattern[0] == '\\') {
914 pattern++;
915 patternLen--;
916 if (pattern[0] == string[0])
917 match = 1;
918 } else if (pattern[0] == ']') {
919 break;
920 } else if (patternLen == 0) {
921 pattern--;
922 patternLen++;
923 break;
924 } else if (pattern[1] == '-' && patternLen >= 3) {
925 int start = pattern[0];
926 int end = pattern[2];
927 int c = string[0];
928 if (start > end) {
929 int t = start;
930 start = end;
931 end = t;
932 }
933 if (nocase) {
934 start = tolower(start);
935 end = tolower(end);
936 c = tolower(c);
937 }
938 pattern += 2;
939 patternLen -= 2;
940 if (c >= start && c <= end)
941 match = 1;
942 } else {
943 if (!nocase) {
944 if (pattern[0] == string[0])
945 match = 1;
946 } else {
947 if (tolower((int)pattern[0]) == tolower((int)string[0]))
948 match = 1;
949 }
950 }
951 pattern++;
952 patternLen--;
953 }
954 if (not)
955 match = !match;
956 if (!match)
957 return 0; /* no match */
958 string++;
959 stringLen--;
960 break;
961 }
962 case '\\':
963 if (patternLen >= 2) {
964 pattern++;
965 patternLen--;
966 }
967 /* fall through */
968 default:
969 if (!nocase) {
970 if (pattern[0] != string[0])
971 return 0; /* no match */
972 } else {
973 if (tolower((int)pattern[0]) != tolower((int)string[0]))
974 return 0; /* no match */
975 }
976 string++;
977 stringLen--;
978 break;
979 }
980 pattern++;
981 patternLen--;
982 if (stringLen == 0) {
983 while(*pattern == '*') {
984 pattern++;
985 patternLen--;
986 }
987 break;
988 }
989 }
990 if (patternLen == 0 && stringLen == 0)
991 return 1;
992 return 0;
993}
994
500ece7c 995static int stringmatch(const char *pattern, const char *string, int nocase) {
996 return stringmatchlen(pattern,strlen(pattern),string,strlen(string),nocase);
997}
998
2b619329 999/* Convert a string representing an amount of memory into the number of
1000 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
1001 * (1024*1024*1024).
1002 *
1003 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
1004 * set to 0 */
1005static long long memtoll(const char *p, int *err) {
1006 const char *u;
1007 char buf[128];
1008 long mul; /* unit multiplier */
1009 long long val;
1010 unsigned int digits;
1011
1012 if (err) *err = 0;
1013 /* Search the first non digit character. */
1014 u = p;
1015 if (*u == '-') u++;
1016 while(*u && isdigit(*u)) u++;
1017 if (*u == '\0' || !strcasecmp(u,"b")) {
1018 mul = 1;
72324005 1019 } else if (!strcasecmp(u,"k")) {
2b619329 1020 mul = 1000;
72324005 1021 } else if (!strcasecmp(u,"kb")) {
2b619329 1022 mul = 1024;
72324005 1023 } else if (!strcasecmp(u,"m")) {
2b619329 1024 mul = 1000*1000;
72324005 1025 } else if (!strcasecmp(u,"mb")) {
2b619329 1026 mul = 1024*1024;
72324005 1027 } else if (!strcasecmp(u,"g")) {
2b619329 1028 mul = 1000L*1000*1000;
72324005 1029 } else if (!strcasecmp(u,"gb")) {
2b619329 1030 mul = 1024L*1024*1024;
1031 } else {
1032 if (err) *err = 1;
1033 mul = 1;
1034 }
1035 digits = u-p;
1036 if (digits >= sizeof(buf)) {
1037 if (err) *err = 1;
1038 return LLONG_MAX;
1039 }
1040 memcpy(buf,p,digits);
1041 buf[digits] = '\0';
1042 val = strtoll(buf,NULL,10);
1043 return val*mul;
1044}
1045
ee14da56 1046/* Convert a long long into a string. Returns the number of
1047 * characters needed to represent the number, that can be shorter if passed
1048 * buffer length is not enough to store the whole number. */
1049static int ll2string(char *s, size_t len, long long value) {
1050 char buf[32], *p;
1051 unsigned long long v;
1052 size_t l;
1053
1054 if (len == 0) return 0;
1055 v = (value < 0) ? -value : value;
1056 p = buf+31; /* point to the last character */
1057 do {
1058 *p-- = '0'+(v%10);
1059 v /= 10;
1060 } while(v);
1061 if (value < 0) *p-- = '-';
1062 p++;
1063 l = 32-(p-buf);
1064 if (l+1 > len) l = len-1; /* Make sure it fits, including the nul term */
1065 memcpy(s,p,l);
1066 s[l] = '\0';
1067 return l;
1068}
1069
56906eef 1070static void redisLog(int level, const char *fmt, ...) {
ed9b544e 1071 va_list ap;
1072 FILE *fp;
1073
1074 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
1075 if (!fp) return;
1076
1077 va_start(ap, fmt);
1078 if (level >= server.verbosity) {
6766f45e 1079 char *c = ".-*#";
1904ecc1 1080 char buf[64];
1081 time_t now;
1082
1083 now = time(NULL);
6c9385e0 1084 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
054e426d 1085 fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
ed9b544e 1086 vfprintf(fp, fmt, ap);
1087 fprintf(fp,"\n");
1088 fflush(fp);
1089 }
1090 va_end(ap);
1091
1092 if (server.logfile) fclose(fp);
1093}
1094
1095/*====================== Hash table type implementation ==================== */
1096
1097/* This is an hash table type that uses the SDS dynamic strings libary as
1098 * keys and radis objects as values (objects can hold SDS strings,
1099 * lists, sets). */
1100
1812e024 1101static void dictVanillaFree(void *privdata, void *val)
1102{
1103 DICT_NOTUSED(privdata);
1104 zfree(val);
1105}
1106
4409877e 1107static void dictListDestructor(void *privdata, void *val)
1108{
1109 DICT_NOTUSED(privdata);
1110 listRelease((list*)val);
1111}
1112
ed9b544e 1113static int sdsDictKeyCompare(void *privdata, const void *key1,
1114 const void *key2)
1115{
1116 int l1,l2;
1117 DICT_NOTUSED(privdata);
1118
1119 l1 = sdslen((sds)key1);
1120 l2 = sdslen((sds)key2);
1121 if (l1 != l2) return 0;
1122 return memcmp(key1, key2, l1) == 0;
1123}
1124
1125static void dictRedisObjectDestructor(void *privdata, void *val)
1126{
1127 DICT_NOTUSED(privdata);
1128
a35ddf12 1129 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
ed9b544e 1130 decrRefCount(val);
1131}
1132
942a3961 1133static int dictObjKeyCompare(void *privdata, const void *key1,
ed9b544e 1134 const void *key2)
1135{
1136 const robj *o1 = key1, *o2 = key2;
1137 return sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1138}
1139
942a3961 1140static unsigned int dictObjHash(const void *key) {
ed9b544e 1141 const robj *o = key;
1142 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1143}
1144
942a3961 1145static int dictEncObjKeyCompare(void *privdata, const void *key1,
1146 const void *key2)
1147{
9d65a1bb 1148 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
1149 int cmp;
942a3961 1150
2a1198b4 1151 if (o1->encoding == REDIS_ENCODING_INT &&
dc05abde 1152 o2->encoding == REDIS_ENCODING_INT)
1153 return o1->ptr == o2->ptr;
2a1198b4 1154
9d65a1bb 1155 o1 = getDecodedObject(o1);
1156 o2 = getDecodedObject(o2);
1157 cmp = sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1158 decrRefCount(o1);
1159 decrRefCount(o2);
1160 return cmp;
942a3961 1161}
1162
1163static unsigned int dictEncObjHash(const void *key) {
9d65a1bb 1164 robj *o = (robj*) key;
942a3961 1165
ed9e4966 1166 if (o->encoding == REDIS_ENCODING_RAW) {
1167 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1168 } else {
1169 if (o->encoding == REDIS_ENCODING_INT) {
1170 char buf[32];
1171 int len;
1172
ee14da56 1173 len = ll2string(buf,32,(long)o->ptr);
ed9e4966 1174 return dictGenHashFunction((unsigned char*)buf, len);
1175 } else {
1176 unsigned int hash;
1177
1178 o = getDecodedObject(o);
1179 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1180 decrRefCount(o);
1181 return hash;
1182 }
1183 }
942a3961 1184}
1185
f2d9f50f 1186/* Sets type and expires */
ed9b544e 1187static dictType setDictType = {
942a3961 1188 dictEncObjHash, /* hash function */
ed9b544e 1189 NULL, /* key dup */
1190 NULL, /* val dup */
942a3961 1191 dictEncObjKeyCompare, /* key compare */
ed9b544e 1192 dictRedisObjectDestructor, /* key destructor */
1193 NULL /* val destructor */
1194};
1195
f2d9f50f 1196/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1812e024 1197static dictType zsetDictType = {
1198 dictEncObjHash, /* hash function */
1199 NULL, /* key dup */
1200 NULL, /* val dup */
1201 dictEncObjKeyCompare, /* key compare */
1202 dictRedisObjectDestructor, /* key destructor */
da0a1620 1203 dictVanillaFree /* val destructor of malloc(sizeof(double)) */
1812e024 1204};
1205
f2d9f50f 1206/* Db->dict */
5234952b 1207static dictType dbDictType = {
942a3961 1208 dictObjHash, /* hash function */
ed9b544e 1209 NULL, /* key dup */
1210 NULL, /* val dup */
942a3961 1211 dictObjKeyCompare, /* key compare */
ed9b544e 1212 dictRedisObjectDestructor, /* key destructor */
1213 dictRedisObjectDestructor /* val destructor */
1214};
1215
f2d9f50f 1216/* Db->expires */
1217static dictType keyptrDictType = {
1218 dictObjHash, /* hash function */
1219 NULL, /* key dup */
1220 NULL, /* val dup */
1221 dictObjKeyCompare, /* key compare */
1222 dictRedisObjectDestructor, /* key destructor */
1223 NULL /* val destructor */
1224};
1225
5234952b 1226/* Hash type hash table (note that small hashes are represented with zimpaps) */
1227static dictType hashDictType = {
1228 dictEncObjHash, /* hash function */
1229 NULL, /* key dup */
1230 NULL, /* val dup */
1231 dictEncObjKeyCompare, /* key compare */
1232 dictRedisObjectDestructor, /* key destructor */
1233 dictRedisObjectDestructor /* val destructor */
1234};
1235
4409877e 1236/* Keylist hash table type has unencoded redis objects as keys and
d5d55fc3 1237 * lists as values. It's used for blocking operations (BLPOP) and to
1238 * map swapped keys to a list of clients waiting for this keys to be loaded. */
4409877e 1239static dictType keylistDictType = {
1240 dictObjHash, /* hash function */
1241 NULL, /* key dup */
1242 NULL, /* val dup */
1243 dictObjKeyCompare, /* key compare */
1244 dictRedisObjectDestructor, /* key destructor */
1245 dictListDestructor /* val destructor */
1246};
1247
42ab0172
AO
1248static void version();
1249
ed9b544e 1250/* ========================= Random utility functions ======================= */
1251
1252/* Redis generally does not try to recover from out of memory conditions
1253 * when allocating objects or strings, it is not clear if it will be possible
1254 * to report this condition to the client since the networking layer itself
1255 * is based on heap allocation for send buffers, so we simply abort.
1256 * At least the code will be simpler to read... */
1257static void oom(const char *msg) {
71c54b21 1258 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
ed9b544e 1259 sleep(1);
1260 abort();
1261}
1262
1263/* ====================== Redis server networking stuff ===================== */
56906eef 1264static void closeTimedoutClients(void) {
ed9b544e 1265 redisClient *c;
ed9b544e 1266 listNode *ln;
1267 time_t now = time(NULL);
c7df85a4 1268 listIter li;
ed9b544e 1269
c7df85a4 1270 listRewind(server.clients,&li);
1271 while ((ln = listNext(&li)) != NULL) {
ed9b544e 1272 c = listNodeValue(ln);
f86a74e9 1273 if (server.maxidletime &&
1274 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
c7cf2ec9 1275 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
ffc6b7f8 1276 dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
1277 listLength(c->pubsub_patterns) == 0 &&
d6cc8867 1278 (now - c->lastinteraction > server.maxidletime))
f86a74e9 1279 {
f870935d 1280 redisLog(REDIS_VERBOSE,"Closing idle client");
ed9b544e 1281 freeClient(c);
f86a74e9 1282 } else if (c->flags & REDIS_BLOCKED) {
58d976b8 1283 if (c->blockingto != 0 && c->blockingto < now) {
b177fd30 1284 addReply(c,shared.nullmultibulk);
b0d8747d 1285 unblockClientWaitingData(c);
f86a74e9 1286 }
ed9b544e 1287 }
1288 }
ed9b544e 1289}
1290
12fea928 1291static int htNeedsResize(dict *dict) {
1292 long long size, used;
1293
1294 size = dictSlots(dict);
1295 used = dictSize(dict);
1296 return (size && used && size > DICT_HT_INITIAL_SIZE &&
1297 (used*100/size < REDIS_HT_MINFILL));
1298}
1299
0bc03378 1300/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1301 * we resize the hash table to save memory */
56906eef 1302static void tryResizeHashTables(void) {
0bc03378 1303 int j;
1304
1305 for (j = 0; j < server.dbnum; j++) {
5413c40d 1306 if (htNeedsResize(server.db[j].dict))
0bc03378 1307 dictResize(server.db[j].dict);
12fea928 1308 if (htNeedsResize(server.db[j].expires))
1309 dictResize(server.db[j].expires);
0bc03378 1310 }
1311}
1312
8ca3e9d1 1313/* Our hash table implementation performs rehashing incrementally while
1314 * we write/read from the hash table. Still if the server is idle, the hash
1315 * table will use two tables for a long time. So we try to use 1 millisecond
1316 * of CPU time at every serverCron() loop in order to rehash some key. */
1317static void incrementallyRehash(void) {
1318 int j;
1319
1320 for (j = 0; j < server.dbnum; j++) {
1321 if (dictIsRehashing(server.db[j].dict)) {
1322 dictRehashMilliseconds(server.db[j].dict,1);
1323 break; /* already used our millisecond for this loop... */
1324 }
1325 }
1326}
1327
9d65a1bb 1328/* A background saving child (BGSAVE) terminated its work. Handle this. */
1329void backgroundSaveDoneHandler(int statloc) {
1330 int exitcode = WEXITSTATUS(statloc);
1331 int bysignal = WIFSIGNALED(statloc);
1332
1333 if (!bysignal && exitcode == 0) {
1334 redisLog(REDIS_NOTICE,
1335 "Background saving terminated with success");
1336 server.dirty = 0;
1337 server.lastsave = time(NULL);
1338 } else if (!bysignal && exitcode != 0) {
1339 redisLog(REDIS_WARNING, "Background saving error");
1340 } else {
1341 redisLog(REDIS_WARNING,
454eea7c 1342 "Background saving terminated by signal %d", WTERMSIG(statloc));
9d65a1bb 1343 rdbRemoveTempFile(server.bgsavechildpid);
1344 }
1345 server.bgsavechildpid = -1;
1346 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1347 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1348 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1349}
1350
1351/* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1352 * Handle this. */
1353void backgroundRewriteDoneHandler(int statloc) {
1354 int exitcode = WEXITSTATUS(statloc);
1355 int bysignal = WIFSIGNALED(statloc);
1356
1357 if (!bysignal && exitcode == 0) {
1358 int fd;
1359 char tmpfile[256];
1360
1361 redisLog(REDIS_NOTICE,
1362 "Background append only file rewriting terminated with success");
1363 /* Now it's time to flush the differences accumulated by the parent */
1364 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
1365 fd = open(tmpfile,O_WRONLY|O_APPEND);
1366 if (fd == -1) {
1367 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
1368 goto cleanup;
1369 }
1370 /* Flush our data... */
1371 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
1372 (signed) sdslen(server.bgrewritebuf)) {
1373 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));
1374 close(fd);
1375 goto cleanup;
1376 }
b32627cd 1377 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
9d65a1bb 1378 /* Now our work is to rename the temp file into the stable file. And
1379 * switch the file descriptor used by the server for append only. */
1380 if (rename(tmpfile,server.appendfilename) == -1) {
1381 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
1382 close(fd);
1383 goto cleanup;
1384 }
1385 /* Mission completed... almost */
1386 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
1387 if (server.appendfd != -1) {
1388 /* If append only is actually enabled... */
1389 close(server.appendfd);
1390 server.appendfd = fd;
1391 fsync(fd);
85a83172 1392 server.appendseldb = -1; /* Make sure it will issue SELECT */
9d65a1bb 1393 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
1394 } else {
1395 /* If append only is disabled we just generate a dump in this
1396 * format. Why not? */
1397 close(fd);
1398 }
1399 } else if (!bysignal && exitcode != 0) {
1400 redisLog(REDIS_WARNING, "Background append only file rewriting error");
1401 } else {
1402 redisLog(REDIS_WARNING,
454eea7c 1403 "Background append only file rewriting terminated by signal %d",
1404 WTERMSIG(statloc));
9d65a1bb 1405 }
1406cleanup:
1407 sdsfree(server.bgrewritebuf);
1408 server.bgrewritebuf = sdsempty();
1409 aofRemoveTempFile(server.bgrewritechildpid);
1410 server.bgrewritechildpid = -1;
1411}
1412
884d4b39 1413/* This function is called once a background process of some kind terminates,
1414 * as we want to avoid resizing the hash tables when there is a child in order
1415 * to play well with copy-on-write (otherwise when a resize happens lots of
1416 * memory pages are copied). The goal of this function is to update the ability
1417 * for dict.c to resize the hash tables accordingly to the fact we have o not
1418 * running childs. */
1419static void updateDictResizePolicy(void) {
1420 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
1421 dictEnableResize();
1422 else
1423 dictDisableResize();
1424}
1425
56906eef 1426static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
94754ccc 1427 int j, loops = server.cronloops++;
ed9b544e 1428 REDIS_NOTUSED(eventLoop);
1429 REDIS_NOTUSED(id);
1430 REDIS_NOTUSED(clientData);
1431
3a66edc7 1432 /* We take a cached value of the unix time in the global state because
1433 * with virtual memory and aging there is to store the current time
1434 * in objects at every object access, and accuracy is not needed.
1435 * To access a global var is faster than calling time(NULL) */
1436 server.unixtime = time(NULL);
1437
fab43727 1438 /* We received a SIGTERM, shutting down here in a safe way, as it is
1439 * not ok doing so inside the signal handler. */
1440 if (server.shutdown_asap) {
1441 if (prepareForShutdown() == REDIS_OK) exit(0);
1442 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
1443 }
1444
0bc03378 1445 /* Show some info about non-empty databases */
ed9b544e 1446 for (j = 0; j < server.dbnum; j++) {
dec423d9 1447 long long size, used, vkeys;
94754ccc 1448
3305306f 1449 size = dictSlots(server.db[j].dict);
1450 used = dictSize(server.db[j].dict);
94754ccc 1451 vkeys = dictSize(server.db[j].expires);
1763929f 1452 if (!(loops % 50) && (used || vkeys)) {
f870935d 1453 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
a4d1ba9a 1454 /* dictPrintStats(server.dict); */
ed9b544e 1455 }
ed9b544e 1456 }
1457
0bc03378 1458 /* We don't want to resize the hash tables while a bacground saving
1459 * is in progress: the saving child is created using fork() that is
1460 * implemented with a copy-on-write semantic in most modern systems, so
1461 * if we resize the HT while there is the saving child at work actually
1462 * a lot of memory movements in the parent will cause a lot of pages
1463 * copied. */
8ca3e9d1 1464 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
1465 if (!(loops % 10)) tryResizeHashTables();
1466 if (server.activerehashing) incrementallyRehash();
884d4b39 1467 }
0bc03378 1468
ed9b544e 1469 /* Show information about connected clients */
1763929f 1470 if (!(loops % 50)) {
bdcb92f2 1471 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
ed9b544e 1472 listLength(server.clients)-listLength(server.slaves),
1473 listLength(server.slaves),
bdcb92f2 1474 zmalloc_used_memory());
ed9b544e 1475 }
1476
1477 /* Close connections of timedout clients */
1763929f 1478 if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients)
ed9b544e 1479 closeTimedoutClients();
1480
9d65a1bb 1481 /* Check if a background saving or AOF rewrite in progress terminated */
1482 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
ed9b544e 1483 int statloc;
9d65a1bb 1484 pid_t pid;
1485
1486 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
1487 if (pid == server.bgsavechildpid) {
1488 backgroundSaveDoneHandler(statloc);
ed9b544e 1489 } else {
9d65a1bb 1490 backgroundRewriteDoneHandler(statloc);
ed9b544e 1491 }
884d4b39 1492 updateDictResizePolicy();
ed9b544e 1493 }
1494 } else {
1495 /* If there is not a background saving in progress check if
1496 * we have to save now */
1497 time_t now = time(NULL);
1498 for (j = 0; j < server.saveparamslen; j++) {
1499 struct saveparam *sp = server.saveparams+j;
1500
1501 if (server.dirty >= sp->changes &&
1502 now-server.lastsave > sp->seconds) {
1503 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
1504 sp->changes, sp->seconds);
f78fd11b 1505 rdbSaveBackground(server.dbfilename);
ed9b544e 1506 break;
1507 }
1508 }
1509 }
94754ccc 1510
f2324293 1511 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1512 * will use few CPU cycles if there are few expiring keys, otherwise
1513 * it will get more aggressive to avoid that too much memory is used by
1514 * keys that can be removed from the keyspace. */
94754ccc 1515 for (j = 0; j < server.dbnum; j++) {
f2324293 1516 int expired;
94754ccc 1517 redisDb *db = server.db+j;
94754ccc 1518
f2324293 1519 /* Continue to expire if at the end of the cycle more than 25%
1520 * of the keys were expired. */
1521 do {
4ef8de8a 1522 long num = dictSize(db->expires);
94754ccc 1523 time_t now = time(NULL);
1524
f2324293 1525 expired = 0;
94754ccc 1526 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
1527 num = REDIS_EXPIRELOOKUPS_PER_CRON;
1528 while (num--) {
1529 dictEntry *de;
1530 time_t t;
1531
1532 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
1533 t = (time_t) dictGetEntryVal(de);
1534 if (now > t) {
1535 deleteKey(db,dictGetEntryKey(de));
f2324293 1536 expired++;
2a6a2ed1 1537 server.stat_expiredkeys++;
94754ccc 1538 }
1539 }
f2324293 1540 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
94754ccc 1541 }
1542
4ef8de8a 1543 /* Swap a few keys on disk if we are over the memory limit and VM
f870935d 1544 * is enbled. Try to free objects from the free list first. */
7e69548d 1545 if (vmCanSwapOut()) {
1546 while (server.vm_enabled && zmalloc_used_memory() >
f870935d 1547 server.vm_max_memory)
1548 {
72e9fd40 1549 int retval;
1550
a5819310 1551 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
72e9fd40 1552 retval = (server.vm_max_threads == 0) ?
1553 vmSwapOneObjectBlocking() :
1554 vmSwapOneObjectThreaded();
1763929f 1555 if (retval == REDIS_ERR && !(loops % 300) &&
72e9fd40 1556 zmalloc_used_memory() >
1557 (server.vm_max_memory+server.vm_max_memory/10))
1558 {
1559 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
7e69548d 1560 }
72e9fd40 1561 /* Note that when using threade I/O we free just one object,
1562 * because anyway when the I/O thread in charge to swap this
1563 * object out will finish, the handler of completed jobs
1564 * will try to swap more objects if we are still out of memory. */
1565 if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
4ef8de8a 1566 }
1567 }
1568
ed9b544e 1569 /* Check if we should connect to a MASTER */
1763929f 1570 if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) {
ed9b544e 1571 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
1572 if (syncWithMaster() == REDIS_OK) {
1573 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
8f63ddca 1574 if (server.appendonly) rewriteAppendOnlyFileBackground();
ed9b544e 1575 }
1576 }
1763929f 1577 return 100;
ed9b544e 1578}
1579
d5d55fc3 1580/* This function gets called every time Redis is entering the
1581 * main loop of the event driven library, that is, before to sleep
1582 * for ready file descriptors. */
1583static void beforeSleep(struct aeEventLoop *eventLoop) {
1584 REDIS_NOTUSED(eventLoop);
1585
28ed1f33 1586 /* Awake clients that got all the swapped keys they requested */
d5d55fc3 1587 if (server.vm_enabled && listLength(server.io_ready_clients)) {
1588 listIter li;
1589 listNode *ln;
1590
1591 listRewind(server.io_ready_clients,&li);
1592 while((ln = listNext(&li))) {
1593 redisClient *c = ln->value;
1594 struct redisCommand *cmd;
1595
1596 /* Resume the client. */
1597 listDelNode(server.io_ready_clients,ln);
1598 c->flags &= (~REDIS_IO_WAIT);
1599 server.vm_blocked_clients--;
1600 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1601 readQueryFromClient, c);
1602 cmd = lookupCommand(c->argv[0]->ptr);
1603 assert(cmd != NULL);
1604 call(c,cmd);
1605 resetClient(c);
1606 /* There may be more data to process in the input buffer. */
1607 if (c->querybuf && sdslen(c->querybuf) > 0)
1608 processInputBuffer(c);
1609 }
1610 }
28ed1f33 1611 /* Write the AOF buffer on disk */
1612 flushAppendOnlyFile();
d5d55fc3 1613}
1614
ed9b544e 1615static void createSharedObjects(void) {
05df7621 1616 int j;
1617
ed9b544e 1618 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
1619 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
1620 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
c937aa89 1621 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
1622 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
1623 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
1624 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
1625 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
1626 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
ed9b544e 1627 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
6e469882 1628 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
ed9b544e 1629 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
1630 "-ERR Operation against a key holding the wrong kind of value\r\n"));
ed9b544e 1631 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
1632 "-ERR no such key\r\n"));
ed9b544e 1633 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
1634 "-ERR syntax error\r\n"));
c937aa89 1635 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
1636 "-ERR source and destination objects are the same\r\n"));
1637 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
1638 "-ERR index out of range\r\n"));
ed9b544e 1639 shared.space = createObject(REDIS_STRING,sdsnew(" "));
c937aa89 1640 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
1641 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
ed9b544e 1642 shared.select0 = createStringObject("select 0\r\n",10);
1643 shared.select1 = createStringObject("select 1\r\n",10);
1644 shared.select2 = createStringObject("select 2\r\n",10);
1645 shared.select3 = createStringObject("select 3\r\n",10);
1646 shared.select4 = createStringObject("select 4\r\n",10);
1647 shared.select5 = createStringObject("select 5\r\n",10);
1648 shared.select6 = createStringObject("select 6\r\n",10);
1649 shared.select7 = createStringObject("select 7\r\n",10);
1650 shared.select8 = createStringObject("select 8\r\n",10);
1651 shared.select9 = createStringObject("select 9\r\n",10);
befec3cd 1652 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
c8d0ea0e 1653 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
befec3cd 1654 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
fc46bb71 1655 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
ffc6b7f8 1656 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
1657 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
befec3cd 1658 shared.mbulk3 = createStringObject("*3\r\n",4);
c8d0ea0e 1659 shared.mbulk4 = createStringObject("*4\r\n",4);
05df7621 1660 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
1661 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
1662 shared.integers[j]->encoding = REDIS_ENCODING_INT;
1663 }
ed9b544e 1664}
1665
1666static void appendServerSaveParams(time_t seconds, int changes) {
1667 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
ed9b544e 1668 server.saveparams[server.saveparamslen].seconds = seconds;
1669 server.saveparams[server.saveparamslen].changes = changes;
1670 server.saveparamslen++;
1671}
1672
bcfc686d 1673static void resetServerSaveParams() {
ed9b544e 1674 zfree(server.saveparams);
1675 server.saveparams = NULL;
1676 server.saveparamslen = 0;
1677}
1678
1679static void initServerConfig() {
1680 server.dbnum = REDIS_DEFAULT_DBNUM;
1681 server.port = REDIS_SERVERPORT;
f870935d 1682 server.verbosity = REDIS_VERBOSE;
ed9b544e 1683 server.maxidletime = REDIS_MAXIDLETIME;
1684 server.saveparams = NULL;
1685 server.logfile = NULL; /* NULL = log on standard output */
1686 server.bindaddr = NULL;
1687 server.glueoutputbuf = 1;
1688 server.daemonize = 0;
44b38ef4 1689 server.appendonly = 0;
1b677732 1690 server.appendfsync = APPENDFSYNC_EVERYSEC;
48f0308a 1691 server.lastfsync = time(NULL);
44b38ef4 1692 server.appendfd = -1;
1693 server.appendseldb = -1; /* Make sure the first time will not match */
500ece7c 1694 server.pidfile = zstrdup("/var/run/redis.pid");
1695 server.dbfilename = zstrdup("dump.rdb");
1696 server.appendfilename = zstrdup("appendonly.aof");
abcb223e 1697 server.requirepass = NULL;
b0553789 1698 server.rdbcompression = 1;
8ca3e9d1 1699 server.activerehashing = 1;
285add55 1700 server.maxclients = 0;
d5d55fc3 1701 server.blpop_blocked_clients = 0;
3fd78bcd 1702 server.maxmemory = 0;
75680a3c 1703 server.vm_enabled = 0;
054e426d 1704 server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
75680a3c 1705 server.vm_page_size = 256; /* 256 bytes per page */
1706 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
1707 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
92f8e882 1708 server.vm_max_threads = 4;
d5d55fc3 1709 server.vm_blocked_clients = 0;
cbba7dd7 1710 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
1711 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
fab43727 1712 server.shutdown_asap = 0;
75680a3c 1713
bcfc686d 1714 resetServerSaveParams();
ed9b544e 1715
1716 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1717 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1718 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1719 /* Replication related */
1720 server.isslave = 0;
d0ccebcf 1721 server.masterauth = NULL;
ed9b544e 1722 server.masterhost = NULL;
1723 server.masterport = 6379;
1724 server.master = NULL;
1725 server.replstate = REDIS_REPL_NONE;
a7866db6 1726
1727 /* Double constants initialization */
1728 R_Zero = 0.0;
1729 R_PosInf = 1.0/R_Zero;
1730 R_NegInf = -1.0/R_Zero;
1731 R_Nan = R_Zero/R_Zero;
ed9b544e 1732}
1733
1734static void initServer() {
1735 int j;
1736
1737 signal(SIGHUP, SIG_IGN);
1738 signal(SIGPIPE, SIG_IGN);
fe3bbfbe 1739 setupSigSegvAction();
ed9b544e 1740
b9bc0eef 1741 server.devnull = fopen("/dev/null","w");
1742 if (server.devnull == NULL) {
1743 redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr);
1744 exit(1);
1745 }
ed9b544e 1746 server.clients = listCreate();
1747 server.slaves = listCreate();
87eca727 1748 server.monitors = listCreate();
ed9b544e 1749 server.objfreelist = listCreate();
1750 createSharedObjects();
1751 server.el = aeCreateEventLoop();
3305306f 1752 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
ed9b544e 1753 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
1754 if (server.fd == -1) {
1755 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
1756 exit(1);
1757 }
3305306f 1758 for (j = 0; j < server.dbnum; j++) {
5234952b 1759 server.db[j].dict = dictCreate(&dbDictType,NULL);
f2d9f50f 1760 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
37ab76c9 1761 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
1762 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
d5d55fc3 1763 if (server.vm_enabled)
1764 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
3305306f 1765 server.db[j].id = j;
1766 }
ffc6b7f8 1767 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1768 server.pubsub_patterns = listCreate();
1769 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1770 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
ed9b544e 1771 server.cronloops = 0;
9f3c422c 1772 server.bgsavechildpid = -1;
9d65a1bb 1773 server.bgrewritechildpid = -1;
1774 server.bgrewritebuf = sdsempty();
28ed1f33 1775 server.aofbuf = sdsempty();
ed9b544e 1776 server.lastsave = time(NULL);
1777 server.dirty = 0;
ed9b544e 1778 server.stat_numcommands = 0;
1779 server.stat_numconnections = 0;
2a6a2ed1 1780 server.stat_expiredkeys = 0;
ed9b544e 1781 server.stat_starttime = time(NULL);
3a66edc7 1782 server.unixtime = time(NULL);
d8f8b666 1783 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
996cb5f7 1784 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
1785 acceptHandler, NULL) == AE_ERR) oom("creating file event");
44b38ef4 1786
1787 if (server.appendonly) {
3bb225d6 1788 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
44b38ef4 1789 if (server.appendfd == -1) {
1790 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1791 strerror(errno));
1792 exit(1);
1793 }
1794 }
75680a3c 1795
1796 if (server.vm_enabled) vmInit();
ed9b544e 1797}
1798
1799/* Empty the whole database */
ca37e9cd 1800static long long emptyDb() {
ed9b544e 1801 int j;
ca37e9cd 1802 long long removed = 0;
ed9b544e 1803
3305306f 1804 for (j = 0; j < server.dbnum; j++) {
ca37e9cd 1805 removed += dictSize(server.db[j].dict);
3305306f 1806 dictEmpty(server.db[j].dict);
1807 dictEmpty(server.db[j].expires);
1808 }
ca37e9cd 1809 return removed;
ed9b544e 1810}
1811
85dd2f3a 1812static int yesnotoi(char *s) {
1813 if (!strcasecmp(s,"yes")) return 1;
1814 else if (!strcasecmp(s,"no")) return 0;
1815 else return -1;
1816}
1817
ed9b544e 1818/* I agree, this is a very rudimental way to load a configuration...
1819 will improve later if the config gets more complex */
1820static void loadServerConfig(char *filename) {
c9a111ac 1821 FILE *fp;
ed9b544e 1822 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
1823 int linenum = 0;
1824 sds line = NULL;
c9a111ac 1825
1826 if (filename[0] == '-' && filename[1] == '\0')
1827 fp = stdin;
1828 else {
1829 if ((fp = fopen(filename,"r")) == NULL) {
9a22de82 1830 redisLog(REDIS_WARNING, "Fatal error, can't open config file '%s'", filename);
c9a111ac 1831 exit(1);
1832 }
ed9b544e 1833 }
c9a111ac 1834
ed9b544e 1835 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1836 sds *argv;
1837 int argc, j;
1838
1839 linenum++;
1840 line = sdsnew(buf);
1841 line = sdstrim(line," \t\r\n");
1842
1843 /* Skip comments and blank lines*/
1844 if (line[0] == '#' || line[0] == '\0') {
1845 sdsfree(line);
1846 continue;
1847 }
1848
1849 /* Split into arguments */
1850 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
1851 sdstolower(argv[0]);
1852
1853 /* Execute config directives */
bb0b03a3 1854 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
ed9b544e 1855 server.maxidletime = atoi(argv[1]);
0150db36 1856 if (server.maxidletime < 0) {
ed9b544e 1857 err = "Invalid timeout value"; goto loaderr;
1858 }
bb0b03a3 1859 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
ed9b544e 1860 server.port = atoi(argv[1]);
1861 if (server.port < 1 || server.port > 65535) {
1862 err = "Invalid port"; goto loaderr;
1863 }
bb0b03a3 1864 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
ed9b544e 1865 server.bindaddr = zstrdup(argv[1]);
bb0b03a3 1866 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
ed9b544e 1867 int seconds = atoi(argv[1]);
1868 int changes = atoi(argv[2]);
1869 if (seconds < 1 || changes < 0) {
1870 err = "Invalid save parameters"; goto loaderr;
1871 }
1872 appendServerSaveParams(seconds,changes);
bb0b03a3 1873 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
ed9b544e 1874 if (chdir(argv[1]) == -1) {
1875 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
1876 argv[1], strerror(errno));
1877 exit(1);
1878 }
bb0b03a3 1879 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
1880 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
f870935d 1881 else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
bb0b03a3 1882 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
1883 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
ed9b544e 1884 else {
1885 err = "Invalid log level. Must be one of debug, notice, warning";
1886 goto loaderr;
1887 }
bb0b03a3 1888 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
c9a111ac 1889 FILE *logfp;
ed9b544e 1890
1891 server.logfile = zstrdup(argv[1]);
bb0b03a3 1892 if (!strcasecmp(server.logfile,"stdout")) {
ed9b544e 1893 zfree(server.logfile);
1894 server.logfile = NULL;
1895 }
1896 if (server.logfile) {
1897 /* Test if we are able to open the file. The server will not
1898 * be able to abort just for this problem later... */
c9a111ac 1899 logfp = fopen(server.logfile,"a");
1900 if (logfp == NULL) {
ed9b544e 1901 err = sdscatprintf(sdsempty(),
1902 "Can't open the log file: %s", strerror(errno));
1903 goto loaderr;
1904 }
c9a111ac 1905 fclose(logfp);
ed9b544e 1906 }
bb0b03a3 1907 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
ed9b544e 1908 server.dbnum = atoi(argv[1]);
1909 if (server.dbnum < 1) {
1910 err = "Invalid number of databases"; goto loaderr;
1911 }
b3f83f12
JZ
1912 } else if (!strcasecmp(argv[0],"include") && argc == 2) {
1913 loadServerConfig(argv[1]);
285add55 1914 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
1915 server.maxclients = atoi(argv[1]);
3fd78bcd 1916 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
2b619329 1917 server.maxmemory = memtoll(argv[1],NULL);
bb0b03a3 1918 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
ed9b544e 1919 server.masterhost = sdsnew(argv[1]);
1920 server.masterport = atoi(argv[2]);
1921 server.replstate = REDIS_REPL_CONNECT;
d0ccebcf 1922 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
1923 server.masterauth = zstrdup(argv[1]);
bb0b03a3 1924 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
85dd2f3a 1925 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
ed9b544e 1926 err = "argument must be 'yes' or 'no'"; goto loaderr;
1927 }
121f70cf 1928 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
1929 if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
8ca3e9d1 1930 err = "argument must be 'yes' or 'no'"; goto loaderr;
1931 }
1932 } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
1933 if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
121f70cf 1934 err = "argument must be 'yes' or 'no'"; goto loaderr;
1935 }
bb0b03a3 1936 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
85dd2f3a 1937 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
ed9b544e 1938 err = "argument must be 'yes' or 'no'"; goto loaderr;
1939 }
44b38ef4 1940 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
1941 if ((server.appendonly = yesnotoi(argv[1])) == -1) {
1942 err = "argument must be 'yes' or 'no'"; goto loaderr;
1943 }
f3b52411
PN
1944 } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
1945 zfree(server.appendfilename);
1946 server.appendfilename = zstrdup(argv[1]);
48f0308a 1947 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
1766c6da 1948 if (!strcasecmp(argv[1],"no")) {
48f0308a 1949 server.appendfsync = APPENDFSYNC_NO;
1766c6da 1950 } else if (!strcasecmp(argv[1],"always")) {
48f0308a 1951 server.appendfsync = APPENDFSYNC_ALWAYS;
1766c6da 1952 } else if (!strcasecmp(argv[1],"everysec")) {
48f0308a 1953 server.appendfsync = APPENDFSYNC_EVERYSEC;
1954 } else {
1955 err = "argument must be 'no', 'always' or 'everysec'";
1956 goto loaderr;
1957 }
bb0b03a3 1958 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
054e426d 1959 server.requirepass = zstrdup(argv[1]);
bb0b03a3 1960 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
500ece7c 1961 zfree(server.pidfile);
054e426d 1962 server.pidfile = zstrdup(argv[1]);
bb0b03a3 1963 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
500ece7c 1964 zfree(server.dbfilename);
054e426d 1965 server.dbfilename = zstrdup(argv[1]);
75680a3c 1966 } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
1967 if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
1968 err = "argument must be 'yes' or 'no'"; goto loaderr;
1969 }
054e426d 1970 } else if (!strcasecmp(argv[0],"vm-swap-file") && argc == 2) {
fefed597 1971 zfree(server.vm_swap_file);
054e426d 1972 server.vm_swap_file = zstrdup(argv[1]);
4ef8de8a 1973 } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
2b619329 1974 server.vm_max_memory = memtoll(argv[1],NULL);
4ef8de8a 1975 } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
2b619329 1976 server.vm_page_size = memtoll(argv[1], NULL);
4ef8de8a 1977 } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
2b619329 1978 server.vm_pages = memtoll(argv[1], NULL);
92f8e882 1979 } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
1980 server.vm_max_threads = strtoll(argv[1], NULL, 10);
cbba7dd7 1981 } else if (!strcasecmp(argv[0],"hash-max-zipmap-entries") && argc == 2){
2b619329 1982 server.hash_max_zipmap_entries = memtoll(argv[1], NULL);
cbba7dd7 1983 } else if (!strcasecmp(argv[0],"hash-max-zipmap-value") && argc == 2){
2b619329 1984 server.hash_max_zipmap_value = memtoll(argv[1], NULL);
ed9b544e 1985 } else {
1986 err = "Bad directive or wrong number of arguments"; goto loaderr;
1987 }
1988 for (j = 0; j < argc; j++)
1989 sdsfree(argv[j]);
1990 zfree(argv);
1991 sdsfree(line);
1992 }
c9a111ac 1993 if (fp != stdin) fclose(fp);
ed9b544e 1994 return;
1995
1996loaderr:
1997 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
1998 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
1999 fprintf(stderr, ">>> '%s'\n", line);
2000 fprintf(stderr, "%s\n", err);
2001 exit(1);
2002}
2003
2004static void freeClientArgv(redisClient *c) {
2005 int j;
2006
2007 for (j = 0; j < c->argc; j++)
2008 decrRefCount(c->argv[j]);
e8a74421 2009 for (j = 0; j < c->mbargc; j++)
2010 decrRefCount(c->mbargv[j]);
ed9b544e 2011 c->argc = 0;
e8a74421 2012 c->mbargc = 0;
ed9b544e 2013}
2014
2015static void freeClient(redisClient *c) {
2016 listNode *ln;
2017
4409877e 2018 /* Note that if the client we are freeing is blocked into a blocking
b0d8747d 2019 * call, we have to set querybuf to NULL *before* to call
2020 * unblockClientWaitingData() to avoid processInputBuffer() will get
2021 * called. Also it is important to remove the file events after
2022 * this, because this call adds the READABLE event. */
4409877e 2023 sdsfree(c->querybuf);
2024 c->querybuf = NULL;
2025 if (c->flags & REDIS_BLOCKED)
b0d8747d 2026 unblockClientWaitingData(c);
4409877e 2027
37ab76c9 2028 /* UNWATCH all the keys */
2029 unwatchAllKeys(c);
2030 listRelease(c->watched_keys);
ffc6b7f8 2031 /* Unsubscribe from all the pubsub channels */
2032 pubsubUnsubscribeAllChannels(c,0);
2033 pubsubUnsubscribeAllPatterns(c,0);
2034 dictRelease(c->pubsub_channels);
2035 listRelease(c->pubsub_patterns);
befec3cd 2036 /* Obvious cleanup */
ed9b544e 2037 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
2038 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
ed9b544e 2039 listRelease(c->reply);
2040 freeClientArgv(c);
2041 close(c->fd);
92f8e882 2042 /* Remove from the list of clients */
ed9b544e 2043 ln = listSearchKey(server.clients,c);
dfc5e96c 2044 redisAssert(ln != NULL);
ed9b544e 2045 listDelNode(server.clients,ln);
37ab76c9 2046 /* Remove from the list of clients that are now ready to be restarted
2047 * after waiting for swapped keys */
d5d55fc3 2048 if (c->flags & REDIS_IO_WAIT && listLength(c->io_keys) == 0) {
2049 ln = listSearchKey(server.io_ready_clients,c);
2050 if (ln) {
2051 listDelNode(server.io_ready_clients,ln);
2052 server.vm_blocked_clients--;
2053 }
2054 }
37ab76c9 2055 /* Remove from the list of clients waiting for swapped keys */
d5d55fc3 2056 while (server.vm_enabled && listLength(c->io_keys)) {
2057 ln = listFirst(c->io_keys);
2058 dontWaitForSwappedKey(c,ln->value);
92f8e882 2059 }
b3e3d0d7 2060 listRelease(c->io_keys);
befec3cd 2061 /* Master/slave cleanup */
ed9b544e 2062 if (c->flags & REDIS_SLAVE) {
6208b3a7 2063 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
2064 close(c->repldbfd);
87eca727 2065 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
2066 ln = listSearchKey(l,c);
dfc5e96c 2067 redisAssert(ln != NULL);
87eca727 2068 listDelNode(l,ln);
ed9b544e 2069 }
2070 if (c->flags & REDIS_MASTER) {
2071 server.master = NULL;
2072 server.replstate = REDIS_REPL_CONNECT;
2073 }
befec3cd 2074 /* Release memory */
93ea3759 2075 zfree(c->argv);
e8a74421 2076 zfree(c->mbargv);
6e469882 2077 freeClientMultiState(c);
ed9b544e 2078 zfree(c);
2079}
2080
cc30e368 2081#define GLUEREPLY_UP_TO (1024)
ed9b544e 2082static void glueReplyBuffersIfNeeded(redisClient *c) {
c28b42ac 2083 int copylen = 0;
2084 char buf[GLUEREPLY_UP_TO];
6208b3a7 2085 listNode *ln;
c7df85a4 2086 listIter li;
ed9b544e 2087 robj *o;
2088
c7df85a4 2089 listRewind(c->reply,&li);
2090 while((ln = listNext(&li))) {
c28b42ac 2091 int objlen;
2092
ed9b544e 2093 o = ln->value;
c28b42ac 2094 objlen = sdslen(o->ptr);
2095 if (copylen + objlen <= GLUEREPLY_UP_TO) {
2096 memcpy(buf+copylen,o->ptr,objlen);
2097 copylen += objlen;
ed9b544e 2098 listDelNode(c->reply,ln);
c28b42ac 2099 } else {
2100 if (copylen == 0) return;
2101 break;
ed9b544e 2102 }
ed9b544e 2103 }
c28b42ac 2104 /* Now the output buffer is empty, add the new single element */
2105 o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
2106 listAddNodeHead(c->reply,o);
ed9b544e 2107}
2108
2109static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2110 redisClient *c = privdata;
2111 int nwritten = 0, totwritten = 0, objlen;
2112 robj *o;
2113 REDIS_NOTUSED(el);
2114 REDIS_NOTUSED(mask);
2115
2895e862 2116 /* Use writev() if we have enough buffers to send */
7ea870c0 2117 if (!server.glueoutputbuf &&
e0a62c7f 2118 listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
7ea870c0 2119 !(c->flags & REDIS_MASTER))
2895e862 2120 {
2121 sendReplyToClientWritev(el, fd, privdata, mask);
2122 return;
2123 }
2895e862 2124
ed9b544e 2125 while(listLength(c->reply)) {
c28b42ac 2126 if (server.glueoutputbuf && listLength(c->reply) > 1)
2127 glueReplyBuffersIfNeeded(c);
2128
ed9b544e 2129 o = listNodeValue(listFirst(c->reply));
2130 objlen = sdslen(o->ptr);
2131
2132 if (objlen == 0) {
2133 listDelNode(c->reply,listFirst(c->reply));
2134 continue;
2135 }
2136
2137 if (c->flags & REDIS_MASTER) {
6f376729 2138 /* Don't reply to a master */
ed9b544e 2139 nwritten = objlen - c->sentlen;
2140 } else {
a4d1ba9a 2141 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
ed9b544e 2142 if (nwritten <= 0) break;
2143 }
2144 c->sentlen += nwritten;
2145 totwritten += nwritten;
2146 /* If we fully sent the object on head go to the next one */
2147 if (c->sentlen == objlen) {
2148 listDelNode(c->reply,listFirst(c->reply));
2149 c->sentlen = 0;
2150 }
6f376729 2151 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
12f9d551 2152 * bytes, in a single threaded server it's a good idea to serve
6f376729 2153 * other clients as well, even if a very large request comes from
2154 * super fast link that is always able to accept data (in real world
12f9d551 2155 * scenario think about 'KEYS *' against the loopback interfae) */
6f376729 2156 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
ed9b544e 2157 }
2158 if (nwritten == -1) {
2159 if (errno == EAGAIN) {
2160 nwritten = 0;
2161 } else {
f870935d 2162 redisLog(REDIS_VERBOSE,
ed9b544e 2163 "Error writing to client: %s", strerror(errno));
2164 freeClient(c);
2165 return;
2166 }
2167 }
2168 if (totwritten > 0) c->lastinteraction = time(NULL);
2169 if (listLength(c->reply) == 0) {
2170 c->sentlen = 0;
2171 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2172 }
2173}
2174
2895e862 2175static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
2176{
2177 redisClient *c = privdata;
2178 int nwritten = 0, totwritten = 0, objlen, willwrite;
2179 robj *o;
2180 struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
2181 int offset, ion = 0;
2182 REDIS_NOTUSED(el);
2183 REDIS_NOTUSED(mask);
2184
2185 listNode *node;
2186 while (listLength(c->reply)) {
2187 offset = c->sentlen;
2188 ion = 0;
2189 willwrite = 0;
2190
2191 /* fill-in the iov[] array */
2192 for(node = listFirst(c->reply); node; node = listNextNode(node)) {
2193 o = listNodeValue(node);
2194 objlen = sdslen(o->ptr);
2195
e0a62c7f 2196 if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
2895e862 2197 break;
2198
2199 if(ion == REDIS_WRITEV_IOVEC_COUNT)
2200 break; /* no more iovecs */
2201
2202 iov[ion].iov_base = ((char*)o->ptr) + offset;
2203 iov[ion].iov_len = objlen - offset;
2204 willwrite += objlen - offset;
2205 offset = 0; /* just for the first item */
2206 ion++;
2207 }
2208
2209 if(willwrite == 0)
2210 break;
2211
2212 /* write all collected blocks at once */
2213 if((nwritten = writev(fd, iov, ion)) < 0) {
2214 if (errno != EAGAIN) {
f870935d 2215 redisLog(REDIS_VERBOSE,
2895e862 2216 "Error writing to client: %s", strerror(errno));
2217 freeClient(c);
2218 return;
2219 }
2220 break;
2221 }
2222
2223 totwritten += nwritten;
2224 offset = c->sentlen;
2225
2226 /* remove written robjs from c->reply */
2227 while (nwritten && listLength(c->reply)) {
2228 o = listNodeValue(listFirst(c->reply));
2229 objlen = sdslen(o->ptr);
2230
2231 if(nwritten >= objlen - offset) {
2232 listDelNode(c->reply, listFirst(c->reply));
2233 nwritten -= objlen - offset;
2234 c->sentlen = 0;
2235 } else {
2236 /* partial write */
2237 c->sentlen += nwritten;
2238 break;
2239 }
2240 offset = 0;
2241 }
2242 }
2243
e0a62c7f 2244 if (totwritten > 0)
2895e862 2245 c->lastinteraction = time(NULL);
2246
2247 if (listLength(c->reply) == 0) {
2248 c->sentlen = 0;
2249 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2250 }
2251}
2252
1a132bbc
PN
2253static int qsortRedisCommands(const void *r1, const void *r2) {
2254 return strcasecmp(
2255 ((struct redisCommand*)r1)->name,
2256 ((struct redisCommand*)r2)->name);
2257}
2258
2259static void sortCommandTable() {
1a132bbc
PN
2260 /* Copy and sort the read-only version of the command table */
2261 commandTable = (struct redisCommand*)malloc(sizeof(readonlyCommandTable));
2262 memcpy(commandTable,readonlyCommandTable,sizeof(readonlyCommandTable));
d55d5c5d 2263 qsort(commandTable,
2264 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
2265 sizeof(struct redisCommand),qsortRedisCommands);
1a132bbc
PN
2266}
2267
ed9b544e 2268static struct redisCommand *lookupCommand(char *name) {
1a132bbc
PN
2269 struct redisCommand tmp = {name,NULL,0,0,NULL,0,0,0};
2270 return bsearch(
2271 &tmp,
2272 commandTable,
d55d5c5d 2273 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
1a132bbc
PN
2274 sizeof(struct redisCommand),
2275 qsortRedisCommands);
ed9b544e 2276}
2277
2278/* resetClient prepare the client to process the next command */
2279static void resetClient(redisClient *c) {
2280 freeClientArgv(c);
2281 c->bulklen = -1;
e8a74421 2282 c->multibulk = 0;
ed9b544e 2283}
2284
6e469882 2285/* Call() is the core of Redis execution of a command */
2286static void call(redisClient *c, struct redisCommand *cmd) {
2287 long long dirty;
2288
2289 dirty = server.dirty;
2290 cmd->proc(c);
4005fef1 2291 dirty = server.dirty-dirty;
2292
2293 if (server.appendonly && dirty)
6e469882 2294 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
4005fef1 2295 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
2296 listLength(server.slaves))
248ea310 2297 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
6e469882 2298 if (listLength(server.monitors))
dd142b9c 2299 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
6e469882 2300 server.stat_numcommands++;
2301}
2302
ed9b544e 2303/* If this function gets called we already read a whole
2304 * command, argments are in the client argv/argc fields.
2305 * processCommand() execute the command or prepare the
2306 * server for a bulk read from the client.
2307 *
2308 * If 1 is returned the client is still alive and valid and
2309 * and other operations can be performed by the caller. Otherwise
2310 * if 0 is returned the client was destroied (i.e. after QUIT). */
2311static int processCommand(redisClient *c) {
2312 struct redisCommand *cmd;
ed9b544e 2313
3fd78bcd 2314 /* Free some memory if needed (maxmemory setting) */
2315 if (server.maxmemory) freeMemoryIfNeeded();
2316
e8a74421 2317 /* Handle the multi bulk command type. This is an alternative protocol
2318 * supported by Redis in order to receive commands that are composed of
2319 * multiple binary-safe "bulk" arguments. The latency of processing is
2320 * a bit higher but this allows things like multi-sets, so if this
2321 * protocol is used only for MSET and similar commands this is a big win. */
2322 if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
2323 c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
2324 if (c->multibulk <= 0) {
2325 resetClient(c);
2326 return 1;
2327 } else {
2328 decrRefCount(c->argv[c->argc-1]);
2329 c->argc--;
2330 return 1;
2331 }
2332 } else if (c->multibulk) {
2333 if (c->bulklen == -1) {
2334 if (((char*)c->argv[0]->ptr)[0] != '$') {
2335 addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
2336 resetClient(c);
2337 return 1;
2338 } else {
2339 int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
2340 decrRefCount(c->argv[0]);
2341 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2342 c->argc--;
2343 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2344 resetClient(c);
2345 return 1;
2346 }
2347 c->argc--;
2348 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2349 return 1;
2350 }
2351 } else {
2352 c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
2353 c->mbargv[c->mbargc] = c->argv[0];
2354 c->mbargc++;
2355 c->argc--;
2356 c->multibulk--;
2357 if (c->multibulk == 0) {
2358 robj **auxargv;
2359 int auxargc;
2360
2361 /* Here we need to swap the multi-bulk argc/argv with the
2362 * normal argc/argv of the client structure. */
2363 auxargv = c->argv;
2364 c->argv = c->mbargv;
2365 c->mbargv = auxargv;
2366
2367 auxargc = c->argc;
2368 c->argc = c->mbargc;
2369 c->mbargc = auxargc;
2370
2371 /* We need to set bulklen to something different than -1
2372 * in order for the code below to process the command without
2373 * to try to read the last argument of a bulk command as
2374 * a special argument. */
2375 c->bulklen = 0;
2376 /* continue below and process the command */
2377 } else {
2378 c->bulklen = -1;
2379 return 1;
2380 }
2381 }
2382 }
2383 /* -- end of multi bulk commands processing -- */
2384
ed9b544e 2385 /* The QUIT command is handled as a special case. Normal command
2386 * procs are unable to close the client connection safely */
bb0b03a3 2387 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
ed9b544e 2388 freeClient(c);
2389 return 0;
2390 }
d5d55fc3 2391
2392 /* Now lookup the command and check ASAP about trivial error conditions
2393 * such wrong arity, bad command name and so forth. */
ed9b544e 2394 cmd = lookupCommand(c->argv[0]->ptr);
2395 if (!cmd) {
2c14807b 2396 addReplySds(c,
2397 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2398 (char*)c->argv[0]->ptr));
ed9b544e 2399 resetClient(c);
2400 return 1;
2401 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
2402 (c->argc < -cmd->arity)) {
454d4e43 2403 addReplySds(c,
2404 sdscatprintf(sdsempty(),
2405 "-ERR wrong number of arguments for '%s' command\r\n",
2406 cmd->name));
ed9b544e 2407 resetClient(c);
2408 return 1;
2409 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
d5d55fc3 2410 /* This is a bulk command, we have to read the last argument yet. */
ed9b544e 2411 int bulklen = atoi(c->argv[c->argc-1]->ptr);
2412
2413 decrRefCount(c->argv[c->argc-1]);
2414 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2415 c->argc--;
2416 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2417 resetClient(c);
2418 return 1;
2419 }
2420 c->argc--;
2421 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2422 /* It is possible that the bulk read is already in the
8d0490e7 2423 * buffer. Check this condition and handle it accordingly.
2424 * This is just a fast path, alternative to call processInputBuffer().
2425 * It's a good idea since the code is small and this condition
2426 * happens most of the times. */
ed9b544e 2427 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
2428 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2429 c->argc++;
2430 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2431 } else {
d5d55fc3 2432 /* Otherwise return... there is to read the last argument
2433 * from the socket. */
ed9b544e 2434 return 1;
2435 }
2436 }
942a3961 2437 /* Let's try to encode the bulk object to save space. */
2438 if (cmd->flags & REDIS_CMD_BULK)
05df7621 2439 c->argv[c->argc-1] = tryObjectEncoding(c->argv[c->argc-1]);
942a3961 2440
e63943a4 2441 /* Check if the user is authenticated */
2442 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
2443 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
2444 resetClient(c);
2445 return 1;
2446 }
2447
b61a28fe 2448 /* Handle the maxmemory directive */
2449 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
2450 zmalloc_used_memory() > server.maxmemory)
2451 {
2452 addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2453 resetClient(c);
2454 return 1;
2455 }
2456
d6cc8867 2457 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
e6cca5db 2458 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
2459 &&
ffc6b7f8 2460 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
2461 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
2462 addReplySds(c,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
d6cc8867 2463 resetClient(c);
2464 return 1;
2465 }
2466
ed9b544e 2467 /* Exec the command */
6531c94d 2468 if (c->flags & REDIS_MULTI &&
2469 cmd->proc != execCommand && cmd->proc != discardCommand &&
2470 cmd->proc != multiCommand && cmd->proc != watchCommand)
2471 {
6e469882 2472 queueMultiCommand(c,cmd);
2473 addReply(c,shared.queued);
2474 } else {
d5d55fc3 2475 if (server.vm_enabled && server.vm_max_threads > 0 &&
0a6f3f0f 2476 blockClientOnSwappedKeys(c,cmd)) return 1;
6e469882 2477 call(c,cmd);
2478 }
ed9b544e 2479
2480 /* Prepare the client for the next command */
ed9b544e 2481 resetClient(c);
2482 return 1;
2483}
2484
248ea310 2485static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
6208b3a7 2486 listNode *ln;
c7df85a4 2487 listIter li;
ed9b544e 2488 int outc = 0, j;
93ea3759 2489 robj **outv;
248ea310 2490 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2491 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2492 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2493 robj *static_outv[REDIS_STATIC_ARGS*3+1];
2494 robj *lenobj;
93ea3759 2495
2496 if (argc <= REDIS_STATIC_ARGS) {
2497 outv = static_outv;
2498 } else {
248ea310 2499 outv = zmalloc(sizeof(robj*)*(argc*3+1));
93ea3759 2500 }
248ea310 2501
2502 lenobj = createObject(REDIS_STRING,
2503 sdscatprintf(sdsempty(), "*%d\r\n", argc));
2504 lenobj->refcount = 0;
2505 outv[outc++] = lenobj;
ed9b544e 2506 for (j = 0; j < argc; j++) {
248ea310 2507 lenobj = createObject(REDIS_STRING,
2508 sdscatprintf(sdsempty(),"$%lu\r\n",
2509 (unsigned long) stringObjectLen(argv[j])));
2510 lenobj->refcount = 0;
2511 outv[outc++] = lenobj;
ed9b544e 2512 outv[outc++] = argv[j];
248ea310 2513 outv[outc++] = shared.crlf;
ed9b544e 2514 }
ed9b544e 2515
40d224a9 2516 /* Increment all the refcounts at start and decrement at end in order to
2517 * be sure to free objects if there is no slave in a replication state
2518 * able to be feed with commands */
2519 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
c7df85a4 2520 listRewind(slaves,&li);
2521 while((ln = listNext(&li))) {
ed9b544e 2522 redisClient *slave = ln->value;
40d224a9 2523
2524 /* Don't feed slaves that are still waiting for BGSAVE to start */
6208b3a7 2525 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
40d224a9 2526
2527 /* Feed all the other slaves, MONITORs and so on */
ed9b544e 2528 if (slave->slaveseldb != dictid) {
2529 robj *selectcmd;
2530
2531 switch(dictid) {
2532 case 0: selectcmd = shared.select0; break;
2533 case 1: selectcmd = shared.select1; break;
2534 case 2: selectcmd = shared.select2; break;
2535 case 3: selectcmd = shared.select3; break;
2536 case 4: selectcmd = shared.select4; break;
2537 case 5: selectcmd = shared.select5; break;
2538 case 6: selectcmd = shared.select6; break;
2539 case 7: selectcmd = shared.select7; break;
2540 case 8: selectcmd = shared.select8; break;
2541 case 9: selectcmd = shared.select9; break;
2542 default:
2543 selectcmd = createObject(REDIS_STRING,
2544 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
2545 selectcmd->refcount = 0;
2546 break;
2547 }
2548 addReply(slave,selectcmd);
2549 slave->slaveseldb = dictid;
2550 }
2551 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
ed9b544e 2552 }
40d224a9 2553 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
93ea3759 2554 if (outv != static_outv) zfree(outv);
ed9b544e 2555}
2556
dd142b9c 2557static sds sdscatrepr(sds s, char *p, size_t len) {
2558 s = sdscatlen(s,"\"",1);
2559 while(len--) {
2560 switch(*p) {
2561 case '\\':
2562 case '"':
2563 s = sdscatprintf(s,"\\%c",*p);
2564 break;
2565 case '\n': s = sdscatlen(s,"\\n",1); break;
2566 case '\r': s = sdscatlen(s,"\\r",1); break;
2567 case '\t': s = sdscatlen(s,"\\t",1); break;
2568 case '\a': s = sdscatlen(s,"\\a",1); break;
2569 case '\b': s = sdscatlen(s,"\\b",1); break;
2570 default:
2571 if (isprint(*p))
2572 s = sdscatprintf(s,"%c",*p);
2573 else
2574 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
2575 break;
2576 }
2577 p++;
2578 }
2579 return sdscatlen(s,"\"",1);
2580}
2581
2582static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc) {
2583 listNode *ln;
2584 listIter li;
2585 int j;
2586 sds cmdrepr = sdsnew("+");
2587 robj *cmdobj;
2588 struct timeval tv;
2589
2590 gettimeofday(&tv,NULL);
2591 cmdrepr = sdscatprintf(cmdrepr,"%ld.%ld ",(long)tv.tv_sec,(long)tv.tv_usec);
2592 if (dictid != 0) cmdrepr = sdscatprintf(cmdrepr,"(db %d) ", dictid);
2593
2594 for (j = 0; j < argc; j++) {
2595 if (argv[j]->encoding == REDIS_ENCODING_INT) {
2596 cmdrepr = sdscatprintf(cmdrepr, "%ld", (long)argv[j]->ptr);
2597 } else {
2598 cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
2599 sdslen(argv[j]->ptr));
2600 }
2601 if (j != argc-1)
2602 cmdrepr = sdscatlen(cmdrepr," ",1);
2603 }
2604 cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
2605 cmdobj = createObject(REDIS_STRING,cmdrepr);
2606
2607 listRewind(monitors,&li);
2608 while((ln = listNext(&li))) {
2609 redisClient *monitor = ln->value;
2610 addReply(monitor,cmdobj);
2611 }
2612 decrRefCount(cmdobj);
2613}
2614
638e42ac 2615static void processInputBuffer(redisClient *c) {
ed9b544e 2616again:
4409877e 2617 /* Before to process the input buffer, make sure the client is not
2618 * waitig for a blocking operation such as BLPOP. Note that the first
2619 * iteration the client is never blocked, otherwise the processInputBuffer
2620 * would not be called at all, but after the execution of the first commands
2621 * in the input buffer the client may be blocked, and the "goto again"
2622 * will try to reiterate. The following line will make it return asap. */
92f8e882 2623 if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
ed9b544e 2624 if (c->bulklen == -1) {
2625 /* Read the first line of the query */
2626 char *p = strchr(c->querybuf,'\n');
2627 size_t querylen;
644fafa3 2628
ed9b544e 2629 if (p) {
2630 sds query, *argv;
2631 int argc, j;
e0a62c7f 2632
ed9b544e 2633 query = c->querybuf;
2634 c->querybuf = sdsempty();
2635 querylen = 1+(p-(query));
2636 if (sdslen(query) > querylen) {
2637 /* leave data after the first line of the query in the buffer */
2638 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
2639 }
2640 *p = '\0'; /* remove "\n" */
2641 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
2642 sdsupdatelen(query);
2643
2644 /* Now we can split the query in arguments */
ed9b544e 2645 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
93ea3759 2646 sdsfree(query);
2647
2648 if (c->argv) zfree(c->argv);
2649 c->argv = zmalloc(sizeof(robj*)*argc);
93ea3759 2650
2651 for (j = 0; j < argc; j++) {
ed9b544e 2652 if (sdslen(argv[j])) {
2653 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
2654 c->argc++;
2655 } else {
2656 sdsfree(argv[j]);
2657 }
2658 }
2659 zfree(argv);
7c49733c 2660 if (c->argc) {
2661 /* Execute the command. If the client is still valid
2662 * after processCommand() return and there is something
2663 * on the query buffer try to process the next command. */
2664 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2665 } else {
2666 /* Nothing to process, argc == 0. Just process the query
2667 * buffer if it's not empty or return to the caller */
2668 if (sdslen(c->querybuf)) goto again;
2669 }
ed9b544e 2670 return;
644fafa3 2671 } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
f870935d 2672 redisLog(REDIS_VERBOSE, "Client protocol error");
ed9b544e 2673 freeClient(c);
2674 return;
2675 }
2676 } else {
2677 /* Bulk read handling. Note that if we are at this point
2678 the client already sent a command terminated with a newline,
2679 we are reading the bulk data that is actually the last
2680 argument of the command. */
2681 int qbl = sdslen(c->querybuf);
2682
2683 if (c->bulklen <= qbl) {
2684 /* Copy everything but the final CRLF as final argument */
2685 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2686 c->argc++;
2687 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
638e42ac 2688 /* Process the command. If the client is still valid after
2689 * the processing and there is more data in the buffer
2690 * try to parse it. */
2691 if (processCommand(c) && sdslen(c->querybuf)) goto again;
ed9b544e 2692 return;
2693 }
2694 }
2695}
2696
638e42ac 2697static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2698 redisClient *c = (redisClient*) privdata;
2699 char buf[REDIS_IOBUF_LEN];
2700 int nread;
2701 REDIS_NOTUSED(el);
2702 REDIS_NOTUSED(mask);
2703
2704 nread = read(fd, buf, REDIS_IOBUF_LEN);
2705 if (nread == -1) {
2706 if (errno == EAGAIN) {
2707 nread = 0;
2708 } else {
f870935d 2709 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
638e42ac 2710 freeClient(c);
2711 return;
2712 }
2713 } else if (nread == 0) {
f870935d 2714 redisLog(REDIS_VERBOSE, "Client closed connection");
638e42ac 2715 freeClient(c);
2716 return;
2717 }
2718 if (nread) {
2719 c->querybuf = sdscatlen(c->querybuf, buf, nread);
2720 c->lastinteraction = time(NULL);
2721 } else {
2722 return;
2723 }
168ac5c6 2724 processInputBuffer(c);
638e42ac 2725}
2726
ed9b544e 2727static int selectDb(redisClient *c, int id) {
2728 if (id < 0 || id >= server.dbnum)
2729 return REDIS_ERR;
3305306f 2730 c->db = &server.db[id];
ed9b544e 2731 return REDIS_OK;
2732}
2733
40d224a9 2734static void *dupClientReplyValue(void *o) {
2735 incrRefCount((robj*)o);
12d090d2 2736 return o;
40d224a9 2737}
2738
ffc6b7f8 2739static int listMatchObjects(void *a, void *b) {
bf028098 2740 return equalStringObjects(a,b);
ffc6b7f8 2741}
2742
ed9b544e 2743static redisClient *createClient(int fd) {
2744 redisClient *c = zmalloc(sizeof(*c));
2745
2746 anetNonBlock(NULL,fd);
2747 anetTcpNoDelay(NULL,fd);
2748 if (!c) return NULL;
2749 selectDb(c,0);
2750 c->fd = fd;
2751 c->querybuf = sdsempty();
2752 c->argc = 0;
93ea3759 2753 c->argv = NULL;
ed9b544e 2754 c->bulklen = -1;
e8a74421 2755 c->multibulk = 0;
2756 c->mbargc = 0;
2757 c->mbargv = NULL;
ed9b544e 2758 c->sentlen = 0;
2759 c->flags = 0;
2760 c->lastinteraction = time(NULL);
abcb223e 2761 c->authenticated = 0;
40d224a9 2762 c->replstate = REDIS_REPL_NONE;
6b47e12e 2763 c->reply = listCreate();
ed9b544e 2764 listSetFreeMethod(c->reply,decrRefCount);
40d224a9 2765 listSetDupMethod(c->reply,dupClientReplyValue);
37ab76c9 2766 c->blocking_keys = NULL;
2767 c->blocking_keys_num = 0;
92f8e882 2768 c->io_keys = listCreate();
87c68815 2769 c->watched_keys = listCreate();
92f8e882 2770 listSetFreeMethod(c->io_keys,decrRefCount);
ffc6b7f8 2771 c->pubsub_channels = dictCreate(&setDictType,NULL);
2772 c->pubsub_patterns = listCreate();
2773 listSetFreeMethod(c->pubsub_patterns,decrRefCount);
2774 listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
ed9b544e 2775 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
266373b2 2776 readQueryFromClient, c) == AE_ERR) {
ed9b544e 2777 freeClient(c);
2778 return NULL;
2779 }
6b47e12e 2780 listAddNodeTail(server.clients,c);
6e469882 2781 initClientMultiState(c);
ed9b544e 2782 return c;
2783}
2784
2785static void addReply(redisClient *c, robj *obj) {
2786 if (listLength(c->reply) == 0 &&
6208b3a7 2787 (c->replstate == REDIS_REPL_NONE ||
2788 c->replstate == REDIS_REPL_ONLINE) &&
ed9b544e 2789 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
266373b2 2790 sendReplyToClient, c) == AE_ERR) return;
e3cadb8a 2791
2792 if (server.vm_enabled && obj->storage != REDIS_VM_MEMORY) {
2793 obj = dupStringObject(obj);
2794 obj->refcount = 0; /* getDecodedObject() will increment the refcount */
2795 }
9d65a1bb 2796 listAddNodeTail(c->reply,getDecodedObject(obj));
ed9b544e 2797}
2798
2799static void addReplySds(redisClient *c, sds s) {
2800 robj *o = createObject(REDIS_STRING,s);
2801 addReply(c,o);
2802 decrRefCount(o);
2803}
2804
e2665397 2805static void addReplyDouble(redisClient *c, double d) {
2806 char buf[128];
2807
2808 snprintf(buf,sizeof(buf),"%.17g",d);
682ac724 2809 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
83c6a618 2810 (unsigned long) strlen(buf),buf));
e2665397 2811}
2812
aa7c2934
PN
2813static void addReplyLongLong(redisClient *c, long long ll) {
2814 char buf[128];
2815 size_t len;
2816
2817 if (ll == 0) {
2818 addReply(c,shared.czero);
2819 return;
2820 } else if (ll == 1) {
2821 addReply(c,shared.cone);
2822 return;
2823 }
482b672d 2824 buf[0] = ':';
2825 len = ll2string(buf+1,sizeof(buf)-1,ll);
2826 buf[len+1] = '\r';
2827 buf[len+2] = '\n';
2828 addReplySds(c,sdsnewlen(buf,len+3));
aa7c2934
PN
2829}
2830
92b27fe9 2831static void addReplyUlong(redisClient *c, unsigned long ul) {
2832 char buf[128];
2833 size_t len;
2834
dd88747b 2835 if (ul == 0) {
2836 addReply(c,shared.czero);
2837 return;
2838 } else if (ul == 1) {
2839 addReply(c,shared.cone);
2840 return;
2841 }
92b27fe9 2842 len = snprintf(buf,sizeof(buf),":%lu\r\n",ul);
2843 addReplySds(c,sdsnewlen(buf,len));
2844}
2845
942a3961 2846static void addReplyBulkLen(redisClient *c, robj *obj) {
482b672d 2847 size_t len, intlen;
2848 char buf[128];
942a3961 2849
2850 if (obj->encoding == REDIS_ENCODING_RAW) {
2851 len = sdslen(obj->ptr);
2852 } else {
2853 long n = (long)obj->ptr;
2854
e054afda 2855 /* Compute how many bytes will take this integer as a radix 10 string */
942a3961 2856 len = 1;
2857 if (n < 0) {
2858 len++;
2859 n = -n;
2860 }
2861 while((n = n/10) != 0) {
2862 len++;
2863 }
2864 }
482b672d 2865 buf[0] = '$';
2866 intlen = ll2string(buf+1,sizeof(buf)-1,(long long)len);
2867 buf[intlen+1] = '\r';
2868 buf[intlen+2] = '\n';
2869 addReplySds(c,sdsnewlen(buf,intlen+3));
942a3961 2870}
2871
dd88747b 2872static void addReplyBulk(redisClient *c, robj *obj) {
2873 addReplyBulkLen(c,obj);
2874 addReply(c,obj);
2875 addReply(c,shared.crlf);
2876}
2877
500ece7c 2878/* In the CONFIG command we need to add vanilla C string as bulk replies */
2879static void addReplyBulkCString(redisClient *c, char *s) {
2880 if (s == NULL) {
2881 addReply(c,shared.nullbulk);
2882 } else {
2883 robj *o = createStringObject(s,strlen(s));
2884 addReplyBulk(c,o);
2885 decrRefCount(o);
2886 }
2887}
2888
ed9b544e 2889static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2890 int cport, cfd;
2891 char cip[128];
285add55 2892 redisClient *c;
ed9b544e 2893 REDIS_NOTUSED(el);
2894 REDIS_NOTUSED(mask);
2895 REDIS_NOTUSED(privdata);
2896
2897 cfd = anetAccept(server.neterr, fd, cip, &cport);
2898 if (cfd == AE_ERR) {
f870935d 2899 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
ed9b544e 2900 return;
2901 }
f870935d 2902 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
285add55 2903 if ((c = createClient(cfd)) == NULL) {
ed9b544e 2904 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2905 close(cfd); /* May be already closed, just ingore errors */
2906 return;
2907 }
285add55 2908 /* If maxclient directive is set and this is one client more... close the
2909 * connection. Note that we create the client instead to check before
2910 * for this condition, since now the socket is already set in nonblocking
2911 * mode and we can send an error for free using the Kernel I/O */
2912 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2913 char *err = "-ERR max number of clients reached\r\n";
2914
2915 /* That's a best effort error message, don't check write errors */
fee803ba 2916 if (write(c->fd,err,strlen(err)) == -1) {
2917 /* Nothing to do, Just to avoid the warning... */
2918 }
285add55 2919 freeClient(c);
2920 return;
2921 }
ed9b544e 2922 server.stat_numconnections++;
2923}
2924
2925/* ======================= Redis objects implementation ===================== */
2926
2927static robj *createObject(int type, void *ptr) {
2928 robj *o;
2929
a5819310 2930 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
ed9b544e 2931 if (listLength(server.objfreelist)) {
2932 listNode *head = listFirst(server.objfreelist);
2933 o = listNodeValue(head);
2934 listDelNode(server.objfreelist,head);
a5819310 2935 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
ed9b544e 2936 } else {
75680a3c 2937 if (server.vm_enabled) {
a5819310 2938 pthread_mutex_unlock(&server.obj_freelist_mutex);
75680a3c 2939 o = zmalloc(sizeof(*o));
2940 } else {
2941 o = zmalloc(sizeof(*o)-sizeof(struct redisObjectVM));
2942 }
ed9b544e 2943 }
ed9b544e 2944 o->type = type;
942a3961 2945 o->encoding = REDIS_ENCODING_RAW;
ed9b544e 2946 o->ptr = ptr;
2947 o->refcount = 1;
3a66edc7 2948 if (server.vm_enabled) {
1064ef87 2949 /* Note that this code may run in the context of an I/O thread
2950 * and accessing to server.unixtime in theory is an error
2951 * (no locks). But in practice this is safe, and even if we read
2952 * garbage Redis will not fail, as it's just a statistical info */
3a66edc7 2953 o->vm.atime = server.unixtime;
2954 o->storage = REDIS_VM_MEMORY;
2955 }
ed9b544e 2956 return o;
2957}
2958
2959static robj *createStringObject(char *ptr, size_t len) {
2960 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
2961}
2962
3f973463
PN
2963static robj *createStringObjectFromLongLong(long long value) {
2964 robj *o;
2965 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
2966 incrRefCount(shared.integers[value]);
2967 o = shared.integers[value];
2968 } else {
3f973463 2969 if (value >= LONG_MIN && value <= LONG_MAX) {
10dea8dc 2970 o = createObject(REDIS_STRING, NULL);
3f973463
PN
2971 o->encoding = REDIS_ENCODING_INT;
2972 o->ptr = (void*)((long)value);
2973 } else {
ee14da56 2974 o = createObject(REDIS_STRING,sdsfromlonglong(value));
3f973463
PN
2975 }
2976 }
2977 return o;
2978}
2979
4ef8de8a 2980static robj *dupStringObject(robj *o) {
b9bc0eef 2981 assert(o->encoding == REDIS_ENCODING_RAW);
4ef8de8a 2982 return createStringObject(o->ptr,sdslen(o->ptr));
2983}
2984
ed9b544e 2985static robj *createListObject(void) {
2986 list *l = listCreate();
2987
ed9b544e 2988 listSetFreeMethod(l,decrRefCount);
2989 return createObject(REDIS_LIST,l);
2990}
2991
2992static robj *createSetObject(void) {
2993 dict *d = dictCreate(&setDictType,NULL);
ed9b544e 2994 return createObject(REDIS_SET,d);
2995}
2996
5234952b 2997static robj *createHashObject(void) {
2998 /* All the Hashes start as zipmaps. Will be automatically converted
2999 * into hash tables if there are enough elements or big elements
3000 * inside. */
3001 unsigned char *zm = zipmapNew();
3002 robj *o = createObject(REDIS_HASH,zm);
3003 o->encoding = REDIS_ENCODING_ZIPMAP;
3004 return o;
3005}
3006
1812e024 3007static robj *createZsetObject(void) {
6b47e12e 3008 zset *zs = zmalloc(sizeof(*zs));
3009
3010 zs->dict = dictCreate(&zsetDictType,NULL);
3011 zs->zsl = zslCreate();
3012 return createObject(REDIS_ZSET,zs);
1812e024 3013}
3014
ed9b544e 3015static void freeStringObject(robj *o) {
942a3961 3016 if (o->encoding == REDIS_ENCODING_RAW) {
3017 sdsfree(o->ptr);
3018 }
ed9b544e 3019}
3020
3021static void freeListObject(robj *o) {
c7d9d662
PN
3022 switch (o->encoding) {
3023 case REDIS_ENCODING_LIST:
3024 listRelease((list*) o->ptr);
3025 break;
3026 case REDIS_ENCODING_ZIPLIST:
3027 zfree(o->ptr);
3028 break;
3029 default:
3030 redisPanic("Unknown list encoding type");
3031 }
ed9b544e 3032}
3033
3034static void freeSetObject(robj *o) {
3035 dictRelease((dict*) o->ptr);
3036}
3037
fd8ccf44 3038static void freeZsetObject(robj *o) {
3039 zset *zs = o->ptr;
3040
3041 dictRelease(zs->dict);
3042 zslFree(zs->zsl);
3043 zfree(zs);
3044}
3045
ed9b544e 3046static void freeHashObject(robj *o) {
cbba7dd7 3047 switch (o->encoding) {
3048 case REDIS_ENCODING_HT:
3049 dictRelease((dict*) o->ptr);
3050 break;
3051 case REDIS_ENCODING_ZIPMAP:
3052 zfree(o->ptr);
3053 break;
3054 default:
f83c6cb5 3055 redisPanic("Unknown hash encoding type");
cbba7dd7 3056 break;
3057 }
ed9b544e 3058}
3059
3060static void incrRefCount(robj *o) {
3061 o->refcount++;
3062}
3063
3064static void decrRefCount(void *obj) {
3065 robj *o = obj;
94754ccc 3066
c651fd9e 3067 if (o->refcount <= 0) redisPanic("decrRefCount against refcount <= 0");
970e10bb 3068 /* Object is a key of a swapped out value, or in the process of being
3069 * loaded. */
996cb5f7 3070 if (server.vm_enabled &&
3071 (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
3072 {
996cb5f7 3073 if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(obj);
f2b8ab34 3074 redisAssert(o->type == REDIS_STRING);
a35ddf12 3075 freeStringObject(o);
3076 vmMarkPagesFree(o->vm.page,o->vm.usedpages);
a5819310 3077 pthread_mutex_lock(&server.obj_freelist_mutex);
a35ddf12 3078 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3079 !listAddNodeHead(server.objfreelist,o))
3080 zfree(o);
a5819310 3081 pthread_mutex_unlock(&server.obj_freelist_mutex);
7d98e08c 3082 server.vm_stats_swapped_objects--;
a35ddf12 3083 return;
3084 }
996cb5f7 3085 /* Object is in memory, or in the process of being swapped out. */
ed9b544e 3086 if (--(o->refcount) == 0) {
996cb5f7 3087 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
3088 vmCancelThreadedIOJob(obj);
ed9b544e 3089 switch(o->type) {
3090 case REDIS_STRING: freeStringObject(o); break;
3091 case REDIS_LIST: freeListObject(o); break;
3092 case REDIS_SET: freeSetObject(o); break;
fd8ccf44 3093 case REDIS_ZSET: freeZsetObject(o); break;
ed9b544e 3094 case REDIS_HASH: freeHashObject(o); break;
f83c6cb5 3095 default: redisPanic("Unknown object type"); break;
ed9b544e 3096 }
a5819310 3097 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
ed9b544e 3098 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3099 !listAddNodeHead(server.objfreelist,o))
3100 zfree(o);
a5819310 3101 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
ed9b544e 3102 }
3103}
3104
942a3961 3105static robj *lookupKey(redisDb *db, robj *key) {
3106 dictEntry *de = dictFind(db->dict,key);
3a66edc7 3107 if (de) {
55cf8433 3108 robj *key = dictGetEntryKey(de);
3109 robj *val = dictGetEntryVal(de);
3a66edc7 3110
55cf8433 3111 if (server.vm_enabled) {
996cb5f7 3112 if (key->storage == REDIS_VM_MEMORY ||
3113 key->storage == REDIS_VM_SWAPPING)
3114 {
3115 /* If we were swapping the object out, stop it, this key
3116 * was requested. */
3117 if (key->storage == REDIS_VM_SWAPPING)
3118 vmCancelThreadedIOJob(key);
55cf8433 3119 /* Update the access time of the key for the aging algorithm. */
3120 key->vm.atime = server.unixtime;
3121 } else {
d5d55fc3 3122 int notify = (key->storage == REDIS_VM_LOADING);
3123
55cf8433 3124 /* Our value was swapped on disk. Bring it at home. */
f2b8ab34 3125 redisAssert(val == NULL);
55cf8433 3126 val = vmLoadObject(key);
3127 dictGetEntryVal(de) = val;
d5d55fc3 3128
3129 /* Clients blocked by the VM subsystem may be waiting for
3130 * this key... */
3131 if (notify) handleClientsBlockedOnSwappedKey(db,key);
55cf8433 3132 }
3133 }
3134 return val;
3a66edc7 3135 } else {
3136 return NULL;
3137 }
942a3961 3138}
3139
3140static robj *lookupKeyRead(redisDb *db, robj *key) {
3141 expireIfNeeded(db,key);
3142 return lookupKey(db,key);
3143}
3144
3145static robj *lookupKeyWrite(redisDb *db, robj *key) {
3146 deleteIfVolatile(db,key);
37ab76c9 3147 touchWatchedKey(db,key);
942a3961 3148 return lookupKey(db,key);
3149}
3150
92b27fe9 3151static robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
3152 robj *o = lookupKeyRead(c->db, key);
3153 if (!o) addReply(c,reply);
3154 return o;
3155}
3156
3157static robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
3158 robj *o = lookupKeyWrite(c->db, key);
3159 if (!o) addReply(c,reply);
3160 return o;
3161}
3162
3163static int checkType(redisClient *c, robj *o, int type) {
3164 if (o->type != type) {
3165 addReply(c,shared.wrongtypeerr);
3166 return 1;
3167 }
3168 return 0;
3169}
3170
942a3961 3171static int deleteKey(redisDb *db, robj *key) {
3172 int retval;
3173
3174 /* We need to protect key from destruction: after the first dictDelete()
3175 * it may happen that 'key' is no longer valid if we don't increment
3176 * it's count. This may happen when we get the object reference directly
3177 * from the hash table with dictRandomKey() or dict iterators */
3178 incrRefCount(key);
3179 if (dictSize(db->expires)) dictDelete(db->expires,key);
3180 retval = dictDelete(db->dict,key);
3181 decrRefCount(key);
3182
3183 return retval == DICT_OK;
3184}
3185
724a51b1 3186/* Check if the nul-terminated string 's' can be represented by a long
3187 * (that is, is a number that fits into long without any other space or
3188 * character before or after the digits).
3189 *
3190 * If so, the function returns REDIS_OK and *longval is set to the value
3191 * of the number. Otherwise REDIS_ERR is returned */
f69f2cba 3192static int isStringRepresentableAsLong(sds s, long *longval) {
724a51b1 3193 char buf[32], *endptr;
3194 long value;
3195 int slen;
e0a62c7f 3196
724a51b1 3197 value = strtol(s, &endptr, 10);
3198 if (endptr[0] != '\0') return REDIS_ERR;
ee14da56 3199 slen = ll2string(buf,32,value);
724a51b1 3200
3201 /* If the number converted back into a string is not identical
3202 * then it's not possible to encode the string as integer */
f69f2cba 3203 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
724a51b1 3204 if (longval) *longval = value;
3205 return REDIS_OK;
3206}
3207
942a3961 3208/* Try to encode a string object in order to save space */
05df7621 3209static robj *tryObjectEncoding(robj *o) {
942a3961 3210 long value;
942a3961 3211 sds s = o->ptr;
3305306f 3212
942a3961 3213 if (o->encoding != REDIS_ENCODING_RAW)
05df7621 3214 return o; /* Already encoded */
3305306f 3215
05df7621 3216 /* It's not safe to encode shared objects: shared objects can be shared
942a3961 3217 * everywhere in the "object space" of Redis. Encoded objects can only
3218 * appear as "values" (and not, for instance, as keys) */
05df7621 3219 if (o->refcount > 1) return o;
3305306f 3220
942a3961 3221 /* Currently we try to encode only strings */
dfc5e96c 3222 redisAssert(o->type == REDIS_STRING);
94754ccc 3223
724a51b1 3224 /* Check if we can represent this string as a long integer */
05df7621 3225 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return o;
942a3961 3226
3227 /* Ok, this object can be encoded */
05df7621 3228 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3229 decrRefCount(o);
3230 incrRefCount(shared.integers[value]);
3231 return shared.integers[value];
3232 } else {
3233 o->encoding = REDIS_ENCODING_INT;
3234 sdsfree(o->ptr);
3235 o->ptr = (void*) value;
3236 return o;
3237 }
942a3961 3238}
3239
9d65a1bb 3240/* Get a decoded version of an encoded object (returned as a new object).
3241 * If the object is already raw-encoded just increment the ref count. */
3242static robj *getDecodedObject(robj *o) {
942a3961 3243 robj *dec;
e0a62c7f 3244
9d65a1bb 3245 if (o->encoding == REDIS_ENCODING_RAW) {
3246 incrRefCount(o);
3247 return o;
3248 }
942a3961 3249 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
3250 char buf[32];
3251
ee14da56 3252 ll2string(buf,32,(long)o->ptr);
942a3961 3253 dec = createStringObject(buf,strlen(buf));
3254 return dec;
3255 } else {
08ee9b57 3256 redisPanic("Unknown encoding type");
942a3961 3257 }
3305306f 3258}
3259
d7f43c08 3260/* Compare two string objects via strcmp() or alike.
3261 * Note that the objects may be integer-encoded. In such a case we
ee14da56 3262 * use ll2string() to get a string representation of the numbers on the stack
1fd9bc8a 3263 * and compare the strings, it's much faster than calling getDecodedObject().
3264 *
3265 * Important note: if objects are not integer encoded, but binary-safe strings,
3266 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3267 * binary safe. */
724a51b1 3268static int compareStringObjects(robj *a, robj *b) {
dfc5e96c 3269 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
d7f43c08 3270 char bufa[128], bufb[128], *astr, *bstr;
3271 int bothsds = 1;
724a51b1 3272
e197b441 3273 if (a == b) return 0;
d7f43c08 3274 if (a->encoding != REDIS_ENCODING_RAW) {
ee14da56 3275 ll2string(bufa,sizeof(bufa),(long) a->ptr);
d7f43c08 3276 astr = bufa;
3277 bothsds = 0;
724a51b1 3278 } else {
d7f43c08 3279 astr = a->ptr;
724a51b1 3280 }
d7f43c08 3281 if (b->encoding != REDIS_ENCODING_RAW) {
ee14da56 3282 ll2string(bufb,sizeof(bufb),(long) b->ptr);
d7f43c08 3283 bstr = bufb;
3284 bothsds = 0;
3285 } else {
3286 bstr = b->ptr;
3287 }
3288 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
724a51b1 3289}
3290
bf028098 3291/* Equal string objects return 1 if the two objects are the same from the
3292 * point of view of a string comparison, otherwise 0 is returned. Note that
3293 * this function is faster then checking for (compareStringObject(a,b) == 0)
3294 * because it can perform some more optimization. */
3295static int equalStringObjects(robj *a, robj *b) {
3296 if (a->encoding != REDIS_ENCODING_RAW && b->encoding != REDIS_ENCODING_RAW){
3297 return a->ptr == b->ptr;
3298 } else {
3299 return compareStringObjects(a,b) == 0;
3300 }
3301}
3302
0ea663ea 3303static size_t stringObjectLen(robj *o) {
dfc5e96c 3304 redisAssert(o->type == REDIS_STRING);
0ea663ea 3305 if (o->encoding == REDIS_ENCODING_RAW) {
3306 return sdslen(o->ptr);
3307 } else {
3308 char buf[32];
3309
ee14da56 3310 return ll2string(buf,32,(long)o->ptr);
0ea663ea 3311 }
3312}
3313
bd79a6bd
PN
3314static int getDoubleFromObject(robj *o, double *target) {
3315 double value;
682c73e8 3316 char *eptr;
bbe025e0 3317
bd79a6bd
PN
3318 if (o == NULL) {
3319 value = 0;
3320 } else {
3321 redisAssert(o->type == REDIS_STRING);
3322 if (o->encoding == REDIS_ENCODING_RAW) {
3323 value = strtod(o->ptr, &eptr);
682c73e8 3324 if (eptr[0] != '\0') return REDIS_ERR;
bd79a6bd
PN
3325 } else if (o->encoding == REDIS_ENCODING_INT) {
3326 value = (long)o->ptr;
3327 } else {
946342c1 3328 redisPanic("Unknown string encoding");
bd79a6bd
PN
3329 }
3330 }
3331
bd79a6bd
PN
3332 *target = value;
3333 return REDIS_OK;
3334}
bbe025e0 3335
bd79a6bd
PN
3336static int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg) {
3337 double value;
3338 if (getDoubleFromObject(o, &value) != REDIS_OK) {
3339 if (msg != NULL) {
3340 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3341 } else {
3342 addReplySds(c, sdsnew("-ERR value is not a double\r\n"));
3343 }
bbe025e0
AM
3344 return REDIS_ERR;
3345 }
3346
bd79a6bd 3347 *target = value;
bbe025e0
AM
3348 return REDIS_OK;
3349}
3350
bd79a6bd
PN
3351static int getLongLongFromObject(robj *o, long long *target) {
3352 long long value;
682c73e8 3353 char *eptr;
bbe025e0 3354
bd79a6bd
PN
3355 if (o == NULL) {
3356 value = 0;
3357 } else {
3358 redisAssert(o->type == REDIS_STRING);
3359 if (o->encoding == REDIS_ENCODING_RAW) {
3360 value = strtoll(o->ptr, &eptr, 10);
682c73e8 3361 if (eptr[0] != '\0') return REDIS_ERR;
bd79a6bd
PN
3362 } else if (o->encoding == REDIS_ENCODING_INT) {
3363 value = (long)o->ptr;
3364 } else {
946342c1 3365 redisPanic("Unknown string encoding");
bd79a6bd
PN
3366 }
3367 }
3368
bd79a6bd
PN
3369 *target = value;
3370 return REDIS_OK;
3371}
bbe025e0 3372
bd79a6bd
PN
3373static int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg) {
3374 long long value;
3375 if (getLongLongFromObject(o, &value) != REDIS_OK) {
3376 if (msg != NULL) {
3377 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3378 } else {
3379 addReplySds(c, sdsnew("-ERR value is not an integer\r\n"));
3380 }
bbe025e0
AM
3381 return REDIS_ERR;
3382 }
3383
bd79a6bd 3384 *target = value;
bbe025e0
AM
3385 return REDIS_OK;
3386}
3387
bd79a6bd
PN
3388static int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg) {
3389 long long value;
bbe025e0 3390
bd79a6bd
PN
3391 if (getLongLongFromObjectOrReply(c, o, &value, msg) != REDIS_OK) return REDIS_ERR;
3392 if (value < LONG_MIN || value > LONG_MAX) {
3393 if (msg != NULL) {
3394 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3395 } else {
3396 addReplySds(c, sdsnew("-ERR value is out of range\r\n"));
3397 }
bbe025e0
AM
3398 return REDIS_ERR;
3399 }
3400
bd79a6bd 3401 *target = value;
bbe025e0
AM
3402 return REDIS_OK;
3403}
3404
06233c45 3405/*============================ RDB saving/loading =========================== */
ed9b544e 3406
f78fd11b 3407static int rdbSaveType(FILE *fp, unsigned char type) {
3408 if (fwrite(&type,1,1,fp) == 0) return -1;
3409 return 0;
3410}
3411
bb32ede5 3412static int rdbSaveTime(FILE *fp, time_t t) {
3413 int32_t t32 = (int32_t) t;
3414 if (fwrite(&t32,4,1,fp) == 0) return -1;
3415 return 0;
3416}
3417
e3566d4b 3418/* check rdbLoadLen() comments for more info */
f78fd11b 3419static int rdbSaveLen(FILE *fp, uint32_t len) {
3420 unsigned char buf[2];
3421
3422 if (len < (1<<6)) {
3423 /* Save a 6 bit len */
10c43610 3424 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
f78fd11b 3425 if (fwrite(buf,1,1,fp) == 0) return -1;
3426 } else if (len < (1<<14)) {
3427 /* Save a 14 bit len */
10c43610 3428 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
f78fd11b 3429 buf[1] = len&0xFF;
17be1a4a 3430 if (fwrite(buf,2,1,fp) == 0) return -1;
f78fd11b 3431 } else {
3432 /* Save a 32 bit len */
10c43610 3433 buf[0] = (REDIS_RDB_32BITLEN<<6);
f78fd11b 3434 if (fwrite(buf,1,1,fp) == 0) return -1;
3435 len = htonl(len);
3436 if (fwrite(&len,4,1,fp) == 0) return -1;
3437 }
3438 return 0;
3439}
3440
32a66513 3441/* Encode 'value' as an integer if possible (if integer will fit the
3442 * supported range). If the function sucessful encoded the integer
3443 * then the (up to 5 bytes) encoded representation is written in the
3444 * string pointed by 'enc' and the length is returned. Otherwise
3445 * 0 is returned. */
3446static int rdbEncodeInteger(long long value, unsigned char *enc) {
e3566d4b 3447 /* Finally check if it fits in our ranges */
3448 if (value >= -(1<<7) && value <= (1<<7)-1) {
3449 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
3450 enc[1] = value&0xFF;
3451 return 2;
3452 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
3453 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
3454 enc[1] = value&0xFF;
3455 enc[2] = (value>>8)&0xFF;
3456 return 3;
3457 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
3458 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
3459 enc[1] = value&0xFF;
3460 enc[2] = (value>>8)&0xFF;
3461 enc[3] = (value>>16)&0xFF;
3462 enc[4] = (value>>24)&0xFF;
3463 return 5;
3464 } else {
3465 return 0;
3466 }
3467}
3468
32a66513 3469/* String objects in the form "2391" "-100" without any space and with a
3470 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3471 * encoded as integers to save space */
3472static int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
3473 long long value;
3474 char *endptr, buf[32];
3475
3476 /* Check if it's possible to encode this value as a number */
3477 value = strtoll(s, &endptr, 10);
3478 if (endptr[0] != '\0') return 0;
3479 ll2string(buf,32,value);
3480
3481 /* If the number converted back into a string is not identical
3482 * then it's not possible to encode the string as integer */
3483 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
3484
3485 return rdbEncodeInteger(value,enc);
3486}
3487
b1befe6a 3488static int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
3489 size_t comprlen, outlen;
774e3047 3490 unsigned char byte;
3491 void *out;
3492
3493 /* We require at least four bytes compression for this to be worth it */
b1befe6a 3494 if (len <= 4) return 0;
3495 outlen = len-4;
3a2694c4 3496 if ((out = zmalloc(outlen+1)) == NULL) return 0;
b1befe6a 3497 comprlen = lzf_compress(s, len, out, outlen);
774e3047 3498 if (comprlen == 0) {
88e85998 3499 zfree(out);
774e3047 3500 return 0;
3501 }
3502 /* Data compressed! Let's save it on disk */
3503 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
3504 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
3505 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
b1befe6a 3506 if (rdbSaveLen(fp,len) == -1) goto writeerr;
774e3047 3507 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
88e85998 3508 zfree(out);
774e3047 3509 return comprlen;
3510
3511writeerr:
88e85998 3512 zfree(out);
774e3047 3513 return -1;
3514}
3515
e3566d4b 3516/* Save a string objet as [len][data] on disk. If the object is a string
3517 * representation of an integer value we try to safe it in a special form */
b1befe6a 3518static int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
e3566d4b 3519 int enclen;
10c43610 3520
774e3047 3521 /* Try integer encoding */
e3566d4b 3522 if (len <= 11) {
3523 unsigned char buf[5];
b1befe6a 3524 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
e3566d4b 3525 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3526 return 0;
3527 }
3528 }
774e3047 3529
3530 /* Try LZF compression - under 20 bytes it's unable to compress even
88e85998 3531 * aaaaaaaaaaaaaaaaaa so skip it */
121f70cf 3532 if (server.rdbcompression && len > 20) {
774e3047 3533 int retval;
3534
b1befe6a 3535 retval = rdbSaveLzfStringObject(fp,s,len);
774e3047 3536 if (retval == -1) return -1;
3537 if (retval > 0) return 0;
3538 /* retval == 0 means data can't be compressed, save the old way */
3539 }
3540
3541 /* Store verbatim */
10c43610 3542 if (rdbSaveLen(fp,len) == -1) return -1;
b1befe6a 3543 if (len && fwrite(s,len,1,fp) == 0) return -1;
10c43610 3544 return 0;
3545}
3546
2796f6da
PN
3547/* Save a long long value as either an encoded string or a string. */
3548static int rdbSaveLongLongAsStringObject(FILE *fp, long long value) {
3549 unsigned char buf[32];
3550 int enclen = rdbEncodeInteger(value,buf);
3551 if (enclen > 0) {
3552 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3553 } else {
3554 /* Encode as string */
3555 enclen = ll2string((char*)buf,32,value);
3556 redisAssert(enclen < 32);
3557 if (rdbSaveLen(fp,enclen) == -1) return -1;
3558 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3559 }
3560 return 0;
3561}
3562
942a3961 3563/* Like rdbSaveStringObjectRaw() but handle encoded objects */
3564static int rdbSaveStringObject(FILE *fp, robj *obj) {
32a66513 3565 /* Avoid to decode the object, then encode it again, if the
3566 * object is alrady integer encoded. */
3567 if (obj->encoding == REDIS_ENCODING_INT) {
2796f6da 3568 return rdbSaveLongLongAsStringObject(fp,(long)obj->ptr);
996cb5f7 3569 } else {
2796f6da
PN
3570 redisAssert(obj->encoding == REDIS_ENCODING_RAW);
3571 return rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
996cb5f7 3572 }
942a3961 3573}
3574
a7866db6 3575/* Save a double value. Doubles are saved as strings prefixed by an unsigned
3576 * 8 bit integer specifing the length of the representation.
3577 * This 8 bit integer has special values in order to specify the following
3578 * conditions:
3579 * 253: not a number
3580 * 254: + inf
3581 * 255: - inf
3582 */
3583static int rdbSaveDoubleValue(FILE *fp, double val) {
3584 unsigned char buf[128];
3585 int len;
3586
3587 if (isnan(val)) {
3588 buf[0] = 253;
3589 len = 1;
3590 } else if (!isfinite(val)) {
3591 len = 1;
3592 buf[0] = (val < 0) ? 255 : 254;
3593 } else {
88e8d89f 3594#if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
fe244589 3595 /* Check if the float is in a safe range to be casted into a
3596 * long long. We are assuming that long long is 64 bit here.
3597 * Also we are assuming that there are no implementations around where
3598 * double has precision < 52 bit.
3599 *
3600 * Under this assumptions we test if a double is inside an interval
3601 * where casting to long long is safe. Then using two castings we
3602 * make sure the decimal part is zero. If all this is true we use
3603 * integer printing function that is much faster. */
fb82e75c 3604 double min = -4503599627370495; /* (2^52)-1 */
3605 double max = 4503599627370496; /* -(2^52) */
fe244589 3606 if (val > min && val < max && val == ((double)((long long)val)))
8c096b16 3607 ll2string((char*)buf+1,sizeof(buf),(long long)val);
3608 else
88e8d89f 3609#endif
8c096b16 3610 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
6c446631 3611 buf[0] = strlen((char*)buf+1);
a7866db6 3612 len = buf[0]+1;
3613 }
3614 if (fwrite(buf,len,1,fp) == 0) return -1;
3615 return 0;
3616}
3617
06233c45 3618/* Save a Redis object. */
3619static int rdbSaveObject(FILE *fp, robj *o) {
3620 if (o->type == REDIS_STRING) {
3621 /* Save a string value */
3622 if (rdbSaveStringObject(fp,o) == -1) return -1;
3623 } else if (o->type == REDIS_LIST) {
3624 /* Save a list value */
23f96494
PN
3625 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
3626 unsigned char *p;
3627 unsigned char *vstr;
3628 unsigned int vlen;
3629 long long vlong;
3630
3631 if (rdbSaveLen(fp,ziplistLen(o->ptr)) == -1) return -1;
3632 p = ziplistIndex(o->ptr,0);
3633 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
3634 if (vstr) {
3635 if (rdbSaveRawString(fp,vstr,vlen) == -1)
3636 return -1;
3637 } else {
3638 if (rdbSaveLongLongAsStringObject(fp,vlong) == -1)
3639 return -1;
3640 }
3641 p = ziplistNext(o->ptr,p);
3642 }
3643 } else if (o->encoding == REDIS_ENCODING_LIST) {
3644 list *list = o->ptr;
3645 listIter li;
3646 listNode *ln;
3647
3648 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
3649 listRewind(list,&li);
3650 while((ln = listNext(&li))) {
3651 robj *eleobj = listNodeValue(ln);
3652 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3653 }
3654 } else {
3655 redisPanic("Unknown list encoding");
06233c45 3656 }
3657 } else if (o->type == REDIS_SET) {
3658 /* Save a set value */
3659 dict *set = o->ptr;
3660 dictIterator *di = dictGetIterator(set);
3661 dictEntry *de;
3662
3663 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
3664 while((de = dictNext(di)) != NULL) {
3665 robj *eleobj = dictGetEntryKey(de);
3666
3667 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3668 }
3669 dictReleaseIterator(di);
3670 } else if (o->type == REDIS_ZSET) {
3671 /* Save a set value */
3672 zset *zs = o->ptr;
3673 dictIterator *di = dictGetIterator(zs->dict);
3674 dictEntry *de;
3675
3676 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
3677 while((de = dictNext(di)) != NULL) {
3678 robj *eleobj = dictGetEntryKey(de);
3679 double *score = dictGetEntryVal(de);
3680
3681 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3682 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
3683 }
3684 dictReleaseIterator(di);
b1befe6a 3685 } else if (o->type == REDIS_HASH) {
3686 /* Save a hash value */
3687 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3688 unsigned char *p = zipmapRewind(o->ptr);
3689 unsigned int count = zipmapLen(o->ptr);
3690 unsigned char *key, *val;
3691 unsigned int klen, vlen;
3692
3693 if (rdbSaveLen(fp,count) == -1) return -1;
3694 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
3695 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
3696 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
3697 }
3698 } else {
3699 dictIterator *di = dictGetIterator(o->ptr);
3700 dictEntry *de;
3701
3702 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
3703 while((de = dictNext(di)) != NULL) {
3704 robj *key = dictGetEntryKey(de);
3705 robj *val = dictGetEntryVal(de);
3706
3707 if (rdbSaveStringObject(fp,key) == -1) return -1;
3708 if (rdbSaveStringObject(fp,val) == -1) return -1;
3709 }
3710 dictReleaseIterator(di);
3711 }
06233c45 3712 } else {
f83c6cb5 3713 redisPanic("Unknown object type");
06233c45 3714 }
3715 return 0;
3716}
3717
3718/* Return the length the object will have on disk if saved with
3719 * the rdbSaveObject() function. Currently we use a trick to get
3720 * this length with very little changes to the code. In the future
3721 * we could switch to a faster solution. */
b9bc0eef 3722static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
3723 if (fp == NULL) fp = server.devnull;
06233c45 3724 rewind(fp);
3725 assert(rdbSaveObject(fp,o) != 1);
3726 return ftello(fp);
3727}
3728
06224fec 3729/* Return the number of pages required to save this object in the swap file */
b9bc0eef 3730static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
3731 off_t bytes = rdbSavedObjectLen(o,fp);
e0a62c7f 3732
06224fec 3733 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
3734}
3735
ed9b544e 3736/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
f78fd11b 3737static int rdbSave(char *filename) {
ed9b544e 3738 dictIterator *di = NULL;
3739 dictEntry *de;
ed9b544e 3740 FILE *fp;
3741 char tmpfile[256];
3742 int j;
bb32ede5 3743 time_t now = time(NULL);
ed9b544e 3744
2316bb3b 3745 /* Wait for I/O therads to terminate, just in case this is a
3746 * foreground-saving, to avoid seeking the swap file descriptor at the
3747 * same time. */
3748 if (server.vm_enabled)
3749 waitEmptyIOJobsQueue();
3750
a3b21203 3751 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
ed9b544e 3752 fp = fopen(tmpfile,"w");
3753 if (!fp) {
3754 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
3755 return REDIS_ERR;
3756 }
f78fd11b 3757 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
ed9b544e 3758 for (j = 0; j < server.dbnum; j++) {
bb32ede5 3759 redisDb *db = server.db+j;
3760 dict *d = db->dict;
3305306f 3761 if (dictSize(d) == 0) continue;
ed9b544e 3762 di = dictGetIterator(d);
3763 if (!di) {
3764 fclose(fp);
3765 return REDIS_ERR;
3766 }
3767
3768 /* Write the SELECT DB opcode */
f78fd11b 3769 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
3770 if (rdbSaveLen(fp,j) == -1) goto werr;
ed9b544e 3771
3772 /* Iterate this DB writing every entry */
3773 while((de = dictNext(di)) != NULL) {
3774 robj *key = dictGetEntryKey(de);
3775 robj *o = dictGetEntryVal(de);
bb32ede5 3776 time_t expiretime = getExpire(db,key);
3777
3778 /* Save the expire time */
3779 if (expiretime != -1) {
3780 /* If this key is already expired skip it */
3781 if (expiretime < now) continue;
3782 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
3783 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
3784 }
7e69548d 3785 /* Save the key and associated value. This requires special
3786 * handling if the value is swapped out. */
996cb5f7 3787 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
3788 key->storage == REDIS_VM_SWAPPING) {
7e69548d 3789 /* Save type, key, value */
3790 if (rdbSaveType(fp,o->type) == -1) goto werr;
3791 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3792 if (rdbSaveObject(fp,o) == -1) goto werr;
3793 } else {
996cb5f7 3794 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
b9bc0eef 3795 robj *po;
7e69548d 3796 /* Get a preview of the object in memory */
3797 po = vmPreviewObject(key);
7e69548d 3798 /* Save type, key, value */
3799 if (rdbSaveType(fp,key->vtype) == -1) goto werr;
b9bc0eef 3800 if (rdbSaveStringObject(fp,key) == -1) goto werr;
7e69548d 3801 if (rdbSaveObject(fp,po) == -1) goto werr;
3802 /* Remove the loaded object from memory */
3803 decrRefCount(po);
7e69548d 3804 }
ed9b544e 3805 }
3806 dictReleaseIterator(di);
3807 }
3808 /* EOF opcode */
f78fd11b 3809 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
3810
3811 /* Make sure data will not remain on the OS's output buffers */
ed9b544e 3812 fflush(fp);
3813 fsync(fileno(fp));
3814 fclose(fp);
e0a62c7f 3815
ed9b544e 3816 /* Use RENAME to make sure the DB file is changed atomically only
3817 * if the generate DB file is ok. */
3818 if (rename(tmpfile,filename) == -1) {
325d1eb4 3819 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
ed9b544e 3820 unlink(tmpfile);
3821 return REDIS_ERR;
3822 }
3823 redisLog(REDIS_NOTICE,"DB saved on disk");
3824 server.dirty = 0;
3825 server.lastsave = time(NULL);
3826 return REDIS_OK;
3827
3828werr:
3829 fclose(fp);
3830 unlink(tmpfile);
3831 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
3832 if (di) dictReleaseIterator(di);
3833 return REDIS_ERR;
3834}
3835
f78fd11b 3836static int rdbSaveBackground(char *filename) {
ed9b544e 3837 pid_t childpid;
3838
9d65a1bb 3839 if (server.bgsavechildpid != -1) return REDIS_ERR;
054e426d 3840 if (server.vm_enabled) waitEmptyIOJobsQueue();
ed9b544e 3841 if ((childpid = fork()) == 0) {
3842 /* Child */
054e426d 3843 if (server.vm_enabled) vmReopenSwapFile();
ed9b544e 3844 close(server.fd);
f78fd11b 3845 if (rdbSave(filename) == REDIS_OK) {
478c2c6f 3846 _exit(0);
ed9b544e 3847 } else {
478c2c6f 3848 _exit(1);
ed9b544e 3849 }
3850 } else {
3851 /* Parent */
5a7c647e 3852 if (childpid == -1) {
3853 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
3854 strerror(errno));
3855 return REDIS_ERR;
3856 }
ed9b544e 3857 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
9f3c422c 3858 server.bgsavechildpid = childpid;
884d4b39 3859 updateDictResizePolicy();
ed9b544e 3860 return REDIS_OK;
3861 }
3862 return REDIS_OK; /* unreached */
3863}
3864
a3b21203 3865static void rdbRemoveTempFile(pid_t childpid) {
3866 char tmpfile[256];
3867
3868 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
3869 unlink(tmpfile);
3870}
3871
f78fd11b 3872static int rdbLoadType(FILE *fp) {
3873 unsigned char type;
7b45bfb2 3874 if (fread(&type,1,1,fp) == 0) return -1;
3875 return type;
3876}
3877
bb32ede5 3878static time_t rdbLoadTime(FILE *fp) {
3879 int32_t t32;
3880 if (fread(&t32,4,1,fp) == 0) return -1;
3881 return (time_t) t32;
3882}
3883
e3566d4b 3884/* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3885 * of this file for a description of how this are stored on disk.
3886 *
3887 * isencoded is set to 1 if the readed length is not actually a length but
3888 * an "encoding type", check the above comments for more info */
c78a8ccc 3889static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
f78fd11b 3890 unsigned char buf[2];
3891 uint32_t len;
c78a8ccc 3892 int type;
f78fd11b 3893
e3566d4b 3894 if (isencoded) *isencoded = 0;
c78a8ccc 3895 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
3896 type = (buf[0]&0xC0)>>6;
3897 if (type == REDIS_RDB_6BITLEN) {
3898 /* Read a 6 bit len */
3899 return buf[0]&0x3F;
3900 } else if (type == REDIS_RDB_ENCVAL) {
3901 /* Read a 6 bit len encoding type */
3902 if (isencoded) *isencoded = 1;
3903 return buf[0]&0x3F;
3904 } else if (type == REDIS_RDB_14BITLEN) {
3905 /* Read a 14 bit len */
3906 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
3907 return ((buf[0]&0x3F)<<8)|buf[1];
3908 } else {
3909 /* Read a 32 bit len */
f78fd11b 3910 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
3911 return ntohl(len);
f78fd11b 3912 }
f78fd11b 3913}
3914
ad30aa60 3915/* Load an integer-encoded object from file 'fp', with the specified
3916 * encoding type 'enctype'. If encode is true the function may return
3917 * an integer-encoded object as reply, otherwise the returned object
3918 * will always be encoded as a raw string. */
3919static robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
e3566d4b 3920 unsigned char enc[4];
3921 long long val;
3922
3923 if (enctype == REDIS_RDB_ENC_INT8) {
3924 if (fread(enc,1,1,fp) == 0) return NULL;
3925 val = (signed char)enc[0];
3926 } else if (enctype == REDIS_RDB_ENC_INT16) {
3927 uint16_t v;
3928 if (fread(enc,2,1,fp) == 0) return NULL;
3929 v = enc[0]|(enc[1]<<8);
3930 val = (int16_t)v;
3931 } else if (enctype == REDIS_RDB_ENC_INT32) {
3932 uint32_t v;
3933 if (fread(enc,4,1,fp) == 0) return NULL;
3934 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
3935 val = (int32_t)v;
3936 } else {
3937 val = 0; /* anti-warning */
f83c6cb5 3938 redisPanic("Unknown RDB integer encoding type");
e3566d4b 3939 }
ad30aa60 3940 if (encode)
3941 return createStringObjectFromLongLong(val);
3942 else
3943 return createObject(REDIS_STRING,sdsfromlonglong(val));
e3566d4b 3944}
3945
c78a8ccc 3946static robj *rdbLoadLzfStringObject(FILE*fp) {
88e85998 3947 unsigned int len, clen;
3948 unsigned char *c = NULL;
3949 sds val = NULL;
3950
c78a8ccc 3951 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3952 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
88e85998 3953 if ((c = zmalloc(clen)) == NULL) goto err;
3954 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
3955 if (fread(c,clen,1,fp) == 0) goto err;
3956 if (lzf_decompress(c,clen,val,len) == 0) goto err;
5109cdff 3957 zfree(c);
88e85998 3958 return createObject(REDIS_STRING,val);
3959err:
3960 zfree(c);
3961 sdsfree(val);
3962 return NULL;
3963}
3964
ad30aa60 3965static robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
e3566d4b 3966 int isencoded;
3967 uint32_t len;
f78fd11b 3968 sds val;
3969
c78a8ccc 3970 len = rdbLoadLen(fp,&isencoded);
e3566d4b 3971 if (isencoded) {
3972 switch(len) {
3973 case REDIS_RDB_ENC_INT8:
3974 case REDIS_RDB_ENC_INT16:
3975 case REDIS_RDB_ENC_INT32:
ad30aa60 3976 return rdbLoadIntegerObject(fp,len,encode);
88e85998 3977 case REDIS_RDB_ENC_LZF:
bdcb92f2 3978 return rdbLoadLzfStringObject(fp);
e3566d4b 3979 default:
f83c6cb5 3980 redisPanic("Unknown RDB encoding type");
e3566d4b 3981 }
3982 }
3983
f78fd11b 3984 if (len == REDIS_RDB_LENERR) return NULL;
3985 val = sdsnewlen(NULL,len);
3986 if (len && fread(val,len,1,fp) == 0) {
3987 sdsfree(val);
3988 return NULL;
3989 }
bdcb92f2 3990 return createObject(REDIS_STRING,val);
f78fd11b 3991}
3992
ad30aa60 3993static robj *rdbLoadStringObject(FILE *fp) {
3994 return rdbGenericLoadStringObject(fp,0);
3995}
3996
3997static robj *rdbLoadEncodedStringObject(FILE *fp) {
3998 return rdbGenericLoadStringObject(fp,1);
3999}
4000
a7866db6 4001/* For information about double serialization check rdbSaveDoubleValue() */
4002static int rdbLoadDoubleValue(FILE *fp, double *val) {
4003 char buf[128];
4004 unsigned char len;
4005
4006 if (fread(&len,1,1,fp) == 0) return -1;
4007 switch(len) {
4008 case 255: *val = R_NegInf; return 0;
4009 case 254: *val = R_PosInf; return 0;
4010 case 253: *val = R_Nan; return 0;
4011 default:
4012 if (fread(buf,len,1,fp) == 0) return -1;
231d758e 4013 buf[len] = '\0';
a7866db6 4014 sscanf(buf, "%lg", val);
4015 return 0;
4016 }
4017}
4018
c78a8ccc 4019/* Load a Redis object of the specified type from the specified file.
4020 * On success a newly allocated object is returned, otherwise NULL. */
4021static robj *rdbLoadObject(int type, FILE *fp) {
23f96494
PN
4022 robj *o, *ele, *dec;
4023 size_t len;
c78a8ccc 4024
bcd11906 4025 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
c78a8ccc 4026 if (type == REDIS_STRING) {
4027 /* Read string value */
ad30aa60 4028 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 4029 o = tryObjectEncoding(o);
23f96494
PN
4030 } else if (type == REDIS_LIST) {
4031 /* Read list value */
4032 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4033
4034 o = createObject(REDIS_LIST,ziplistNew());
4035 o->encoding = REDIS_ENCODING_ZIPLIST;
c78a8ccc 4036
23f96494
PN
4037 /* Load every single element of the list */
4038 while(len--) {
4039 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4040
4041 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
4042 dec = getDecodedObject(ele);
4043 o->ptr = ziplistPush(o->ptr,dec->ptr,sdslen(dec->ptr),REDIS_TAIL);
4044 decrRefCount(dec);
4045 decrRefCount(ele);
4046 } else {
4047 ele = tryObjectEncoding(ele);
4048 listAddNodeTail(o->ptr,ele);
4049 incrRefCount(ele);
4050 }
4051 }
4052 } else if (type == REDIS_SET) {
4053 /* Read list/set value */
4054 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4055 o = createSetObject();
3c68de9b 4056 /* It's faster to expand the dict to the right size asap in order
4057 * to avoid rehashing */
23f96494
PN
4058 if (len > DICT_HT_INITIAL_SIZE)
4059 dictExpand(o->ptr,len);
c78a8ccc 4060 /* Load every single element of the list/set */
23f96494 4061 while(len--) {
ad30aa60 4062 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 4063 ele = tryObjectEncoding(ele);
23f96494 4064 dictAdd((dict*)o->ptr,ele,NULL);
c78a8ccc 4065 }
4066 } else if (type == REDIS_ZSET) {
4067 /* Read list/set value */
ada386b2 4068 size_t zsetlen;
c78a8ccc 4069 zset *zs;
4070
4071 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4072 o = createZsetObject();
4073 zs = o->ptr;
4074 /* Load every single element of the list/set */
4075 while(zsetlen--) {
4076 robj *ele;
4077 double *score = zmalloc(sizeof(double));
4078
ad30aa60 4079 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 4080 ele = tryObjectEncoding(ele);
c78a8ccc 4081 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
4082 dictAdd(zs->dict,ele,score);
4083 zslInsert(zs->zsl,*score,ele);
4084 incrRefCount(ele); /* added to skiplist */
4085 }
ada386b2 4086 } else if (type == REDIS_HASH) {
4087 size_t hashlen;
4088
4089 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4090 o = createHashObject();
4091 /* Too many entries? Use an hash table. */
4092 if (hashlen > server.hash_max_zipmap_entries)
4093 convertToRealHash(o);
4094 /* Load every key/value, then set it into the zipmap or hash
4095 * table, as needed. */
4096 while(hashlen--) {
4097 robj *key, *val;
4098
4099 if ((key = rdbLoadStringObject(fp)) == NULL) return NULL;
4100 if ((val = rdbLoadStringObject(fp)) == NULL) return NULL;
4101 /* If we are using a zipmap and there are too big values
4102 * the object is converted to real hash table encoding. */
4103 if (o->encoding != REDIS_ENCODING_HT &&
4104 (sdslen(key->ptr) > server.hash_max_zipmap_value ||
4105 sdslen(val->ptr) > server.hash_max_zipmap_value))
4106 {
4107 convertToRealHash(o);
4108 }
4109
4110 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
4111 unsigned char *zm = o->ptr;
4112
4113 zm = zipmapSet(zm,key->ptr,sdslen(key->ptr),
4114 val->ptr,sdslen(val->ptr),NULL);
4115 o->ptr = zm;
4116 decrRefCount(key);
4117 decrRefCount(val);
4118 } else {
05df7621 4119 key = tryObjectEncoding(key);
4120 val = tryObjectEncoding(val);
ada386b2 4121 dictAdd((dict*)o->ptr,key,val);
ada386b2 4122 }
4123 }
c78a8ccc 4124 } else {
f83c6cb5 4125 redisPanic("Unknown object type");
c78a8ccc 4126 }
4127 return o;
4128}
4129
f78fd11b 4130static int rdbLoad(char *filename) {
ed9b544e 4131 FILE *fp;
f78fd11b 4132 uint32_t dbid;
bb32ede5 4133 int type, retval, rdbver;
585af7e2 4134 int swap_all_values = 0;
3305306f 4135 dict *d = server.db[0].dict;
bb32ede5 4136 redisDb *db = server.db+0;
f78fd11b 4137 char buf[1024];
242a64f3 4138 time_t expiretime, now = time(NULL);
b492cf00 4139 long long loadedkeys = 0;
bb32ede5 4140
ed9b544e 4141 fp = fopen(filename,"r");
4142 if (!fp) return REDIS_ERR;
4143 if (fread(buf,9,1,fp) == 0) goto eoferr;
f78fd11b 4144 buf[9] = '\0';
4145 if (memcmp(buf,"REDIS",5) != 0) {
ed9b544e 4146 fclose(fp);
4147 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
4148 return REDIS_ERR;
4149 }
f78fd11b 4150 rdbver = atoi(buf+5);
c78a8ccc 4151 if (rdbver != 1) {
f78fd11b 4152 fclose(fp);
4153 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
4154 return REDIS_ERR;
4155 }
ed9b544e 4156 while(1) {
585af7e2 4157 robj *key, *val;
ed9b544e 4158
585af7e2 4159 expiretime = -1;
ed9b544e 4160 /* Read type. */
f78fd11b 4161 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
bb32ede5 4162 if (type == REDIS_EXPIRETIME) {
4163 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
4164 /* We read the time so we need to read the object type again */
4165 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4166 }
ed9b544e 4167 if (type == REDIS_EOF) break;
4168 /* Handle SELECT DB opcode as a special case */
4169 if (type == REDIS_SELECTDB) {
c78a8ccc 4170 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
e3566d4b 4171 goto eoferr;
ed9b544e 4172 if (dbid >= (unsigned)server.dbnum) {
f78fd11b 4173 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
ed9b544e 4174 exit(1);
4175 }
bb32ede5 4176 db = server.db+dbid;
4177 d = db->dict;
ed9b544e 4178 continue;
4179 }
4180 /* Read key */
585af7e2 4181 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
c78a8ccc 4182 /* Read value */
585af7e2 4183 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
89e689c5 4184 /* Check if the key already expired */
4185 if (expiretime != -1 && expiretime < now) {
4186 decrRefCount(key);
4187 decrRefCount(val);
4188 continue;
4189 }
ed9b544e 4190 /* Add the new object in the hash table */
585af7e2 4191 retval = dictAdd(d,key,val);
ed9b544e 4192 if (retval == DICT_ERR) {
585af7e2 4193 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
ed9b544e 4194 exit(1);
4195 }
242a64f3 4196 loadedkeys++;
bb32ede5 4197 /* Set the expire time if needed */
89e689c5 4198 if (expiretime != -1) setExpire(db,key,expiretime);
242a64f3 4199
b492cf00 4200 /* Handle swapping while loading big datasets when VM is on */
242a64f3 4201
4202 /* If we detecter we are hopeless about fitting something in memory
4203 * we just swap every new key on disk. Directly...
4204 * Note that's important to check for this condition before resorting
4205 * to random sampling, otherwise we may try to swap already
4206 * swapped keys. */
585af7e2 4207 if (swap_all_values) {
4208 dictEntry *de = dictFind(d,key);
242a64f3 4209
4210 /* de may be NULL since the key already expired */
4211 if (de) {
585af7e2 4212 key = dictGetEntryKey(de);
4213 val = dictGetEntryVal(de);
242a64f3 4214
585af7e2 4215 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
242a64f3 4216 dictGetEntryVal(de) = NULL;
4217 }
4218 }
4219 continue;
4220 }
4221
4222 /* If we have still some hope of having some value fitting memory
4223 * then we try random sampling. */
585af7e2 4224 if (!swap_all_values && server.vm_enabled && (loadedkeys % 5000) == 0) {
b492cf00 4225 while (zmalloc_used_memory() > server.vm_max_memory) {
a69a0c9c 4226 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
b492cf00 4227 }
242a64f3 4228 if (zmalloc_used_memory() > server.vm_max_memory)
585af7e2 4229 swap_all_values = 1; /* We are already using too much mem */
b492cf00 4230 }
ed9b544e 4231 }
4232 fclose(fp);
4233 return REDIS_OK;
4234
4235eoferr: /* unexpected end of file is handled here with a fatal exit */
f80dff62 4236 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
ed9b544e 4237 exit(1);
4238 return REDIS_ERR; /* Just to avoid warning */
4239}
4240
b58ba105 4241/*================================== Shutdown =============================== */
fab43727 4242static int prepareForShutdown() {
b58ba105
AM
4243 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
4244 /* Kill the saving child if there is a background saving in progress.
4245 We want to avoid race conditions, for instance our saving child may
4246 overwrite the synchronous saving did by SHUTDOWN. */
4247 if (server.bgsavechildpid != -1) {
4248 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
4249 kill(server.bgsavechildpid,SIGKILL);
4250 rdbRemoveTempFile(server.bgsavechildpid);
4251 }
4252 if (server.appendonly) {
4253 /* Append only file: fsync() the AOF and exit */
4254 fsync(server.appendfd);
4255 if (server.vm_enabled) unlink(server.vm_swap_file);
b58ba105
AM
4256 } else {
4257 /* Snapshotting. Perform a SYNC SAVE and exit */
4258 if (rdbSave(server.dbfilename) == REDIS_OK) {
4259 if (server.daemonize)
4260 unlink(server.pidfile);
4261 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
b58ba105
AM
4262 } else {
4263 /* Ooops.. error saving! The best we can do is to continue
4264 * operating. Note that if there was a background saving process,
4265 * in the next cron() Redis will be notified that the background
4266 * saving aborted, handling special stuff like slaves pending for
4267 * synchronization... */
4268 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
fab43727 4269 return REDIS_ERR;
b58ba105
AM
4270 }
4271 }
8513a757 4272 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
fab43727 4273 return REDIS_OK;
b58ba105
AM
4274}
4275
ed9b544e 4276/*================================== Commands =============================== */
4277
abcb223e 4278static void authCommand(redisClient *c) {
2e77c2ee 4279 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
abcb223e
BH
4280 c->authenticated = 1;
4281 addReply(c,shared.ok);
4282 } else {
4283 c->authenticated = 0;
fa4c0aba 4284 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
abcb223e
BH
4285 }
4286}
4287
ed9b544e 4288static void pingCommand(redisClient *c) {
4289 addReply(c,shared.pong);
4290}
4291
4292static void echoCommand(redisClient *c) {
dd88747b 4293 addReplyBulk(c,c->argv[1]);
ed9b544e 4294}
4295
4296/*=================================== Strings =============================== */
4297
526d00a5 4298static void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
ed9b544e 4299 int retval;
10ce1276 4300 long seconds = 0; /* initialized to avoid an harmness warning */
ed9b544e 4301
526d00a5 4302 if (expire) {
4303 if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
4304 return;
4305 if (seconds <= 0) {
4306 addReplySds(c,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4307 return;
4308 }
4309 }
4310
37ab76c9 4311 touchWatchedKey(c->db,key);
526d00a5 4312 if (nx) deleteIfVolatile(c->db,key);
4313 retval = dictAdd(c->db->dict,key,val);
ed9b544e 4314 if (retval == DICT_ERR) {
4315 if (!nx) {
1b03836c 4316 /* If the key is about a swapped value, we want a new key object
4317 * to overwrite the old. So we delete the old key in the database.
4318 * This will also make sure that swap pages about the old object
4319 * will be marked as free. */
526d00a5 4320 if (server.vm_enabled && deleteIfSwapped(c->db,key))
4321 incrRefCount(key);
4322 dictReplace(c->db->dict,key,val);
4323 incrRefCount(val);
ed9b544e 4324 } else {
c937aa89 4325 addReply(c,shared.czero);
ed9b544e 4326 return;
4327 }
4328 } else {
526d00a5 4329 incrRefCount(key);
4330 incrRefCount(val);
ed9b544e 4331 }
4332 server.dirty++;
526d00a5 4333 removeExpire(c->db,key);
4334 if (expire) setExpire(c->db,key,time(NULL)+seconds);
c937aa89 4335 addReply(c, nx ? shared.cone : shared.ok);
ed9b544e 4336}
4337
4338static void setCommand(redisClient *c) {
526d00a5 4339 setGenericCommand(c,0,c->argv[1],c->argv[2],NULL);
ed9b544e 4340}
4341
4342static void setnxCommand(redisClient *c) {
526d00a5 4343 setGenericCommand(c,1,c->argv[1],c->argv[2],NULL);
4344}
4345
4346static void setexCommand(redisClient *c) {
4347 setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
ed9b544e 4348}
4349
322fc7d8 4350static int getGenericCommand(redisClient *c) {
dd88747b 4351 robj *o;
e0a62c7f 4352
dd88747b 4353 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
322fc7d8 4354 return REDIS_OK;
dd88747b 4355
4356 if (o->type != REDIS_STRING) {
4357 addReply(c,shared.wrongtypeerr);
4358 return REDIS_ERR;
ed9b544e 4359 } else {
dd88747b 4360 addReplyBulk(c,o);
4361 return REDIS_OK;
ed9b544e 4362 }
4363}
4364
322fc7d8 4365static void getCommand(redisClient *c) {
4366 getGenericCommand(c);
4367}
4368
f6b141c5 4369static void getsetCommand(redisClient *c) {
322fc7d8 4370 if (getGenericCommand(c) == REDIS_ERR) return;
a431eb74 4371 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
4372 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
4373 } else {
4374 incrRefCount(c->argv[1]);
4375 }
4376 incrRefCount(c->argv[2]);
4377 server.dirty++;
4378 removeExpire(c->db,c->argv[1]);
4379}
4380
70003d28 4381static void mgetCommand(redisClient *c) {
70003d28 4382 int j;
e0a62c7f 4383
c937aa89 4384 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
70003d28 4385 for (j = 1; j < c->argc; j++) {
3305306f 4386 robj *o = lookupKeyRead(c->db,c->argv[j]);
4387 if (o == NULL) {
c937aa89 4388 addReply(c,shared.nullbulk);
70003d28 4389 } else {
70003d28 4390 if (o->type != REDIS_STRING) {
c937aa89 4391 addReply(c,shared.nullbulk);
70003d28 4392 } else {
dd88747b 4393 addReplyBulk(c,o);
70003d28 4394 }
4395 }
4396 }
4397}
4398
6c446631 4399static void msetGenericCommand(redisClient *c, int nx) {
906573e7 4400 int j, busykeys = 0;
6c446631 4401
4402 if ((c->argc % 2) == 0) {
454d4e43 4403 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
6c446631 4404 return;
4405 }
4406 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4407 * set nothing at all if at least one already key exists. */
4408 if (nx) {
4409 for (j = 1; j < c->argc; j += 2) {
906573e7 4410 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
4411 busykeys++;
6c446631 4412 }
4413 }
4414 }
906573e7 4415 if (busykeys) {
4416 addReply(c, shared.czero);
4417 return;
4418 }
6c446631 4419
4420 for (j = 1; j < c->argc; j += 2) {
4421 int retval;
4422
05df7621 4423 c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
6c446631 4424 retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
4425 if (retval == DICT_ERR) {
4426 dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
4427 incrRefCount(c->argv[j+1]);
4428 } else {
4429 incrRefCount(c->argv[j]);
4430 incrRefCount(c->argv[j+1]);
4431 }
4432 removeExpire(c->db,c->argv[j]);
4433 }
4434 server.dirty += (c->argc-1)/2;
4435 addReply(c, nx ? shared.cone : shared.ok);
4436}
4437
4438static void msetCommand(redisClient *c) {
4439 msetGenericCommand(c,0);
4440}
4441
4442static void msetnxCommand(redisClient *c) {
4443 msetGenericCommand(c,1);
4444}
4445
d68ed120 4446static void incrDecrCommand(redisClient *c, long long incr) {
ed9b544e 4447 long long value;
4448 int retval;
4449 robj *o;
e0a62c7f 4450
3305306f 4451 o = lookupKeyWrite(c->db,c->argv[1]);
6485f293
PN
4452 if (o != NULL && checkType(c,o,REDIS_STRING)) return;
4453 if (getLongLongFromObjectOrReply(c,o,&value,NULL) != REDIS_OK) return;
ed9b544e 4454
4455 value += incr;
d6f4c262 4456 o = createStringObjectFromLongLong(value);
3305306f 4457 retval = dictAdd(c->db->dict,c->argv[1],o);
ed9b544e 4458 if (retval == DICT_ERR) {
3305306f 4459 dictReplace(c->db->dict,c->argv[1],o);
4460 removeExpire(c->db,c->argv[1]);
ed9b544e 4461 } else {
4462 incrRefCount(c->argv[1]);
4463 }
4464 server.dirty++;
c937aa89 4465 addReply(c,shared.colon);
ed9b544e 4466 addReply(c,o);
4467 addReply(c,shared.crlf);
4468}
4469
4470static void incrCommand(redisClient *c) {
a4d1ba9a 4471 incrDecrCommand(c,1);
ed9b544e 4472}
4473
4474static void decrCommand(redisClient *c) {
a4d1ba9a 4475 incrDecrCommand(c,-1);
ed9b544e 4476}
4477
4478static void incrbyCommand(redisClient *c) {
bbe025e0
AM
4479 long long incr;
4480
bd79a6bd 4481 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
a4d1ba9a 4482 incrDecrCommand(c,incr);
ed9b544e 4483}
4484
4485static void decrbyCommand(redisClient *c) {
bbe025e0
AM
4486 long long incr;
4487
bd79a6bd 4488 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
a4d1ba9a 4489 incrDecrCommand(c,-incr);
ed9b544e 4490}
4491
4b00bebd 4492static void appendCommand(redisClient *c) {
4493 int retval;
4494 size_t totlen;
4495 robj *o;
4496
4497 o = lookupKeyWrite(c->db,c->argv[1]);
4498 if (o == NULL) {
4499 /* Create the key */
4500 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
4501 incrRefCount(c->argv[1]);
4502 incrRefCount(c->argv[2]);
4503 totlen = stringObjectLen(c->argv[2]);
4504 } else {
4505 dictEntry *de;
e0a62c7f 4506
4b00bebd 4507 de = dictFind(c->db->dict,c->argv[1]);
4508 assert(de != NULL);
4509
4510 o = dictGetEntryVal(de);
4511 if (o->type != REDIS_STRING) {
4512 addReply(c,shared.wrongtypeerr);
4513 return;
4514 }
4515 /* If the object is specially encoded or shared we have to make
4516 * a copy */
4517 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
4518 robj *decoded = getDecodedObject(o);
4519
4520 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
4521 decrRefCount(decoded);
4522 dictReplace(c->db->dict,c->argv[1],o);
4523 }
4524 /* APPEND! */
4525 if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
4526 o->ptr = sdscatlen(o->ptr,
4527 c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
4528 } else {
4529 o->ptr = sdscatprintf(o->ptr, "%ld",
4530 (unsigned long) c->argv[2]->ptr);
4531 }
4532 totlen = sdslen(o->ptr);
4533 }
4534 server.dirty++;
4535 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
4536}
4537
39191553 4538static void substrCommand(redisClient *c) {
4539 robj *o;
4540 long start = atoi(c->argv[2]->ptr);
4541 long end = atoi(c->argv[3]->ptr);
dd88747b 4542 size_t rangelen, strlen;
4543 sds range;
39191553 4544
dd88747b 4545 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4546 checkType(c,o,REDIS_STRING)) return;
39191553 4547
dd88747b 4548 o = getDecodedObject(o);
4549 strlen = sdslen(o->ptr);
8fe7fad7 4550
dd88747b 4551 /* convert negative indexes */
4552 if (start < 0) start = strlen+start;
4553 if (end < 0) end = strlen+end;
4554 if (start < 0) start = 0;
4555 if (end < 0) end = 0;
39191553 4556
dd88747b 4557 /* indexes sanity checks */
4558 if (start > end || (size_t)start >= strlen) {
4559 /* Out of range start or start > end result in null reply */
4560 addReply(c,shared.nullbulk);
4561 decrRefCount(o);
4562 return;
39191553 4563 }
dd88747b 4564 if ((size_t)end >= strlen) end = strlen-1;
4565 rangelen = (end-start)+1;
4566
4567 /* Return the result */
4568 addReplySds(c,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen));
4569 range = sdsnewlen((char*)o->ptr+start,rangelen);
4570 addReplySds(c,range);
4571 addReply(c,shared.crlf);
4572 decrRefCount(o);
39191553 4573}
4574
ed9b544e 4575/* ========================= Type agnostic commands ========================= */
4576
4577static void delCommand(redisClient *c) {
5109cdff 4578 int deleted = 0, j;
4579
4580 for (j = 1; j < c->argc; j++) {
4581 if (deleteKey(c->db,c->argv[j])) {
37ab76c9 4582 touchWatchedKey(c->db,c->argv[j]);
5109cdff 4583 server.dirty++;
4584 deleted++;
4585 }
4586 }
482b672d 4587 addReplyLongLong(c,deleted);
ed9b544e 4588}
4589
4590static void existsCommand(redisClient *c) {
f4f06efc
PN
4591 expireIfNeeded(c->db,c->argv[1]);
4592 if (dictFind(c->db->dict,c->argv[1])) {
4593 addReply(c, shared.cone);
4594 } else {
4595 addReply(c, shared.czero);
4596 }
ed9b544e 4597}
4598
4599static void selectCommand(redisClient *c) {
4600 int id = atoi(c->argv[1]->ptr);
e0a62c7f 4601
ed9b544e 4602 if (selectDb(c,id) == REDIS_ERR) {
774e3047 4603 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
ed9b544e 4604 } else {
4605 addReply(c,shared.ok);
4606 }
4607}
4608
4609static void randomkeyCommand(redisClient *c) {
4610 dictEntry *de;
dc4be23e 4611 robj *key;
e0a62c7f 4612
3305306f 4613 while(1) {
4614 de = dictGetRandomKey(c->db->dict);
ce7bef07 4615 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
3305306f 4616 }
2b619329 4617
ed9b544e 4618 if (de == NULL) {
dc4be23e 4619 addReply(c,shared.nullbulk);
4620 return;
4621 }
4622
4623 key = dictGetEntryKey(de);
4624 if (server.vm_enabled) {
4625 key = dupStringObject(key);
4626 addReplyBulk(c,key);
4627 decrRefCount(key);
ed9b544e 4628 } else {
dc4be23e 4629 addReplyBulk(c,key);
ed9b544e 4630 }
4631}
4632
4633static void keysCommand(redisClient *c) {
4634 dictIterator *di;
4635 dictEntry *de;
4636 sds pattern = c->argv[1]->ptr;
4637 int plen = sdslen(pattern);
a3f9eec2 4638 unsigned long numkeys = 0;
ed9b544e 4639 robj *lenobj = createObject(REDIS_STRING,NULL);
4640
3305306f 4641 di = dictGetIterator(c->db->dict);
ed9b544e 4642 addReply(c,lenobj);
4643 decrRefCount(lenobj);
4644 while((de = dictNext(di)) != NULL) {
4645 robj *keyobj = dictGetEntryKey(de);
3305306f 4646
ed9b544e 4647 sds key = keyobj->ptr;
4648 if ((pattern[0] == '*' && pattern[1] == '\0') ||
4649 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
3305306f 4650 if (expireIfNeeded(c->db,keyobj) == 0) {
dd88747b 4651 addReplyBulk(c,keyobj);
3305306f 4652 numkeys++;
3305306f 4653 }
ed9b544e 4654 }
4655 }
4656 dictReleaseIterator(di);
a3f9eec2 4657 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
ed9b544e 4658}
4659
4660static void dbsizeCommand(redisClient *c) {
4661 addReplySds(c,
3305306f 4662 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
ed9b544e 4663}
4664
4665static void lastsaveCommand(redisClient *c) {
4666 addReplySds(c,
c937aa89 4667 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
ed9b544e 4668}
4669
4670static void typeCommand(redisClient *c) {
3305306f 4671 robj *o;
ed9b544e 4672 char *type;
3305306f 4673
4674 o = lookupKeyRead(c->db,c->argv[1]);
4675 if (o == NULL) {
c937aa89 4676 type = "+none";
ed9b544e 4677 } else {
ed9b544e 4678 switch(o->type) {
c937aa89 4679 case REDIS_STRING: type = "+string"; break;
4680 case REDIS_LIST: type = "+list"; break;
4681 case REDIS_SET: type = "+set"; break;
412a8bce 4682 case REDIS_ZSET: type = "+zset"; break;
ada386b2 4683 case REDIS_HASH: type = "+hash"; break;
4684 default: type = "+unknown"; break;
ed9b544e 4685 }
4686 }
4687 addReplySds(c,sdsnew(type));
4688 addReply(c,shared.crlf);
4689}
4690
4691static void saveCommand(redisClient *c) {
9d65a1bb 4692 if (server.bgsavechildpid != -1) {
05557f6d 4693 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
4694 return;
4695 }
f78fd11b 4696 if (rdbSave(server.dbfilename) == REDIS_OK) {
ed9b544e 4697 addReply(c,shared.ok);
4698 } else {
4699 addReply(c,shared.err);
4700 }
4701}
4702
4703static void bgsaveCommand(redisClient *c) {
9d65a1bb 4704 if (server.bgsavechildpid != -1) {
ed9b544e 4705 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
4706 return;
4707 }
f78fd11b 4708 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
49b99ab4 4709 char *status = "+Background saving started\r\n";
4710 addReplySds(c,sdsnew(status));
ed9b544e 4711 } else {
4712 addReply(c,shared.err);
4713 }
4714}
4715
4716static void shutdownCommand(redisClient *c) {
fab43727 4717 if (prepareForShutdown() == REDIS_OK)
4718 exit(0);
4719 addReplySds(c, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
ed9b544e 4720}
4721
4722static void renameGenericCommand(redisClient *c, int nx) {
ed9b544e 4723 robj *o;
4724
4725 /* To use the same key as src and dst is probably an error */
4726 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
c937aa89 4727 addReply(c,shared.sameobjecterr);
ed9b544e 4728 return;
4729 }
4730
dd88747b 4731 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
ed9b544e 4732 return;
dd88747b 4733
ed9b544e 4734 incrRefCount(o);
3305306f 4735 deleteIfVolatile(c->db,c->argv[2]);
4736 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
ed9b544e 4737 if (nx) {
4738 decrRefCount(o);
c937aa89 4739 addReply(c,shared.czero);
ed9b544e 4740 return;
4741 }
3305306f 4742 dictReplace(c->db->dict,c->argv[2],o);
ed9b544e 4743 } else {
4744 incrRefCount(c->argv[2]);
4745 }
3305306f 4746 deleteKey(c->db,c->argv[1]);
b167f877 4747 touchWatchedKey(c->db,c->argv[2]);
ed9b544e 4748 server.dirty++;
c937aa89 4749 addReply(c,nx ? shared.cone : shared.ok);
ed9b544e 4750}
4751
4752static void renameCommand(redisClient *c) {
4753 renameGenericCommand(c,0);
4754}
4755
4756static void renamenxCommand(redisClient *c) {
4757 renameGenericCommand(c,1);
4758}
4759
4760static void moveCommand(redisClient *c) {
3305306f 4761 robj *o;
4762 redisDb *src, *dst;
ed9b544e 4763 int srcid;
4764
4765 /* Obtain source and target DB pointers */
3305306f 4766 src = c->db;
4767 srcid = c->db->id;
ed9b544e 4768 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
c937aa89 4769 addReply(c,shared.outofrangeerr);
ed9b544e 4770 return;
4771 }
3305306f 4772 dst = c->db;
4773 selectDb(c,srcid); /* Back to the source DB */
ed9b544e 4774
4775 /* If the user is moving using as target the same
4776 * DB as the source DB it is probably an error. */
4777 if (src == dst) {
c937aa89 4778 addReply(c,shared.sameobjecterr);
ed9b544e 4779 return;
4780 }
4781
4782 /* Check if the element exists and get a reference */
3305306f 4783 o = lookupKeyWrite(c->db,c->argv[1]);
4784 if (!o) {
c937aa89 4785 addReply(c,shared.czero);
ed9b544e 4786 return;
4787 }
4788
4789 /* Try to add the element to the target DB */
3305306f 4790 deleteIfVolatile(dst,c->argv[1]);
4791 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
c937aa89 4792 addReply(c,shared.czero);
ed9b544e 4793 return;
4794 }
3305306f 4795 incrRefCount(c->argv[1]);
ed9b544e 4796 incrRefCount(o);
4797
4798 /* OK! key moved, free the entry in the source DB */
3305306f 4799 deleteKey(src,c->argv[1]);
ed9b544e 4800 server.dirty++;
c937aa89 4801 addReply(c,shared.cone);
ed9b544e 4802}
4803
4804/* =================================== Lists ================================ */
c7d9d662
PN
4805static void lPush(robj *subject, robj *value, int where) {
4806 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4807 int pos = (where == REDIS_HEAD) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
4808 value = getDecodedObject(value);
4809 subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),pos);
4810 decrRefCount(value);
4811 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4812 if (where == REDIS_HEAD) {
4813 listAddNodeHead(subject->ptr,value);
4814 } else {
4815 listAddNodeTail(subject->ptr,value);
4816 }
4817 incrRefCount(value);
4818 } else {
4819 redisPanic("Unknown list encoding");
4820 }
4821}
4822
d72562f7
PN
4823static robj *lPop(robj *subject, int where) {
4824 robj *value = NULL;
4825 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4826 unsigned char *p;
b6eb9703 4827 unsigned char *vstr;
d72562f7 4828 unsigned int vlen;
b6eb9703 4829 long long vlong;
d72562f7
PN
4830 int pos = (where == REDIS_HEAD) ? 0 : -1;
4831 p = ziplistIndex(subject->ptr,pos);
b6eb9703
PN
4832 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
4833 if (vstr) {
4834 value = createStringObject((char*)vstr,vlen);
d72562f7 4835 } else {
b6eb9703 4836 value = createStringObjectFromLongLong(vlong);
d72562f7 4837 }
0f62e177
PN
4838 /* We only need to delete an element when it exists */
4839 subject->ptr = ziplistDelete(subject->ptr,&p);
d72562f7 4840 }
d72562f7
PN
4841 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4842 list *list = subject->ptr;
4843 listNode *ln;
4844 if (where == REDIS_HEAD) {
4845 ln = listFirst(list);
4846 } else {
4847 ln = listLast(list);
4848 }
4849 if (ln != NULL) {
4850 value = listNodeValue(ln);
4851 incrRefCount(value);
4852 listDelNode(list,ln);
4853 }
4854 } else {
4855 redisPanic("Unknown list encoding");
4856 }
4857 return value;
4858}
4859
4860static unsigned long lLength(robj *subject) {
4861 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4862 return ziplistLen(subject->ptr);
4863 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4864 return listLength((list*)subject->ptr);
4865 } else {
4866 redisPanic("Unknown list encoding");
4867 }
4868}
4869
a6dd455b
PN
4870/* Structure to hold set iteration abstraction. */
4871typedef struct {
4872 robj *subject;
4873 unsigned char encoding;
be02a7c0 4874 unsigned char direction; /* Iteration direction */
a6dd455b
PN
4875 unsigned char *zi;
4876 listNode *ln;
4877} lIterator;
4878
be02a7c0
PN
4879/* Structure for an entry while iterating over a list. */
4880typedef struct {
4881 lIterator *li;
4882 unsigned char *zi; /* Entry in ziplist */
4883 listNode *ln; /* Entry in linked list */
4884} lEntry;
4885
a6dd455b 4886/* Initialize an iterator at the specified index. */
be02a7c0 4887static lIterator *lInitIterator(robj *subject, int index, unsigned char direction) {
a6dd455b
PN
4888 lIterator *li = zmalloc(sizeof(lIterator));
4889 li->subject = subject;
4890 li->encoding = subject->encoding;
be02a7c0 4891 li->direction = direction;
a6dd455b
PN
4892 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4893 li->zi = ziplistIndex(subject->ptr,index);
4894 } else if (li->encoding == REDIS_ENCODING_LIST) {
4895 li->ln = listIndex(subject->ptr,index);
4896 } else {
4897 redisPanic("Unknown list encoding");
4898 }
4899 return li;
4900}
4901
4902/* Clean up the iterator. */
4903static void lReleaseIterator(lIterator *li) {
4904 zfree(li);
4905}
4906
be02a7c0
PN
4907/* Stores pointer to current the entry in the provided entry structure
4908 * and advances the position of the iterator. Returns 1 when the current
4909 * entry is in fact an entry, 0 otherwise. */
4910static int lNext(lIterator *li, lEntry *entry) {
4911 entry->li = li;
d2ee16ab 4912 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
be02a7c0
PN
4913 entry->zi = li->zi;
4914 if (entry->zi != NULL) {
4915 if (li->direction == REDIS_TAIL)
4916 li->zi = ziplistNext(li->subject->ptr,li->zi);
4917 else
4918 li->zi = ziplistPrev(li->subject->ptr,li->zi);
4919 return 1;
4920 }
d2ee16ab 4921 } else if (li->encoding == REDIS_ENCODING_LIST) {
be02a7c0
PN
4922 entry->ln = li->ln;
4923 if (entry->ln != NULL) {
4924 if (li->direction == REDIS_TAIL)
4925 li->ln = li->ln->next;
4926 else
4927 li->ln = li->ln->prev;
4928 return 1;
4929 }
d2ee16ab
PN
4930 } else {
4931 redisPanic("Unknown list encoding");
4932 }
be02a7c0 4933 return 0;
d2ee16ab
PN
4934}
4935
a6dd455b 4936/* Return entry or NULL at the current position of the iterator. */
be02a7c0
PN
4937static robj *lGet(lEntry *entry) {
4938 lIterator *li = entry->li;
a6dd455b
PN
4939 robj *value = NULL;
4940 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
b6eb9703 4941 unsigned char *vstr;
a6dd455b 4942 unsigned int vlen;
b6eb9703 4943 long long vlong;
be02a7c0 4944 redisAssert(entry->zi != NULL);
b6eb9703
PN
4945 if (ziplistGet(entry->zi,&vstr,&vlen,&vlong)) {
4946 if (vstr) {
4947 value = createStringObject((char*)vstr,vlen);
a6dd455b 4948 } else {
b6eb9703 4949 value = createStringObjectFromLongLong(vlong);
a6dd455b
PN
4950 }
4951 }
4952 } else if (li->encoding == REDIS_ENCODING_LIST) {
be02a7c0
PN
4953 redisAssert(entry->ln != NULL);
4954 value = listNodeValue(entry->ln);
a6dd455b
PN
4955 incrRefCount(value);
4956 } else {
4957 redisPanic("Unknown list encoding");
4958 }
4959 return value;
4960}
4961
d2ee16ab 4962/* Compare the given object with the entry at the current position. */
be02a7c0
PN
4963static int lEqual(lEntry *entry, robj *o) {
4964 lIterator *li = entry->li;
d2ee16ab
PN
4965 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
4966 redisAssert(o->encoding == REDIS_ENCODING_RAW);
be02a7c0 4967 return ziplistCompare(entry->zi,o->ptr,sdslen(o->ptr));
d2ee16ab 4968 } else if (li->encoding == REDIS_ENCODING_LIST) {
be02a7c0 4969 return equalStringObjects(o,listNodeValue(entry->ln));
d2ee16ab
PN
4970 } else {
4971 redisPanic("Unknown list encoding");
4972 }
4973}
4974
be02a7c0
PN
4975/* Delete the element pointed to. */
4976static void lDelete(lEntry *entry) {
4977 lIterator *li = entry->li;
a6dd455b 4978 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
be02a7c0
PN
4979 unsigned char *p = entry->zi;
4980 li->subject->ptr = ziplistDelete(li->subject->ptr,&p);
4981
4982 /* Update position of the iterator depending on the direction */
4983 if (li->direction == REDIS_TAIL)
4984 li->zi = p;
a6dd455b 4985 else
be02a7c0
PN
4986 li->zi = ziplistPrev(li->subject->ptr,p);
4987 } else if (entry->li->encoding == REDIS_ENCODING_LIST) {
4988 listNode *next;
4989 if (li->direction == REDIS_TAIL)
4990 next = entry->ln->next;
a6dd455b 4991 else
be02a7c0
PN
4992 next = entry->ln->prev;
4993 listDelNode(li->subject->ptr,entry->ln);
4994 li->ln = next;
a6dd455b
PN
4995 } else {
4996 redisPanic("Unknown list encoding");
4997 }
4998}
3305306f 4999
c7d9d662
PN
5000static void pushGenericCommand(redisClient *c, int where) {
5001 robj *lobj = lookupKeyWrite(c->db,c->argv[1]);
3305306f 5002 if (lobj == NULL) {
95242ab5 5003 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
520b5a33 5004 addReply(c,shared.cone);
95242ab5 5005 return;
5006 }
c7d9d662
PN
5007 lobj = createObject(REDIS_LIST,ziplistNew());
5008 lobj->encoding = REDIS_ENCODING_ZIPLIST;
3305306f 5009 dictAdd(c->db->dict,c->argv[1],lobj);
ed9b544e 5010 incrRefCount(c->argv[1]);
ed9b544e 5011 } else {
ed9b544e 5012 if (lobj->type != REDIS_LIST) {
5013 addReply(c,shared.wrongtypeerr);
5014 return;
5015 }
95242ab5 5016 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
520b5a33 5017 addReply(c,shared.cone);
95242ab5 5018 return;
5019 }
ed9b544e 5020 }
c7d9d662
PN
5021 lPush(lobj,c->argv[2],where);
5022 addReplyLongLong(c,lLength(lobj));
ed9b544e 5023 server.dirty++;
ed9b544e 5024}
5025
5026static void lpushCommand(redisClient *c) {
5027 pushGenericCommand(c,REDIS_HEAD);
5028}
5029
5030static void rpushCommand(redisClient *c) {
5031 pushGenericCommand(c,REDIS_TAIL);
5032}
5033
5034static void llenCommand(redisClient *c) {
d72562f7
PN
5035 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.czero);
5036 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5037 addReplyUlong(c,lLength(o));
ed9b544e 5038}
5039
5040static void lindexCommand(redisClient *c) {
697bd567
PN
5041 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk);
5042 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
ed9b544e 5043 int index = atoi(c->argv[2]->ptr);
bd8db0ad 5044 robj *value = NULL;
dd88747b 5045
697bd567
PN
5046 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5047 unsigned char *p;
b6eb9703 5048 unsigned char *vstr;
697bd567 5049 unsigned int vlen;
b6eb9703 5050 long long vlong;
697bd567 5051 p = ziplistIndex(o->ptr,index);
b6eb9703
PN
5052 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
5053 if (vstr) {
5054 value = createStringObject((char*)vstr,vlen);
697bd567 5055 } else {
b6eb9703 5056 value = createStringObjectFromLongLong(vlong);
697bd567 5057 }
bd8db0ad
PN
5058 addReplyBulk(c,value);
5059 decrRefCount(value);
697bd567
PN
5060 } else {
5061 addReply(c,shared.nullbulk);
5062 }
5063 } else if (o->encoding == REDIS_ENCODING_LIST) {
5064 listNode *ln = listIndex(o->ptr,index);
5065 if (ln != NULL) {
bd8db0ad
PN
5066 value = listNodeValue(ln);
5067 addReplyBulk(c,value);
697bd567
PN
5068 } else {
5069 addReply(c,shared.nullbulk);
5070 }
ed9b544e 5071 } else {
697bd567 5072 redisPanic("Unknown list encoding");
ed9b544e 5073 }
5074}
5075
5076static void lsetCommand(redisClient *c) {
697bd567
PN
5077 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr);
5078 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
ed9b544e 5079 int index = atoi(c->argv[2]->ptr);
697bd567 5080 robj *value = c->argv[3];
dd88747b 5081
697bd567
PN
5082 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5083 unsigned char *p, *zl = o->ptr;
5084 p = ziplistIndex(zl,index);
5085 if (p == NULL) {
5086 addReply(c,shared.outofrangeerr);
5087 } else {
be02a7c0 5088 o->ptr = ziplistDelete(o->ptr,&p);
697bd567
PN
5089 value = getDecodedObject(value);
5090 o->ptr = ziplistInsert(o->ptr,p,value->ptr,sdslen(value->ptr));
5091 decrRefCount(value);
5092 addReply(c,shared.ok);
5093 server.dirty++;
5094 }
5095 } else if (o->encoding == REDIS_ENCODING_LIST) {
5096 listNode *ln = listIndex(o->ptr,index);
5097 if (ln == NULL) {
5098 addReply(c,shared.outofrangeerr);
5099 } else {
5100 decrRefCount((robj*)listNodeValue(ln));
5101 listNodeValue(ln) = value;
5102 incrRefCount(value);
5103 addReply(c,shared.ok);
5104 server.dirty++;
5105 }
ed9b544e 5106 } else {
697bd567 5107 redisPanic("Unknown list encoding");
ed9b544e 5108 }
5109}
5110
5111static void popGenericCommand(redisClient *c, int where) {
d72562f7
PN
5112 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk);
5113 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
3305306f 5114
d72562f7
PN
5115 robj *value = lPop(o,where);
5116 if (value == NULL) {
dd88747b 5117 addReply(c,shared.nullbulk);
5118 } else {
d72562f7
PN
5119 addReplyBulk(c,value);
5120 decrRefCount(value);
5121 if (lLength(o) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5122 server.dirty++;
ed9b544e 5123 }
5124}
5125
5126static void lpopCommand(redisClient *c) {
5127 popGenericCommand(c,REDIS_HEAD);
5128}
5129
5130static void rpopCommand(redisClient *c) {
5131 popGenericCommand(c,REDIS_TAIL);
5132}
5133
5134static void lrangeCommand(redisClient *c) {
a6dd455b 5135 robj *o, *value;
ed9b544e 5136 int start = atoi(c->argv[2]->ptr);
5137 int end = atoi(c->argv[3]->ptr);
dd88747b 5138 int llen;
5139 int rangelen, j;
be02a7c0 5140 lEntry entry;
dd88747b 5141
4e27f268 5142 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
5143 || checkType(c,o,REDIS_LIST)) return;
a6dd455b 5144 llen = lLength(o);
dd88747b 5145
5146 /* convert negative indexes */
5147 if (start < 0) start = llen+start;
5148 if (end < 0) end = llen+end;
5149 if (start < 0) start = 0;
5150 if (end < 0) end = 0;
5151
5152 /* indexes sanity checks */
5153 if (start > end || start >= llen) {
5154 /* Out of range start or start > end result in empty list */
5155 addReply(c,shared.emptymultibulk);
5156 return;
5157 }
5158 if (end >= llen) end = llen-1;
5159 rangelen = (end-start)+1;
3305306f 5160
dd88747b 5161 /* Return the result in form of a multi-bulk reply */
dd88747b 5162 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
be02a7c0 5163 lIterator *li = lInitIterator(o,start,REDIS_TAIL);
dd88747b 5164 for (j = 0; j < rangelen; j++) {
be02a7c0
PN
5165 redisAssert(lNext(li,&entry));
5166 value = lGet(&entry);
a6dd455b 5167 addReplyBulk(c,value);
be02a7c0 5168 decrRefCount(value);
ed9b544e 5169 }
a6dd455b 5170 lReleaseIterator(li);
ed9b544e 5171}
5172
5173static void ltrimCommand(redisClient *c) {
3305306f 5174 robj *o;
ed9b544e 5175 int start = atoi(c->argv[2]->ptr);
5176 int end = atoi(c->argv[3]->ptr);
dd88747b 5177 int llen;
5178 int j, ltrim, rtrim;
5179 list *list;
5180 listNode *ln;
5181
5182 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
5183 checkType(c,o,REDIS_LIST)) return;
9ae6b0be 5184 llen = lLength(o);
dd88747b 5185
5186 /* convert negative indexes */
5187 if (start < 0) start = llen+start;
5188 if (end < 0) end = llen+end;
5189 if (start < 0) start = 0;
5190 if (end < 0) end = 0;
5191
5192 /* indexes sanity checks */
5193 if (start > end || start >= llen) {
5194 /* Out of range start or start > end result in empty list */
5195 ltrim = llen;
5196 rtrim = 0;
ed9b544e 5197 } else {
dd88747b 5198 if (end >= llen) end = llen-1;
5199 ltrim = start;
5200 rtrim = llen-end-1;
5201 }
ed9b544e 5202
dd88747b 5203 /* Remove list elements to perform the trim */
9ae6b0be
PN
5204 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5205 o->ptr = ziplistDeleteRange(o->ptr,0,ltrim);
5206 o->ptr = ziplistDeleteRange(o->ptr,-rtrim,rtrim);
5207 } else if (o->encoding == REDIS_ENCODING_LIST) {
5208 list = o->ptr;
5209 for (j = 0; j < ltrim; j++) {
5210 ln = listFirst(list);
5211 listDelNode(list,ln);
5212 }
5213 for (j = 0; j < rtrim; j++) {
5214 ln = listLast(list);
5215 listDelNode(list,ln);
5216 }
5217 } else {
5218 redisPanic("Unknown list encoding");
ed9b544e 5219 }
9ae6b0be 5220 if (lLength(o) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5221 server.dirty++;
5222 addReply(c,shared.ok);
ed9b544e 5223}
5224
5225static void lremCommand(redisClient *c) {
d2ee16ab 5226 robj *subject, *obj = c->argv[3];
dd88747b 5227 int toremove = atoi(c->argv[2]->ptr);
5228 int removed = 0;
be02a7c0 5229 lEntry entry;
a4d1ba9a 5230
d2ee16ab
PN
5231 subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero);
5232 if (subject == NULL || checkType(c,subject,REDIS_LIST)) return;
dd88747b 5233
d2ee16ab
PN
5234 /* Make sure obj is raw when we're dealing with a ziplist */
5235 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
5236 obj = getDecodedObject(obj);
5237
5238 lIterator *li;
dd88747b 5239 if (toremove < 0) {
5240 toremove = -toremove;
be02a7c0 5241 li = lInitIterator(subject,-1,REDIS_HEAD);
d2ee16ab 5242 } else {
be02a7c0 5243 li = lInitIterator(subject,0,REDIS_TAIL);
dd88747b 5244 }
dd88747b 5245
be02a7c0
PN
5246 while (lNext(li,&entry)) {
5247 if (lEqual(&entry,obj)) {
5248 lDelete(&entry);
dd88747b 5249 server.dirty++;
5250 removed++;
3fbf9001 5251 if (toremove && removed == toremove) break;
ed9b544e 5252 }
5253 }
d2ee16ab
PN
5254 lReleaseIterator(li);
5255
5256 /* Clean up raw encoded object */
5257 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
5258 decrRefCount(obj);
5259
5260 if (lLength(subject) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5261 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
ed9b544e 5262}
5263
12f9d551 5264/* This is the semantic of this command:
0f5f7e9a 5265 * RPOPLPUSH srclist dstlist:
12f9d551 5266 * IF LLEN(srclist) > 0
5267 * element = RPOP srclist
5268 * LPUSH dstlist element
5269 * RETURN element
5270 * ELSE
5271 * RETURN nil
5272 * END
5273 * END
5274 *
5275 * The idea is to be able to get an element from a list in a reliable way
5276 * since the element is not just returned but pushed against another list
5277 * as well. This command was originally proposed by Ezra Zygmuntowicz.
5278 */
0f5f7e9a 5279static void rpoplpushcommand(redisClient *c) {
0f62e177 5280 robj *sobj, *value;
dd88747b 5281 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5282 checkType(c,sobj,REDIS_LIST)) return;
12f9d551 5283
0f62e177 5284 if (lLength(sobj) == 0) {
12f9d551 5285 addReply(c,shared.nullbulk);
5286 } else {
dd88747b 5287 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
0f62e177
PN
5288 if (dobj && checkType(c,dobj,REDIS_LIST)) return;
5289 value = lPop(sobj,REDIS_TAIL);
12f9d551 5290
dd88747b 5291 /* Add the element to the target list (unless it's directly
5292 * passed to some BLPOP-ing client */
0f62e177
PN
5293 if (!handleClientsWaitingListPush(c,c->argv[2],value)) {
5294 /* Create the list if the key does not exist */
5295 if (!dobj) {
5296 dobj = createObject(REDIS_LIST,ziplistNew());
5297 dobj->encoding = REDIS_ENCODING_ZIPLIST;
dd88747b 5298 dictAdd(c->db->dict,c->argv[2],dobj);
5299 incrRefCount(c->argv[2]);
12f9d551 5300 }
0f62e177 5301 lPush(dobj,value,REDIS_HEAD);
12f9d551 5302 }
dd88747b 5303
5304 /* Send the element to the client as reply as well */
0f62e177
PN
5305 addReplyBulk(c,value);
5306
5307 /* lPop returns an object with its refcount incremented */
5308 decrRefCount(value);
dd88747b 5309
0f62e177
PN
5310 /* Delete the source list when it is empty */
5311 if (lLength(sobj) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5312 server.dirty++;
12f9d551 5313 }
5314}
5315
ed9b544e 5316/* ==================================== Sets ================================ */
5317
5318static void saddCommand(redisClient *c) {
ed9b544e 5319 robj *set;
5320
3305306f 5321 set = lookupKeyWrite(c->db,c->argv[1]);
5322 if (set == NULL) {
ed9b544e 5323 set = createSetObject();
3305306f 5324 dictAdd(c->db->dict,c->argv[1],set);
ed9b544e 5325 incrRefCount(c->argv[1]);
5326 } else {
ed9b544e 5327 if (set->type != REDIS_SET) {
c937aa89 5328 addReply(c,shared.wrongtypeerr);
ed9b544e 5329 return;
5330 }
5331 }
5332 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
5333 incrRefCount(c->argv[2]);
5334 server.dirty++;
c937aa89 5335 addReply(c,shared.cone);
ed9b544e 5336 } else {
c937aa89 5337 addReply(c,shared.czero);
ed9b544e 5338 }
5339}
5340
5341static void sremCommand(redisClient *c) {
3305306f 5342 robj *set;
ed9b544e 5343
dd88747b 5344 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5345 checkType(c,set,REDIS_SET)) return;
5346
5347 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
5348 server.dirty++;
5349 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
3ea27d37 5350 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5351 addReply(c,shared.cone);
ed9b544e 5352 } else {
dd88747b 5353 addReply(c,shared.czero);
ed9b544e 5354 }
5355}
5356
a4460ef4 5357static void smoveCommand(redisClient *c) {
5358 robj *srcset, *dstset;
5359
5360 srcset = lookupKeyWrite(c->db,c->argv[1]);
5361 dstset = lookupKeyWrite(c->db,c->argv[2]);
5362
5363 /* If the source key does not exist return 0, if it's of the wrong type
5364 * raise an error */
5365 if (srcset == NULL || srcset->type != REDIS_SET) {
5366 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
5367 return;
5368 }
5369 /* Error if the destination key is not a set as well */
5370 if (dstset && dstset->type != REDIS_SET) {
5371 addReply(c,shared.wrongtypeerr);
5372 return;
5373 }
5374 /* Remove the element from the source set */
5375 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
5376 /* Key not found in the src set! return zero */
5377 addReply(c,shared.czero);
5378 return;
5379 }
3ea27d37 5380 if (dictSize((dict*)srcset->ptr) == 0 && srcset != dstset)
5381 deleteKey(c->db,c->argv[1]);
a4460ef4 5382 server.dirty++;
5383 /* Add the element to the destination set */
5384 if (!dstset) {
5385 dstset = createSetObject();
5386 dictAdd(c->db->dict,c->argv[2],dstset);
5387 incrRefCount(c->argv[2]);
5388 }
5389 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
5390 incrRefCount(c->argv[3]);
5391 addReply(c,shared.cone);
5392}
5393
ed9b544e 5394static void sismemberCommand(redisClient *c) {
3305306f 5395 robj *set;
ed9b544e 5396
dd88747b 5397 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5398 checkType(c,set,REDIS_SET)) return;
5399
5400 if (dictFind(set->ptr,c->argv[2]))
5401 addReply(c,shared.cone);
5402 else
c937aa89 5403 addReply(c,shared.czero);
ed9b544e 5404}
5405
5406static void scardCommand(redisClient *c) {
3305306f 5407 robj *o;
ed9b544e 5408 dict *s;
dd88747b 5409
5410 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5411 checkType(c,o,REDIS_SET)) return;
e0a62c7f 5412
dd88747b 5413 s = o->ptr;
5414 addReplyUlong(c,dictSize(s));
ed9b544e 5415}
5416
12fea928 5417static void spopCommand(redisClient *c) {
5418 robj *set;
5419 dictEntry *de;
5420
dd88747b 5421 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5422 checkType(c,set,REDIS_SET)) return;
5423
5424 de = dictGetRandomKey(set->ptr);
5425 if (de == NULL) {
12fea928 5426 addReply(c,shared.nullbulk);
5427 } else {
dd88747b 5428 robj *ele = dictGetEntryKey(de);
12fea928 5429
dd88747b 5430 addReplyBulk(c,ele);
5431 dictDelete(set->ptr,ele);
5432 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
3ea27d37 5433 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5434 server.dirty++;
12fea928 5435 }
5436}
5437
2abb95a9 5438static void srandmemberCommand(redisClient *c) {
5439 robj *set;
5440 dictEntry *de;
5441
dd88747b 5442 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5443 checkType(c,set,REDIS_SET)) return;
5444
5445 de = dictGetRandomKey(set->ptr);
5446 if (de == NULL) {
2abb95a9 5447 addReply(c,shared.nullbulk);
5448 } else {
dd88747b 5449 robj *ele = dictGetEntryKey(de);
2abb95a9 5450
dd88747b 5451 addReplyBulk(c,ele);
2abb95a9 5452 }
5453}
5454
ed9b544e 5455static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
5456 dict **d1 = (void*) s1, **d2 = (void*) s2;
5457
3305306f 5458 return dictSize(*d1)-dictSize(*d2);
ed9b544e 5459}
5460
682ac724 5461static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
ed9b544e 5462 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5463 dictIterator *di;
5464 dictEntry *de;
5465 robj *lenobj = NULL, *dstset = NULL;
682ac724 5466 unsigned long j, cardinality = 0;
ed9b544e 5467
ed9b544e 5468 for (j = 0; j < setsnum; j++) {
5469 robj *setobj;
3305306f 5470
5471 setobj = dstkey ?
5472 lookupKeyWrite(c->db,setskeys[j]) :
5473 lookupKeyRead(c->db,setskeys[j]);
5474 if (!setobj) {
ed9b544e 5475 zfree(dv);
5faa6025 5476 if (dstkey) {
fdcaae84 5477 if (deleteKey(c->db,dstkey))
5478 server.dirty++;
0d36ded0 5479 addReply(c,shared.czero);
5faa6025 5480 } else {
4e27f268 5481 addReply(c,shared.emptymultibulk);
5faa6025 5482 }
ed9b544e 5483 return;
5484 }
ed9b544e 5485 if (setobj->type != REDIS_SET) {
5486 zfree(dv);
c937aa89 5487 addReply(c,shared.wrongtypeerr);
ed9b544e 5488 return;
5489 }
5490 dv[j] = setobj->ptr;
5491 }
5492 /* Sort sets from the smallest to largest, this will improve our
5493 * algorithm's performace */
5494 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
5495
5496 /* The first thing we should output is the total number of elements...
5497 * since this is a multi-bulk write, but at this stage we don't know
5498 * the intersection set size, so we use a trick, append an empty object
5499 * to the output list and save the pointer to later modify it with the
5500 * right length */
5501 if (!dstkey) {
5502 lenobj = createObject(REDIS_STRING,NULL);
5503 addReply(c,lenobj);
5504 decrRefCount(lenobj);
5505 } else {
5506 /* If we have a target key where to store the resulting set
5507 * create this key with an empty set inside */
5508 dstset = createSetObject();
ed9b544e 5509 }
5510
5511 /* Iterate all the elements of the first (smallest) set, and test
5512 * the element against all the other sets, if at least one set does
5513 * not include the element it is discarded */
5514 di = dictGetIterator(dv[0]);
ed9b544e 5515
5516 while((de = dictNext(di)) != NULL) {
5517 robj *ele;
5518
5519 for (j = 1; j < setsnum; j++)
5520 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
5521 if (j != setsnum)
5522 continue; /* at least one set does not contain the member */
5523 ele = dictGetEntryKey(de);
5524 if (!dstkey) {
dd88747b 5525 addReplyBulk(c,ele);
ed9b544e 5526 cardinality++;
5527 } else {
5528 dictAdd(dstset->ptr,ele,NULL);
5529 incrRefCount(ele);
5530 }
5531 }
5532 dictReleaseIterator(di);
5533
83cdfe18 5534 if (dstkey) {
3ea27d37 5535 /* Store the resulting set into the target, if the intersection
5536 * is not an empty set. */
83cdfe18 5537 deleteKey(c->db,dstkey);
3ea27d37 5538 if (dictSize((dict*)dstset->ptr) > 0) {
5539 dictAdd(c->db->dict,dstkey,dstset);
5540 incrRefCount(dstkey);
482b672d 5541 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
3ea27d37 5542 } else {
5543 decrRefCount(dstset);
d36c4e97 5544 addReply(c,shared.czero);
3ea27d37 5545 }
40d224a9 5546 server.dirty++;
d36c4e97 5547 } else {
5548 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
40d224a9 5549 }
ed9b544e 5550 zfree(dv);
5551}
5552
5553static void sinterCommand(redisClient *c) {
5554 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
5555}
5556
5557static void sinterstoreCommand(redisClient *c) {
5558 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
5559}
5560
f4f56e1d 5561#define REDIS_OP_UNION 0
5562#define REDIS_OP_DIFF 1
2830ca53 5563#define REDIS_OP_INTER 2
f4f56e1d 5564
5565static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
40d224a9 5566 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5567 dictIterator *di;
5568 dictEntry *de;
f4f56e1d 5569 robj *dstset = NULL;
40d224a9 5570 int j, cardinality = 0;
5571
40d224a9 5572 for (j = 0; j < setsnum; j++) {
5573 robj *setobj;
5574
5575 setobj = dstkey ?
5576 lookupKeyWrite(c->db,setskeys[j]) :
5577 lookupKeyRead(c->db,setskeys[j]);
5578 if (!setobj) {
5579 dv[j] = NULL;
5580 continue;
5581 }
5582 if (setobj->type != REDIS_SET) {
5583 zfree(dv);
5584 addReply(c,shared.wrongtypeerr);
5585 return;
5586 }
5587 dv[j] = setobj->ptr;
5588 }
5589
5590 /* We need a temp set object to store our union. If the dstkey
5591 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5592 * this set object will be the resulting object to set into the target key*/
5593 dstset = createSetObject();
5594
40d224a9 5595 /* Iterate all the elements of all the sets, add every element a single
5596 * time to the result set */
5597 for (j = 0; j < setsnum; j++) {
51829ed3 5598 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
40d224a9 5599 if (!dv[j]) continue; /* non existing keys are like empty sets */
5600
5601 di = dictGetIterator(dv[j]);
40d224a9 5602
5603 while((de = dictNext(di)) != NULL) {
5604 robj *ele;
5605
5606 /* dictAdd will not add the same element multiple times */
5607 ele = dictGetEntryKey(de);
f4f56e1d 5608 if (op == REDIS_OP_UNION || j == 0) {
5609 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
5610 incrRefCount(ele);
40d224a9 5611 cardinality++;
5612 }
f4f56e1d 5613 } else if (op == REDIS_OP_DIFF) {
5614 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
5615 cardinality--;
5616 }
40d224a9 5617 }
5618 }
5619 dictReleaseIterator(di);
51829ed3 5620
d36c4e97 5621 /* result set is empty? Exit asap. */
5622 if (op == REDIS_OP_DIFF && cardinality == 0) break;
40d224a9 5623 }
5624
f4f56e1d 5625 /* Output the content of the resulting set, if not in STORE mode */
5626 if (!dstkey) {
5627 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
5628 di = dictGetIterator(dstset->ptr);
f4f56e1d 5629 while((de = dictNext(di)) != NULL) {
5630 robj *ele;
5631
5632 ele = dictGetEntryKey(de);
dd88747b 5633 addReplyBulk(c,ele);
f4f56e1d 5634 }
5635 dictReleaseIterator(di);
d36c4e97 5636 decrRefCount(dstset);
83cdfe18
AG
5637 } else {
5638 /* If we have a target key where to store the resulting set
5639 * create this key with the result set inside */
5640 deleteKey(c->db,dstkey);
3ea27d37 5641 if (dictSize((dict*)dstset->ptr) > 0) {
5642 dictAdd(c->db->dict,dstkey,dstset);
5643 incrRefCount(dstkey);
482b672d 5644 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
3ea27d37 5645 } else {
5646 decrRefCount(dstset);
d36c4e97 5647 addReply(c,shared.czero);
3ea27d37 5648 }
40d224a9 5649 server.dirty++;
5650 }
5651 zfree(dv);
5652}
5653
5654static void sunionCommand(redisClient *c) {
f4f56e1d 5655 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
40d224a9 5656}
5657
5658static void sunionstoreCommand(redisClient *c) {
f4f56e1d 5659 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
5660}
5661
5662static void sdiffCommand(redisClient *c) {
5663 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
5664}
5665
5666static void sdiffstoreCommand(redisClient *c) {
5667 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
40d224a9 5668}
5669
6b47e12e 5670/* ==================================== ZSets =============================== */
5671
5672/* ZSETs are ordered sets using two data structures to hold the same elements
5673 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5674 * data structure.
5675 *
5676 * The elements are added to an hash table mapping Redis objects to scores.
5677 * At the same time the elements are added to a skip list mapping scores
5678 * to Redis objects (so objects are sorted by scores in this "view"). */
5679
5680/* This skiplist implementation is almost a C translation of the original
5681 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5682 * Alternative to Balanced Trees", modified in three ways:
5683 * a) this implementation allows for repeated values.
5684 * b) the comparison is not just by key (our 'score') but by satellite data.
5685 * c) there is a back pointer, so it's a doubly linked list with the back
5686 * pointers being only at "level 1". This allows to traverse the list
5687 * from tail to head, useful for ZREVRANGE. */
5688
5689static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
5690 zskiplistNode *zn = zmalloc(sizeof(*zn));
5691
5692 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
2f4dd7e0 5693 if (level > 1)
2b37892e 5694 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
2f4dd7e0 5695 else
5696 zn->span = NULL;
6b47e12e 5697 zn->score = score;
5698 zn->obj = obj;
5699 return zn;
5700}
5701
5702static zskiplist *zslCreate(void) {
5703 int j;
5704 zskiplist *zsl;
e0a62c7f 5705
6b47e12e 5706 zsl = zmalloc(sizeof(*zsl));
5707 zsl->level = 1;
cc812361 5708 zsl->length = 0;
6b47e12e 5709 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
69d95c3e 5710 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
6b47e12e 5711 zsl->header->forward[j] = NULL;
94e543b5 5712
5713 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5714 if (j < ZSKIPLIST_MAXLEVEL-1)
5715 zsl->header->span[j] = 0;
69d95c3e 5716 }
e3870fab 5717 zsl->header->backward = NULL;
5718 zsl->tail = NULL;
6b47e12e 5719 return zsl;
5720}
5721
fd8ccf44 5722static void zslFreeNode(zskiplistNode *node) {
5723 decrRefCount(node->obj);
ad807e6f 5724 zfree(node->forward);
69d95c3e 5725 zfree(node->span);
fd8ccf44 5726 zfree(node);
5727}
5728
5729static void zslFree(zskiplist *zsl) {
ad807e6f 5730 zskiplistNode *node = zsl->header->forward[0], *next;
fd8ccf44 5731
ad807e6f 5732 zfree(zsl->header->forward);
69d95c3e 5733 zfree(zsl->header->span);
ad807e6f 5734 zfree(zsl->header);
fd8ccf44 5735 while(node) {
599379dd 5736 next = node->forward[0];
fd8ccf44 5737 zslFreeNode(node);
5738 node = next;
5739 }
ad807e6f 5740 zfree(zsl);
fd8ccf44 5741}
5742
6b47e12e 5743static int zslRandomLevel(void) {
5744 int level = 1;
5745 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
5746 level += 1;
10c2baa5 5747 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
6b47e12e 5748}
5749
5750static void zslInsert(zskiplist *zsl, double score, robj *obj) {
5751 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
2b37892e 5752 unsigned int rank[ZSKIPLIST_MAXLEVEL];
6b47e12e 5753 int i, level;
5754
5755 x = zsl->header;
5756 for (i = zsl->level-1; i >= 0; i--) {
2b37892e
PN
5757 /* store rank that is crossed to reach the insert position */
5758 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
69d95c3e 5759
9d60e6e4 5760 while (x->forward[i] &&
5761 (x->forward[i]->score < score ||
5762 (x->forward[i]->score == score &&
69d95c3e 5763 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
a50ea45c 5764 rank[i] += i > 0 ? x->span[i-1] : 1;
6b47e12e 5765 x = x->forward[i];
69d95c3e 5766 }
6b47e12e 5767 update[i] = x;
5768 }
6b47e12e 5769 /* we assume the key is not already inside, since we allow duplicated
5770 * scores, and the re-insertion of score and redis object should never
5771 * happpen since the caller of zslInsert() should test in the hash table
5772 * if the element is already inside or not. */
5773 level = zslRandomLevel();
5774 if (level > zsl->level) {
69d95c3e 5775 for (i = zsl->level; i < level; i++) {
2b37892e 5776 rank[i] = 0;
6b47e12e 5777 update[i] = zsl->header;
2b37892e 5778 update[i]->span[i-1] = zsl->length;
69d95c3e 5779 }
6b47e12e 5780 zsl->level = level;
5781 }
5782 x = zslCreateNode(level,score,obj);
5783 for (i = 0; i < level; i++) {
5784 x->forward[i] = update[i]->forward[i];
5785 update[i]->forward[i] = x;
69d95c3e
PN
5786
5787 /* update span covered by update[i] as x is inserted here */
2b37892e
PN
5788 if (i > 0) {
5789 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
5790 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
5791 }
6b47e12e 5792 }
69d95c3e
PN
5793
5794 /* increment span for untouched levels */
5795 for (i = level; i < zsl->level; i++) {
2b37892e 5796 update[i]->span[i-1]++;
69d95c3e
PN
5797 }
5798
bb975144 5799 x->backward = (update[0] == zsl->header) ? NULL : update[0];
e3870fab 5800 if (x->forward[0])
5801 x->forward[0]->backward = x;
5802 else
5803 zsl->tail = x;
cc812361 5804 zsl->length++;
6b47e12e 5805}
5806
84105336
PN
5807/* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5808void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
5809 int i;
5810 for (i = 0; i < zsl->level; i++) {
5811 if (update[i]->forward[i] == x) {
5812 if (i > 0) {
5813 update[i]->span[i-1] += x->span[i-1] - 1;
5814 }
5815 update[i]->forward[i] = x->forward[i];
5816 } else {
5817 /* invariant: i > 0, because update[0]->forward[0]
5818 * is always equal to x */
5819 update[i]->span[i-1] -= 1;
5820 }
5821 }
5822 if (x->forward[0]) {
5823 x->forward[0]->backward = x->backward;
5824 } else {
5825 zsl->tail = x->backward;
5826 }
5827 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
5828 zsl->level--;
5829 zsl->length--;
5830}
5831
50c55df5 5832/* Delete an element with matching score/object from the skiplist. */
fd8ccf44 5833static int zslDelete(zskiplist *zsl, double score, robj *obj) {
e197b441 5834 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5835 int i;
5836
5837 x = zsl->header;
5838 for (i = zsl->level-1; i >= 0; i--) {
9d60e6e4 5839 while (x->forward[i] &&
5840 (x->forward[i]->score < score ||
5841 (x->forward[i]->score == score &&
5842 compareStringObjects(x->forward[i]->obj,obj) < 0)))
e197b441 5843 x = x->forward[i];
5844 update[i] = x;
5845 }
5846 /* We may have multiple elements with the same score, what we need
5847 * is to find the element with both the right score and object. */
5848 x = x->forward[0];
bf028098 5849 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
84105336 5850 zslDeleteNode(zsl, x, update);
9d60e6e4 5851 zslFreeNode(x);
9d60e6e4 5852 return 1;
5853 } else {
5854 return 0; /* not found */
e197b441 5855 }
5856 return 0; /* not found */
fd8ccf44 5857}
5858
1807985b 5859/* Delete all the elements with score between min and max from the skiplist.
5860 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5861 * Note that this function takes the reference to the hash table view of the
5862 * sorted set, in order to remove the elements from the hash table too. */
f84d3933 5863static unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
1807985b 5864 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5865 unsigned long removed = 0;
5866 int i;
5867
5868 x = zsl->header;
5869 for (i = zsl->level-1; i >= 0; i--) {
5870 while (x->forward[i] && x->forward[i]->score < min)
5871 x = x->forward[i];
5872 update[i] = x;
5873 }
5874 /* We may have multiple elements with the same score, what we need
5875 * is to find the element with both the right score and object. */
5876 x = x->forward[0];
5877 while (x && x->score <= max) {
84105336
PN
5878 zskiplistNode *next = x->forward[0];
5879 zslDeleteNode(zsl, x, update);
1807985b 5880 dictDelete(dict,x->obj);
5881 zslFreeNode(x);
1807985b 5882 removed++;
5883 x = next;
5884 }
5885 return removed; /* not found */
5886}
1807985b 5887
9212eafd 5888/* Delete all the elements with rank between start and end from the skiplist.
2424490f 5889 * Start and end are inclusive. Note that start and end need to be 1-based */
9212eafd
PN
5890static unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
5891 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5892 unsigned long traversed = 0, removed = 0;
5893 int i;
5894
9212eafd
PN
5895 x = zsl->header;
5896 for (i = zsl->level-1; i >= 0; i--) {
5897 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
5898 traversed += i > 0 ? x->span[i-1] : 1;
5899 x = x->forward[i];
1807985b 5900 }
9212eafd
PN
5901 update[i] = x;
5902 }
5903
5904 traversed++;
5905 x = x->forward[0];
5906 while (x && traversed <= end) {
84105336
PN
5907 zskiplistNode *next = x->forward[0];
5908 zslDeleteNode(zsl, x, update);
1807985b 5909 dictDelete(dict,x->obj);
5910 zslFreeNode(x);
1807985b 5911 removed++;
9212eafd 5912 traversed++;
1807985b 5913 x = next;
5914 }
9212eafd 5915 return removed;
1807985b 5916}
5917
50c55df5 5918/* Find the first node having a score equal or greater than the specified one.
5919 * Returns NULL if there is no match. */
5920static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
5921 zskiplistNode *x;
5922 int i;
5923
5924 x = zsl->header;
5925 for (i = zsl->level-1; i >= 0; i--) {
5926 while (x->forward[i] && x->forward[i]->score < score)
5927 x = x->forward[i];
5928 }
5929 /* We may have multiple elements with the same score, what we need
5930 * is to find the element with both the right score and object. */
5931 return x->forward[0];
5932}
5933
27b0ccca
PN
5934/* Find the rank for an element by both score and key.
5935 * Returns 0 when the element cannot be found, rank otherwise.
5936 * Note that the rank is 1-based due to the span of zsl->header to the
5937 * first element. */
5938static unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
5939 zskiplistNode *x;
5940 unsigned long rank = 0;
5941 int i;
5942
5943 x = zsl->header;
5944 for (i = zsl->level-1; i >= 0; i--) {
5945 while (x->forward[i] &&
5946 (x->forward[i]->score < score ||
5947 (x->forward[i]->score == score &&
5948 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
a50ea45c 5949 rank += i > 0 ? x->span[i-1] : 1;
27b0ccca
PN
5950 x = x->forward[i];
5951 }
5952
5953 /* x might be equal to zsl->header, so test if obj is non-NULL */
bf028098 5954 if (x->obj && equalStringObjects(x->obj,o)) {
27b0ccca
PN
5955 return rank;
5956 }
5957 }
5958 return 0;
5959}
5960
e74825c2
PN
5961/* Finds an element by its rank. The rank argument needs to be 1-based. */
5962zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
5963 zskiplistNode *x;
5964 unsigned long traversed = 0;
5965 int i;
5966
5967 x = zsl->header;
5968 for (i = zsl->level-1; i >= 0; i--) {
dd88747b 5969 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
5970 {
a50ea45c 5971 traversed += i > 0 ? x->span[i-1] : 1;
e74825c2
PN
5972 x = x->forward[i];
5973 }
e74825c2
PN
5974 if (traversed == rank) {
5975 return x;
5976 }
5977 }
5978 return NULL;
5979}
5980
fd8ccf44 5981/* The actual Z-commands implementations */
5982
7db723ad 5983/* This generic command implements both ZADD and ZINCRBY.
e2665397 5984 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
7db723ad 5985 * the increment if the operation is a ZINCRBY (doincrement == 1). */
e2665397 5986static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
fd8ccf44 5987 robj *zsetobj;
5988 zset *zs;
5989 double *score;
5990
5fc9229c 5991 if (isnan(scoreval)) {
5992 addReplySds(c,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
5993 return;
5994 }
5995
e2665397 5996 zsetobj = lookupKeyWrite(c->db,key);
fd8ccf44 5997 if (zsetobj == NULL) {
5998 zsetobj = createZsetObject();
e2665397 5999 dictAdd(c->db->dict,key,zsetobj);
6000 incrRefCount(key);
fd8ccf44 6001 } else {
6002 if (zsetobj->type != REDIS_ZSET) {
6003 addReply(c,shared.wrongtypeerr);
6004 return;
6005 }
6006 }
fd8ccf44 6007 zs = zsetobj->ptr;
e2665397 6008
7db723ad 6009 /* Ok now since we implement both ZADD and ZINCRBY here the code
e2665397 6010 * needs to handle the two different conditions. It's all about setting
6011 * '*score', that is, the new score to set, to the right value. */
6012 score = zmalloc(sizeof(double));
6013 if (doincrement) {
6014 dictEntry *de;
6015
6016 /* Read the old score. If the element was not present starts from 0 */
6017 de = dictFind(zs->dict,ele);
6018 if (de) {
6019 double *oldscore = dictGetEntryVal(de);
6020 *score = *oldscore + scoreval;
6021 } else {
6022 *score = scoreval;
6023 }
5fc9229c 6024 if (isnan(*score)) {
6025 addReplySds(c,
6026 sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
6027 zfree(score);
6028 /* Note that we don't need to check if the zset may be empty and
6029 * should be removed here, as we can only obtain Nan as score if
6030 * there was already an element in the sorted set. */
6031 return;
6032 }
e2665397 6033 } else {
6034 *score = scoreval;
6035 }
6036
6037 /* What follows is a simple remove and re-insert operation that is common
7db723ad 6038 * to both ZADD and ZINCRBY... */
e2665397 6039 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
fd8ccf44 6040 /* case 1: New element */
e2665397 6041 incrRefCount(ele); /* added to hash */
6042 zslInsert(zs->zsl,*score,ele);
6043 incrRefCount(ele); /* added to skiplist */
fd8ccf44 6044 server.dirty++;
e2665397 6045 if (doincrement)
e2665397 6046 addReplyDouble(c,*score);
91d71bfc 6047 else
6048 addReply(c,shared.cone);
fd8ccf44 6049 } else {
6050 dictEntry *de;
6051 double *oldscore;
e0a62c7f 6052
fd8ccf44 6053 /* case 2: Score update operation */
e2665397 6054 de = dictFind(zs->dict,ele);
dfc5e96c 6055 redisAssert(de != NULL);
fd8ccf44 6056 oldscore = dictGetEntryVal(de);
6057 if (*score != *oldscore) {
6058 int deleted;
6059
e2665397 6060 /* Remove and insert the element in the skip list with new score */
6061 deleted = zslDelete(zs->zsl,*oldscore,ele);
dfc5e96c 6062 redisAssert(deleted != 0);
e2665397 6063 zslInsert(zs->zsl,*score,ele);
6064 incrRefCount(ele);
6065 /* Update the score in the hash table */
6066 dictReplace(zs->dict,ele,score);
fd8ccf44 6067 server.dirty++;
2161a965 6068 } else {
6069 zfree(score);
fd8ccf44 6070 }
e2665397 6071 if (doincrement)
6072 addReplyDouble(c,*score);
6073 else
6074 addReply(c,shared.czero);
fd8ccf44 6075 }
6076}
6077
e2665397 6078static void zaddCommand(redisClient *c) {
6079 double scoreval;
6080
bd79a6bd 6081 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
e2665397 6082 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
6083}
6084
7db723ad 6085static void zincrbyCommand(redisClient *c) {
e2665397 6086 double scoreval;
6087
bd79a6bd 6088 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
e2665397 6089 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
6090}
6091
1b7106e7 6092static void zremCommand(redisClient *c) {
6093 robj *zsetobj;
6094 zset *zs;
dd88747b 6095 dictEntry *de;
6096 double *oldscore;
6097 int deleted;
1b7106e7 6098
dd88747b 6099 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6100 checkType(c,zsetobj,REDIS_ZSET)) return;
1b7106e7 6101
dd88747b 6102 zs = zsetobj->ptr;
6103 de = dictFind(zs->dict,c->argv[2]);
6104 if (de == NULL) {
6105 addReply(c,shared.czero);
6106 return;
1b7106e7 6107 }
dd88747b 6108 /* Delete from the skiplist */
6109 oldscore = dictGetEntryVal(de);
6110 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
6111 redisAssert(deleted != 0);
6112
6113 /* Delete from the hash table */
6114 dictDelete(zs->dict,c->argv[2]);
6115 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
3ea27d37 6116 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 6117 server.dirty++;
6118 addReply(c,shared.cone);
1b7106e7 6119}
6120
1807985b 6121static void zremrangebyscoreCommand(redisClient *c) {
bbe025e0
AM
6122 double min;
6123 double max;
dd88747b 6124 long deleted;
1807985b 6125 robj *zsetobj;
6126 zset *zs;
6127
bd79a6bd
PN
6128 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
6129 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
bbe025e0 6130
dd88747b 6131 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6132 checkType(c,zsetobj,REDIS_ZSET)) return;
1807985b 6133
dd88747b 6134 zs = zsetobj->ptr;
6135 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
6136 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
3ea27d37 6137 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 6138 server.dirty += deleted;
482b672d 6139 addReplyLongLong(c,deleted);
1807985b 6140}
6141
9212eafd 6142static void zremrangebyrankCommand(redisClient *c) {
bbe025e0
AM
6143 long start;
6144 long end;
dd88747b 6145 int llen;
6146 long deleted;
9212eafd
PN
6147 robj *zsetobj;
6148 zset *zs;
6149
bd79a6bd
PN
6150 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6151 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
bbe025e0 6152
dd88747b 6153 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6154 checkType(c,zsetobj,REDIS_ZSET)) return;
6155 zs = zsetobj->ptr;
6156 llen = zs->zsl->length;
9212eafd 6157
dd88747b 6158 /* convert negative indexes */
6159 if (start < 0) start = llen+start;
6160 if (end < 0) end = llen+end;
6161 if (start < 0) start = 0;
6162 if (end < 0) end = 0;
9212eafd 6163
dd88747b 6164 /* indexes sanity checks */
6165 if (start > end || start >= llen) {
6166 addReply(c,shared.czero);
6167 return;
9212eafd 6168 }
dd88747b 6169 if (end >= llen) end = llen-1;
6170
6171 /* increment start and end because zsl*Rank functions
6172 * use 1-based rank */
6173 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
6174 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
3ea27d37 6175 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 6176 server.dirty += deleted;
482b672d 6177 addReplyLongLong(c, deleted);
9212eafd
PN
6178}
6179
8f92e768
PN
6180typedef struct {
6181 dict *dict;
6182 double weight;
6183} zsetopsrc;
6184
6185static int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
6186 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
6187 unsigned long size1, size2;
6188 size1 = d1->dict ? dictSize(d1->dict) : 0;
6189 size2 = d2->dict ? dictSize(d2->dict) : 0;
6190 return size1 - size2;
6191}
6192
d2764cd6
PN
6193#define REDIS_AGGR_SUM 1
6194#define REDIS_AGGR_MIN 2
6195#define REDIS_AGGR_MAX 3
bc000c1d 6196#define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
d2764cd6
PN
6197
6198inline static void zunionInterAggregate(double *target, double val, int aggregate) {
6199 if (aggregate == REDIS_AGGR_SUM) {
6200 *target = *target + val;
6201 } else if (aggregate == REDIS_AGGR_MIN) {
6202 *target = val < *target ? val : *target;
6203 } else if (aggregate == REDIS_AGGR_MAX) {
6204 *target = val > *target ? val : *target;
6205 } else {
6206 /* safety net */
f83c6cb5 6207 redisPanic("Unknown ZUNION/INTER aggregate type");
d2764cd6
PN
6208 }
6209}
6210
2830ca53 6211static void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
bc000c1d 6212 int i, j, setnum;
d2764cd6 6213 int aggregate = REDIS_AGGR_SUM;
8f92e768 6214 zsetopsrc *src;
2830ca53
PN
6215 robj *dstobj;
6216 zset *dstzset;
b287c9bb
PN
6217 dictIterator *di;
6218 dictEntry *de;
6219
bc000c1d
JC
6220 /* expect setnum input keys to be given */
6221 setnum = atoi(c->argv[2]->ptr);
6222 if (setnum < 1) {
5d373da9 6223 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
2830ca53 6224 return;
b287c9bb 6225 }
2830ca53
PN
6226
6227 /* test if the expected number of keys would overflow */
bc000c1d 6228 if (3+setnum > c->argc) {
b287c9bb
PN
6229 addReply(c,shared.syntaxerr);
6230 return;
6231 }
6232
2830ca53 6233 /* read keys to be used for input */
bc000c1d
JC
6234 src = zmalloc(sizeof(zsetopsrc) * setnum);
6235 for (i = 0, j = 3; i < setnum; i++, j++) {
6236 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
6237 if (!obj) {
8f92e768 6238 src[i].dict = NULL;
b287c9bb 6239 } else {
bc000c1d
JC
6240 if (obj->type == REDIS_ZSET) {
6241 src[i].dict = ((zset*)obj->ptr)->dict;
6242 } else if (obj->type == REDIS_SET) {
6243 src[i].dict = (obj->ptr);
6244 } else {
8f92e768 6245 zfree(src);
b287c9bb
PN
6246 addReply(c,shared.wrongtypeerr);
6247 return;
6248 }
b287c9bb 6249 }
2830ca53
PN
6250
6251 /* default all weights to 1 */
8f92e768 6252 src[i].weight = 1.0;
b287c9bb
PN
6253 }
6254
2830ca53
PN
6255 /* parse optional extra arguments */
6256 if (j < c->argc) {
d2764cd6 6257 int remaining = c->argc - j;
b287c9bb 6258
2830ca53 6259 while (remaining) {
bc000c1d 6260 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
2830ca53 6261 j++; remaining--;
bc000c1d 6262 for (i = 0; i < setnum; i++, j++, remaining--) {
bd79a6bd 6263 if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK)
bbe025e0 6264 return;
2830ca53 6265 }
d2764cd6
PN
6266 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
6267 j++; remaining--;
6268 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
6269 aggregate = REDIS_AGGR_SUM;
6270 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
6271 aggregate = REDIS_AGGR_MIN;
6272 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
6273 aggregate = REDIS_AGGR_MAX;
6274 } else {
6275 zfree(src);
6276 addReply(c,shared.syntaxerr);
6277 return;
6278 }
6279 j++; remaining--;
2830ca53 6280 } else {
8f92e768 6281 zfree(src);
2830ca53
PN
6282 addReply(c,shared.syntaxerr);
6283 return;
6284 }
6285 }
6286 }
b287c9bb 6287
d2764cd6
PN
6288 /* sort sets from the smallest to largest, this will improve our
6289 * algorithm's performance */
bc000c1d 6290 qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);
d2764cd6 6291
2830ca53
PN
6292 dstobj = createZsetObject();
6293 dstzset = dstobj->ptr;
6294
6295 if (op == REDIS_OP_INTER) {
8f92e768
PN
6296 /* skip going over all entries if the smallest zset is NULL or empty */
6297 if (src[0].dict && dictSize(src[0].dict) > 0) {
6298 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6299 * from small to large, all src[i > 0].dict are non-empty too */
6300 di = dictGetIterator(src[0].dict);
2830ca53 6301 while((de = dictNext(di)) != NULL) {
d2764cd6 6302 double *score = zmalloc(sizeof(double)), value;
bc000c1d 6303 *score = src[0].weight * zunionInterDictValue(de);
2830ca53 6304
bc000c1d 6305 for (j = 1; j < setnum; j++) {
d2764cd6 6306 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
2830ca53 6307 if (other) {
bc000c1d 6308 value = src[j].weight * zunionInterDictValue(other);
d2764cd6 6309 zunionInterAggregate(score, value, aggregate);
2830ca53
PN
6310 } else {
6311 break;
6312 }
6313 }
b287c9bb 6314
2830ca53 6315 /* skip entry when not present in every source dict */
bc000c1d 6316 if (j != setnum) {
2830ca53
PN
6317 zfree(score);
6318 } else {
6319 robj *o = dictGetEntryKey(de);
6320 dictAdd(dstzset->dict,o,score);
6321 incrRefCount(o); /* added to dictionary */
6322 zslInsert(dstzset->zsl,*score,o);
6323 incrRefCount(o); /* added to skiplist */
b287c9bb
PN
6324 }
6325 }
2830ca53
PN
6326 dictReleaseIterator(di);
6327 }
6328 } else if (op == REDIS_OP_UNION) {
bc000c1d 6329 for (i = 0; i < setnum; i++) {
8f92e768 6330 if (!src[i].dict) continue;
2830ca53 6331
8f92e768 6332 di = dictGetIterator(src[i].dict);
2830ca53
PN
6333 while((de = dictNext(di)) != NULL) {
6334 /* skip key when already processed */
6335 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
6336
d2764cd6 6337 double *score = zmalloc(sizeof(double)), value;
bc000c1d 6338 *score = src[i].weight * zunionInterDictValue(de);
2830ca53 6339
d2764cd6
PN
6340 /* because the zsets are sorted by size, its only possible
6341 * for sets at larger indices to hold this entry */
bc000c1d 6342 for (j = (i+1); j < setnum; j++) {
d2764cd6 6343 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
2830ca53 6344 if (other) {
bc000c1d 6345 value = src[j].weight * zunionInterDictValue(other);
d2764cd6 6346 zunionInterAggregate(score, value, aggregate);
2830ca53
PN
6347 }
6348 }
b287c9bb 6349
2830ca53
PN
6350 robj *o = dictGetEntryKey(de);
6351 dictAdd(dstzset->dict,o,score);
6352 incrRefCount(o); /* added to dictionary */
6353 zslInsert(dstzset->zsl,*score,o);
6354 incrRefCount(o); /* added to skiplist */
6355 }
6356 dictReleaseIterator(di);
b287c9bb 6357 }
2830ca53
PN
6358 } else {
6359 /* unknown operator */
6360 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
b287c9bb
PN
6361 }
6362
6363 deleteKey(c->db,dstkey);
3ea27d37 6364 if (dstzset->zsl->length) {
6365 dictAdd(c->db->dict,dstkey,dstobj);
6366 incrRefCount(dstkey);
482b672d 6367 addReplyLongLong(c, dstzset->zsl->length);
3ea27d37 6368 server.dirty++;
6369 } else {
8bca8773 6370 decrRefCount(dstobj);
3ea27d37 6371 addReply(c, shared.czero);
6372 }
8f92e768 6373 zfree(src);
b287c9bb
PN
6374}
6375
5d373da9 6376static void zunionstoreCommand(redisClient *c) {
2830ca53 6377 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
b287c9bb
PN
6378}
6379
5d373da9 6380static void zinterstoreCommand(redisClient *c) {
2830ca53 6381 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
b287c9bb
PN
6382}
6383
e3870fab 6384static void zrangeGenericCommand(redisClient *c, int reverse) {
cc812361 6385 robj *o;
bbe025e0
AM
6386 long start;
6387 long end;
752da584 6388 int withscores = 0;
dd88747b 6389 int llen;
6390 int rangelen, j;
6391 zset *zsetobj;
6392 zskiplist *zsl;
6393 zskiplistNode *ln;
6394 robj *ele;
752da584 6395
bd79a6bd
PN
6396 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6397 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
bbe025e0 6398
752da584 6399 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
6400 withscores = 1;
6401 } else if (c->argc >= 5) {
6402 addReply(c,shared.syntaxerr);
6403 return;
6404 }
cc812361 6405
4e27f268 6406 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6407 || checkType(c,o,REDIS_ZSET)) return;
dd88747b 6408 zsetobj = o->ptr;
6409 zsl = zsetobj->zsl;
6410 llen = zsl->length;
cc812361 6411
dd88747b 6412 /* convert negative indexes */
6413 if (start < 0) start = llen+start;
6414 if (end < 0) end = llen+end;
6415 if (start < 0) start = 0;
6416 if (end < 0) end = 0;
cc812361 6417
dd88747b 6418 /* indexes sanity checks */
6419 if (start > end || start >= llen) {
6420 /* Out of range start or start > end result in empty list */
6421 addReply(c,shared.emptymultibulk);
6422 return;
6423 }
6424 if (end >= llen) end = llen-1;
6425 rangelen = (end-start)+1;
cc812361 6426
dd88747b 6427 /* check if starting point is trivial, before searching
6428 * the element in log(N) time */
6429 if (reverse) {
6430 ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start);
6431 } else {
6432 ln = start == 0 ?
6433 zsl->header->forward[0] : zslGetElementByRank(zsl, start+1);
6434 }
cc812361 6435
dd88747b 6436 /* Return the result in form of a multi-bulk reply */
6437 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
6438 withscores ? (rangelen*2) : rangelen));
6439 for (j = 0; j < rangelen; j++) {
6440 ele = ln->obj;
6441 addReplyBulk(c,ele);
6442 if (withscores)
6443 addReplyDouble(c,ln->score);
6444 ln = reverse ? ln->backward : ln->forward[0];
cc812361 6445 }
6446}
6447
e3870fab 6448static void zrangeCommand(redisClient *c) {
6449 zrangeGenericCommand(c,0);
6450}
6451
6452static void zrevrangeCommand(redisClient *c) {
6453 zrangeGenericCommand(c,1);
6454}
6455
f44dd428 6456/* This command implements both ZRANGEBYSCORE and ZCOUNT.
6457 * If justcount is non-zero, just the count is returned. */
6458static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
50c55df5 6459 robj *o;
f44dd428 6460 double min, max;
6461 int minex = 0, maxex = 0; /* are min or max exclusive? */
80181f78 6462 int offset = 0, limit = -1;
0500ef27
SH
6463 int withscores = 0;
6464 int badsyntax = 0;
6465
f44dd428 6466 /* Parse the min-max interval. If one of the values is prefixed
6467 * by the "(" character, it's considered "open". For instance
6468 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6469 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6470 if (((char*)c->argv[2]->ptr)[0] == '(') {
6471 min = strtod((char*)c->argv[2]->ptr+1,NULL);
6472 minex = 1;
6473 } else {
6474 min = strtod(c->argv[2]->ptr,NULL);
6475 }
6476 if (((char*)c->argv[3]->ptr)[0] == '(') {
6477 max = strtod((char*)c->argv[3]->ptr+1,NULL);
6478 maxex = 1;
6479 } else {
6480 max = strtod(c->argv[3]->ptr,NULL);
6481 }
6482
6483 /* Parse "WITHSCORES": note that if the command was called with
6484 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6485 * enter the following paths to parse WITHSCORES and LIMIT. */
0500ef27 6486 if (c->argc == 5 || c->argc == 8) {
3a3978b1 6487 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
6488 withscores = 1;
6489 else
6490 badsyntax = 1;
0500ef27 6491 }
3a3978b1 6492 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
0500ef27 6493 badsyntax = 1;
0500ef27 6494 if (badsyntax) {
454d4e43 6495 addReplySds(c,
6496 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
80181f78 6497 return;
0500ef27
SH
6498 }
6499
f44dd428 6500 /* Parse "LIMIT" */
0500ef27 6501 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
80181f78 6502 addReply(c,shared.syntaxerr);
6503 return;
0500ef27 6504 } else if (c->argc == (7 + withscores)) {
80181f78 6505 offset = atoi(c->argv[5]->ptr);
6506 limit = atoi(c->argv[6]->ptr);
0b13687c 6507 if (offset < 0) offset = 0;
80181f78 6508 }
50c55df5 6509
f44dd428 6510 /* Ok, lookup the key and get the range */
50c55df5 6511 o = lookupKeyRead(c->db,c->argv[1]);
6512 if (o == NULL) {
4e27f268 6513 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
50c55df5 6514 } else {
6515 if (o->type != REDIS_ZSET) {
6516 addReply(c,shared.wrongtypeerr);
6517 } else {
6518 zset *zsetobj = o->ptr;
6519 zskiplist *zsl = zsetobj->zsl;
6520 zskiplistNode *ln;
f44dd428 6521 robj *ele, *lenobj = NULL;
6522 unsigned long rangelen = 0;
50c55df5 6523
f44dd428 6524 /* Get the first node with the score >= min, or with
6525 * score > min if 'minex' is true. */
50c55df5 6526 ln = zslFirstWithScore(zsl,min);
f44dd428 6527 while (minex && ln && ln->score == min) ln = ln->forward[0];
6528
50c55df5 6529 if (ln == NULL) {
6530 /* No element matching the speciifed interval */
f44dd428 6531 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
50c55df5 6532 return;
6533 }
6534
6535 /* We don't know in advance how many matching elements there
6536 * are in the list, so we push this object that will represent
6537 * the multi-bulk length in the output buffer, and will "fix"
6538 * it later */
f44dd428 6539 if (!justcount) {
6540 lenobj = createObject(REDIS_STRING,NULL);
6541 addReply(c,lenobj);
6542 decrRefCount(lenobj);
6543 }
50c55df5 6544
f44dd428 6545 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
80181f78 6546 if (offset) {
6547 offset--;
6548 ln = ln->forward[0];
6549 continue;
6550 }
6551 if (limit == 0) break;
f44dd428 6552 if (!justcount) {
6553 ele = ln->obj;
dd88747b 6554 addReplyBulk(c,ele);
f44dd428 6555 if (withscores)
6556 addReplyDouble(c,ln->score);
6557 }
50c55df5 6558 ln = ln->forward[0];
6559 rangelen++;
80181f78 6560 if (limit > 0) limit--;
50c55df5 6561 }
f44dd428 6562 if (justcount) {
482b672d 6563 addReplyLongLong(c,(long)rangelen);
f44dd428 6564 } else {
6565 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
6566 withscores ? (rangelen*2) : rangelen);
6567 }
50c55df5 6568 }
6569 }
6570}
6571
f44dd428 6572static void zrangebyscoreCommand(redisClient *c) {
6573 genericZrangebyscoreCommand(c,0);
6574}
6575
6576static void zcountCommand(redisClient *c) {
6577 genericZrangebyscoreCommand(c,1);
6578}
6579
3c41331e 6580static void zcardCommand(redisClient *c) {
e197b441 6581 robj *o;
6582 zset *zs;
dd88747b 6583
6584 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6585 checkType(c,o,REDIS_ZSET)) return;
6586
6587 zs = o->ptr;
6588 addReplyUlong(c,zs->zsl->length);
e197b441 6589}
6590
6e333bbe 6591static void zscoreCommand(redisClient *c) {
6592 robj *o;
6593 zset *zs;
dd88747b 6594 dictEntry *de;
6595
6596 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6597 checkType(c,o,REDIS_ZSET)) return;
6598
6599 zs = o->ptr;
6600 de = dictFind(zs->dict,c->argv[2]);
6601 if (!de) {
96d8b4ee 6602 addReply(c,shared.nullbulk);
6e333bbe 6603 } else {
dd88747b 6604 double *score = dictGetEntryVal(de);
6e333bbe 6605
dd88747b 6606 addReplyDouble(c,*score);
6e333bbe 6607 }
6608}
6609
798d9e55 6610static void zrankGenericCommand(redisClient *c, int reverse) {
69d95c3e 6611 robj *o;
dd88747b 6612 zset *zs;
6613 zskiplist *zsl;
6614 dictEntry *de;
6615 unsigned long rank;
6616 double *score;
6617
6618 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6619 checkType(c,o,REDIS_ZSET)) return;
6620
6621 zs = o->ptr;
6622 zsl = zs->zsl;
6623 de = dictFind(zs->dict,c->argv[2]);
6624 if (!de) {
69d95c3e
PN
6625 addReply(c,shared.nullbulk);
6626 return;
6627 }
69d95c3e 6628
dd88747b 6629 score = dictGetEntryVal(de);
6630 rank = zslGetRank(zsl, *score, c->argv[2]);
6631 if (rank) {
6632 if (reverse) {
482b672d 6633 addReplyLongLong(c, zsl->length - rank);
27b0ccca 6634 } else {
482b672d 6635 addReplyLongLong(c, rank-1);
69d95c3e 6636 }
dd88747b 6637 } else {
6638 addReply(c,shared.nullbulk);
978c2c94 6639 }
6640}
6641
798d9e55
PN
6642static void zrankCommand(redisClient *c) {
6643 zrankGenericCommand(c, 0);
6644}
6645
6646static void zrevrankCommand(redisClient *c) {
6647 zrankGenericCommand(c, 1);
6648}
6649
7fb16bac
PN
6650/* ========================= Hashes utility functions ======================= */
6651#define REDIS_HASH_KEY 1
6652#define REDIS_HASH_VALUE 2
978c2c94 6653
7fb16bac
PN
6654/* Check the length of a number of objects to see if we need to convert a
6655 * zipmap to a real hash. Note that we only check string encoded objects
6656 * as their string length can be queried in constant time. */
6657static void hashTryConversion(robj *subject, robj **argv, int start, int end) {
6658 int i;
6659 if (subject->encoding != REDIS_ENCODING_ZIPMAP) return;
978c2c94 6660
7fb16bac
PN
6661 for (i = start; i <= end; i++) {
6662 if (argv[i]->encoding == REDIS_ENCODING_RAW &&
6663 sdslen(argv[i]->ptr) > server.hash_max_zipmap_value)
6664 {
6665 convertToRealHash(subject);
978c2c94 6666 return;
6667 }
6668 }
7fb16bac 6669}
bae2c7ec 6670
97224de7
PN
6671/* Encode given objects in-place when the hash uses a dict. */
6672static void hashTryObjectEncoding(robj *subject, robj **o1, robj **o2) {
6673 if (subject->encoding == REDIS_ENCODING_HT) {
3f973463
PN
6674 if (o1) *o1 = tryObjectEncoding(*o1);
6675 if (o2) *o2 = tryObjectEncoding(*o2);
97224de7
PN
6676 }
6677}
6678
7fb16bac 6679/* Get the value from a hash identified by key. Returns either a string
a3f3af86
PN
6680 * object or NULL if the value cannot be found. The refcount of the object
6681 * is always increased by 1 when the value was found. */
7fb16bac
PN
6682static robj *hashGet(robj *o, robj *key) {
6683 robj *value = NULL;
978c2c94 6684 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
7fb16bac
PN
6685 unsigned char *v;
6686 unsigned int vlen;
6687 key = getDecodedObject(key);
6688 if (zipmapGet(o->ptr,key->ptr,sdslen(key->ptr),&v,&vlen)) {
6689 value = createStringObject((char*)v,vlen);
6690 }
6691 decrRefCount(key);
6692 } else {
6693 dictEntry *de = dictFind(o->ptr,key);
6694 if (de != NULL) {
6695 value = dictGetEntryVal(de);
a3f3af86 6696 incrRefCount(value);
7fb16bac
PN
6697 }
6698 }
6699 return value;
6700}
978c2c94 6701
7fb16bac
PN
6702/* Test if the key exists in the given hash. Returns 1 if the key
6703 * exists and 0 when it doesn't. */
6704static int hashExists(robj *o, robj *key) {
6705 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6706 key = getDecodedObject(key);
6707 if (zipmapExists(o->ptr,key->ptr,sdslen(key->ptr))) {
6708 decrRefCount(key);
6709 return 1;
6710 }
6711 decrRefCount(key);
6712 } else {
6713 if (dictFind(o->ptr,key) != NULL) {
6714 return 1;
6715 }
6716 }
6717 return 0;
6718}
bae2c7ec 6719
7fb16bac
PN
6720/* Add an element, discard the old if the key already exists.
6721 * Return 0 on insert and 1 on update. */
feb8d7e6 6722static int hashSet(robj *o, robj *key, robj *value) {
7fb16bac
PN
6723 int update = 0;
6724 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6725 key = getDecodedObject(key);
6726 value = getDecodedObject(value);
6727 o->ptr = zipmapSet(o->ptr,
6728 key->ptr,sdslen(key->ptr),
6729 value->ptr,sdslen(value->ptr), &update);
6730 decrRefCount(key);
6731 decrRefCount(value);
6732
6733 /* Check if the zipmap needs to be upgraded to a real hash table */
6734 if (zipmapLen(o->ptr) > server.hash_max_zipmap_entries)
bae2c7ec 6735 convertToRealHash(o);
978c2c94 6736 } else {
7fb16bac
PN
6737 if (dictReplace(o->ptr,key,value)) {
6738 /* Insert */
6739 incrRefCount(key);
978c2c94 6740 } else {
7fb16bac 6741 /* Update */
978c2c94 6742 update = 1;
6743 }
7fb16bac 6744 incrRefCount(value);
978c2c94 6745 }
7fb16bac 6746 return update;
978c2c94 6747}
6748
7fb16bac
PN
6749/* Delete an element from a hash.
6750 * Return 1 on deleted and 0 on not found. */
6751static int hashDelete(robj *o, robj *key) {
6752 int deleted = 0;
6753 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6754 key = getDecodedObject(key);
6755 o->ptr = zipmapDel(o->ptr,key->ptr,sdslen(key->ptr), &deleted);
6756 decrRefCount(key);
6757 } else {
6758 deleted = dictDelete((dict*)o->ptr,key) == DICT_OK;
6759 /* Always check if the dictionary needs a resize after a delete. */
6760 if (deleted && htNeedsResize(o->ptr)) dictResize(o->ptr);
d33278d1 6761 }
7fb16bac
PN
6762 return deleted;
6763}
d33278d1 6764
7fb16bac 6765/* Return the number of elements in a hash. */
c811bb38 6766static unsigned long hashLength(robj *o) {
7fb16bac
PN
6767 return (o->encoding == REDIS_ENCODING_ZIPMAP) ?
6768 zipmapLen((unsigned char*)o->ptr) : dictSize((dict*)o->ptr);
6769}
6770
6771/* Structure to hold hash iteration abstration. Note that iteration over
6772 * hashes involves both fields and values. Because it is possible that
6773 * not both are required, store pointers in the iterator to avoid
6774 * unnecessary memory allocation for fields/values. */
6775typedef struct {
6776 int encoding;
6777 unsigned char *zi;
6778 unsigned char *zk, *zv;
6779 unsigned int zklen, zvlen;
6780
6781 dictIterator *di;
6782 dictEntry *de;
6783} hashIterator;
6784
c44d3b56
PN
6785static hashIterator *hashInitIterator(robj *subject) {
6786 hashIterator *hi = zmalloc(sizeof(hashIterator));
7fb16bac
PN
6787 hi->encoding = subject->encoding;
6788 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6789 hi->zi = zipmapRewind(subject->ptr);
6790 } else if (hi->encoding == REDIS_ENCODING_HT) {
6791 hi->di = dictGetIterator(subject->ptr);
d33278d1 6792 } else {
7fb16bac 6793 redisAssert(NULL);
d33278d1 6794 }
c44d3b56 6795 return hi;
7fb16bac 6796}
d33278d1 6797
7fb16bac
PN
6798static void hashReleaseIterator(hashIterator *hi) {
6799 if (hi->encoding == REDIS_ENCODING_HT) {
6800 dictReleaseIterator(hi->di);
d33278d1 6801 }
c44d3b56 6802 zfree(hi);
7fb16bac 6803}
d33278d1 6804
7fb16bac
PN
6805/* Move to the next entry in the hash. Return REDIS_OK when the next entry
6806 * could be found and REDIS_ERR when the iterator reaches the end. */
c811bb38 6807static int hashNext(hashIterator *hi) {
7fb16bac
PN
6808 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6809 if ((hi->zi = zipmapNext(hi->zi, &hi->zk, &hi->zklen,
6810 &hi->zv, &hi->zvlen)) == NULL) return REDIS_ERR;
6811 } else {
6812 if ((hi->de = dictNext(hi->di)) == NULL) return REDIS_ERR;
6813 }
6814 return REDIS_OK;
6815}
d33278d1 6816
0c390abc 6817/* Get key or value object at current iteration position.
a3f3af86 6818 * This increases the refcount of the field object by 1. */
c811bb38 6819static robj *hashCurrent(hashIterator *hi, int what) {
7fb16bac
PN
6820 robj *o;
6821 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6822 if (what & REDIS_HASH_KEY) {
6823 o = createStringObject((char*)hi->zk,hi->zklen);
6824 } else {
6825 o = createStringObject((char*)hi->zv,hi->zvlen);
d33278d1 6826 }
d33278d1 6827 } else {
7fb16bac
PN
6828 if (what & REDIS_HASH_KEY) {
6829 o = dictGetEntryKey(hi->de);
6830 } else {
6831 o = dictGetEntryVal(hi->de);
d33278d1 6832 }
a3f3af86 6833 incrRefCount(o);
d33278d1 6834 }
7fb16bac 6835 return o;
d33278d1
PN
6836}
6837
7fb16bac
PN
6838static robj *hashLookupWriteOrCreate(redisClient *c, robj *key) {
6839 robj *o = lookupKeyWrite(c->db,key);
01426b05
PN
6840 if (o == NULL) {
6841 o = createHashObject();
7fb16bac
PN
6842 dictAdd(c->db->dict,key,o);
6843 incrRefCount(key);
01426b05
PN
6844 } else {
6845 if (o->type != REDIS_HASH) {
6846 addReply(c,shared.wrongtypeerr);
7fb16bac 6847 return NULL;
01426b05
PN
6848 }
6849 }
7fb16bac
PN
6850 return o;
6851}
01426b05 6852
7fb16bac
PN
6853/* ============================= Hash commands ============================== */
6854static void hsetCommand(redisClient *c) {
6e9e463f 6855 int update;
7fb16bac 6856 robj *o;
bbe025e0 6857
7fb16bac
PN
6858 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6859 hashTryConversion(o,c->argv,2,3);
97224de7 6860 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
feb8d7e6 6861 update = hashSet(o,c->argv[2],c->argv[3]);
6e9e463f 6862 addReply(c, update ? shared.czero : shared.cone);
7fb16bac
PN
6863 server.dirty++;
6864}
01426b05 6865
1f1c7695
PN
6866static void hsetnxCommand(redisClient *c) {
6867 robj *o;
6868 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6869 hashTryConversion(o,c->argv,2,3);
6870
6871 if (hashExists(o, c->argv[2])) {
6872 addReply(c, shared.czero);
01426b05 6873 } else {
97224de7 6874 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
feb8d7e6 6875 hashSet(o,c->argv[2],c->argv[3]);
1f1c7695
PN
6876 addReply(c, shared.cone);
6877 server.dirty++;
6878 }
6879}
01426b05 6880
7fb16bac
PN
6881static void hmsetCommand(redisClient *c) {
6882 int i;
6883 robj *o;
01426b05 6884
7fb16bac
PN
6885 if ((c->argc % 2) == 1) {
6886 addReplySds(c,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6887 return;
6888 }
01426b05 6889
7fb16bac
PN
6890 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6891 hashTryConversion(o,c->argv,2,c->argc-1);
6892 for (i = 2; i < c->argc; i += 2) {
97224de7 6893 hashTryObjectEncoding(o,&c->argv[i], &c->argv[i+1]);
feb8d7e6 6894 hashSet(o,c->argv[i],c->argv[i+1]);
7fb16bac
PN
6895 }
6896 addReply(c, shared.ok);
edc2f63a 6897 server.dirty++;
7fb16bac
PN
6898}
6899
6900static void hincrbyCommand(redisClient *c) {
6901 long long value, incr;
6902 robj *o, *current, *new;
6903
bd79a6bd 6904 if (getLongLongFromObjectOrReply(c,c->argv[3],&incr,NULL) != REDIS_OK) return;
7fb16bac
PN
6905 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6906 if ((current = hashGet(o,c->argv[2])) != NULL) {
946342c1
PN
6907 if (getLongLongFromObjectOrReply(c,current,&value,
6908 "hash value is not an integer") != REDIS_OK) {
6909 decrRefCount(current);
6910 return;
6911 }
a3f3af86 6912 decrRefCount(current);
7fb16bac
PN
6913 } else {
6914 value = 0;
01426b05
PN
6915 }
6916
7fb16bac 6917 value += incr;
3f973463
PN
6918 new = createStringObjectFromLongLong(value);
6919 hashTryObjectEncoding(o,&c->argv[2],NULL);
feb8d7e6 6920 hashSet(o,c->argv[2],new);
7fb16bac
PN
6921 decrRefCount(new);
6922 addReplyLongLong(c,value);
01426b05 6923 server.dirty++;
01426b05
PN
6924}
6925
978c2c94 6926static void hgetCommand(redisClient *c) {
7fb16bac 6927 robj *o, *value;
dd88747b 6928 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6929 checkType(c,o,REDIS_HASH)) return;
6930
7fb16bac
PN
6931 if ((value = hashGet(o,c->argv[2])) != NULL) {
6932 addReplyBulk(c,value);
a3f3af86 6933 decrRefCount(value);
dd88747b 6934 } else {
7fb16bac 6935 addReply(c,shared.nullbulk);
69d95c3e 6936 }
69d95c3e
PN
6937}
6938
09aeb579
PN
6939static void hmgetCommand(redisClient *c) {
6940 int i;
7fb16bac
PN
6941 robj *o, *value;
6942 o = lookupKeyRead(c->db,c->argv[1]);
6943 if (o != NULL && o->type != REDIS_HASH) {
6944 addReply(c,shared.wrongtypeerr);
09aeb579
PN
6945 }
6946
7fb16bac
PN
6947 /* Note the check for o != NULL happens inside the loop. This is
6948 * done because objects that cannot be found are considered to be
6949 * an empty hash. The reply should then be a series of NULLs. */
09aeb579 6950 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-2));
7fb16bac
PN
6951 for (i = 2; i < c->argc; i++) {
6952 if (o != NULL && (value = hashGet(o,c->argv[i])) != NULL) {
6953 addReplyBulk(c,value);
a3f3af86 6954 decrRefCount(value);
7fb16bac
PN
6955 } else {
6956 addReply(c,shared.nullbulk);
09aeb579
PN
6957 }
6958 }
6959}
6960
07efaf74 6961static void hdelCommand(redisClient *c) {
dd88747b 6962 robj *o;
dd88747b 6963 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6964 checkType(c,o,REDIS_HASH)) return;
07efaf74 6965
7fb16bac
PN
6966 if (hashDelete(o,c->argv[2])) {
6967 if (hashLength(o) == 0) deleteKey(c->db,c->argv[1]);
6968 addReply(c,shared.cone);
6969 server.dirty++;
dd88747b 6970 } else {
7fb16bac 6971 addReply(c,shared.czero);
07efaf74 6972 }
6973}
6974
92b27fe9 6975static void hlenCommand(redisClient *c) {
6976 robj *o;
dd88747b 6977 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
92b27fe9 6978 checkType(c,o,REDIS_HASH)) return;
6979
7fb16bac 6980 addReplyUlong(c,hashLength(o));
92b27fe9 6981}
6982
78409a0f 6983static void genericHgetallCommand(redisClient *c, int flags) {
7fb16bac 6984 robj *o, *lenobj, *obj;
78409a0f 6985 unsigned long count = 0;
c44d3b56 6986 hashIterator *hi;
78409a0f 6987
4e27f268 6988 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
78409a0f 6989 || checkType(c,o,REDIS_HASH)) return;
6990
6991 lenobj = createObject(REDIS_STRING,NULL);
6992 addReply(c,lenobj);
6993 decrRefCount(lenobj);
6994
c44d3b56
PN
6995 hi = hashInitIterator(o);
6996 while (hashNext(hi) != REDIS_ERR) {
7fb16bac 6997 if (flags & REDIS_HASH_KEY) {
c44d3b56 6998 obj = hashCurrent(hi,REDIS_HASH_KEY);
7fb16bac 6999 addReplyBulk(c,obj);
a3f3af86 7000 decrRefCount(obj);
7fb16bac 7001 count++;
78409a0f 7002 }
7fb16bac 7003 if (flags & REDIS_HASH_VALUE) {
c44d3b56 7004 obj = hashCurrent(hi,REDIS_HASH_VALUE);
7fb16bac 7005 addReplyBulk(c,obj);
a3f3af86 7006 decrRefCount(obj);
7fb16bac 7007 count++;
78409a0f 7008 }
78409a0f 7009 }
c44d3b56 7010 hashReleaseIterator(hi);
7fb16bac 7011
78409a0f 7012 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",count);
7013}
7014
7015static void hkeysCommand(redisClient *c) {
7fb16bac 7016 genericHgetallCommand(c,REDIS_HASH_KEY);
78409a0f 7017}
7018
7019static void hvalsCommand(redisClient *c) {
7fb16bac 7020 genericHgetallCommand(c,REDIS_HASH_VALUE);
78409a0f 7021}
7022
7023static void hgetallCommand(redisClient *c) {
7fb16bac 7024 genericHgetallCommand(c,REDIS_HASH_KEY|REDIS_HASH_VALUE);
78409a0f 7025}
7026
a86f14b1 7027static void hexistsCommand(redisClient *c) {
7028 robj *o;
a86f14b1 7029 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
7030 checkType(c,o,REDIS_HASH)) return;
7031
7fb16bac 7032 addReply(c, hashExists(o,c->argv[2]) ? shared.cone : shared.czero);
a86f14b1 7033}
7034
ada386b2 7035static void convertToRealHash(robj *o) {
7036 unsigned char *key, *val, *p, *zm = o->ptr;
7037 unsigned int klen, vlen;
7038 dict *dict = dictCreate(&hashDictType,NULL);
7039
7040 assert(o->type == REDIS_HASH && o->encoding != REDIS_ENCODING_HT);
7041 p = zipmapRewind(zm);
7042 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
7043 robj *keyobj, *valobj;
7044
7045 keyobj = createStringObject((char*)key,klen);
7046 valobj = createStringObject((char*)val,vlen);
05df7621 7047 keyobj = tryObjectEncoding(keyobj);
7048 valobj = tryObjectEncoding(valobj);
ada386b2 7049 dictAdd(dict,keyobj,valobj);
7050 }
7051 o->encoding = REDIS_ENCODING_HT;
7052 o->ptr = dict;
7053 zfree(zm);
7054}
7055
6b47e12e 7056/* ========================= Non type-specific commands ==================== */
7057
ed9b544e 7058static void flushdbCommand(redisClient *c) {
ca37e9cd 7059 server.dirty += dictSize(c->db->dict);
9b30e1a2 7060 touchWatchedKeysOnFlush(c->db->id);
3305306f 7061 dictEmpty(c->db->dict);
7062 dictEmpty(c->db->expires);
ed9b544e 7063 addReply(c,shared.ok);
ed9b544e 7064}
7065
7066static void flushallCommand(redisClient *c) {
9b30e1a2 7067 touchWatchedKeysOnFlush(-1);
ca37e9cd 7068 server.dirty += emptyDb();
ed9b544e 7069 addReply(c,shared.ok);
500ece7c 7070 if (server.bgsavechildpid != -1) {
7071 kill(server.bgsavechildpid,SIGKILL);
7072 rdbRemoveTempFile(server.bgsavechildpid);
7073 }
f78fd11b 7074 rdbSave(server.dbfilename);
ca37e9cd 7075 server.dirty++;
ed9b544e 7076}
7077
56906eef 7078static redisSortOperation *createSortOperation(int type, robj *pattern) {
ed9b544e 7079 redisSortOperation *so = zmalloc(sizeof(*so));
ed9b544e 7080 so->type = type;
7081 so->pattern = pattern;
7082 return so;
7083}
7084
7085/* Return the value associated to the key with a name obtained
55017f9d
PN
7086 * substituting the first occurence of '*' in 'pattern' with 'subst'.
7087 * The returned object will always have its refcount increased by 1
7088 * when it is non-NULL. */
56906eef 7089static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
6d7d1370 7090 char *p, *f;
ed9b544e 7091 sds spat, ssub;
6d7d1370
PN
7092 robj keyobj, fieldobj, *o;
7093 int prefixlen, sublen, postfixlen, fieldlen;
ed9b544e 7094 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
7095 struct {
f1017b3f 7096 long len;
7097 long free;
ed9b544e 7098 char buf[REDIS_SORTKEY_MAX+1];
6d7d1370 7099 } keyname, fieldname;
ed9b544e 7100
28173a49 7101 /* If the pattern is "#" return the substitution object itself in order
7102 * to implement the "SORT ... GET #" feature. */
7103 spat = pattern->ptr;
7104 if (spat[0] == '#' && spat[1] == '\0') {
55017f9d 7105 incrRefCount(subst);
28173a49 7106 return subst;
7107 }
7108
7109 /* The substitution object may be specially encoded. If so we create
9d65a1bb 7110 * a decoded object on the fly. Otherwise getDecodedObject will just
7111 * increment the ref count, that we'll decrement later. */
7112 subst = getDecodedObject(subst);
942a3961 7113
ed9b544e 7114 ssub = subst->ptr;
7115 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
7116 p = strchr(spat,'*');
ed5a857a 7117 if (!p) {
7118 decrRefCount(subst);
7119 return NULL;
7120 }
ed9b544e 7121
6d7d1370
PN
7122 /* Find out if we're dealing with a hash dereference. */
7123 if ((f = strstr(p+1, "->")) != NULL) {
7124 fieldlen = sdslen(spat)-(f-spat);
7125 /* this also copies \0 character */
7126 memcpy(fieldname.buf,f+2,fieldlen-1);
7127 fieldname.len = fieldlen-2;
7128 } else {
7129 fieldlen = 0;
7130 }
7131
ed9b544e 7132 prefixlen = p-spat;
7133 sublen = sdslen(ssub);
6d7d1370 7134 postfixlen = sdslen(spat)-(prefixlen+1)-fieldlen;
ed9b544e 7135 memcpy(keyname.buf,spat,prefixlen);
7136 memcpy(keyname.buf+prefixlen,ssub,sublen);
7137 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
7138 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
7139 keyname.len = prefixlen+sublen+postfixlen;
942a3961 7140 decrRefCount(subst);
7141
6d7d1370
PN
7142 /* Lookup substituted key */
7143 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2));
7144 o = lookupKeyRead(db,&keyobj);
55017f9d
PN
7145 if (o == NULL) return NULL;
7146
7147 if (fieldlen > 0) {
7148 if (o->type != REDIS_HASH || fieldname.len < 1) return NULL;
6d7d1370 7149
705dad38
PN
7150 /* Retrieve value from hash by the field name. This operation
7151 * already increases the refcount of the returned object. */
6d7d1370
PN
7152 initStaticStringObject(fieldobj,((char*)&fieldname)+(sizeof(long)*2));
7153 o = hashGet(o, &fieldobj);
705dad38 7154 } else {
55017f9d 7155 if (o->type != REDIS_STRING) return NULL;
b6f07345 7156
705dad38
PN
7157 /* Every object that this function returns needs to have its refcount
7158 * increased. sortCommand decreases it again. */
7159 incrRefCount(o);
6d7d1370
PN
7160 }
7161
7162 return o;
ed9b544e 7163}
7164
7165/* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
7166 * the additional parameter is not standard but a BSD-specific we have to
7167 * pass sorting parameters via the global 'server' structure */
7168static int sortCompare(const void *s1, const void *s2) {
7169 const redisSortObject *so1 = s1, *so2 = s2;
7170 int cmp;
7171
7172 if (!server.sort_alpha) {
7173 /* Numeric sorting. Here it's trivial as we precomputed scores */
7174 if (so1->u.score > so2->u.score) {
7175 cmp = 1;
7176 } else if (so1->u.score < so2->u.score) {
7177 cmp = -1;
7178 } else {
7179 cmp = 0;
7180 }
7181 } else {
7182 /* Alphanumeric sorting */
7183 if (server.sort_bypattern) {
7184 if (!so1->u.cmpobj || !so2->u.cmpobj) {
7185 /* At least one compare object is NULL */
7186 if (so1->u.cmpobj == so2->u.cmpobj)
7187 cmp = 0;
7188 else if (so1->u.cmpobj == NULL)
7189 cmp = -1;
7190 else
7191 cmp = 1;
7192 } else {
7193 /* We have both the objects, use strcoll */
7194 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
7195 }
7196 } else {
08ee9b57 7197 /* Compare elements directly. */
7198 cmp = compareStringObjects(so1->obj,so2->obj);
ed9b544e 7199 }
7200 }
7201 return server.sort_desc ? -cmp : cmp;
7202}
7203
7204/* The SORT command is the most complex command in Redis. Warning: this code
7205 * is optimized for speed and a bit less for readability */
7206static void sortCommand(redisClient *c) {
ed9b544e 7207 list *operations;
7208 int outputlen = 0;
7209 int desc = 0, alpha = 0;
7210 int limit_start = 0, limit_count = -1, start, end;
7211 int j, dontsort = 0, vectorlen;
7212 int getop = 0; /* GET operation counter */
443c6409 7213 robj *sortval, *sortby = NULL, *storekey = NULL;
ed9b544e 7214 redisSortObject *vector; /* Resulting vector to sort */
7215
7216 /* Lookup the key to sort. It must be of the right types */
3305306f 7217 sortval = lookupKeyRead(c->db,c->argv[1]);
7218 if (sortval == NULL) {
4e27f268 7219 addReply(c,shared.emptymultibulk);
ed9b544e 7220 return;
7221 }
a5eb649b 7222 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
7223 sortval->type != REDIS_ZSET)
7224 {
c937aa89 7225 addReply(c,shared.wrongtypeerr);
ed9b544e 7226 return;
7227 }
7228
7229 /* Create a list of operations to perform for every sorted element.
7230 * Operations can be GET/DEL/INCR/DECR */
7231 operations = listCreate();
092dac2a 7232 listSetFreeMethod(operations,zfree);
ed9b544e 7233 j = 2;
7234
7235 /* Now we need to protect sortval incrementing its count, in the future
7236 * SORT may have options able to overwrite/delete keys during the sorting
7237 * and the sorted key itself may get destroied */
7238 incrRefCount(sortval);
7239
7240 /* The SORT command has an SQL-alike syntax, parse it */
7241 while(j < c->argc) {
7242 int leftargs = c->argc-j-1;
7243 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
7244 desc = 0;
7245 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
7246 desc = 1;
7247 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
7248 alpha = 1;
7249 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
7250 limit_start = atoi(c->argv[j+1]->ptr);
7251 limit_count = atoi(c->argv[j+2]->ptr);
7252 j+=2;
443c6409 7253 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
7254 storekey = c->argv[j+1];
7255 j++;
ed9b544e 7256 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
7257 sortby = c->argv[j+1];
7258 /* If the BY pattern does not contain '*', i.e. it is constant,
7259 * we don't need to sort nor to lookup the weight keys. */
7260 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
7261 j++;
7262 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
7263 listAddNodeTail(operations,createSortOperation(
7264 REDIS_SORT_GET,c->argv[j+1]));
7265 getop++;
7266 j++;
ed9b544e 7267 } else {
7268 decrRefCount(sortval);
7269 listRelease(operations);
c937aa89 7270 addReply(c,shared.syntaxerr);
ed9b544e 7271 return;
7272 }
7273 j++;
7274 }
7275
7276 /* Load the sorting vector with all the objects to sort */
a5eb649b 7277 switch(sortval->type) {
7278 case REDIS_LIST: vectorlen = listLength((list*)sortval->ptr); break;
7279 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
7280 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
f83c6cb5 7281 default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
a5eb649b 7282 }
ed9b544e 7283 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
ed9b544e 7284 j = 0;
a5eb649b 7285
ed9b544e 7286 if (sortval->type == REDIS_LIST) {
7287 list *list = sortval->ptr;
6208b3a7 7288 listNode *ln;
c7df85a4 7289 listIter li;
6208b3a7 7290
c7df85a4 7291 listRewind(list,&li);
7292 while((ln = listNext(&li))) {
ed9b544e 7293 robj *ele = ln->value;
7294 vector[j].obj = ele;
7295 vector[j].u.score = 0;
7296 vector[j].u.cmpobj = NULL;
ed9b544e 7297 j++;
7298 }
7299 } else {
a5eb649b 7300 dict *set;
ed9b544e 7301 dictIterator *di;
7302 dictEntry *setele;
7303
a5eb649b 7304 if (sortval->type == REDIS_SET) {
7305 set = sortval->ptr;
7306 } else {
7307 zset *zs = sortval->ptr;
7308 set = zs->dict;
7309 }
7310
ed9b544e 7311 di = dictGetIterator(set);
ed9b544e 7312 while((setele = dictNext(di)) != NULL) {
7313 vector[j].obj = dictGetEntryKey(setele);
7314 vector[j].u.score = 0;
7315 vector[j].u.cmpobj = NULL;
7316 j++;
7317 }
7318 dictReleaseIterator(di);
7319 }
dfc5e96c 7320 redisAssert(j == vectorlen);
ed9b544e 7321
7322 /* Now it's time to load the right scores in the sorting vector */
7323 if (dontsort == 0) {
7324 for (j = 0; j < vectorlen; j++) {
6d7d1370 7325 robj *byval;
ed9b544e 7326 if (sortby) {
6d7d1370 7327 /* lookup value to sort by */
3305306f 7328 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
705dad38 7329 if (!byval) continue;
ed9b544e 7330 } else {
6d7d1370
PN
7331 /* use object itself to sort by */
7332 byval = vector[j].obj;
7333 }
7334
7335 if (alpha) {
08ee9b57 7336 if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
6d7d1370
PN
7337 } else {
7338 if (byval->encoding == REDIS_ENCODING_RAW) {
7339 vector[j].u.score = strtod(byval->ptr,NULL);
16fa22f1 7340 } else if (byval->encoding == REDIS_ENCODING_INT) {
6d7d1370
PN
7341 /* Don't need to decode the object if it's
7342 * integer-encoded (the only encoding supported) so
7343 * far. We can just cast it */
16fa22f1
PN
7344 vector[j].u.score = (long)byval->ptr;
7345 } else {
7346 redisAssert(1 != 1);
942a3961 7347 }
ed9b544e 7348 }
6d7d1370 7349
705dad38
PN
7350 /* when the object was retrieved using lookupKeyByPattern,
7351 * its refcount needs to be decreased. */
7352 if (sortby) {
7353 decrRefCount(byval);
ed9b544e 7354 }
7355 }
7356 }
7357
7358 /* We are ready to sort the vector... perform a bit of sanity check
7359 * on the LIMIT option too. We'll use a partial version of quicksort. */
7360 start = (limit_start < 0) ? 0 : limit_start;
7361 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
7362 if (start >= vectorlen) {
7363 start = vectorlen-1;
7364 end = vectorlen-2;
7365 }
7366 if (end >= vectorlen) end = vectorlen-1;
7367
7368 if (dontsort == 0) {
7369 server.sort_desc = desc;
7370 server.sort_alpha = alpha;
7371 server.sort_bypattern = sortby ? 1 : 0;
5f5b9840 7372 if (sortby && (start != 0 || end != vectorlen-1))
7373 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
7374 else
7375 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
ed9b544e 7376 }
7377
7378 /* Send command output to the output buffer, performing the specified
7379 * GET/DEL/INCR/DECR operations if any. */
7380 outputlen = getop ? getop*(end-start+1) : end-start+1;
443c6409 7381 if (storekey == NULL) {
7382 /* STORE option not specified, sent the sorting result to client */
7383 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
7384 for (j = start; j <= end; j++) {
7385 listNode *ln;
c7df85a4 7386 listIter li;
7387
dd88747b 7388 if (!getop) addReplyBulk(c,vector[j].obj);
c7df85a4 7389 listRewind(operations,&li);
7390 while((ln = listNext(&li))) {
443c6409 7391 redisSortOperation *sop = ln->value;
7392 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7393 vector[j].obj);
7394
7395 if (sop->type == REDIS_SORT_GET) {
55017f9d 7396 if (!val) {
443c6409 7397 addReply(c,shared.nullbulk);
7398 } else {
dd88747b 7399 addReplyBulk(c,val);
55017f9d 7400 decrRefCount(val);
443c6409 7401 }
7402 } else {
dfc5e96c 7403 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
443c6409 7404 }
7405 }
ed9b544e 7406 }
443c6409 7407 } else {
7408 robj *listObject = createListObject();
7409 list *listPtr = (list*) listObject->ptr;
7410
7411 /* STORE option specified, set the sorting result as a List object */
7412 for (j = start; j <= end; j++) {
7413 listNode *ln;
c7df85a4 7414 listIter li;
7415
443c6409 7416 if (!getop) {
7417 listAddNodeTail(listPtr,vector[j].obj);
7418 incrRefCount(vector[j].obj);
7419 }
c7df85a4 7420 listRewind(operations,&li);
7421 while((ln = listNext(&li))) {
443c6409 7422 redisSortOperation *sop = ln->value;
7423 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7424 vector[j].obj);
7425
7426 if (sop->type == REDIS_SORT_GET) {
55017f9d 7427 if (!val) {
443c6409 7428 listAddNodeTail(listPtr,createStringObject("",0));
7429 } else {
55017f9d
PN
7430 /* We should do a incrRefCount on val because it is
7431 * added to the list, but also a decrRefCount because
7432 * it is returned by lookupKeyByPattern. This results
7433 * in doing nothing at all. */
443c6409 7434 listAddNodeTail(listPtr,val);
443c6409 7435 }
ed9b544e 7436 } else {
dfc5e96c 7437 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
ed9b544e 7438 }
ed9b544e 7439 }
ed9b544e 7440 }
121796f7 7441 if (dictReplace(c->db->dict,storekey,listObject)) {
7442 incrRefCount(storekey);
7443 }
443c6409 7444 /* Note: we add 1 because the DB is dirty anyway since even if the
7445 * SORT result is empty a new key is set and maybe the old content
7446 * replaced. */
7447 server.dirty += 1+outputlen;
7448 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
ed9b544e 7449 }
7450
7451 /* Cleanup */
7452 decrRefCount(sortval);
7453 listRelease(operations);
7454 for (j = 0; j < vectorlen; j++) {
16fa22f1 7455 if (alpha && vector[j].u.cmpobj)
ed9b544e 7456 decrRefCount(vector[j].u.cmpobj);
7457 }
7458 zfree(vector);
7459}
7460
ec6c7a1d 7461/* Convert an amount of bytes into a human readable string in the form
7462 * of 100B, 2G, 100M, 4K, and so forth. */
7463static void bytesToHuman(char *s, unsigned long long n) {
7464 double d;
7465
7466 if (n < 1024) {
7467 /* Bytes */
7468 sprintf(s,"%lluB",n);
7469 return;
7470 } else if (n < (1024*1024)) {
7471 d = (double)n/(1024);
7472 sprintf(s,"%.2fK",d);
7473 } else if (n < (1024LL*1024*1024)) {
7474 d = (double)n/(1024*1024);
7475 sprintf(s,"%.2fM",d);
7476 } else if (n < (1024LL*1024*1024*1024)) {
7477 d = (double)n/(1024LL*1024*1024);
b72f6a4b 7478 sprintf(s,"%.2fG",d);
ec6c7a1d 7479 }
7480}
7481
1c85b79f 7482/* Create the string returned by the INFO command. This is decoupled
7483 * by the INFO command itself as we need to report the same information
7484 * on memory corruption problems. */
7485static sds genRedisInfoString(void) {
ed9b544e 7486 sds info;
7487 time_t uptime = time(NULL)-server.stat_starttime;
c3cb078d 7488 int j;
ec6c7a1d 7489 char hmem[64];
55a8298f 7490
b72f6a4b 7491 bytesToHuman(hmem,zmalloc_used_memory());
ed9b544e 7492 info = sdscatprintf(sdsempty(),
7493 "redis_version:%s\r\n"
5436146c
PN
7494 "redis_git_sha1:%s\r\n"
7495 "redis_git_dirty:%d\r\n"
f1017b3f 7496 "arch_bits:%s\r\n"
7a932b74 7497 "multiplexing_api:%s\r\n"
0d7170a4 7498 "process_id:%ld\r\n"
682ac724 7499 "uptime_in_seconds:%ld\r\n"
7500 "uptime_in_days:%ld\r\n"
ed9b544e 7501 "connected_clients:%d\r\n"
7502 "connected_slaves:%d\r\n"
f86a74e9 7503 "blocked_clients:%d\r\n"
5fba9f71 7504 "used_memory:%zu\r\n"
ec6c7a1d 7505 "used_memory_human:%s\r\n"
ed9b544e 7506 "changes_since_last_save:%lld\r\n"
be2bb6b0 7507 "bgsave_in_progress:%d\r\n"
682ac724 7508 "last_save_time:%ld\r\n"
b3fad521 7509 "bgrewriteaof_in_progress:%d\r\n"
ed9b544e 7510 "total_connections_received:%lld\r\n"
7511 "total_commands_processed:%lld\r\n"
2a6a2ed1 7512 "expired_keys:%lld\r\n"
3be2c9d7 7513 "hash_max_zipmap_entries:%zu\r\n"
7514 "hash_max_zipmap_value:%zu\r\n"
ffc6b7f8 7515 "pubsub_channels:%ld\r\n"
7516 "pubsub_patterns:%u\r\n"
7d98e08c 7517 "vm_enabled:%d\r\n"
a0f643ea 7518 "role:%s\r\n"
ed9b544e 7519 ,REDIS_VERSION,
5436146c 7520 REDIS_GIT_SHA1,
274e45e3 7521 strtol(REDIS_GIT_DIRTY,NULL,10) > 0,
f1017b3f 7522 (sizeof(long) == 8) ? "64" : "32",
7a932b74 7523 aeGetApiName(),
0d7170a4 7524 (long) getpid(),
a0f643ea 7525 uptime,
7526 uptime/(3600*24),
ed9b544e 7527 listLength(server.clients)-listLength(server.slaves),
7528 listLength(server.slaves),
d5d55fc3 7529 server.blpop_blocked_clients,
b72f6a4b 7530 zmalloc_used_memory(),
ec6c7a1d 7531 hmem,
ed9b544e 7532 server.dirty,
9d65a1bb 7533 server.bgsavechildpid != -1,
ed9b544e 7534 server.lastsave,
b3fad521 7535 server.bgrewritechildpid != -1,
ed9b544e 7536 server.stat_numconnections,
7537 server.stat_numcommands,
2a6a2ed1 7538 server.stat_expiredkeys,
55a8298f 7539 server.hash_max_zipmap_entries,
7540 server.hash_max_zipmap_value,
ffc6b7f8 7541 dictSize(server.pubsub_channels),
7542 listLength(server.pubsub_patterns),
7d98e08c 7543 server.vm_enabled != 0,
a0f643ea 7544 server.masterhost == NULL ? "master" : "slave"
ed9b544e 7545 );
a0f643ea 7546 if (server.masterhost) {
7547 info = sdscatprintf(info,
7548 "master_host:%s\r\n"
7549 "master_port:%d\r\n"
7550 "master_link_status:%s\r\n"
7551 "master_last_io_seconds_ago:%d\r\n"
7552 ,server.masterhost,
7553 server.masterport,
7554 (server.replstate == REDIS_REPL_CONNECTED) ?
7555 "up" : "down",
f72b934d 7556 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
a0f643ea 7557 );
7558 }
7d98e08c 7559 if (server.vm_enabled) {
1064ef87 7560 lockThreadedIO();
7d98e08c 7561 info = sdscatprintf(info,
7562 "vm_conf_max_memory:%llu\r\n"
7563 "vm_conf_page_size:%llu\r\n"
7564 "vm_conf_pages:%llu\r\n"
7565 "vm_stats_used_pages:%llu\r\n"
7566 "vm_stats_swapped_objects:%llu\r\n"
7567 "vm_stats_swappin_count:%llu\r\n"
7568 "vm_stats_swappout_count:%llu\r\n"
b9bc0eef 7569 "vm_stats_io_newjobs_len:%lu\r\n"
7570 "vm_stats_io_processing_len:%lu\r\n"
7571 "vm_stats_io_processed_len:%lu\r\n"
25fd2cb2 7572 "vm_stats_io_active_threads:%lu\r\n"
d5d55fc3 7573 "vm_stats_blocked_clients:%lu\r\n"
7d98e08c 7574 ,(unsigned long long) server.vm_max_memory,
7575 (unsigned long long) server.vm_page_size,
7576 (unsigned long long) server.vm_pages,
7577 (unsigned long long) server.vm_stats_used_pages,
7578 (unsigned long long) server.vm_stats_swapped_objects,
7579 (unsigned long long) server.vm_stats_swapins,
b9bc0eef 7580 (unsigned long long) server.vm_stats_swapouts,
7581 (unsigned long) listLength(server.io_newjobs),
7582 (unsigned long) listLength(server.io_processing),
7583 (unsigned long) listLength(server.io_processed),
d5d55fc3 7584 (unsigned long) server.io_active_threads,
7585 (unsigned long) server.vm_blocked_clients
7d98e08c 7586 );
1064ef87 7587 unlockThreadedIO();
7d98e08c 7588 }
c3cb078d 7589 for (j = 0; j < server.dbnum; j++) {
7590 long long keys, vkeys;
7591
7592 keys = dictSize(server.db[j].dict);
7593 vkeys = dictSize(server.db[j].expires);
7594 if (keys || vkeys) {
9d65a1bb 7595 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
c3cb078d 7596 j, keys, vkeys);
7597 }
7598 }
1c85b79f 7599 return info;
7600}
7601
7602static void infoCommand(redisClient *c) {
7603 sds info = genRedisInfoString();
83c6a618 7604 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
7605 (unsigned long)sdslen(info)));
ed9b544e 7606 addReplySds(c,info);
70003d28 7607 addReply(c,shared.crlf);
ed9b544e 7608}
7609
3305306f 7610static void monitorCommand(redisClient *c) {
7611 /* ignore MONITOR if aleady slave or in monitor mode */
7612 if (c->flags & REDIS_SLAVE) return;
7613
7614 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
7615 c->slaveseldb = 0;
6b47e12e 7616 listAddNodeTail(server.monitors,c);
3305306f 7617 addReply(c,shared.ok);
7618}
7619
7620/* ================================= Expire ================================= */
7621static int removeExpire(redisDb *db, robj *key) {
7622 if (dictDelete(db->expires,key) == DICT_OK) {
7623 return 1;
7624 } else {
7625 return 0;
7626 }
7627}
7628
7629static int setExpire(redisDb *db, robj *key, time_t when) {
7630 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
7631 return 0;
7632 } else {
7633 incrRefCount(key);
7634 return 1;
7635 }
7636}
7637
bb32ede5 7638/* Return the expire time of the specified key, or -1 if no expire
7639 * is associated with this key (i.e. the key is non volatile) */
7640static time_t getExpire(redisDb *db, robj *key) {
7641 dictEntry *de;
7642
7643 /* No expire? return ASAP */
7644 if (dictSize(db->expires) == 0 ||
7645 (de = dictFind(db->expires,key)) == NULL) return -1;
7646
7647 return (time_t) dictGetEntryVal(de);
7648}
7649
3305306f 7650static int expireIfNeeded(redisDb *db, robj *key) {
7651 time_t when;
7652 dictEntry *de;
7653
7654 /* No expire? return ASAP */
7655 if (dictSize(db->expires) == 0 ||
7656 (de = dictFind(db->expires,key)) == NULL) return 0;
7657
7658 /* Lookup the expire */
7659 when = (time_t) dictGetEntryVal(de);
7660 if (time(NULL) <= when) return 0;
7661
7662 /* Delete the key */
7663 dictDelete(db->expires,key);
2a6a2ed1 7664 server.stat_expiredkeys++;
3305306f 7665 return dictDelete(db->dict,key) == DICT_OK;
7666}
7667
7668static int deleteIfVolatile(redisDb *db, robj *key) {
7669 dictEntry *de;
7670
7671 /* No expire? return ASAP */
7672 if (dictSize(db->expires) == 0 ||
7673 (de = dictFind(db->expires,key)) == NULL) return 0;
7674
7675 /* Delete the key */
0c66a471 7676 server.dirty++;
2a6a2ed1 7677 server.stat_expiredkeys++;
3305306f 7678 dictDelete(db->expires,key);
7679 return dictDelete(db->dict,key) == DICT_OK;
7680}
7681
bbe025e0 7682static void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
3305306f 7683 dictEntry *de;
bbe025e0
AM
7684 time_t seconds;
7685
bd79a6bd 7686 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
bbe025e0
AM
7687
7688 seconds -= offset;
3305306f 7689
802e8373 7690 de = dictFind(c->db->dict,key);
3305306f 7691 if (de == NULL) {
7692 addReply(c,shared.czero);
7693 return;
7694 }
d4dd6556 7695 if (seconds <= 0) {
43e5ccdf 7696 if (deleteKey(c->db,key)) server.dirty++;
7697 addReply(c, shared.cone);
3305306f 7698 return;
7699 } else {
7700 time_t when = time(NULL)+seconds;
802e8373 7701 if (setExpire(c->db,key,when)) {
3305306f 7702 addReply(c,shared.cone);
77423026 7703 server.dirty++;
7704 } else {
3305306f 7705 addReply(c,shared.czero);
77423026 7706 }
3305306f 7707 return;
7708 }
7709}
7710
802e8373 7711static void expireCommand(redisClient *c) {
bbe025e0 7712 expireGenericCommand(c,c->argv[1],c->argv[2],0);
802e8373 7713}
7714
7715static void expireatCommand(redisClient *c) {
bbe025e0 7716 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
802e8373 7717}
7718
fd88489a 7719static void ttlCommand(redisClient *c) {
7720 time_t expire;
7721 int ttl = -1;
7722
7723 expire = getExpire(c->db,c->argv[1]);
7724 if (expire != -1) {
7725 ttl = (int) (expire-time(NULL));
7726 if (ttl < 0) ttl = -1;
7727 }
7728 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
7729}
7730
6e469882 7731/* ================================ MULTI/EXEC ============================== */
7732
7733/* Client state initialization for MULTI/EXEC */
7734static void initClientMultiState(redisClient *c) {
7735 c->mstate.commands = NULL;
7736 c->mstate.count = 0;
7737}
7738
7739/* Release all the resources associated with MULTI/EXEC state */
7740static void freeClientMultiState(redisClient *c) {
7741 int j;
7742
7743 for (j = 0; j < c->mstate.count; j++) {
7744 int i;
7745 multiCmd *mc = c->mstate.commands+j;
7746
7747 for (i = 0; i < mc->argc; i++)
7748 decrRefCount(mc->argv[i]);
7749 zfree(mc->argv);
7750 }
7751 zfree(c->mstate.commands);
7752}
7753
7754/* Add a new command into the MULTI commands queue */
7755static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
7756 multiCmd *mc;
7757 int j;
7758
7759 c->mstate.commands = zrealloc(c->mstate.commands,
7760 sizeof(multiCmd)*(c->mstate.count+1));
7761 mc = c->mstate.commands+c->mstate.count;
7762 mc->cmd = cmd;
7763 mc->argc = c->argc;
7764 mc->argv = zmalloc(sizeof(robj*)*c->argc);
7765 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
7766 for (j = 0; j < c->argc; j++)
7767 incrRefCount(mc->argv[j]);
7768 c->mstate.count++;
7769}
7770
7771static void multiCommand(redisClient *c) {
6531c94d 7772 if (c->flags & REDIS_MULTI) {
7773 addReplySds(c,sdsnew("-ERR MULTI calls can not be nested\r\n"));
7774 return;
7775 }
6e469882 7776 c->flags |= REDIS_MULTI;
36c548f0 7777 addReply(c,shared.ok);
6e469882 7778}
7779
18b6cb76
DJ
7780static void discardCommand(redisClient *c) {
7781 if (!(c->flags & REDIS_MULTI)) {
7782 addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
7783 return;
7784 }
7785
7786 freeClientMultiState(c);
7787 initClientMultiState(c);
7788 c->flags &= (~REDIS_MULTI);
7789 addReply(c,shared.ok);
7790}
7791
66c8853f 7792/* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7793 * implememntation for more information. */
7794static void execCommandReplicateMulti(redisClient *c) {
7795 struct redisCommand *cmd;
7796 robj *multistring = createStringObject("MULTI",5);
7797
7798 cmd = lookupCommand("multi");
7799 if (server.appendonly)
7800 feedAppendOnlyFile(cmd,c->db->id,&multistring,1);
7801 if (listLength(server.slaves))
7802 replicationFeedSlaves(server.slaves,c->db->id,&multistring,1);
7803 decrRefCount(multistring);
7804}
7805
6e469882 7806static void execCommand(redisClient *c) {
7807 int j;
7808 robj **orig_argv;
7809 int orig_argc;
7810
7811 if (!(c->flags & REDIS_MULTI)) {
7812 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
7813 return;
7814 }
7815
37ab76c9 7816 /* Check if we need to abort the EXEC if some WATCHed key was touched.
7817 * A failed EXEC will return a multi bulk nil object. */
7818 if (c->flags & REDIS_DIRTY_CAS) {
7819 freeClientMultiState(c);
7820 initClientMultiState(c);
7821 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
7822 unwatchAllKeys(c);
7823 addReply(c,shared.nullmultibulk);
7824 return;
7825 }
7826
66c8853f 7827 /* Replicate a MULTI request now that we are sure the block is executed.
7828 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7829 * both the AOF and the replication link will have the same consistency
7830 * and atomicity guarantees. */
7831 execCommandReplicateMulti(c);
7832
7833 /* Exec all the queued commands */
1ad4d316 7834 unwatchAllKeys(c); /* Unwatch ASAP otherwise we'll waste CPU cycles */
6e469882 7835 orig_argv = c->argv;
7836 orig_argc = c->argc;
7837 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
7838 for (j = 0; j < c->mstate.count; j++) {
7839 c->argc = c->mstate.commands[j].argc;
7840 c->argv = c->mstate.commands[j].argv;
7841 call(c,c->mstate.commands[j].cmd);
7842 }
7843 c->argv = orig_argv;
7844 c->argc = orig_argc;
7845 freeClientMultiState(c);
7846 initClientMultiState(c);
1ad4d316 7847 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
66c8853f 7848 /* Make sure the EXEC command is always replicated / AOF, since we
7849 * always send the MULTI command (we can't know beforehand if the
7850 * next operations will contain at least a modification to the DB). */
7851 server.dirty++;
6e469882 7852}
7853
4409877e 7854/* =========================== Blocking Operations ========================= */
7855
7856/* Currently Redis blocking operations support is limited to list POP ops,
7857 * so the current implementation is not fully generic, but it is also not
7858 * completely specific so it will not require a rewrite to support new
7859 * kind of blocking operations in the future.
7860 *
7861 * Still it's important to note that list blocking operations can be already
7862 * used as a notification mechanism in order to implement other blocking
7863 * operations at application level, so there must be a very strong evidence
7864 * of usefulness and generality before new blocking operations are implemented.
7865 *
7866 * This is how the current blocking POP works, we use BLPOP as example:
7867 * - If the user calls BLPOP and the key exists and contains a non empty list
7868 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7869 * if there is not to block.
7870 * - If instead BLPOP is called and the key does not exists or the list is
7871 * empty we need to block. In order to do so we remove the notification for
7872 * new data to read in the client socket (so that we'll not serve new
7873 * requests if the blocking request is not served). Also we put the client
37ab76c9 7874 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
4409877e 7875 * blocking for this keys.
7876 * - If a PUSH operation against a key with blocked clients waiting is
7877 * performed, we serve the first in the list: basically instead to push
7878 * the new element inside the list we return it to the (first / oldest)
7879 * blocking client, unblock the client, and remove it form the list.
7880 *
7881 * The above comment and the source code should be enough in order to understand
7882 * the implementation and modify / fix it later.
7883 */
7884
7885/* Set a client in blocking mode for the specified key, with the specified
7886 * timeout */
b177fd30 7887static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
4409877e 7888 dictEntry *de;
7889 list *l;
b177fd30 7890 int j;
4409877e 7891
37ab76c9 7892 c->blocking_keys = zmalloc(sizeof(robj*)*numkeys);
7893 c->blocking_keys_num = numkeys;
4409877e 7894 c->blockingto = timeout;
b177fd30 7895 for (j = 0; j < numkeys; j++) {
7896 /* Add the key in the client structure, to map clients -> keys */
37ab76c9 7897 c->blocking_keys[j] = keys[j];
b177fd30 7898 incrRefCount(keys[j]);
4409877e 7899
b177fd30 7900 /* And in the other "side", to map keys -> clients */
37ab76c9 7901 de = dictFind(c->db->blocking_keys,keys[j]);
b177fd30 7902 if (de == NULL) {
7903 int retval;
7904
7905 /* For every key we take a list of clients blocked for it */
7906 l = listCreate();
37ab76c9 7907 retval = dictAdd(c->db->blocking_keys,keys[j],l);
b177fd30 7908 incrRefCount(keys[j]);
7909 assert(retval == DICT_OK);
7910 } else {
7911 l = dictGetEntryVal(de);
7912 }
7913 listAddNodeTail(l,c);
4409877e 7914 }
b177fd30 7915 /* Mark the client as a blocked client */
4409877e 7916 c->flags |= REDIS_BLOCKED;
d5d55fc3 7917 server.blpop_blocked_clients++;
4409877e 7918}
7919
7920/* Unblock a client that's waiting in a blocking operation such as BLPOP */
b0d8747d 7921static void unblockClientWaitingData(redisClient *c) {
4409877e 7922 dictEntry *de;
7923 list *l;
b177fd30 7924 int j;
4409877e 7925
37ab76c9 7926 assert(c->blocking_keys != NULL);
b177fd30 7927 /* The client may wait for multiple keys, so unblock it for every key. */
37ab76c9 7928 for (j = 0; j < c->blocking_keys_num; j++) {
b177fd30 7929 /* Remove this client from the list of clients waiting for this key. */
37ab76c9 7930 de = dictFind(c->db->blocking_keys,c->blocking_keys[j]);
b177fd30 7931 assert(de != NULL);
7932 l = dictGetEntryVal(de);
7933 listDelNode(l,listSearchKey(l,c));
7934 /* If the list is empty we need to remove it to avoid wasting memory */
7935 if (listLength(l) == 0)
37ab76c9 7936 dictDelete(c->db->blocking_keys,c->blocking_keys[j]);
7937 decrRefCount(c->blocking_keys[j]);
b177fd30 7938 }
7939 /* Cleanup the client structure */
37ab76c9 7940 zfree(c->blocking_keys);
7941 c->blocking_keys = NULL;
4409877e 7942 c->flags &= (~REDIS_BLOCKED);
d5d55fc3 7943 server.blpop_blocked_clients--;
5921aa36 7944 /* We want to process data if there is some command waiting
b0d8747d 7945 * in the input buffer. Note that this is safe even if
7946 * unblockClientWaitingData() gets called from freeClient() because
7947 * freeClient() will be smart enough to call this function
7948 * *after* c->querybuf was set to NULL. */
4409877e 7949 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
7950}
7951
7952/* This should be called from any function PUSHing into lists.
7953 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7954 * 'ele' is the element pushed.
7955 *
7956 * If the function returns 0 there was no client waiting for a list push
7957 * against this key.
7958 *
7959 * If the function returns 1 there was a client waiting for a list push
7960 * against this key, the element was passed to this client thus it's not
7961 * needed to actually add it to the list and the caller should return asap. */
7962static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
7963 struct dictEntry *de;
7964 redisClient *receiver;
7965 list *l;
7966 listNode *ln;
7967
37ab76c9 7968 de = dictFind(c->db->blocking_keys,key);
4409877e 7969 if (de == NULL) return 0;
7970 l = dictGetEntryVal(de);
7971 ln = listFirst(l);
7972 assert(ln != NULL);
7973 receiver = ln->value;
4409877e 7974
b177fd30 7975 addReplySds(receiver,sdsnew("*2\r\n"));
dd88747b 7976 addReplyBulk(receiver,key);
7977 addReplyBulk(receiver,ele);
b0d8747d 7978 unblockClientWaitingData(receiver);
4409877e 7979 return 1;
7980}
7981
7982/* Blocking RPOP/LPOP */
7983static void blockingPopGenericCommand(redisClient *c, int where) {
7984 robj *o;
7985 time_t timeout;
b177fd30 7986 int j;
4409877e 7987
b177fd30 7988 for (j = 1; j < c->argc-1; j++) {
7989 o = lookupKeyWrite(c->db,c->argv[j]);
7990 if (o != NULL) {
7991 if (o->type != REDIS_LIST) {
7992 addReply(c,shared.wrongtypeerr);
4409877e 7993 return;
b177fd30 7994 } else {
7995 list *list = o->ptr;
7996 if (listLength(list) != 0) {
7997 /* If the list contains elements fall back to the usual
7998 * non-blocking POP operation */
7999 robj *argv[2], **orig_argv;
8000 int orig_argc;
e0a62c7f 8001
b177fd30 8002 /* We need to alter the command arguments before to call
8003 * popGenericCommand() as the command takes a single key. */
8004 orig_argv = c->argv;
8005 orig_argc = c->argc;
8006 argv[1] = c->argv[j];
8007 c->argv = argv;
8008 c->argc = 2;
8009
8010 /* Also the return value is different, we need to output
8011 * the multi bulk reply header and the key name. The
8012 * "real" command will add the last element (the value)
8013 * for us. If this souds like an hack to you it's just
8014 * because it is... */
8015 addReplySds(c,sdsnew("*2\r\n"));
dd88747b 8016 addReplyBulk(c,argv[1]);
b177fd30 8017 popGenericCommand(c,where);
8018
8019 /* Fix the client structure with the original stuff */
8020 c->argv = orig_argv;
8021 c->argc = orig_argc;
8022 return;
8023 }
4409877e 8024 }
8025 }
8026 }
8027 /* If the list is empty or the key does not exists we must block */
b177fd30 8028 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
4409877e 8029 if (timeout > 0) timeout += time(NULL);
b177fd30 8030 blockForKeys(c,c->argv+1,c->argc-2,timeout);
4409877e 8031}
8032
8033static void blpopCommand(redisClient *c) {
8034 blockingPopGenericCommand(c,REDIS_HEAD);
8035}
8036
8037static void brpopCommand(redisClient *c) {
8038 blockingPopGenericCommand(c,REDIS_TAIL);
8039}
8040
ed9b544e 8041/* =============================== Replication ============================= */
8042
a4d1ba9a 8043static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 8044 ssize_t nwritten, ret = size;
8045 time_t start = time(NULL);
8046
8047 timeout++;
8048 while(size) {
8049 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
8050 nwritten = write(fd,ptr,size);
8051 if (nwritten == -1) return -1;
8052 ptr += nwritten;
8053 size -= nwritten;
8054 }
8055 if ((time(NULL)-start) > timeout) {
8056 errno = ETIMEDOUT;
8057 return -1;
8058 }
8059 }
8060 return ret;
8061}
8062
a4d1ba9a 8063static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 8064 ssize_t nread, totread = 0;
8065 time_t start = time(NULL);
8066
8067 timeout++;
8068 while(size) {
8069 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
8070 nread = read(fd,ptr,size);
8071 if (nread == -1) return -1;
8072 ptr += nread;
8073 size -= nread;
8074 totread += nread;
8075 }
8076 if ((time(NULL)-start) > timeout) {
8077 errno = ETIMEDOUT;
8078 return -1;
8079 }
8080 }
8081 return totread;
8082}
8083
8084static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
8085 ssize_t nread = 0;
8086
8087 size--;
8088 while(size) {
8089 char c;
8090
8091 if (syncRead(fd,&c,1,timeout) == -1) return -1;
8092 if (c == '\n') {
8093 *ptr = '\0';
8094 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
8095 return nread;
8096 } else {
8097 *ptr++ = c;
8098 *ptr = '\0';
8099 nread++;
8100 }
8101 }
8102 return nread;
8103}
8104
8105static void syncCommand(redisClient *c) {
40d224a9 8106 /* ignore SYNC if aleady slave or in monitor mode */
8107 if (c->flags & REDIS_SLAVE) return;
8108
8109 /* SYNC can't be issued when the server has pending data to send to
8110 * the client about already issued commands. We need a fresh reply
8111 * buffer registering the differences between the BGSAVE and the current
8112 * dataset, so that we can copy to other slaves if needed. */
8113 if (listLength(c->reply) != 0) {
8114 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
8115 return;
8116 }
8117
8118 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
8119 /* Here we need to check if there is a background saving operation
8120 * in progress, or if it is required to start one */
9d65a1bb 8121 if (server.bgsavechildpid != -1) {
40d224a9 8122 /* Ok a background save is in progress. Let's check if it is a good
8123 * one for replication, i.e. if there is another slave that is
8124 * registering differences since the server forked to save */
8125 redisClient *slave;
8126 listNode *ln;
c7df85a4 8127 listIter li;
40d224a9 8128
c7df85a4 8129 listRewind(server.slaves,&li);
8130 while((ln = listNext(&li))) {
40d224a9 8131 slave = ln->value;
8132 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
40d224a9 8133 }
8134 if (ln) {
8135 /* Perfect, the server is already registering differences for
8136 * another slave. Set the right state, and copy the buffer. */
8137 listRelease(c->reply);
8138 c->reply = listDup(slave->reply);
40d224a9 8139 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8140 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
8141 } else {
8142 /* No way, we need to wait for the next BGSAVE in order to
8143 * register differences */
8144 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
8145 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
8146 }
8147 } else {
8148 /* Ok we don't have a BGSAVE in progress, let's start one */
8149 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
8150 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
8151 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
8152 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
8153 return;
8154 }
8155 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8156 }
6208b3a7 8157 c->repldbfd = -1;
40d224a9 8158 c->flags |= REDIS_SLAVE;
8159 c->slaveseldb = 0;
6b47e12e 8160 listAddNodeTail(server.slaves,c);
40d224a9 8161 return;
8162}
8163
6208b3a7 8164static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
8165 redisClient *slave = privdata;
8166 REDIS_NOTUSED(el);
8167 REDIS_NOTUSED(mask);
8168 char buf[REDIS_IOBUF_LEN];
8169 ssize_t nwritten, buflen;
8170
8171 if (slave->repldboff == 0) {
8172 /* Write the bulk write count before to transfer the DB. In theory here
8173 * we don't know how much room there is in the output buffer of the
8174 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
8175 * operations) will never be smaller than the few bytes we need. */
8176 sds bulkcount;
8177
8178 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
8179 slave->repldbsize);
8180 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
8181 {
8182 sdsfree(bulkcount);
8183 freeClient(slave);
8184 return;
8185 }
8186 sdsfree(bulkcount);
8187 }
8188 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
8189 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
8190 if (buflen <= 0) {
8191 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
8192 (buflen == 0) ? "premature EOF" : strerror(errno));
8193 freeClient(slave);
8194 return;
8195 }
8196 if ((nwritten = write(fd,buf,buflen)) == -1) {
f870935d 8197 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
6208b3a7 8198 strerror(errno));
8199 freeClient(slave);
8200 return;
8201 }
8202 slave->repldboff += nwritten;
8203 if (slave->repldboff == slave->repldbsize) {
8204 close(slave->repldbfd);
8205 slave->repldbfd = -1;
8206 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8207 slave->replstate = REDIS_REPL_ONLINE;
8208 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
266373b2 8209 sendReplyToClient, slave) == AE_ERR) {
6208b3a7 8210 freeClient(slave);
8211 return;
8212 }
8213 addReplySds(slave,sdsempty());
8214 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
8215 }
8216}
ed9b544e 8217
a3b21203 8218/* This function is called at the end of every backgrond saving.
8219 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
8220 * otherwise REDIS_ERR is passed to the function.
8221 *
8222 * The goal of this function is to handle slaves waiting for a successful
8223 * background saving in order to perform non-blocking synchronization. */
8224static void updateSlavesWaitingBgsave(int bgsaveerr) {
6208b3a7 8225 listNode *ln;
8226 int startbgsave = 0;
c7df85a4 8227 listIter li;
ed9b544e 8228
c7df85a4 8229 listRewind(server.slaves,&li);
8230 while((ln = listNext(&li))) {
6208b3a7 8231 redisClient *slave = ln->value;
ed9b544e 8232
6208b3a7 8233 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
8234 startbgsave = 1;
8235 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8236 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
dde65f3f 8237 struct redis_stat buf;
e0a62c7f 8238
6208b3a7 8239 if (bgsaveerr != REDIS_OK) {
8240 freeClient(slave);
8241 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
8242 continue;
8243 }
8244 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
dde65f3f 8245 redis_fstat(slave->repldbfd,&buf) == -1) {
6208b3a7 8246 freeClient(slave);
8247 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
8248 continue;
8249 }
8250 slave->repldboff = 0;
8251 slave->repldbsize = buf.st_size;
8252 slave->replstate = REDIS_REPL_SEND_BULK;
8253 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
266373b2 8254 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
6208b3a7 8255 freeClient(slave);
8256 continue;
8257 }
8258 }
ed9b544e 8259 }
6208b3a7 8260 if (startbgsave) {
8261 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
c7df85a4 8262 listIter li;
8263
8264 listRewind(server.slaves,&li);
6208b3a7 8265 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
c7df85a4 8266 while((ln = listNext(&li))) {
6208b3a7 8267 redisClient *slave = ln->value;
ed9b544e 8268
6208b3a7 8269 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
8270 freeClient(slave);
8271 }
8272 }
8273 }
ed9b544e 8274}
8275
8276static int syncWithMaster(void) {
d0ccebcf 8277 char buf[1024], tmpfile[256], authcmd[1024];
18e61fa2 8278 long dumpsize;
ed9b544e 8279 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
8c5abee8 8280 int dfd, maxtries = 5;
ed9b544e 8281
8282 if (fd == -1) {
8283 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
8284 strerror(errno));
8285 return REDIS_ERR;
8286 }
d0ccebcf 8287
8288 /* AUTH with the master if required. */
8289 if(server.masterauth) {
8290 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
8291 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
8292 close(fd);
8293 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
8294 strerror(errno));
8295 return REDIS_ERR;
8296 }
8297 /* Read the AUTH result. */
8298 if (syncReadLine(fd,buf,1024,3600) == -1) {
8299 close(fd);
8300 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
8301 strerror(errno));
8302 return REDIS_ERR;
8303 }
8304 if (buf[0] != '+') {
8305 close(fd);
8306 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
8307 return REDIS_ERR;
8308 }
8309 }
8310
ed9b544e 8311 /* Issue the SYNC command */
8312 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
8313 close(fd);
8314 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
8315 strerror(errno));
8316 return REDIS_ERR;
8317 }
8318 /* Read the bulk write count */
8c4d91fc 8319 if (syncReadLine(fd,buf,1024,3600) == -1) {
ed9b544e 8320 close(fd);
8321 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
8322 strerror(errno));
8323 return REDIS_ERR;
8324 }
4aa701c1 8325 if (buf[0] != '$') {
8326 close(fd);
8327 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8328 return REDIS_ERR;
8329 }
18e61fa2 8330 dumpsize = strtol(buf+1,NULL,10);
8331 redisLog(REDIS_NOTICE,"Receiving %ld bytes data dump from MASTER",dumpsize);
ed9b544e 8332 /* Read the bulk write data on a temp file */
8c5abee8 8333 while(maxtries--) {
8334 snprintf(tmpfile,256,
8335 "temp-%d.%ld.rdb",(int)time(NULL),(long int)getpid());
8336 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
8337 if (dfd != -1) break;
5de9ad7c 8338 sleep(1);
8c5abee8 8339 }
ed9b544e 8340 if (dfd == -1) {
8341 close(fd);
8342 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
8343 return REDIS_ERR;
8344 }
8345 while(dumpsize) {
8346 int nread, nwritten;
8347
8348 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
8349 if (nread == -1) {
8350 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
8351 strerror(errno));
8352 close(fd);
8353 close(dfd);
8354 return REDIS_ERR;
8355 }
8356 nwritten = write(dfd,buf,nread);
8357 if (nwritten == -1) {
8358 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
8359 close(fd);
8360 close(dfd);
8361 return REDIS_ERR;
8362 }
8363 dumpsize -= nread;
8364 }
8365 close(dfd);
8366 if (rename(tmpfile,server.dbfilename) == -1) {
8367 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
8368 unlink(tmpfile);
8369 close(fd);
8370 return REDIS_ERR;
8371 }
8372 emptyDb();
f78fd11b 8373 if (rdbLoad(server.dbfilename) != REDIS_OK) {
ed9b544e 8374 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
8375 close(fd);
8376 return REDIS_ERR;
8377 }
8378 server.master = createClient(fd);
8379 server.master->flags |= REDIS_MASTER;
179b3952 8380 server.master->authenticated = 1;
ed9b544e 8381 server.replstate = REDIS_REPL_CONNECTED;
8382 return REDIS_OK;
8383}
8384
321b0e13 8385static void slaveofCommand(redisClient *c) {
8386 if (!strcasecmp(c->argv[1]->ptr,"no") &&
8387 !strcasecmp(c->argv[2]->ptr,"one")) {
8388 if (server.masterhost) {
8389 sdsfree(server.masterhost);
8390 server.masterhost = NULL;
8391 if (server.master) freeClient(server.master);
8392 server.replstate = REDIS_REPL_NONE;
8393 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
8394 }
8395 } else {
8396 sdsfree(server.masterhost);
8397 server.masterhost = sdsdup(c->argv[1]->ptr);
8398 server.masterport = atoi(c->argv[2]->ptr);
8399 if (server.master) freeClient(server.master);
8400 server.replstate = REDIS_REPL_CONNECT;
8401 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
8402 server.masterhost, server.masterport);
8403 }
8404 addReply(c,shared.ok);
8405}
8406
3fd78bcd 8407/* ============================ Maxmemory directive ======================== */
8408
a5819310 8409/* Try to free one object form the pre-allocated objects free list.
8410 * This is useful under low mem conditions as by default we take 1 million
8411 * free objects allocated. On success REDIS_OK is returned, otherwise
8412 * REDIS_ERR. */
8413static int tryFreeOneObjectFromFreelist(void) {
f870935d 8414 robj *o;
8415
a5819310 8416 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
8417 if (listLength(server.objfreelist)) {
8418 listNode *head = listFirst(server.objfreelist);
8419 o = listNodeValue(head);
8420 listDelNode(server.objfreelist,head);
8421 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8422 zfree(o);
8423 return REDIS_OK;
8424 } else {
8425 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8426 return REDIS_ERR;
8427 }
f870935d 8428}
8429
3fd78bcd 8430/* This function gets called when 'maxmemory' is set on the config file to limit
8431 * the max memory used by the server, and we are out of memory.
8432 * This function will try to, in order:
8433 *
8434 * - Free objects from the free list
8435 * - Try to remove keys with an EXPIRE set
8436 *
8437 * It is not possible to free enough memory to reach used-memory < maxmemory
8438 * the server will start refusing commands that will enlarge even more the
8439 * memory usage.
8440 */
8441static void freeMemoryIfNeeded(void) {
8442 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
a5819310 8443 int j, k, freed = 0;
8444
8445 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
8446 for (j = 0; j < server.dbnum; j++) {
8447 int minttl = -1;
8448 robj *minkey = NULL;
8449 struct dictEntry *de;
8450
8451 if (dictSize(server.db[j].expires)) {
8452 freed = 1;
8453 /* From a sample of three keys drop the one nearest to
8454 * the natural expire */
8455 for (k = 0; k < 3; k++) {
8456 time_t t;
8457
8458 de = dictGetRandomKey(server.db[j].expires);
8459 t = (time_t) dictGetEntryVal(de);
8460 if (minttl == -1 || t < minttl) {
8461 minkey = dictGetEntryKey(de);
8462 minttl = t;
3fd78bcd 8463 }
3fd78bcd 8464 }
a5819310 8465 deleteKey(server.db+j,minkey);
3fd78bcd 8466 }
3fd78bcd 8467 }
a5819310 8468 if (!freed) return; /* nothing to free... */
3fd78bcd 8469 }
8470}
8471
f80dff62 8472/* ============================== Append Only file ========================== */
8473
28ed1f33 8474/* Write the append only file buffer on disk.
8475 *
8476 * Since we are required to write the AOF before replying to the client,
8477 * and the only way the client socket can get a write is entering when the
8478 * the event loop, we accumulate all the AOF writes in a memory
8479 * buffer and write it on disk using this function just before entering
8480 * the event loop again. */
8481static void flushAppendOnlyFile(void) {
8482 time_t now;
8483 ssize_t nwritten;
8484
8485 if (sdslen(server.aofbuf) == 0) return;
8486
8487 /* We want to perform a single write. This should be guaranteed atomic
8488 * at least if the filesystem we are writing is a real physical one.
8489 * While this will save us against the server being killed I don't think
8490 * there is much to do about the whole server stopping for power problems
8491 * or alike */
8492 nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf));
8493 if (nwritten != (signed)sdslen(server.aofbuf)) {
8494 /* Ooops, we are in troubles. The best thing to do for now is
8495 * aborting instead of giving the illusion that everything is
8496 * working as expected. */
8497 if (nwritten == -1) {
8498 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
8499 } else {
8500 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
8501 }
8502 exit(1);
8503 }
8504 sdsfree(server.aofbuf);
8505 server.aofbuf = sdsempty();
8506
8507 /* Fsync if needed */
8508 now = time(NULL);
8509 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
8510 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
8511 now-server.lastfsync > 1))
8512 {
8513 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8514 * flushing metadata. */
8515 aof_fsync(server.appendfd); /* Let's try to get this data on the disk */
8516 server.lastfsync = now;
8517 }
8518}
8519
9376e434
PN
8520static sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) {
8521 int j;
8522 buf = sdscatprintf(buf,"*%d\r\n",argc);
8523 for (j = 0; j < argc; j++) {
8524 robj *o = getDecodedObject(argv[j]);
8525 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
8526 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
8527 buf = sdscatlen(buf,"\r\n",2);
8528 decrRefCount(o);
8529 }
8530 return buf;
8531}
8532
8533static sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) {
8534 int argc = 3;
8535 long when;
8536 robj *argv[3];
8537
8538 /* Make sure we can use strtol */
8539 seconds = getDecodedObject(seconds);
8540 when = time(NULL)+strtol(seconds->ptr,NULL,10);
8541 decrRefCount(seconds);
8542
8543 argv[0] = createStringObject("EXPIREAT",8);
8544 argv[1] = key;
8545 argv[2] = createObject(REDIS_STRING,
8546 sdscatprintf(sdsempty(),"%ld",when));
8547 buf = catAppendOnlyGenericCommand(buf, argc, argv);
8548 decrRefCount(argv[0]);
8549 decrRefCount(argv[2]);
8550 return buf;
8551}
8552
f80dff62 8553static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
8554 sds buf = sdsempty();
f80dff62 8555 robj *tmpargv[3];
8556
8557 /* The DB this command was targetting is not the same as the last command
8558 * we appendend. To issue a SELECT command is needed. */
8559 if (dictid != server.appendseldb) {
8560 char seldb[64];
8561
8562 snprintf(seldb,sizeof(seldb),"%d",dictid);
682ac724 8563 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
83c6a618 8564 (unsigned long)strlen(seldb),seldb);
f80dff62 8565 server.appendseldb = dictid;
8566 }
8567
f80dff62 8568 if (cmd->proc == expireCommand) {
9376e434
PN
8569 /* Translate EXPIRE into EXPIREAT */
8570 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8571 } else if (cmd->proc == setexCommand) {
8572 /* Translate SETEX to SET and EXPIREAT */
8573 tmpargv[0] = createStringObject("SET",3);
f80dff62 8574 tmpargv[1] = argv[1];
9376e434
PN
8575 tmpargv[2] = argv[3];
8576 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
8577 decrRefCount(tmpargv[0]);
8578 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8579 } else {
8580 buf = catAppendOnlyGenericCommand(buf,argc,argv);
f80dff62 8581 }
8582
28ed1f33 8583 /* Append to the AOF buffer. This will be flushed on disk just before
8584 * of re-entering the event loop, so before the client will get a
8585 * positive reply about the operation performed. */
8586 server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf));
8587
85a83172 8588 /* If a background append only file rewriting is in progress we want to
8589 * accumulate the differences between the child DB and the current one
8590 * in a buffer, so that when the child process will do its work we
8591 * can append the differences to the new append only file. */
8592 if (server.bgrewritechildpid != -1)
8593 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
8594
8595 sdsfree(buf);
f80dff62 8596}
8597
8598/* In Redis commands are always executed in the context of a client, so in
8599 * order to load the append only file we need to create a fake client. */
8600static struct redisClient *createFakeClient(void) {
8601 struct redisClient *c = zmalloc(sizeof(*c));
8602
8603 selectDb(c,0);
8604 c->fd = -1;
8605 c->querybuf = sdsempty();
8606 c->argc = 0;
8607 c->argv = NULL;
8608 c->flags = 0;
9387d17d 8609 /* We set the fake client as a slave waiting for the synchronization
8610 * so that Redis will not try to send replies to this client. */
8611 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
f80dff62 8612 c->reply = listCreate();
8613 listSetFreeMethod(c->reply,decrRefCount);
8614 listSetDupMethod(c->reply,dupClientReplyValue);
4132ad8d 8615 initClientMultiState(c);
f80dff62 8616 return c;
8617}
8618
8619static void freeFakeClient(struct redisClient *c) {
8620 sdsfree(c->querybuf);
8621 listRelease(c->reply);
4132ad8d 8622 freeClientMultiState(c);
f80dff62 8623 zfree(c);
8624}
8625
8626/* Replay the append log file. On error REDIS_OK is returned. On non fatal
8627 * error (the append only file is zero-length) REDIS_ERR is returned. On
8628 * fatal error an error message is logged and the program exists. */
8629int loadAppendOnlyFile(char *filename) {
8630 struct redisClient *fakeClient;
8631 FILE *fp = fopen(filename,"r");
8632 struct redis_stat sb;
b492cf00 8633 unsigned long long loadedkeys = 0;
4132ad8d 8634 int appendonly = server.appendonly;
f80dff62 8635
8636 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
8637 return REDIS_ERR;
8638
8639 if (fp == NULL) {
8640 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
8641 exit(1);
8642 }
8643
4132ad8d
PN
8644 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8645 * to the same file we're about to read. */
8646 server.appendonly = 0;
8647
f80dff62 8648 fakeClient = createFakeClient();
8649 while(1) {
8650 int argc, j;
8651 unsigned long len;
8652 robj **argv;
8653 char buf[128];
8654 sds argsds;
8655 struct redisCommand *cmd;
8656
8657 if (fgets(buf,sizeof(buf),fp) == NULL) {
8658 if (feof(fp))
8659 break;
8660 else
8661 goto readerr;
8662 }
8663 if (buf[0] != '*') goto fmterr;
8664 argc = atoi(buf+1);
8665 argv = zmalloc(sizeof(robj*)*argc);
8666 for (j = 0; j < argc; j++) {
8667 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
8668 if (buf[0] != '$') goto fmterr;
8669 len = strtol(buf+1,NULL,10);
8670 argsds = sdsnewlen(NULL,len);
0f151ef1 8671 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
f80dff62 8672 argv[j] = createObject(REDIS_STRING,argsds);
8673 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
8674 }
8675
8676 /* Command lookup */
8677 cmd = lookupCommand(argv[0]->ptr);
8678 if (!cmd) {
8679 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
8680 exit(1);
8681 }
bdcb92f2 8682 /* Try object encoding */
f80dff62 8683 if (cmd->flags & REDIS_CMD_BULK)
05df7621 8684 argv[argc-1] = tryObjectEncoding(argv[argc-1]);
f80dff62 8685 /* Run the command in the context of a fake client */
8686 fakeClient->argc = argc;
8687 fakeClient->argv = argv;
8688 cmd->proc(fakeClient);
8689 /* Discard the reply objects list from the fake client */
8690 while(listLength(fakeClient->reply))
8691 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
8692 /* Clean up, ready for the next command */
8693 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
8694 zfree(argv);
b492cf00 8695 /* Handle swapping while loading big datasets when VM is on */
8696 loadedkeys++;
8697 if (server.vm_enabled && (loadedkeys % 5000) == 0) {
8698 while (zmalloc_used_memory() > server.vm_max_memory) {
a69a0c9c 8699 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
b492cf00 8700 }
8701 }
f80dff62 8702 }
4132ad8d
PN
8703
8704 /* This point can only be reached when EOF is reached without errors.
8705 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8706 if (fakeClient->flags & REDIS_MULTI) goto readerr;
8707
f80dff62 8708 fclose(fp);
8709 freeFakeClient(fakeClient);
4132ad8d 8710 server.appendonly = appendonly;
f80dff62 8711 return REDIS_OK;
8712
8713readerr:
8714 if (feof(fp)) {
8715 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
8716 } else {
8717 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
8718 }
8719 exit(1);
8720fmterr:
8721 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
8722 exit(1);
8723}
8724
9d65a1bb 8725/* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
9c8e3cee 8726static int fwriteBulkObject(FILE *fp, robj *obj) {
9d65a1bb 8727 char buf[128];
b9bc0eef 8728 int decrrc = 0;
8729
f2d9f50f 8730 /* Avoid the incr/decr ref count business if possible to help
8731 * copy-on-write (we are often in a child process when this function
8732 * is called).
8733 * Also makes sure that key objects don't get incrRefCount-ed when VM
8734 * is enabled */
8735 if (obj->encoding != REDIS_ENCODING_RAW) {
b9bc0eef 8736 obj = getDecodedObject(obj);
8737 decrrc = 1;
8738 }
9d65a1bb 8739 snprintf(buf,sizeof(buf),"$%ld\r\n",(long)sdslen(obj->ptr));
8740 if (fwrite(buf,strlen(buf),1,fp) == 0) goto err;
e96e4fbf 8741 if (sdslen(obj->ptr) && fwrite(obj->ptr,sdslen(obj->ptr),1,fp) == 0)
8742 goto err;
9d65a1bb 8743 if (fwrite("\r\n",2,1,fp) == 0) goto err;
b9bc0eef 8744 if (decrrc) decrRefCount(obj);
9d65a1bb 8745 return 1;
8746err:
b9bc0eef 8747 if (decrrc) decrRefCount(obj);
9d65a1bb 8748 return 0;
8749}
8750
9c8e3cee 8751/* Write binary-safe string into a file in the bulkformat
8752 * $<count>\r\n<payload>\r\n */
8753static int fwriteBulkString(FILE *fp, char *s, unsigned long len) {
8754 char buf[128];
8755
8756 snprintf(buf,sizeof(buf),"$%ld\r\n",(unsigned long)len);
8757 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8758 if (len && fwrite(s,len,1,fp) == 0) return 0;
8759 if (fwrite("\r\n",2,1,fp) == 0) return 0;
8760 return 1;
8761}
8762
9d65a1bb 8763/* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8764static int fwriteBulkDouble(FILE *fp, double d) {
8765 char buf[128], dbuf[128];
8766
8767 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
8768 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
8769 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8770 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
8771 return 1;
8772}
8773
8774/* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8775static int fwriteBulkLong(FILE *fp, long l) {
8776 char buf[128], lbuf[128];
8777
8778 snprintf(lbuf,sizeof(lbuf),"%ld\r\n",l);
8779 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(lbuf)-2);
8780 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8781 if (fwrite(lbuf,strlen(lbuf),1,fp) == 0) return 0;
8782 return 1;
8783}
8784
8785/* Write a sequence of commands able to fully rebuild the dataset into
8786 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8787static int rewriteAppendOnlyFile(char *filename) {
8788 dictIterator *di = NULL;
8789 dictEntry *de;
8790 FILE *fp;
8791 char tmpfile[256];
8792 int j;
8793 time_t now = time(NULL);
8794
8795 /* Note that we have to use a different temp name here compared to the
8796 * one used by rewriteAppendOnlyFileBackground() function. */
8797 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
8798 fp = fopen(tmpfile,"w");
8799 if (!fp) {
8800 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
8801 return REDIS_ERR;
8802 }
8803 for (j = 0; j < server.dbnum; j++) {
8804 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
8805 redisDb *db = server.db+j;
8806 dict *d = db->dict;
8807 if (dictSize(d) == 0) continue;
8808 di = dictGetIterator(d);
8809 if (!di) {
8810 fclose(fp);
8811 return REDIS_ERR;
8812 }
8813
8814 /* SELECT the new DB */
8815 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
85a83172 8816 if (fwriteBulkLong(fp,j) == 0) goto werr;
9d65a1bb 8817
8818 /* Iterate this DB writing every entry */
8819 while((de = dictNext(di)) != NULL) {
e7546c63 8820 robj *key, *o;
8821 time_t expiretime;
8822 int swapped;
8823
8824 key = dictGetEntryKey(de);
b9bc0eef 8825 /* If the value for this key is swapped, load a preview in memory.
8826 * We use a "swapped" flag to remember if we need to free the
8827 * value object instead to just increment the ref count anyway
8828 * in order to avoid copy-on-write of pages if we are forked() */
996cb5f7 8829 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
8830 key->storage == REDIS_VM_SWAPPING) {
e7546c63 8831 o = dictGetEntryVal(de);
8832 swapped = 0;
8833 } else {
8834 o = vmPreviewObject(key);
e7546c63 8835 swapped = 1;
8836 }
8837 expiretime = getExpire(db,key);
9d65a1bb 8838
8839 /* Save the key and associated value */
9d65a1bb 8840 if (o->type == REDIS_STRING) {
8841 /* Emit a SET command */
8842 char cmd[]="*3\r\n$3\r\nSET\r\n";
8843 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8844 /* Key and value */
9c8e3cee 8845 if (fwriteBulkObject(fp,key) == 0) goto werr;
8846 if (fwriteBulkObject(fp,o) == 0) goto werr;
9d65a1bb 8847 } else if (o->type == REDIS_LIST) {
8848 /* Emit the RPUSHes needed to rebuild the list */
8849 list *list = o->ptr;
8850 listNode *ln;
c7df85a4 8851 listIter li;
9d65a1bb 8852
c7df85a4 8853 listRewind(list,&li);
8854 while((ln = listNext(&li))) {
9d65a1bb 8855 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
8856 robj *eleobj = listNodeValue(ln);
8857
8858 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8859 if (fwriteBulkObject(fp,key) == 0) goto werr;
8860 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 8861 }
8862 } else if (o->type == REDIS_SET) {
8863 /* Emit the SADDs needed to rebuild the set */
8864 dict *set = o->ptr;
8865 dictIterator *di = dictGetIterator(set);
8866 dictEntry *de;
8867
8868 while((de = dictNext(di)) != NULL) {
8869 char cmd[]="*3\r\n$4\r\nSADD\r\n";
8870 robj *eleobj = dictGetEntryKey(de);
8871
8872 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8873 if (fwriteBulkObject(fp,key) == 0) goto werr;
8874 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 8875 }
8876 dictReleaseIterator(di);
8877 } else if (o->type == REDIS_ZSET) {
8878 /* Emit the ZADDs needed to rebuild the sorted set */
8879 zset *zs = o->ptr;
8880 dictIterator *di = dictGetIterator(zs->dict);
8881 dictEntry *de;
8882
8883 while((de = dictNext(di)) != NULL) {
8884 char cmd[]="*4\r\n$4\r\nZADD\r\n";
8885 robj *eleobj = dictGetEntryKey(de);
8886 double *score = dictGetEntryVal(de);
8887
8888 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8889 if (fwriteBulkObject(fp,key) == 0) goto werr;
9d65a1bb 8890 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
9c8e3cee 8891 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 8892 }
8893 dictReleaseIterator(di);
9c8e3cee 8894 } else if (o->type == REDIS_HASH) {
8895 char cmd[]="*4\r\n$4\r\nHSET\r\n";
8896
8897 /* Emit the HSETs needed to rebuild the hash */
8898 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
8899 unsigned char *p = zipmapRewind(o->ptr);
8900 unsigned char *field, *val;
8901 unsigned int flen, vlen;
8902
8903 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
8904 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8905 if (fwriteBulkObject(fp,key) == 0) goto werr;
8906 if (fwriteBulkString(fp,(char*)field,flen) == -1)
8907 return -1;
8908 if (fwriteBulkString(fp,(char*)val,vlen) == -1)
8909 return -1;
8910 }
8911 } else {
8912 dictIterator *di = dictGetIterator(o->ptr);
8913 dictEntry *de;
8914
8915 while((de = dictNext(di)) != NULL) {
8916 robj *field = dictGetEntryKey(de);
8917 robj *val = dictGetEntryVal(de);
8918
8919 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8920 if (fwriteBulkObject(fp,key) == 0) goto werr;
8921 if (fwriteBulkObject(fp,field) == -1) return -1;
8922 if (fwriteBulkObject(fp,val) == -1) return -1;
8923 }
8924 dictReleaseIterator(di);
8925 }
9d65a1bb 8926 } else {
f83c6cb5 8927 redisPanic("Unknown object type");
9d65a1bb 8928 }
8929 /* Save the expire time */
8930 if (expiretime != -1) {
e96e4fbf 8931 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
9d65a1bb 8932 /* If this key is already expired skip it */
8933 if (expiretime < now) continue;
8934 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8935 if (fwriteBulkObject(fp,key) == 0) goto werr;
9d65a1bb 8936 if (fwriteBulkLong(fp,expiretime) == 0) goto werr;
8937 }
b9bc0eef 8938 if (swapped) decrRefCount(o);
9d65a1bb 8939 }
8940 dictReleaseIterator(di);
8941 }
8942
8943 /* Make sure data will not remain on the OS's output buffers */
8944 fflush(fp);
8945 fsync(fileno(fp));
8946 fclose(fp);
e0a62c7f 8947
9d65a1bb 8948 /* Use RENAME to make sure the DB file is changed atomically only
8949 * if the generate DB file is ok. */
8950 if (rename(tmpfile,filename) == -1) {
8951 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
8952 unlink(tmpfile);
8953 return REDIS_ERR;
8954 }
8955 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
8956 return REDIS_OK;
8957
8958werr:
8959 fclose(fp);
8960 unlink(tmpfile);
e96e4fbf 8961 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
9d65a1bb 8962 if (di) dictReleaseIterator(di);
8963 return REDIS_ERR;
8964}
8965
8966/* This is how rewriting of the append only file in background works:
8967 *
8968 * 1) The user calls BGREWRITEAOF
8969 * 2) Redis calls this function, that forks():
8970 * 2a) the child rewrite the append only file in a temp file.
8971 * 2b) the parent accumulates differences in server.bgrewritebuf.
8972 * 3) When the child finished '2a' exists.
8973 * 4) The parent will trap the exit code, if it's OK, will append the
8974 * data accumulated into server.bgrewritebuf into the temp file, and
8975 * finally will rename(2) the temp file in the actual file name.
8976 * The the new file is reopened as the new append only file. Profit!
8977 */
8978static int rewriteAppendOnlyFileBackground(void) {
8979 pid_t childpid;
8980
8981 if (server.bgrewritechildpid != -1) return REDIS_ERR;
054e426d 8982 if (server.vm_enabled) waitEmptyIOJobsQueue();
9d65a1bb 8983 if ((childpid = fork()) == 0) {
8984 /* Child */
8985 char tmpfile[256];
9d65a1bb 8986
054e426d 8987 if (server.vm_enabled) vmReopenSwapFile();
8988 close(server.fd);
9d65a1bb 8989 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
8990 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
478c2c6f 8991 _exit(0);
9d65a1bb 8992 } else {
478c2c6f 8993 _exit(1);
9d65a1bb 8994 }
8995 } else {
8996 /* Parent */
8997 if (childpid == -1) {
8998 redisLog(REDIS_WARNING,
8999 "Can't rewrite append only file in background: fork: %s",
9000 strerror(errno));
9001 return REDIS_ERR;
9002 }
9003 redisLog(REDIS_NOTICE,
9004 "Background append only file rewriting started by pid %d",childpid);
9005 server.bgrewritechildpid = childpid;
884d4b39 9006 updateDictResizePolicy();
85a83172 9007 /* We set appendseldb to -1 in order to force the next call to the
9008 * feedAppendOnlyFile() to issue a SELECT command, so the differences
9009 * accumulated by the parent into server.bgrewritebuf will start
9010 * with a SELECT statement and it will be safe to merge. */
9011 server.appendseldb = -1;
9d65a1bb 9012 return REDIS_OK;
9013 }
9014 return REDIS_OK; /* unreached */
9015}
9016
9017static void bgrewriteaofCommand(redisClient *c) {
9018 if (server.bgrewritechildpid != -1) {
9019 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
9020 return;
9021 }
9022 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
49b99ab4 9023 char *status = "+Background append only file rewriting started\r\n";
9024 addReplySds(c,sdsnew(status));
9d65a1bb 9025 } else {
9026 addReply(c,shared.err);
9027 }
9028}
9029
9030static void aofRemoveTempFile(pid_t childpid) {
9031 char tmpfile[256];
9032
9033 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
9034 unlink(tmpfile);
9035}
9036
996cb5f7 9037/* Virtual Memory is composed mainly of two subsystems:
9038 * - Blocking Virutal Memory
9039 * - Threaded Virtual Memory I/O
9040 * The two parts are not fully decoupled, but functions are split among two
9041 * different sections of the source code (delimited by comments) in order to
9042 * make more clear what functionality is about the blocking VM and what about
9043 * the threaded (not blocking) VM.
9044 *
9045 * Redis VM design:
9046 *
9047 * Redis VM is a blocking VM (one that blocks reading swapped values from
9048 * disk into memory when a value swapped out is needed in memory) that is made
9049 * unblocking by trying to examine the command argument vector in order to
9050 * load in background values that will likely be needed in order to exec
9051 * the command. The command is executed only once all the relevant keys
9052 * are loaded into memory.
9053 *
9054 * This basically is almost as simple of a blocking VM, but almost as parallel
9055 * as a fully non-blocking VM.
9056 */
9057
2e5eb04e 9058/* Called when the user switches from "appendonly yes" to "appendonly no"
9059 * at runtime using the CONFIG command. */
9060static void stopAppendOnly(void) {
9061 flushAppendOnlyFile();
9062 fsync(server.appendfd);
9063 close(server.appendfd);
9064
9065 server.appendfd = -1;
9066 server.appendseldb = -1;
9067 server.appendonly = 0;
9068 /* rewrite operation in progress? kill it, wait child exit */
9069 if (server.bgsavechildpid != -1) {
9070 int statloc;
9071
30dd89b6 9072 if (kill(server.bgsavechildpid,SIGKILL) != -1)
9073 wait3(&statloc,0,NULL);
2e5eb04e 9074 /* reset the buffer accumulating changes while the child saves */
9075 sdsfree(server.bgrewritebuf);
9076 server.bgrewritebuf = sdsempty();
30dd89b6 9077 server.bgsavechildpid = -1;
2e5eb04e 9078 }
9079}
9080
9081/* Called when the user switches from "appendonly no" to "appendonly yes"
9082 * at runtime using the CONFIG command. */
9083static int startAppendOnly(void) {
9084 server.appendonly = 1;
9085 server.lastfsync = time(NULL);
9086 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
9087 if (server.appendfd == -1) {
9088 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno));
9089 return REDIS_ERR;
9090 }
9091 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
9092 server.appendonly = 0;
9093 close(server.appendfd);
9094 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, I can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.",strerror(errno));
9095 return REDIS_ERR;
9096 }
9097 return REDIS_OK;
9098}
9099
996cb5f7 9100/* =================== Virtual Memory - Blocking Side ====================== */
054e426d 9101
75680a3c 9102static void vmInit(void) {
9103 off_t totsize;
996cb5f7 9104 int pipefds[2];
bcaa7a4f 9105 size_t stacksize;
8b5bb414 9106 struct flock fl;
75680a3c 9107
4ad37480 9108 if (server.vm_max_threads != 0)
9109 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
9110
054e426d 9111 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
8b5bb414 9112 /* Try to open the old swap file, otherwise create it */
6fa987e3 9113 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
9114 server.vm_fp = fopen(server.vm_swap_file,"w+b");
9115 }
75680a3c 9116 if (server.vm_fp == NULL) {
6fa987e3 9117 redisLog(REDIS_WARNING,
8b5bb414 9118 "Can't open the swap file: %s. Exiting.",
6fa987e3 9119 strerror(errno));
75680a3c 9120 exit(1);
9121 }
9122 server.vm_fd = fileno(server.vm_fp);
8b5bb414 9123 /* Lock the swap file for writing, this is useful in order to avoid
9124 * another instance to use the same swap file for a config error. */
9125 fl.l_type = F_WRLCK;
9126 fl.l_whence = SEEK_SET;
9127 fl.l_start = fl.l_len = 0;
9128 if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
9129 redisLog(REDIS_WARNING,
9130 "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));
9131 exit(1);
9132 }
9133 /* Initialize */
75680a3c 9134 server.vm_next_page = 0;
9135 server.vm_near_pages = 0;
7d98e08c 9136 server.vm_stats_used_pages = 0;
9137 server.vm_stats_swapped_objects = 0;
9138 server.vm_stats_swapouts = 0;
9139 server.vm_stats_swapins = 0;
75680a3c 9140 totsize = server.vm_pages*server.vm_page_size;
9141 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
9142 if (ftruncate(server.vm_fd,totsize) == -1) {
9143 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
9144 strerror(errno));
9145 exit(1);
9146 } else {
9147 redisLog(REDIS_NOTICE,"Swap file allocated with success");
9148 }
7d30035d 9149 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
f870935d 9150 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
4ef8de8a 9151 (long long) (server.vm_pages+7)/8, server.vm_pages);
7d30035d 9152 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
92f8e882 9153
996cb5f7 9154 /* Initialize threaded I/O (used by Virtual Memory) */
9155 server.io_newjobs = listCreate();
9156 server.io_processing = listCreate();
9157 server.io_processed = listCreate();
d5d55fc3 9158 server.io_ready_clients = listCreate();
92f8e882 9159 pthread_mutex_init(&server.io_mutex,NULL);
a5819310 9160 pthread_mutex_init(&server.obj_freelist_mutex,NULL);
9161 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
92f8e882 9162 server.io_active_threads = 0;
996cb5f7 9163 if (pipe(pipefds) == -1) {
9164 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
9165 ,strerror(errno));
9166 exit(1);
9167 }
9168 server.io_ready_pipe_read = pipefds[0];
9169 server.io_ready_pipe_write = pipefds[1];
9170 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
bcaa7a4f 9171 /* LZF requires a lot of stack */
9172 pthread_attr_init(&server.io_threads_attr);
9173 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
9174 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
9175 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
b9bc0eef 9176 /* Listen for events in the threaded I/O pipe */
9177 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
9178 vmThreadedIOCompletedJob, NULL) == AE_ERR)
9179 oom("creating file event");
75680a3c 9180}
9181
06224fec 9182/* Mark the page as used */
9183static void vmMarkPageUsed(off_t page) {
9184 off_t byte = page/8;
9185 int bit = page&7;
970e10bb 9186 redisAssert(vmFreePage(page) == 1);
06224fec 9187 server.vm_bitmap[byte] |= 1<<bit;
9188}
9189
9190/* Mark N contiguous pages as used, with 'page' being the first. */
9191static void vmMarkPagesUsed(off_t page, off_t count) {
9192 off_t j;
9193
9194 for (j = 0; j < count; j++)
7d30035d 9195 vmMarkPageUsed(page+j);
7d98e08c 9196 server.vm_stats_used_pages += count;
7c775e09 9197 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
9198 (long long)count, (long long)page);
06224fec 9199}
9200
9201/* Mark the page as free */
9202static void vmMarkPageFree(off_t page) {
9203 off_t byte = page/8;
9204 int bit = page&7;
970e10bb 9205 redisAssert(vmFreePage(page) == 0);
06224fec 9206 server.vm_bitmap[byte] &= ~(1<<bit);
9207}
9208
9209/* Mark N contiguous pages as free, with 'page' being the first. */
9210static void vmMarkPagesFree(off_t page, off_t count) {
9211 off_t j;
9212
9213 for (j = 0; j < count; j++)
7d30035d 9214 vmMarkPageFree(page+j);
7d98e08c 9215 server.vm_stats_used_pages -= count;
7c775e09 9216 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
9217 (long long)count, (long long)page);
06224fec 9218}
9219
9220/* Test if the page is free */
9221static int vmFreePage(off_t page) {
9222 off_t byte = page/8;
9223 int bit = page&7;
7d30035d 9224 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
06224fec 9225}
9226
9227/* Find N contiguous free pages storing the first page of the cluster in *first.
e0a62c7f 9228 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
3a66edc7 9229 * REDIS_ERR is returned.
06224fec 9230 *
9231 * This function uses a simple algorithm: we try to allocate
9232 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
9233 * again from the start of the swap file searching for free spaces.
9234 *
9235 * If it looks pretty clear that there are no free pages near our offset
9236 * we try to find less populated places doing a forward jump of
9237 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
9238 * without hurry, and then we jump again and so forth...
e0a62c7f 9239 *
06224fec 9240 * This function can be improved using a free list to avoid to guess
9241 * too much, since we could collect data about freed pages.
9242 *
9243 * note: I implemented this function just after watching an episode of
9244 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
9245 */
c7df85a4 9246static int vmFindContiguousPages(off_t *first, off_t n) {
06224fec 9247 off_t base, offset = 0, since_jump = 0, numfree = 0;
9248
9249 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
9250 server.vm_near_pages = 0;
9251 server.vm_next_page = 0;
9252 }
9253 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
9254 base = server.vm_next_page;
9255
9256 while(offset < server.vm_pages) {
9257 off_t this = base+offset;
9258
9259 /* If we overflow, restart from page zero */
9260 if (this >= server.vm_pages) {
9261 this -= server.vm_pages;
9262 if (this == 0) {
9263 /* Just overflowed, what we found on tail is no longer
9264 * interesting, as it's no longer contiguous. */
9265 numfree = 0;
9266 }
9267 }
9268 if (vmFreePage(this)) {
9269 /* This is a free page */
9270 numfree++;
9271 /* Already got N free pages? Return to the caller, with success */
9272 if (numfree == n) {
7d30035d 9273 *first = this-(n-1);
9274 server.vm_next_page = this+1;
7c775e09 9275 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
3a66edc7 9276 return REDIS_OK;
06224fec 9277 }
9278 } else {
9279 /* The current one is not a free page */
9280 numfree = 0;
9281 }
9282
9283 /* Fast-forward if the current page is not free and we already
9284 * searched enough near this place. */
9285 since_jump++;
9286 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
9287 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
9288 since_jump = 0;
9289 /* Note that even if we rewind after the jump, we are don't need
9290 * to make sure numfree is set to zero as we only jump *if* it
9291 * is set to zero. */
9292 } else {
9293 /* Otherwise just check the next page */
9294 offset++;
9295 }
9296 }
3a66edc7 9297 return REDIS_ERR;
9298}
9299
a5819310 9300/* Write the specified object at the specified page of the swap file */
9301static int vmWriteObjectOnSwap(robj *o, off_t page) {
9302 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9303 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9304 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9305 redisLog(REDIS_WARNING,
9ebed7cf 9306 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
a5819310 9307 strerror(errno));
9308 return REDIS_ERR;
9309 }
9310 rdbSaveObject(server.vm_fp,o);
ba76a8f9 9311 fflush(server.vm_fp);
a5819310 9312 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9313 return REDIS_OK;
9314}
9315
3a66edc7 9316/* Swap the 'val' object relative to 'key' into disk. Store all the information
9317 * needed to later retrieve the object into the key object.
9318 * If we can't find enough contiguous empty pages to swap the object on disk
9319 * REDIS_ERR is returned. */
a69a0c9c 9320static int vmSwapObjectBlocking(robj *key, robj *val) {
b9bc0eef 9321 off_t pages = rdbSavedObjectPages(val,NULL);
3a66edc7 9322 off_t page;
9323
9324 assert(key->storage == REDIS_VM_MEMORY);
4ef8de8a 9325 assert(key->refcount == 1);
3a66edc7 9326 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return REDIS_ERR;
a5819310 9327 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return REDIS_ERR;
3a66edc7 9328 key->vm.page = page;
9329 key->vm.usedpages = pages;
9330 key->storage = REDIS_VM_SWAPPED;
d894161b 9331 key->vtype = val->type;
3a66edc7 9332 decrRefCount(val); /* Deallocate the object from memory. */
9333 vmMarkPagesUsed(page,pages);
7d30035d 9334 redisLog(REDIS_DEBUG,"VM: object %s swapped out at %lld (%lld pages)",
9335 (unsigned char*) key->ptr,
9336 (unsigned long long) page, (unsigned long long) pages);
7d98e08c 9337 server.vm_stats_swapped_objects++;
9338 server.vm_stats_swapouts++;
3a66edc7 9339 return REDIS_OK;
9340}
9341
a5819310 9342static robj *vmReadObjectFromSwap(off_t page, int type) {
9343 robj *o;
3a66edc7 9344
a5819310 9345 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9346 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
3a66edc7 9347 redisLog(REDIS_WARNING,
d5d55fc3 9348 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
3a66edc7 9349 strerror(errno));
478c2c6f 9350 _exit(1);
3a66edc7 9351 }
a5819310 9352 o = rdbLoadObject(type,server.vm_fp);
9353 if (o == NULL) {
d5d55fc3 9354 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
478c2c6f 9355 _exit(1);
3a66edc7 9356 }
a5819310 9357 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9358 return o;
9359}
9360
9361/* Load the value object relative to the 'key' object from swap to memory.
9362 * The newly allocated object is returned.
9363 *
9364 * If preview is true the unserialized object is returned to the caller but
9365 * no changes are made to the key object, nor the pages are marked as freed */
9366static robj *vmGenericLoadObject(robj *key, int preview) {
9367 robj *val;
9368
d5d55fc3 9369 redisAssert(key->storage == REDIS_VM_SWAPPED || key->storage == REDIS_VM_LOADING);
a5819310 9370 val = vmReadObjectFromSwap(key->vm.page,key->vtype);
7e69548d 9371 if (!preview) {
9372 key->storage = REDIS_VM_MEMORY;
9373 key->vm.atime = server.unixtime;
9374 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9375 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk",
9376 (unsigned char*) key->ptr);
7d98e08c 9377 server.vm_stats_swapped_objects--;
38aba9a1 9378 } else {
9379 redisLog(REDIS_DEBUG, "VM: object %s previewed from disk",
9380 (unsigned char*) key->ptr);
7e69548d 9381 }
7d98e08c 9382 server.vm_stats_swapins++;
3a66edc7 9383 return val;
06224fec 9384}
9385
7e69548d 9386/* Plain object loading, from swap to memory */
9387static robj *vmLoadObject(robj *key) {
996cb5f7 9388 /* If we are loading the object in background, stop it, we
9389 * need to load this object synchronously ASAP. */
9390 if (key->storage == REDIS_VM_LOADING)
9391 vmCancelThreadedIOJob(key);
7e69548d 9392 return vmGenericLoadObject(key,0);
9393}
9394
9395/* Just load the value on disk, without to modify the key.
9396 * This is useful when we want to perform some operation on the value
9397 * without to really bring it from swap to memory, like while saving the
9398 * dataset or rewriting the append only log. */
9399static robj *vmPreviewObject(robj *key) {
9400 return vmGenericLoadObject(key,1);
9401}
9402
4ef8de8a 9403/* How a good candidate is this object for swapping?
9404 * The better candidate it is, the greater the returned value.
9405 *
9406 * Currently we try to perform a fast estimation of the object size in
9407 * memory, and combine it with aging informations.
9408 *
9409 * Basically swappability = idle-time * log(estimated size)
9410 *
9411 * Bigger objects are preferred over smaller objects, but not
9412 * proportionally, this is why we use the logarithm. This algorithm is
9413 * just a first try and will probably be tuned later. */
9414static double computeObjectSwappability(robj *o) {
9415 time_t age = server.unixtime - o->vm.atime;
9416 long asize = 0;
9417 list *l;
9418 dict *d;
9419 struct dictEntry *de;
9420 int z;
9421
9422 if (age <= 0) return 0;
9423 switch(o->type) {
9424 case REDIS_STRING:
9425 if (o->encoding != REDIS_ENCODING_RAW) {
9426 asize = sizeof(*o);
9427 } else {
9428 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
9429 }
9430 break;
9431 case REDIS_LIST:
9432 l = o->ptr;
9433 listNode *ln = listFirst(l);
9434
9435 asize = sizeof(list);
9436 if (ln) {
9437 robj *ele = ln->value;
9438 long elesize;
9439
9440 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9441 (sizeof(*o)+sdslen(ele->ptr)) :
9442 sizeof(*o);
9443 asize += (sizeof(listNode)+elesize)*listLength(l);
9444 }
9445 break;
9446 case REDIS_SET:
9447 case REDIS_ZSET:
9448 z = (o->type == REDIS_ZSET);
9449 d = z ? ((zset*)o->ptr)->dict : o->ptr;
9450
9451 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9452 if (z) asize += sizeof(zset)-sizeof(dict);
9453 if (dictSize(d)) {
9454 long elesize;
9455 robj *ele;
9456
9457 de = dictGetRandomKey(d);
9458 ele = dictGetEntryKey(de);
9459 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9460 (sizeof(*o)+sdslen(ele->ptr)) :
9461 sizeof(*o);
9462 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9463 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
9464 }
9465 break;
a97b9060 9466 case REDIS_HASH:
9467 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9468 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
9469 unsigned int len = zipmapLen((unsigned char*)o->ptr);
9470 unsigned int klen, vlen;
9471 unsigned char *key, *val;
9472
9473 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
9474 klen = 0;
9475 vlen = 0;
9476 }
9477 asize = len*(klen+vlen+3);
9478 } else if (o->encoding == REDIS_ENCODING_HT) {
9479 d = o->ptr;
9480 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9481 if (dictSize(d)) {
9482 long elesize;
9483 robj *ele;
9484
9485 de = dictGetRandomKey(d);
9486 ele = dictGetEntryKey(de);
9487 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9488 (sizeof(*o)+sdslen(ele->ptr)) :
9489 sizeof(*o);
9490 ele = dictGetEntryVal(de);
9491 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9492 (sizeof(*o)+sdslen(ele->ptr)) :
9493 sizeof(*o);
9494 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9495 }
9496 }
9497 break;
4ef8de8a 9498 }
c8c72447 9499 return (double)age*log(1+asize);
4ef8de8a 9500}
9501
9502/* Try to swap an object that's a good candidate for swapping.
9503 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
a69a0c9c 9504 * to swap any object at all.
9505 *
9506 * If 'usethreaded' is true, Redis will try to swap the object in background
9507 * using I/O threads. */
9508static int vmSwapOneObject(int usethreads) {
4ef8de8a 9509 int j, i;
9510 struct dictEntry *best = NULL;
9511 double best_swappability = 0;
b9bc0eef 9512 redisDb *best_db = NULL;
4ef8de8a 9513 robj *key, *val;
9514
9515 for (j = 0; j < server.dbnum; j++) {
9516 redisDb *db = server.db+j;
b72f6a4b 9517 /* Why maxtries is set to 100?
9518 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9519 * are swappable objects */
b0d8747d 9520 int maxtries = 100;
4ef8de8a 9521
9522 if (dictSize(db->dict) == 0) continue;
9523 for (i = 0; i < 5; i++) {
9524 dictEntry *de;
9525 double swappability;
9526
e3cadb8a 9527 if (maxtries) maxtries--;
4ef8de8a 9528 de = dictGetRandomKey(db->dict);
9529 key = dictGetEntryKey(de);
9530 val = dictGetEntryVal(de);
1064ef87 9531 /* Only swap objects that are currently in memory.
9532 *
9533 * Also don't swap shared objects if threaded VM is on, as we
9534 * try to ensure that the main thread does not touch the
9535 * object while the I/O thread is using it, but we can't
9536 * control other keys without adding additional mutex. */
9537 if (key->storage != REDIS_VM_MEMORY ||
9538 (server.vm_max_threads != 0 && val->refcount != 1)) {
e3cadb8a 9539 if (maxtries) i--; /* don't count this try */
9540 continue;
9541 }
4ef8de8a 9542 swappability = computeObjectSwappability(val);
9543 if (!best || swappability > best_swappability) {
9544 best = de;
9545 best_swappability = swappability;
b9bc0eef 9546 best_db = db;
4ef8de8a 9547 }
9548 }
9549 }
7c775e09 9550 if (best == NULL) return REDIS_ERR;
4ef8de8a 9551 key = dictGetEntryKey(best);
9552 val = dictGetEntryVal(best);
9553
e3cadb8a 9554 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
4ef8de8a 9555 key->ptr, best_swappability);
9556
9557 /* Unshare the key if needed */
9558 if (key->refcount > 1) {
9559 robj *newkey = dupStringObject(key);
9560 decrRefCount(key);
9561 key = dictGetEntryKey(best) = newkey;
9562 }
9563 /* Swap it */
a69a0c9c 9564 if (usethreads) {
b9bc0eef 9565 vmSwapObjectThreaded(key,val,best_db);
4ef8de8a 9566 return REDIS_OK;
9567 } else {
a69a0c9c 9568 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
9569 dictGetEntryVal(best) = NULL;
9570 return REDIS_OK;
9571 } else {
9572 return REDIS_ERR;
9573 }
4ef8de8a 9574 }
9575}
9576
a69a0c9c 9577static int vmSwapOneObjectBlocking() {
9578 return vmSwapOneObject(0);
9579}
9580
9581static int vmSwapOneObjectThreaded() {
9582 return vmSwapOneObject(1);
9583}
9584
7e69548d 9585/* Return true if it's safe to swap out objects in a given moment.
9586 * Basically we don't want to swap objects out while there is a BGSAVE
9587 * or a BGAEOREWRITE running in backgroud. */
9588static int vmCanSwapOut(void) {
9589 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
9590}
9591
1b03836c 9592/* Delete a key if swapped. Returns 1 if the key was found, was swapped
9593 * and was deleted. Otherwise 0 is returned. */
9594static int deleteIfSwapped(redisDb *db, robj *key) {
9595 dictEntry *de;
9596 robj *foundkey;
9597
9598 if ((de = dictFind(db->dict,key)) == NULL) return 0;
9599 foundkey = dictGetEntryKey(de);
9600 if (foundkey->storage == REDIS_VM_MEMORY) return 0;
9601 deleteKey(db,key);
9602 return 1;
9603}
9604
996cb5f7 9605/* =================== Virtual Memory - Threaded I/O ======================= */
9606
b9bc0eef 9607static void freeIOJob(iojob *j) {
d5d55fc3 9608 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
9609 j->type == REDIS_IOJOB_DO_SWAP ||
9610 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
b9bc0eef 9611 decrRefCount(j->val);
78ebe4c8 9612 /* We don't decrRefCount the j->key field as we did't incremented
9613 * the count creating IO Jobs. This is because the key field here is
9614 * just used as an indentifier and if a key is removed the Job should
9615 * never be touched again. */
b9bc0eef 9616 zfree(j);
9617}
9618
996cb5f7 9619/* Every time a thread finished a Job, it writes a byte into the write side
9620 * of an unix pipe in order to "awake" the main thread, and this function
9621 * is called. */
9622static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
9623 int mask)
9624{
9625 char buf[1];
b0d8747d 9626 int retval, processed = 0, toprocess = -1, trytoswap = 1;
996cb5f7 9627 REDIS_NOTUSED(el);
9628 REDIS_NOTUSED(mask);
9629 REDIS_NOTUSED(privdata);
9630
9631 /* For every byte we read in the read side of the pipe, there is one
9632 * I/O job completed to process. */
9633 while((retval = read(fd,buf,1)) == 1) {
b9bc0eef 9634 iojob *j;
9635 listNode *ln;
9636 robj *key;
9637 struct dictEntry *de;
9638
996cb5f7 9639 redisLog(REDIS_DEBUG,"Processing I/O completed job");
b9bc0eef 9640
9641 /* Get the processed element (the oldest one) */
9642 lockThreadedIO();
1064ef87 9643 assert(listLength(server.io_processed) != 0);
f6c0bba8 9644 if (toprocess == -1) {
9645 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
9646 if (toprocess <= 0) toprocess = 1;
9647 }
b9bc0eef 9648 ln = listFirst(server.io_processed);
9649 j = ln->value;
9650 listDelNode(server.io_processed,ln);
9651 unlockThreadedIO();
9652 /* If this job is marked as canceled, just ignore it */
9653 if (j->canceled) {
9654 freeIOJob(j);
9655 continue;
9656 }
9657 /* Post process it in the main thread, as there are things we
9658 * can do just here to avoid race conditions and/or invasive locks */
6c96ba7d 9659 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 9660 de = dictFind(j->db->dict,j->key);
9661 assert(de != NULL);
9662 key = dictGetEntryKey(de);
9663 if (j->type == REDIS_IOJOB_LOAD) {
d5d55fc3 9664 redisDb *db;
9665
b9bc0eef 9666 /* Key loaded, bring it at home */
9667 key->storage = REDIS_VM_MEMORY;
9668 key->vm.atime = server.unixtime;
9669 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9670 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
9671 (unsigned char*) key->ptr);
9672 server.vm_stats_swapped_objects--;
9673 server.vm_stats_swapins++;
d5d55fc3 9674 dictGetEntryVal(de) = j->val;
9675 incrRefCount(j->val);
9676 db = j->db;
b9bc0eef 9677 freeIOJob(j);
d5d55fc3 9678 /* Handle clients waiting for this key to be loaded. */
9679 handleClientsBlockedOnSwappedKey(db,key);
b9bc0eef 9680 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9681 /* Now we know the amount of pages required to swap this object.
9682 * Let's find some space for it, and queue this task again
9683 * rebranded as REDIS_IOJOB_DO_SWAP. */
054e426d 9684 if (!vmCanSwapOut() ||
9685 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
9686 {
9687 /* Ooops... no space or we can't swap as there is
9688 * a fork()ed Redis trying to save stuff on disk. */
b9bc0eef 9689 freeIOJob(j);
054e426d 9690 key->storage = REDIS_VM_MEMORY; /* undo operation */
b9bc0eef 9691 } else {
c7df85a4 9692 /* Note that we need to mark this pages as used now,
9693 * if the job will be canceled, we'll mark them as freed
9694 * again. */
9695 vmMarkPagesUsed(j->page,j->pages);
b9bc0eef 9696 j->type = REDIS_IOJOB_DO_SWAP;
9697 lockThreadedIO();
9698 queueIOJob(j);
9699 unlockThreadedIO();
9700 }
9701 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9702 robj *val;
9703
9704 /* Key swapped. We can finally free some memory. */
6c96ba7d 9705 if (key->storage != REDIS_VM_SWAPPING) {
9706 printf("key->storage: %d\n",key->storage);
9707 printf("key->name: %s\n",(char*)key->ptr);
9708 printf("key->refcount: %d\n",key->refcount);
9709 printf("val: %p\n",(void*)j->val);
9710 printf("val->type: %d\n",j->val->type);
9711 printf("val->ptr: %s\n",(char*)j->val->ptr);
9712 }
9713 redisAssert(key->storage == REDIS_VM_SWAPPING);
b9bc0eef 9714 val = dictGetEntryVal(de);
9715 key->vm.page = j->page;
9716 key->vm.usedpages = j->pages;
9717 key->storage = REDIS_VM_SWAPPED;
9718 key->vtype = j->val->type;
9719 decrRefCount(val); /* Deallocate the object from memory. */
f11b8647 9720 dictGetEntryVal(de) = NULL;
b9bc0eef 9721 redisLog(REDIS_DEBUG,
9722 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9723 (unsigned char*) key->ptr,
9724 (unsigned long long) j->page, (unsigned long long) j->pages);
9725 server.vm_stats_swapped_objects++;
9726 server.vm_stats_swapouts++;
9727 freeIOJob(j);
f11b8647 9728 /* Put a few more swap requests in queue if we are still
9729 * out of memory */
b0d8747d 9730 if (trytoswap && vmCanSwapOut() &&
9731 zmalloc_used_memory() > server.vm_max_memory)
9732 {
f11b8647 9733 int more = 1;
9734 while(more) {
9735 lockThreadedIO();
9736 more = listLength(server.io_newjobs) <
9737 (unsigned) server.vm_max_threads;
9738 unlockThreadedIO();
9739 /* Don't waste CPU time if swappable objects are rare. */
b0d8747d 9740 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
9741 trytoswap = 0;
9742 break;
9743 }
f11b8647 9744 }
9745 }
b9bc0eef 9746 }
c953f24b 9747 processed++;
f6c0bba8 9748 if (processed == toprocess) return;
996cb5f7 9749 }
9750 if (retval < 0 && errno != EAGAIN) {
9751 redisLog(REDIS_WARNING,
9752 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9753 strerror(errno));
9754 }
9755}
9756
9757static void lockThreadedIO(void) {
9758 pthread_mutex_lock(&server.io_mutex);
9759}
9760
9761static void unlockThreadedIO(void) {
9762 pthread_mutex_unlock(&server.io_mutex);
9763}
9764
9765/* Remove the specified object from the threaded I/O queue if still not
9766 * processed, otherwise make sure to flag it as canceled. */
9767static void vmCancelThreadedIOJob(robj *o) {
9768 list *lists[3] = {
6c96ba7d 9769 server.io_newjobs, /* 0 */
9770 server.io_processing, /* 1 */
9771 server.io_processed /* 2 */
996cb5f7 9772 };
9773 int i;
9774
9775 assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
2e111efe 9776again:
996cb5f7 9777 lockThreadedIO();
9778 /* Search for a matching key in one of the queues */
9779 for (i = 0; i < 3; i++) {
9780 listNode *ln;
c7df85a4 9781 listIter li;
996cb5f7 9782
c7df85a4 9783 listRewind(lists[i],&li);
9784 while ((ln = listNext(&li)) != NULL) {
996cb5f7 9785 iojob *job = ln->value;
9786
6c96ba7d 9787 if (job->canceled) continue; /* Skip this, already canceled. */
78ebe4c8 9788 if (job->key == o) {
970e10bb 9789 redisLog(REDIS_DEBUG,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
9790 (void*)job, (char*)o->ptr, job->type, i);
427a2153 9791 /* Mark the pages as free since the swap didn't happened
9792 * or happened but is now discarded. */
970e10bb 9793 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
427a2153 9794 vmMarkPagesFree(job->page,job->pages);
9795 /* Cancel the job. It depends on the list the job is
9796 * living in. */
996cb5f7 9797 switch(i) {
9798 case 0: /* io_newjobs */
6c96ba7d 9799 /* If the job was yet not processed the best thing to do
996cb5f7 9800 * is to remove it from the queue at all */
6c96ba7d 9801 freeIOJob(job);
996cb5f7 9802 listDelNode(lists[i],ln);
9803 break;
9804 case 1: /* io_processing */
d5d55fc3 9805 /* Oh Shi- the thread is messing with the Job:
9806 *
9807 * Probably it's accessing the object if this is a
9808 * PREPARE_SWAP or DO_SWAP job.
9809 * If it's a LOAD job it may be reading from disk and
9810 * if we don't wait for the job to terminate before to
9811 * cancel it, maybe in a few microseconds data can be
9812 * corrupted in this pages. So the short story is:
9813 *
9814 * Better to wait for the job to move into the
9815 * next queue (processed)... */
9816
9817 /* We try again and again until the job is completed. */
9818 unlockThreadedIO();
9819 /* But let's wait some time for the I/O thread
9820 * to finish with this job. After all this condition
9821 * should be very rare. */
9822 usleep(1);
9823 goto again;
996cb5f7 9824 case 2: /* io_processed */
2e111efe 9825 /* The job was already processed, that's easy...
9826 * just mark it as canceled so that we'll ignore it
9827 * when processing completed jobs. */
996cb5f7 9828 job->canceled = 1;
9829 break;
9830 }
c7df85a4 9831 /* Finally we have to adjust the storage type of the object
9832 * in order to "UNDO" the operaiton. */
996cb5f7 9833 if (o->storage == REDIS_VM_LOADING)
9834 o->storage = REDIS_VM_SWAPPED;
9835 else if (o->storage == REDIS_VM_SWAPPING)
9836 o->storage = REDIS_VM_MEMORY;
9837 unlockThreadedIO();
9838 return;
9839 }
9840 }
9841 }
9842 unlockThreadedIO();
9843 assert(1 != 1); /* We should never reach this */
9844}
9845
b9bc0eef 9846static void *IOThreadEntryPoint(void *arg) {
9847 iojob *j;
9848 listNode *ln;
9849 REDIS_NOTUSED(arg);
9850
9851 pthread_detach(pthread_self());
9852 while(1) {
9853 /* Get a new job to process */
9854 lockThreadedIO();
9855 if (listLength(server.io_newjobs) == 0) {
9856 /* No new jobs in queue, exit. */
9ebed7cf 9857 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
9858 (long) pthread_self());
b9bc0eef 9859 server.io_active_threads--;
9860 unlockThreadedIO();
9861 return NULL;
9862 }
9863 ln = listFirst(server.io_newjobs);
9864 j = ln->value;
9865 listDelNode(server.io_newjobs,ln);
9866 /* Add the job in the processing queue */
9867 j->thread = pthread_self();
9868 listAddNodeTail(server.io_processing,j);
9869 ln = listLast(server.io_processing); /* We use ln later to remove it */
9870 unlockThreadedIO();
9ebed7cf 9871 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
9872 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
b9bc0eef 9873
9874 /* Process the Job */
9875 if (j->type == REDIS_IOJOB_LOAD) {
d5d55fc3 9876 j->val = vmReadObjectFromSwap(j->page,j->key->vtype);
b9bc0eef 9877 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9878 FILE *fp = fopen("/dev/null","w+");
9879 j->pages = rdbSavedObjectPages(j->val,fp);
9880 fclose(fp);
9881 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
a5819310 9882 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
9883 j->canceled = 1;
b9bc0eef 9884 }
9885
9886 /* Done: insert the job into the processed queue */
9ebed7cf 9887 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
9888 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
b9bc0eef 9889 lockThreadedIO();
9890 listDelNode(server.io_processing,ln);
9891 listAddNodeTail(server.io_processed,j);
9892 unlockThreadedIO();
e0a62c7f 9893
b9bc0eef 9894 /* Signal the main thread there is new stuff to process */
9895 assert(write(server.io_ready_pipe_write,"x",1) == 1);
9896 }
9897 return NULL; /* never reached */
9898}
9899
9900static void spawnIOThread(void) {
9901 pthread_t thread;
478c2c6f 9902 sigset_t mask, omask;
a97b9060 9903 int err;
b9bc0eef 9904
478c2c6f 9905 sigemptyset(&mask);
9906 sigaddset(&mask,SIGCHLD);
9907 sigaddset(&mask,SIGHUP);
9908 sigaddset(&mask,SIGPIPE);
9909 pthread_sigmask(SIG_SETMASK, &mask, &omask);
a97b9060 9910 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
9911 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
9912 strerror(err));
9913 usleep(1000000);
9914 }
478c2c6f 9915 pthread_sigmask(SIG_SETMASK, &omask, NULL);
b9bc0eef 9916 server.io_active_threads++;
9917}
9918
4ee9488d 9919/* We need to wait for the last thread to exit before we are able to
9920 * fork() in order to BGSAVE or BGREWRITEAOF. */
054e426d 9921static void waitEmptyIOJobsQueue(void) {
4ee9488d 9922 while(1) {
76b7233a 9923 int io_processed_len;
9924
4ee9488d 9925 lockThreadedIO();
054e426d 9926 if (listLength(server.io_newjobs) == 0 &&
9927 listLength(server.io_processing) == 0 &&
9928 server.io_active_threads == 0)
9929 {
4ee9488d 9930 unlockThreadedIO();
9931 return;
9932 }
76b7233a 9933 /* While waiting for empty jobs queue condition we post-process some
9934 * finshed job, as I/O threads may be hanging trying to write against
9935 * the io_ready_pipe_write FD but there are so much pending jobs that
9936 * it's blocking. */
9937 io_processed_len = listLength(server.io_processed);
4ee9488d 9938 unlockThreadedIO();
76b7233a 9939 if (io_processed_len) {
9940 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
9941 usleep(1000); /* 1 millisecond */
9942 } else {
9943 usleep(10000); /* 10 milliseconds */
9944 }
4ee9488d 9945 }
9946}
9947
054e426d 9948static void vmReopenSwapFile(void) {
478c2c6f 9949 /* Note: we don't close the old one as we are in the child process
9950 * and don't want to mess at all with the original file object. */
054e426d 9951 server.vm_fp = fopen(server.vm_swap_file,"r+b");
9952 if (server.vm_fp == NULL) {
9953 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
9954 server.vm_swap_file);
478c2c6f 9955 _exit(1);
054e426d 9956 }
9957 server.vm_fd = fileno(server.vm_fp);
9958}
9959
b9bc0eef 9960/* This function must be called while with threaded IO locked */
9961static void queueIOJob(iojob *j) {
6c96ba7d 9962 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
9963 (void*)j, j->type, (char*)j->key->ptr);
b9bc0eef 9964 listAddNodeTail(server.io_newjobs,j);
9965 if (server.io_active_threads < server.vm_max_threads)
9966 spawnIOThread();
9967}
9968
9969static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
9970 iojob *j;
e0a62c7f 9971
b9bc0eef 9972 assert(key->storage == REDIS_VM_MEMORY);
9973 assert(key->refcount == 1);
9974
9975 j = zmalloc(sizeof(*j));
9976 j->type = REDIS_IOJOB_PREPARE_SWAP;
9977 j->db = db;
78ebe4c8 9978 j->key = key;
b9bc0eef 9979 j->val = val;
9980 incrRefCount(val);
9981 j->canceled = 0;
9982 j->thread = (pthread_t) -1;
f11b8647 9983 key->storage = REDIS_VM_SWAPPING;
b9bc0eef 9984
9985 lockThreadedIO();
9986 queueIOJob(j);
9987 unlockThreadedIO();
9988 return REDIS_OK;
9989}
9990
b0d8747d 9991/* ============ Virtual Memory - Blocking clients on missing keys =========== */
9992
d5d55fc3 9993/* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
9994 * If there is not already a job loading the key, it is craeted.
9995 * The key is added to the io_keys list in the client structure, and also
9996 * in the hash table mapping swapped keys to waiting clients, that is,
9997 * server.io_waited_keys. */
9998static int waitForSwappedKey(redisClient *c, robj *key) {
9999 struct dictEntry *de;
10000 robj *o;
10001 list *l;
10002
10003 /* If the key does not exist or is already in RAM we don't need to
10004 * block the client at all. */
10005 de = dictFind(c->db->dict,key);
10006 if (de == NULL) return 0;
10007 o = dictGetEntryKey(de);
10008 if (o->storage == REDIS_VM_MEMORY) {
10009 return 0;
10010 } else if (o->storage == REDIS_VM_SWAPPING) {
10011 /* We were swapping the key, undo it! */
10012 vmCancelThreadedIOJob(o);
10013 return 0;
10014 }
e0a62c7f 10015
d5d55fc3 10016 /* OK: the key is either swapped, or being loaded just now. */
10017
10018 /* Add the key to the list of keys this client is waiting for.
10019 * This maps clients to keys they are waiting for. */
10020 listAddNodeTail(c->io_keys,key);
10021 incrRefCount(key);
10022
10023 /* Add the client to the swapped keys => clients waiting map. */
10024 de = dictFind(c->db->io_keys,key);
10025 if (de == NULL) {
10026 int retval;
10027
10028 /* For every key we take a list of clients blocked for it */
10029 l = listCreate();
10030 retval = dictAdd(c->db->io_keys,key,l);
10031 incrRefCount(key);
10032 assert(retval == DICT_OK);
10033 } else {
10034 l = dictGetEntryVal(de);
10035 }
10036 listAddNodeTail(l,c);
10037
10038 /* Are we already loading the key from disk? If not create a job */
10039 if (o->storage == REDIS_VM_SWAPPED) {
10040 iojob *j;
10041
10042 o->storage = REDIS_VM_LOADING;
10043 j = zmalloc(sizeof(*j));
10044 j->type = REDIS_IOJOB_LOAD;
10045 j->db = c->db;
78ebe4c8 10046 j->key = o;
d5d55fc3 10047 j->key->vtype = o->vtype;
10048 j->page = o->vm.page;
10049 j->val = NULL;
10050 j->canceled = 0;
10051 j->thread = (pthread_t) -1;
10052 lockThreadedIO();
10053 queueIOJob(j);
10054 unlockThreadedIO();
10055 }
10056 return 1;
10057}
10058
6f078746
PN
10059/* Preload keys for any command with first, last and step values for
10060 * the command keys prototype, as defined in the command table. */
10061static void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10062 int j, last;
10063 if (cmd->vm_firstkey == 0) return;
10064 last = cmd->vm_lastkey;
10065 if (last < 0) last = argc+last;
10066 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
10067 redisAssert(j < argc);
10068 waitForSwappedKey(c,argv[j]);
10069 }
10070}
10071
5d373da9 10072/* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
739ba0d2
PN
10073 * Note that the number of keys to preload is user-defined, so we need to
10074 * apply a sanity check against argc. */
ca1788b5 10075static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
76583ea4 10076 int i, num;
ca1788b5 10077 REDIS_NOTUSED(cmd);
ca1788b5
PN
10078
10079 num = atoi(argv[2]->ptr);
739ba0d2 10080 if (num > (argc-3)) return;
76583ea4 10081 for (i = 0; i < num; i++) {
ca1788b5 10082 waitForSwappedKey(c,argv[3+i]);
76583ea4
PN
10083 }
10084}
10085
3805e04f
PN
10086/* Preload keys needed to execute the entire MULTI/EXEC block.
10087 *
10088 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
10089 * and will block the client when any command requires a swapped out value. */
10090static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10091 int i, margc;
10092 struct redisCommand *mcmd;
10093 robj **margv;
10094 REDIS_NOTUSED(cmd);
10095 REDIS_NOTUSED(argc);
10096 REDIS_NOTUSED(argv);
10097
10098 if (!(c->flags & REDIS_MULTI)) return;
10099 for (i = 0; i < c->mstate.count; i++) {
10100 mcmd = c->mstate.commands[i].cmd;
10101 margc = c->mstate.commands[i].argc;
10102 margv = c->mstate.commands[i].argv;
10103
10104 if (mcmd->vm_preload_proc != NULL) {
10105 mcmd->vm_preload_proc(c,mcmd,margc,margv);
10106 } else {
10107 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
10108 }
76583ea4
PN
10109 }
10110}
10111
b0d8747d 10112/* Is this client attempting to run a command against swapped keys?
d5d55fc3 10113 * If so, block it ASAP, load the keys in background, then resume it.
b0d8747d 10114 *
d5d55fc3 10115 * The important idea about this function is that it can fail! If keys will
10116 * still be swapped when the client is resumed, this key lookups will
10117 * just block loading keys from disk. In practical terms this should only
10118 * happen with SORT BY command or if there is a bug in this function.
10119 *
10120 * Return 1 if the client is marked as blocked, 0 if the client can
10121 * continue as the keys it is going to access appear to be in memory. */
0a6f3f0f 10122static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
76583ea4 10123 if (cmd->vm_preload_proc != NULL) {
ca1788b5 10124 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
76583ea4 10125 } else {
6f078746 10126 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
76583ea4
PN
10127 }
10128
d5d55fc3 10129 /* If the client was blocked for at least one key, mark it as blocked. */
10130 if (listLength(c->io_keys)) {
10131 c->flags |= REDIS_IO_WAIT;
10132 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
10133 server.vm_blocked_clients++;
10134 return 1;
10135 } else {
10136 return 0;
10137 }
10138}
10139
10140/* Remove the 'key' from the list of blocked keys for a given client.
10141 *
10142 * The function returns 1 when there are no longer blocking keys after
10143 * the current one was removed (and the client can be unblocked). */
10144static int dontWaitForSwappedKey(redisClient *c, robj *key) {
10145 list *l;
10146 listNode *ln;
10147 listIter li;
10148 struct dictEntry *de;
10149
10150 /* Remove the key from the list of keys this client is waiting for. */
10151 listRewind(c->io_keys,&li);
10152 while ((ln = listNext(&li)) != NULL) {
bf028098 10153 if (equalStringObjects(ln->value,key)) {
d5d55fc3 10154 listDelNode(c->io_keys,ln);
10155 break;
10156 }
10157 }
10158 assert(ln != NULL);
10159
10160 /* Remove the client form the key => waiting clients map. */
10161 de = dictFind(c->db->io_keys,key);
10162 assert(de != NULL);
10163 l = dictGetEntryVal(de);
10164 ln = listSearchKey(l,c);
10165 assert(ln != NULL);
10166 listDelNode(l,ln);
10167 if (listLength(l) == 0)
10168 dictDelete(c->db->io_keys,key);
10169
10170 return listLength(c->io_keys) == 0;
10171}
10172
10173static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
10174 struct dictEntry *de;
10175 list *l;
10176 listNode *ln;
10177 int len;
10178
10179 de = dictFind(db->io_keys,key);
10180 if (!de) return;
10181
10182 l = dictGetEntryVal(de);
10183 len = listLength(l);
10184 /* Note: we can't use something like while(listLength(l)) as the list
10185 * can be freed by the calling function when we remove the last element. */
10186 while (len--) {
10187 ln = listFirst(l);
10188 redisClient *c = ln->value;
10189
10190 if (dontWaitForSwappedKey(c,key)) {
10191 /* Put the client in the list of clients ready to go as we
10192 * loaded all the keys about it. */
10193 listAddNodeTail(server.io_ready_clients,c);
10194 }
10195 }
b0d8747d 10196}
b0d8747d 10197
500ece7c 10198/* =========================== Remote Configuration ========================= */
10199
10200static void configSetCommand(redisClient *c) {
10201 robj *o = getDecodedObject(c->argv[3]);
2e5eb04e 10202 long long ll;
10203
500ece7c 10204 if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
10205 zfree(server.dbfilename);
10206 server.dbfilename = zstrdup(o->ptr);
10207 } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
10208 zfree(server.requirepass);
10209 server.requirepass = zstrdup(o->ptr);
10210 } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
10211 zfree(server.masterauth);
10212 server.masterauth = zstrdup(o->ptr);
10213 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
2e5eb04e 10214 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10215 ll < 0) goto badfmt;
10216 server.maxmemory = ll;
10217 } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
10218 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10219 ll < 0 || ll > LONG_MAX) goto badfmt;
10220 server.maxidletime = ll;
1b677732 10221 } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
10222 if (!strcasecmp(o->ptr,"no")) {
10223 server.appendfsync = APPENDFSYNC_NO;
10224 } else if (!strcasecmp(o->ptr,"everysec")) {
10225 server.appendfsync = APPENDFSYNC_EVERYSEC;
10226 } else if (!strcasecmp(o->ptr,"always")) {
10227 server.appendfsync = APPENDFSYNC_ALWAYS;
10228 } else {
10229 goto badfmt;
10230 }
2e5eb04e 10231 } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
10232 int old = server.appendonly;
10233 int new = yesnotoi(o->ptr);
10234
10235 if (new == -1) goto badfmt;
10236 if (old != new) {
10237 if (new == 0) {
10238 stopAppendOnly();
10239 } else {
10240 if (startAppendOnly() == REDIS_ERR) {
10241 addReplySds(c,sdscatprintf(sdsempty(),
10242 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
10243 decrRefCount(o);
10244 return;
10245 }
10246 }
10247 }
a34e0a25 10248 } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
10249 int vlen, j;
10250 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
10251
10252 /* Perform sanity check before setting the new config:
10253 * - Even number of args
10254 * - Seconds >= 1, changes >= 0 */
10255 if (vlen & 1) {
10256 sdsfreesplitres(v,vlen);
10257 goto badfmt;
10258 }
10259 for (j = 0; j < vlen; j++) {
10260 char *eptr;
10261 long val;
10262
10263 val = strtoll(v[j], &eptr, 10);
10264 if (eptr[0] != '\0' ||
10265 ((j & 1) == 0 && val < 1) ||
10266 ((j & 1) == 1 && val < 0)) {
10267 sdsfreesplitres(v,vlen);
10268 goto badfmt;
10269 }
10270 }
10271 /* Finally set the new config */
10272 resetServerSaveParams();
10273 for (j = 0; j < vlen; j += 2) {
10274 time_t seconds;
10275 int changes;
10276
10277 seconds = strtoll(v[j],NULL,10);
10278 changes = strtoll(v[j+1],NULL,10);
10279 appendServerSaveParams(seconds, changes);
10280 }
10281 sdsfreesplitres(v,vlen);
500ece7c 10282 } else {
10283 addReplySds(c,sdscatprintf(sdsempty(),
10284 "-ERR not supported CONFIG parameter %s\r\n",
10285 (char*)c->argv[2]->ptr));
10286 decrRefCount(o);
10287 return;
10288 }
10289 decrRefCount(o);
10290 addReply(c,shared.ok);
a34e0a25 10291 return;
10292
10293badfmt: /* Bad format errors */
10294 addReplySds(c,sdscatprintf(sdsempty(),
10295 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
10296 (char*)o->ptr,
10297 (char*)c->argv[2]->ptr));
10298 decrRefCount(o);
500ece7c 10299}
10300
10301static void configGetCommand(redisClient *c) {
10302 robj *o = getDecodedObject(c->argv[2]);
10303 robj *lenobj = createObject(REDIS_STRING,NULL);
10304 char *pattern = o->ptr;
10305 int matches = 0;
10306
10307 addReply(c,lenobj);
10308 decrRefCount(lenobj);
10309
10310 if (stringmatch(pattern,"dbfilename",0)) {
10311 addReplyBulkCString(c,"dbfilename");
10312 addReplyBulkCString(c,server.dbfilename);
10313 matches++;
10314 }
10315 if (stringmatch(pattern,"requirepass",0)) {
10316 addReplyBulkCString(c,"requirepass");
10317 addReplyBulkCString(c,server.requirepass);
10318 matches++;
10319 }
10320 if (stringmatch(pattern,"masterauth",0)) {
10321 addReplyBulkCString(c,"masterauth");
10322 addReplyBulkCString(c,server.masterauth);
10323 matches++;
10324 }
10325 if (stringmatch(pattern,"maxmemory",0)) {
10326 char buf[128];
10327
2e5eb04e 10328 ll2string(buf,128,server.maxmemory);
500ece7c 10329 addReplyBulkCString(c,"maxmemory");
10330 addReplyBulkCString(c,buf);
10331 matches++;
10332 }
2e5eb04e 10333 if (stringmatch(pattern,"timeout",0)) {
10334 char buf[128];
10335
10336 ll2string(buf,128,server.maxidletime);
10337 addReplyBulkCString(c,"timeout");
10338 addReplyBulkCString(c,buf);
10339 matches++;
10340 }
10341 if (stringmatch(pattern,"appendonly",0)) {
10342 addReplyBulkCString(c,"appendonly");
10343 addReplyBulkCString(c,server.appendonly ? "yes" : "no");
10344 matches++;
10345 }
1b677732 10346 if (stringmatch(pattern,"appendfsync",0)) {
10347 char *policy;
10348
10349 switch(server.appendfsync) {
10350 case APPENDFSYNC_NO: policy = "no"; break;
10351 case APPENDFSYNC_EVERYSEC: policy = "everysec"; break;
10352 case APPENDFSYNC_ALWAYS: policy = "always"; break;
10353 default: policy = "unknown"; break; /* too harmless to panic */
10354 }
10355 addReplyBulkCString(c,"appendfsync");
10356 addReplyBulkCString(c,policy);
10357 matches++;
10358 }
a34e0a25 10359 if (stringmatch(pattern,"save",0)) {
10360 sds buf = sdsempty();
10361 int j;
10362
10363 for (j = 0; j < server.saveparamslen; j++) {
10364 buf = sdscatprintf(buf,"%ld %d",
10365 server.saveparams[j].seconds,
10366 server.saveparams[j].changes);
10367 if (j != server.saveparamslen-1)
10368 buf = sdscatlen(buf," ",1);
10369 }
10370 addReplyBulkCString(c,"save");
10371 addReplyBulkCString(c,buf);
10372 sdsfree(buf);
10373 matches++;
10374 }
500ece7c 10375 decrRefCount(o);
10376 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",matches*2);
10377}
10378
10379static void configCommand(redisClient *c) {
10380 if (!strcasecmp(c->argv[1]->ptr,"set")) {
10381 if (c->argc != 4) goto badarity;
10382 configSetCommand(c);
10383 } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
10384 if (c->argc != 3) goto badarity;
10385 configGetCommand(c);
10386 } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
10387 if (c->argc != 2) goto badarity;
10388 server.stat_numcommands = 0;
10389 server.stat_numconnections = 0;
10390 server.stat_expiredkeys = 0;
10391 server.stat_starttime = time(NULL);
10392 addReply(c,shared.ok);
10393 } else {
10394 addReplySds(c,sdscatprintf(sdsempty(),
10395 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10396 }
10397 return;
10398
10399badarity:
10400 addReplySds(c,sdscatprintf(sdsempty(),
10401 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10402 (char*) c->argv[1]->ptr));
10403}
10404
befec3cd 10405/* =========================== Pubsub implementation ======================== */
10406
ffc6b7f8 10407static void freePubsubPattern(void *p) {
10408 pubsubPattern *pat = p;
10409
10410 decrRefCount(pat->pattern);
10411 zfree(pat);
10412}
10413
10414static int listMatchPubsubPattern(void *a, void *b) {
10415 pubsubPattern *pa = a, *pb = b;
10416
10417 return (pa->client == pb->client) &&
bf028098 10418 (equalStringObjects(pa->pattern,pb->pattern));
ffc6b7f8 10419}
10420
10421/* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10422 * 0 if the client was already subscribed to that channel. */
10423static int pubsubSubscribeChannel(redisClient *c, robj *channel) {
befec3cd 10424 struct dictEntry *de;
10425 list *clients = NULL;
10426 int retval = 0;
10427
ffc6b7f8 10428 /* Add the channel to the client -> channels hash table */
10429 if (dictAdd(c->pubsub_channels,channel,NULL) == DICT_OK) {
befec3cd 10430 retval = 1;
ffc6b7f8 10431 incrRefCount(channel);
10432 /* Add the client to the channel -> list of clients hash table */
10433 de = dictFind(server.pubsub_channels,channel);
befec3cd 10434 if (de == NULL) {
10435 clients = listCreate();
ffc6b7f8 10436 dictAdd(server.pubsub_channels,channel,clients);
10437 incrRefCount(channel);
befec3cd 10438 } else {
10439 clients = dictGetEntryVal(de);
10440 }
10441 listAddNodeTail(clients,c);
10442 }
10443 /* Notify the client */
10444 addReply(c,shared.mbulk3);
10445 addReply(c,shared.subscribebulk);
ffc6b7f8 10446 addReplyBulk(c,channel);
482b672d 10447 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
befec3cd 10448 return retval;
10449}
10450
ffc6b7f8 10451/* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10452 * 0 if the client was not subscribed to the specified channel. */
10453static int pubsubUnsubscribeChannel(redisClient *c, robj *channel, int notify) {
befec3cd 10454 struct dictEntry *de;
10455 list *clients;
10456 listNode *ln;
10457 int retval = 0;
10458
ffc6b7f8 10459 /* Remove the channel from the client -> channels hash table */
10460 incrRefCount(channel); /* channel may be just a pointer to the same object
201037f5 10461 we have in the hash tables. Protect it... */
ffc6b7f8 10462 if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
befec3cd 10463 retval = 1;
ffc6b7f8 10464 /* Remove the client from the channel -> clients list hash table */
10465 de = dictFind(server.pubsub_channels,channel);
befec3cd 10466 assert(de != NULL);
10467 clients = dictGetEntryVal(de);
10468 ln = listSearchKey(clients,c);
10469 assert(ln != NULL);
10470 listDelNode(clients,ln);
ff767a75 10471 if (listLength(clients) == 0) {
10472 /* Free the list and associated hash entry at all if this was
10473 * the latest client, so that it will be possible to abuse
ffc6b7f8 10474 * Redis PUBSUB creating millions of channels. */
10475 dictDelete(server.pubsub_channels,channel);
ff767a75 10476 }
befec3cd 10477 }
10478 /* Notify the client */
10479 if (notify) {
10480 addReply(c,shared.mbulk3);
10481 addReply(c,shared.unsubscribebulk);
ffc6b7f8 10482 addReplyBulk(c,channel);
482b672d 10483 addReplyLongLong(c,dictSize(c->pubsub_channels)+
ffc6b7f8 10484 listLength(c->pubsub_patterns));
10485
10486 }
10487 decrRefCount(channel); /* it is finally safe to release it */
10488 return retval;
10489}
10490
10491/* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10492static int pubsubSubscribePattern(redisClient *c, robj *pattern) {
10493 int retval = 0;
10494
10495 if (listSearchKey(c->pubsub_patterns,pattern) == NULL) {
10496 retval = 1;
10497 pubsubPattern *pat;
10498 listAddNodeTail(c->pubsub_patterns,pattern);
10499 incrRefCount(pattern);
10500 pat = zmalloc(sizeof(*pat));
10501 pat->pattern = getDecodedObject(pattern);
10502 pat->client = c;
10503 listAddNodeTail(server.pubsub_patterns,pat);
10504 }
10505 /* Notify the client */
10506 addReply(c,shared.mbulk3);
10507 addReply(c,shared.psubscribebulk);
10508 addReplyBulk(c,pattern);
482b672d 10509 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
ffc6b7f8 10510 return retval;
10511}
10512
10513/* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10514 * 0 if the client was not subscribed to the specified channel. */
10515static int pubsubUnsubscribePattern(redisClient *c, robj *pattern, int notify) {
10516 listNode *ln;
10517 pubsubPattern pat;
10518 int retval = 0;
10519
10520 incrRefCount(pattern); /* Protect the object. May be the same we remove */
10521 if ((ln = listSearchKey(c->pubsub_patterns,pattern)) != NULL) {
10522 retval = 1;
10523 listDelNode(c->pubsub_patterns,ln);
10524 pat.client = c;
10525 pat.pattern = pattern;
10526 ln = listSearchKey(server.pubsub_patterns,&pat);
10527 listDelNode(server.pubsub_patterns,ln);
10528 }
10529 /* Notify the client */
10530 if (notify) {
10531 addReply(c,shared.mbulk3);
10532 addReply(c,shared.punsubscribebulk);
10533 addReplyBulk(c,pattern);
482b672d 10534 addReplyLongLong(c,dictSize(c->pubsub_channels)+
ffc6b7f8 10535 listLength(c->pubsub_patterns));
befec3cd 10536 }
ffc6b7f8 10537 decrRefCount(pattern);
befec3cd 10538 return retval;
10539}
10540
ffc6b7f8 10541/* Unsubscribe from all the channels. Return the number of channels the
10542 * client was subscribed from. */
10543static int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
10544 dictIterator *di = dictGetIterator(c->pubsub_channels);
befec3cd 10545 dictEntry *de;
10546 int count = 0;
10547
10548 while((de = dictNext(di)) != NULL) {
ffc6b7f8 10549 robj *channel = dictGetEntryKey(de);
befec3cd 10550
ffc6b7f8 10551 count += pubsubUnsubscribeChannel(c,channel,notify);
befec3cd 10552 }
10553 dictReleaseIterator(di);
10554 return count;
10555}
10556
ffc6b7f8 10557/* Unsubscribe from all the patterns. Return the number of patterns the
10558 * client was subscribed from. */
10559static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify) {
10560 listNode *ln;
10561 listIter li;
10562 int count = 0;
10563
10564 listRewind(c->pubsub_patterns,&li);
10565 while ((ln = listNext(&li)) != NULL) {
10566 robj *pattern = ln->value;
10567
10568 count += pubsubUnsubscribePattern(c,pattern,notify);
10569 }
10570 return count;
10571}
10572
befec3cd 10573/* Publish a message */
ffc6b7f8 10574static int pubsubPublishMessage(robj *channel, robj *message) {
befec3cd 10575 int receivers = 0;
10576 struct dictEntry *de;
ffc6b7f8 10577 listNode *ln;
10578 listIter li;
befec3cd 10579
ffc6b7f8 10580 /* Send to clients listening for that channel */
10581 de = dictFind(server.pubsub_channels,channel);
befec3cd 10582 if (de) {
10583 list *list = dictGetEntryVal(de);
10584 listNode *ln;
10585 listIter li;
10586
10587 listRewind(list,&li);
10588 while ((ln = listNext(&li)) != NULL) {
10589 redisClient *c = ln->value;
10590
10591 addReply(c,shared.mbulk3);
10592 addReply(c,shared.messagebulk);
ffc6b7f8 10593 addReplyBulk(c,channel);
befec3cd 10594 addReplyBulk(c,message);
10595 receivers++;
10596 }
10597 }
ffc6b7f8 10598 /* Send to clients listening to matching channels */
10599 if (listLength(server.pubsub_patterns)) {
10600 listRewind(server.pubsub_patterns,&li);
10601 channel = getDecodedObject(channel);
10602 while ((ln = listNext(&li)) != NULL) {
10603 pubsubPattern *pat = ln->value;
10604
10605 if (stringmatchlen((char*)pat->pattern->ptr,
10606 sdslen(pat->pattern->ptr),
10607 (char*)channel->ptr,
10608 sdslen(channel->ptr),0)) {
c8d0ea0e 10609 addReply(pat->client,shared.mbulk4);
10610 addReply(pat->client,shared.pmessagebulk);
10611 addReplyBulk(pat->client,pat->pattern);
ffc6b7f8 10612 addReplyBulk(pat->client,channel);
10613 addReplyBulk(pat->client,message);
10614 receivers++;
10615 }
10616 }
10617 decrRefCount(channel);
10618 }
befec3cd 10619 return receivers;
10620}
10621
10622static void subscribeCommand(redisClient *c) {
10623 int j;
10624
10625 for (j = 1; j < c->argc; j++)
ffc6b7f8 10626 pubsubSubscribeChannel(c,c->argv[j]);
befec3cd 10627}
10628
10629static void unsubscribeCommand(redisClient *c) {
10630 if (c->argc == 1) {
ffc6b7f8 10631 pubsubUnsubscribeAllChannels(c,1);
10632 return;
10633 } else {
10634 int j;
10635
10636 for (j = 1; j < c->argc; j++)
10637 pubsubUnsubscribeChannel(c,c->argv[j],1);
10638 }
10639}
10640
10641static void psubscribeCommand(redisClient *c) {
10642 int j;
10643
10644 for (j = 1; j < c->argc; j++)
10645 pubsubSubscribePattern(c,c->argv[j]);
10646}
10647
10648static void punsubscribeCommand(redisClient *c) {
10649 if (c->argc == 1) {
10650 pubsubUnsubscribeAllPatterns(c,1);
befec3cd 10651 return;
10652 } else {
10653 int j;
10654
10655 for (j = 1; j < c->argc; j++)
ffc6b7f8 10656 pubsubUnsubscribePattern(c,c->argv[j],1);
befec3cd 10657 }
10658}
10659
10660static void publishCommand(redisClient *c) {
10661 int receivers = pubsubPublishMessage(c->argv[1],c->argv[2]);
482b672d 10662 addReplyLongLong(c,receivers);
befec3cd 10663}
10664
37ab76c9 10665/* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
10666 *
10667 * The implementation uses a per-DB hash table mapping keys to list of clients
10668 * WATCHing those keys, so that given a key that is going to be modified
10669 * we can mark all the associated clients as dirty.
10670 *
10671 * Also every client contains a list of WATCHed keys so that's possible to
10672 * un-watch such keys when the client is freed or when UNWATCH is called. */
10673
10674/* In the client->watched_keys list we need to use watchedKey structures
10675 * as in order to identify a key in Redis we need both the key name and the
10676 * DB */
10677typedef struct watchedKey {
10678 robj *key;
10679 redisDb *db;
10680} watchedKey;
10681
10682/* Watch for the specified key */
10683static void watchForKey(redisClient *c, robj *key) {
10684 list *clients = NULL;
10685 listIter li;
10686 listNode *ln;
10687 watchedKey *wk;
10688
10689 /* Check if we are already watching for this key */
10690 listRewind(c->watched_keys,&li);
10691 while((ln = listNext(&li))) {
10692 wk = listNodeValue(ln);
10693 if (wk->db == c->db && equalStringObjects(key,wk->key))
10694 return; /* Key already watched */
10695 }
10696 /* This key is not already watched in this DB. Let's add it */
10697 clients = dictFetchValue(c->db->watched_keys,key);
10698 if (!clients) {
10699 clients = listCreate();
10700 dictAdd(c->db->watched_keys,key,clients);
10701 incrRefCount(key);
10702 }
10703 listAddNodeTail(clients,c);
10704 /* Add the new key to the lits of keys watched by this client */
10705 wk = zmalloc(sizeof(*wk));
10706 wk->key = key;
10707 wk->db = c->db;
10708 incrRefCount(key);
10709 listAddNodeTail(c->watched_keys,wk);
10710}
10711
10712/* Unwatch all the keys watched by this client. To clean the EXEC dirty
10713 * flag is up to the caller. */
10714static void unwatchAllKeys(redisClient *c) {
10715 listIter li;
10716 listNode *ln;
10717
10718 if (listLength(c->watched_keys) == 0) return;
10719 listRewind(c->watched_keys,&li);
10720 while((ln = listNext(&li))) {
10721 list *clients;
10722 watchedKey *wk;
10723
10724 /* Lookup the watched key -> clients list and remove the client
10725 * from the list */
10726 wk = listNodeValue(ln);
10727 clients = dictFetchValue(wk->db->watched_keys, wk->key);
10728 assert(clients != NULL);
10729 listDelNode(clients,listSearchKey(clients,c));
10730 /* Kill the entry at all if this was the only client */
10731 if (listLength(clients) == 0)
10732 dictDelete(wk->db->watched_keys, wk->key);
10733 /* Remove this watched key from the client->watched list */
10734 listDelNode(c->watched_keys,ln);
10735 decrRefCount(wk->key);
10736 zfree(wk);
10737 }
10738}
10739
ca3f830b 10740/* "Touch" a key, so that if this key is being WATCHed by some client the
37ab76c9 10741 * next EXEC will fail. */
10742static void touchWatchedKey(redisDb *db, robj *key) {
10743 list *clients;
10744 listIter li;
10745 listNode *ln;
10746
10747 if (dictSize(db->watched_keys) == 0) return;
10748 clients = dictFetchValue(db->watched_keys, key);
10749 if (!clients) return;
10750
10751 /* Mark all the clients watching this key as REDIS_DIRTY_CAS */
10752 /* Check if we are already watching for this key */
10753 listRewind(clients,&li);
10754 while((ln = listNext(&li))) {
10755 redisClient *c = listNodeValue(ln);
10756
10757 c->flags |= REDIS_DIRTY_CAS;
10758 }
10759}
10760
9b30e1a2 10761/* On FLUSHDB or FLUSHALL all the watched keys that are present before the
10762 * flush but will be deleted as effect of the flushing operation should
10763 * be touched. "dbid" is the DB that's getting the flush. -1 if it is
10764 * a FLUSHALL operation (all the DBs flushed). */
10765static void touchWatchedKeysOnFlush(int dbid) {
10766 listIter li1, li2;
10767 listNode *ln;
10768
10769 /* For every client, check all the waited keys */
10770 listRewind(server.clients,&li1);
10771 while((ln = listNext(&li1))) {
10772 redisClient *c = listNodeValue(ln);
10773 listRewind(c->watched_keys,&li2);
10774 while((ln = listNext(&li2))) {
10775 watchedKey *wk = listNodeValue(ln);
10776
10777 /* For every watched key matching the specified DB, if the
10778 * key exists, mark the client as dirty, as the key will be
10779 * removed. */
10780 if (dbid == -1 || wk->db->id == dbid) {
10781 if (dictFind(wk->db->dict, wk->key) != NULL)
10782 c->flags |= REDIS_DIRTY_CAS;
10783 }
10784 }
10785 }
10786}
10787
37ab76c9 10788static void watchCommand(redisClient *c) {
10789 int j;
10790
6531c94d 10791 if (c->flags & REDIS_MULTI) {
10792 addReplySds(c,sdsnew("-ERR WATCH inside MULTI is not allowed\r\n"));
10793 return;
10794 }
37ab76c9 10795 for (j = 1; j < c->argc; j++)
10796 watchForKey(c,c->argv[j]);
10797 addReply(c,shared.ok);
10798}
10799
10800static void unwatchCommand(redisClient *c) {
10801 unwatchAllKeys(c);
10802 c->flags &= (~REDIS_DIRTY_CAS);
10803 addReply(c,shared.ok);
10804}
10805
7f957c92 10806/* ================================= Debugging ============================== */
10807
ba798261 10808/* Compute the sha1 of string at 's' with 'len' bytes long.
10809 * The SHA1 is then xored againt the string pointed by digest.
10810 * Since xor is commutative, this operation is used in order to
10811 * "add" digests relative to unordered elements.
10812 *
10813 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10814static void xorDigest(unsigned char *digest, void *ptr, size_t len) {
10815 SHA1_CTX ctx;
10816 unsigned char hash[20], *s = ptr;
10817 int j;
10818
10819 SHA1Init(&ctx);
10820 SHA1Update(&ctx,s,len);
10821 SHA1Final(hash,&ctx);
10822
10823 for (j = 0; j < 20; j++)
10824 digest[j] ^= hash[j];
10825}
10826
10827static void xorObjectDigest(unsigned char *digest, robj *o) {
10828 o = getDecodedObject(o);
10829 xorDigest(digest,o->ptr,sdslen(o->ptr));
10830 decrRefCount(o);
10831}
10832
10833/* This function instead of just computing the SHA1 and xoring it
10834 * against diget, also perform the digest of "digest" itself and
10835 * replace the old value with the new one.
10836 *
10837 * So the final digest will be:
10838 *
10839 * digest = SHA1(digest xor SHA1(data))
10840 *
10841 * This function is used every time we want to preserve the order so
10842 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
10843 *
10844 * Also note that mixdigest("foo") followed by mixdigest("bar")
10845 * will lead to a different digest compared to "fo", "obar".
10846 */
10847static void mixDigest(unsigned char *digest, void *ptr, size_t len) {
10848 SHA1_CTX ctx;
10849 char *s = ptr;
10850
10851 xorDigest(digest,s,len);
10852 SHA1Init(&ctx);
10853 SHA1Update(&ctx,digest,20);
10854 SHA1Final(digest,&ctx);
10855}
10856
10857static void mixObjectDigest(unsigned char *digest, robj *o) {
10858 o = getDecodedObject(o);
10859 mixDigest(digest,o->ptr,sdslen(o->ptr));
10860 decrRefCount(o);
10861}
10862
10863/* Compute the dataset digest. Since keys, sets elements, hashes elements
10864 * are not ordered, we use a trick: every aggregate digest is the xor
10865 * of the digests of their elements. This way the order will not change
10866 * the result. For list instead we use a feedback entering the output digest
10867 * as input in order to ensure that a different ordered list will result in
10868 * a different digest. */
10869static void computeDatasetDigest(unsigned char *final) {
10870 unsigned char digest[20];
10871 char buf[128];
10872 dictIterator *di = NULL;
10873 dictEntry *de;
10874 int j;
10875 uint32_t aux;
10876
10877 memset(final,0,20); /* Start with a clean result */
10878
10879 for (j = 0; j < server.dbnum; j++) {
10880 redisDb *db = server.db+j;
10881
10882 if (dictSize(db->dict) == 0) continue;
10883 di = dictGetIterator(db->dict);
10884
10885 /* hash the DB id, so the same dataset moved in a different
10886 * DB will lead to a different digest */
10887 aux = htonl(j);
10888 mixDigest(final,&aux,sizeof(aux));
10889
10890 /* Iterate this DB writing every entry */
10891 while((de = dictNext(di)) != NULL) {
cbae1d34 10892 robj *key, *o, *kcopy;
ba798261 10893 time_t expiretime;
10894
10895 memset(digest,0,20); /* This key-val digest */
10896 key = dictGetEntryKey(de);
cbae1d34 10897
10898 if (!server.vm_enabled) {
10899 mixObjectDigest(digest,key);
ba798261 10900 o = dictGetEntryVal(de);
ba798261 10901 } else {
cbae1d34 10902 /* Don't work with the key directly as when VM is active
10903 * this is unsafe: TODO: fix decrRefCount to check if the
10904 * count really reached 0 to avoid this mess */
10905 kcopy = dupStringObject(key);
10906 mixObjectDigest(digest,kcopy);
10907 o = lookupKeyRead(db,kcopy);
10908 decrRefCount(kcopy);
ba798261 10909 }
10910 aux = htonl(o->type);
10911 mixDigest(digest,&aux,sizeof(aux));
10912 expiretime = getExpire(db,key);
10913
10914 /* Save the key and associated value */
10915 if (o->type == REDIS_STRING) {
10916 mixObjectDigest(digest,o);
10917 } else if (o->type == REDIS_LIST) {
10918 list *list = o->ptr;
10919 listNode *ln;
10920 listIter li;
10921
10922 listRewind(list,&li);
10923 while((ln = listNext(&li))) {
10924 robj *eleobj = listNodeValue(ln);
10925
10926 mixObjectDigest(digest,eleobj);
10927 }
10928 } else if (o->type == REDIS_SET) {
10929 dict *set = o->ptr;
10930 dictIterator *di = dictGetIterator(set);
10931 dictEntry *de;
10932
10933 while((de = dictNext(di)) != NULL) {
10934 robj *eleobj = dictGetEntryKey(de);
10935
10936 xorObjectDigest(digest,eleobj);
10937 }
10938 dictReleaseIterator(di);
10939 } else if (o->type == REDIS_ZSET) {
10940 zset *zs = o->ptr;
10941 dictIterator *di = dictGetIterator(zs->dict);
10942 dictEntry *de;
10943
10944 while((de = dictNext(di)) != NULL) {
10945 robj *eleobj = dictGetEntryKey(de);
10946 double *score = dictGetEntryVal(de);
10947 unsigned char eledigest[20];
10948
10949 snprintf(buf,sizeof(buf),"%.17g",*score);
10950 memset(eledigest,0,20);
10951 mixObjectDigest(eledigest,eleobj);
10952 mixDigest(eledigest,buf,strlen(buf));
10953 xorDigest(digest,eledigest,20);
10954 }
10955 dictReleaseIterator(di);
10956 } else if (o->type == REDIS_HASH) {
10957 hashIterator *hi;
10958 robj *obj;
10959
10960 hi = hashInitIterator(o);
10961 while (hashNext(hi) != REDIS_ERR) {
10962 unsigned char eledigest[20];
10963
10964 memset(eledigest,0,20);
10965 obj = hashCurrent(hi,REDIS_HASH_KEY);
10966 mixObjectDigest(eledigest,obj);
10967 decrRefCount(obj);
10968 obj = hashCurrent(hi,REDIS_HASH_VALUE);
10969 mixObjectDigest(eledigest,obj);
10970 decrRefCount(obj);
10971 xorDigest(digest,eledigest,20);
10972 }
10973 hashReleaseIterator(hi);
10974 } else {
10975 redisPanic("Unknown object type");
10976 }
ba798261 10977 /* If the key has an expire, add it to the mix */
10978 if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
10979 /* We can finally xor the key-val digest to the final digest */
10980 xorDigest(final,digest,20);
10981 }
10982 dictReleaseIterator(di);
10983 }
10984}
10985
7f957c92 10986static void debugCommand(redisClient *c) {
10987 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
10988 *((char*)-1) = 'x';
210e29f7 10989 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
10990 if (rdbSave(server.dbfilename) != REDIS_OK) {
10991 addReply(c,shared.err);
10992 return;
10993 }
10994 emptyDb();
10995 if (rdbLoad(server.dbfilename) != REDIS_OK) {
10996 addReply(c,shared.err);
10997 return;
10998 }
10999 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
11000 addReply(c,shared.ok);
71c2b467 11001 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
11002 emptyDb();
11003 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
11004 addReply(c,shared.err);
11005 return;
11006 }
11007 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
11008 addReply(c,shared.ok);
333298da 11009 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
11010 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
11011 robj *key, *val;
11012
11013 if (!de) {
11014 addReply(c,shared.nokeyerr);
11015 return;
11016 }
11017 key = dictGetEntryKey(de);
11018 val = dictGetEntryVal(de);
59146ef3 11019 if (!server.vm_enabled || (key->storage == REDIS_VM_MEMORY ||
11020 key->storage == REDIS_VM_SWAPPING)) {
07efaf74 11021 char *strenc;
11022 char buf[128];
11023
11024 if (val->encoding < (sizeof(strencoding)/sizeof(char*))) {
11025 strenc = strencoding[val->encoding];
11026 } else {
11027 snprintf(buf,64,"unknown encoding %d\n", val->encoding);
11028 strenc = buf;
11029 }
ace06542 11030 addReplySds(c,sdscatprintf(sdsempty(),
11031 "+Key at:%p refcount:%d, value at:%p refcount:%d "
07efaf74 11032 "encoding:%s serializedlength:%lld\r\n",
682ac724 11033 (void*)key, key->refcount, (void*)val, val->refcount,
07efaf74 11034 strenc, (long long) rdbSavedObjectLen(val,NULL)));
ace06542 11035 } else {
11036 addReplySds(c,sdscatprintf(sdsempty(),
11037 "+Key at:%p refcount:%d, value swapped at: page %llu "
11038 "using %llu pages\r\n",
11039 (void*)key, key->refcount, (unsigned long long) key->vm.page,
11040 (unsigned long long) key->vm.usedpages));
11041 }
78ebe4c8 11042 } else if (!strcasecmp(c->argv[1]->ptr,"swapin") && c->argc == 3) {
11043 lookupKeyRead(c->db,c->argv[2]);
11044 addReply(c,shared.ok);
7d30035d 11045 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
11046 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
11047 robj *key, *val;
11048
11049 if (!server.vm_enabled) {
11050 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
11051 return;
11052 }
11053 if (!de) {
11054 addReply(c,shared.nokeyerr);
11055 return;
11056 }
11057 key = dictGetEntryKey(de);
11058 val = dictGetEntryVal(de);
4ef8de8a 11059 /* If the key is shared we want to create a copy */
11060 if (key->refcount > 1) {
11061 robj *newkey = dupStringObject(key);
11062 decrRefCount(key);
11063 key = dictGetEntryKey(de) = newkey;
11064 }
11065 /* Swap it */
7d30035d 11066 if (key->storage != REDIS_VM_MEMORY) {
11067 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
a69a0c9c 11068 } else if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
7d30035d 11069 dictGetEntryVal(de) = NULL;
11070 addReply(c,shared.ok);
11071 } else {
11072 addReply(c,shared.err);
11073 }
59305dc7 11074 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
11075 long keys, j;
11076 robj *key, *val;
11077 char buf[128];
11078
11079 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
11080 return;
11081 for (j = 0; j < keys; j++) {
11082 snprintf(buf,sizeof(buf),"key:%lu",j);
11083 key = createStringObject(buf,strlen(buf));
11084 if (lookupKeyRead(c->db,key) != NULL) {
11085 decrRefCount(key);
11086 continue;
11087 }
11088 snprintf(buf,sizeof(buf),"value:%lu",j);
11089 val = createStringObject(buf,strlen(buf));
11090 dictAdd(c->db->dict,key,val);
11091 }
11092 addReply(c,shared.ok);
ba798261 11093 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
11094 unsigned char digest[20];
11095 sds d = sdsnew("+");
11096 int j;
11097
11098 computeDatasetDigest(digest);
11099 for (j = 0; j < 20; j++)
11100 d = sdscatprintf(d, "%02x",digest[j]);
11101
11102 d = sdscatlen(d,"\r\n",2);
11103 addReplySds(c,d);
7f957c92 11104 } else {
333298da 11105 addReplySds(c,sdsnew(
bdcb92f2 11106 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
7f957c92 11107 }
11108}
56906eef 11109
6c96ba7d 11110static void _redisAssert(char *estr, char *file, int line) {
dfc5e96c 11111 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
fdfb02e7 11112 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
dfc5e96c 11113#ifdef HAVE_BACKTRACE
11114 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
11115 *((char*)-1) = 'x';
11116#endif
11117}
11118
c651fd9e 11119static void _redisPanic(char *msg, char *file, int line) {
11120 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
17772754 11121 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
c651fd9e 11122#ifdef HAVE_BACKTRACE
11123 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
11124 *((char*)-1) = 'x';
11125#endif
11126}
11127
bcfc686d 11128/* =================================== Main! ================================ */
56906eef 11129
bcfc686d 11130#ifdef __linux__
11131int linuxOvercommitMemoryValue(void) {
11132 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
11133 char buf[64];
56906eef 11134
bcfc686d 11135 if (!fp) return -1;
11136 if (fgets(buf,64,fp) == NULL) {
11137 fclose(fp);
11138 return -1;
11139 }
11140 fclose(fp);
56906eef 11141
bcfc686d 11142 return atoi(buf);
11143}
11144
11145void linuxOvercommitMemoryWarning(void) {
11146 if (linuxOvercommitMemoryValue() == 0) {
7ccd2d0a 11147 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 11148 }
11149}
11150#endif /* __linux__ */
11151
11152static void daemonize(void) {
11153 int fd;
11154 FILE *fp;
11155
11156 if (fork() != 0) exit(0); /* parent exits */
11157 setsid(); /* create a new session */
11158
11159 /* Every output goes to /dev/null. If Redis is daemonized but
11160 * the 'logfile' is set to 'stdout' in the configuration file
11161 * it will not log at all. */
11162 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
11163 dup2(fd, STDIN_FILENO);
11164 dup2(fd, STDOUT_FILENO);
11165 dup2(fd, STDERR_FILENO);
11166 if (fd > STDERR_FILENO) close(fd);
11167 }
11168 /* Try to write the pid file */
11169 fp = fopen(server.pidfile,"w");
11170 if (fp) {
11171 fprintf(fp,"%d\n",getpid());
11172 fclose(fp);
56906eef 11173 }
56906eef 11174}
11175
42ab0172 11176static void version() {
8a3b0d2d 11177 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
11178 REDIS_GIT_SHA1, atoi(REDIS_GIT_DIRTY) > 0);
42ab0172
AO
11179 exit(0);
11180}
11181
723fb69b
AO
11182static void usage() {
11183 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
e9409273 11184 fprintf(stderr," ./redis-server - (read config from stdin)\n");
723fb69b
AO
11185 exit(1);
11186}
11187
bcfc686d 11188int main(int argc, char **argv) {
9651a787 11189 time_t start;
11190
bcfc686d 11191 initServerConfig();
1a132bbc 11192 sortCommandTable();
bcfc686d 11193 if (argc == 2) {
44efe66e 11194 if (strcmp(argv[1], "-v") == 0 ||
11195 strcmp(argv[1], "--version") == 0) version();
11196 if (strcmp(argv[1], "--help") == 0) usage();
bcfc686d 11197 resetServerSaveParams();
11198 loadServerConfig(argv[1]);
723fb69b
AO
11199 } else if ((argc > 2)) {
11200 usage();
bcfc686d 11201 } else {
11202 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'");
11203 }
bcfc686d 11204 if (server.daemonize) daemonize();
71c54b21 11205 initServer();
bcfc686d 11206 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
11207#ifdef __linux__
11208 linuxOvercommitMemoryWarning();
11209#endif
9651a787 11210 start = time(NULL);
bcfc686d 11211 if (server.appendonly) {
11212 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
9651a787 11213 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
bcfc686d 11214 } else {
11215 if (rdbLoad(server.dbfilename) == REDIS_OK)
9651a787 11216 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
bcfc686d 11217 }
bcfc686d 11218 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
d5d55fc3 11219 aeSetBeforeSleepProc(server.el,beforeSleep);
bcfc686d 11220 aeMain(server.el);
11221 aeDeleteEventLoop(server.el);
11222 return 0;
11223}
11224
11225/* ============================= Backtrace support ========================= */
11226
11227#ifdef HAVE_BACKTRACE
11228static char *findFuncName(void *pointer, unsigned long *offset);
11229
56906eef 11230static void *getMcontextEip(ucontext_t *uc) {
11231#if defined(__FreeBSD__)
11232 return (void*) uc->uc_mcontext.mc_eip;
11233#elif defined(__dietlibc__)
11234 return (void*) uc->uc_mcontext.eip;
06db1f50 11235#elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
da0a1620 11236 #if __x86_64__
11237 return (void*) uc->uc_mcontext->__ss.__rip;
11238 #else
56906eef 11239 return (void*) uc->uc_mcontext->__ss.__eip;
da0a1620 11240 #endif
06db1f50 11241#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
cb7e07cc 11242 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
06db1f50 11243 return (void*) uc->uc_mcontext->__ss.__rip;
cbc59b38 11244 #else
11245 return (void*) uc->uc_mcontext->__ss.__eip;
e0a62c7f 11246 #endif
54bac49d 11247#elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
c04c9ac9 11248 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
b91cf5ef 11249#elif defined(__ia64__) /* Linux IA64 */
11250 return (void*) uc->uc_mcontext.sc_ip;
11251#else
11252 return NULL;
56906eef 11253#endif
11254}
11255
11256static void segvHandler(int sig, siginfo_t *info, void *secret) {
11257 void *trace[100];
11258 char **messages = NULL;
11259 int i, trace_size = 0;
11260 unsigned long offset=0;
56906eef 11261 ucontext_t *uc = (ucontext_t*) secret;
1c85b79f 11262 sds infostring;
56906eef 11263 REDIS_NOTUSED(info);
11264
11265 redisLog(REDIS_WARNING,
11266 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
1c85b79f 11267 infostring = genRedisInfoString();
11268 redisLog(REDIS_WARNING, "%s",infostring);
11269 /* It's not safe to sdsfree() the returned string under memory
11270 * corruption conditions. Let it leak as we are going to abort */
e0a62c7f 11271
56906eef 11272 trace_size = backtrace(trace, 100);
de96dbfe 11273 /* overwrite sigaction with caller's address */
b91cf5ef 11274 if (getMcontextEip(uc) != NULL) {
11275 trace[1] = getMcontextEip(uc);
11276 }
56906eef 11277 messages = backtrace_symbols(trace, trace_size);
fe3bbfbe 11278
d76412d1 11279 for (i=1; i<trace_size; ++i) {
56906eef 11280 char *fn = findFuncName(trace[i], &offset), *p;
11281
11282 p = strchr(messages[i],'+');
11283 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
11284 redisLog(REDIS_WARNING,"%s", messages[i]);
11285 } else {
11286 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
11287 }
11288 }
b177fd30 11289 /* free(messages); Don't call free() with possibly corrupted memory. */
478c2c6f 11290 _exit(0);
fe3bbfbe 11291}
56906eef 11292
fab43727 11293static void sigtermHandler(int sig) {
11294 REDIS_NOTUSED(sig);
b58ba105 11295
fab43727 11296 redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
11297 server.shutdown_asap = 1;
b58ba105
AM
11298}
11299
56906eef 11300static void setupSigSegvAction(void) {
11301 struct sigaction act;
11302
11303 sigemptyset (&act.sa_mask);
11304 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
11305 * is used. Otherwise, sa_handler is used */
11306 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
11307 act.sa_sigaction = segvHandler;
11308 sigaction (SIGSEGV, &act, NULL);
11309 sigaction (SIGBUS, &act, NULL);
12fea928 11310 sigaction (SIGFPE, &act, NULL);
11311 sigaction (SIGILL, &act, NULL);
11312 sigaction (SIGBUS, &act, NULL);
b58ba105
AM
11313
11314 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
fab43727 11315 act.sa_handler = sigtermHandler;
b58ba105 11316 sigaction (SIGTERM, &act, NULL);
e65fdc78 11317 return;
56906eef 11318}
e65fdc78 11319
bcfc686d 11320#include "staticsymbols.h"
11321/* This function try to convert a pointer into a function name. It's used in
11322 * oreder to provide a backtrace under segmentation fault that's able to
11323 * display functions declared as static (otherwise the backtrace is useless). */
11324static char *findFuncName(void *pointer, unsigned long *offset){
11325 int i, ret = -1;
11326 unsigned long off, minoff = 0;
ed9b544e 11327
bcfc686d 11328 /* Try to match against the Symbol with the smallest offset */
11329 for (i=0; symsTable[i].pointer; i++) {
11330 unsigned long lp = (unsigned long) pointer;
0bc03378 11331
bcfc686d 11332 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
11333 off=lp-symsTable[i].pointer;
11334 if (ret < 0 || off < minoff) {
11335 minoff=off;
11336 ret=i;
11337 }
11338 }
0bc03378 11339 }
bcfc686d 11340 if (ret == -1) return NULL;
11341 *offset = minoff;
11342 return symsTable[ret].name;
0bc03378 11343}
bcfc686d 11344#else /* HAVE_BACKTRACE */
11345static void setupSigSegvAction(void) {
0bc03378 11346}
bcfc686d 11347#endif /* HAVE_BACKTRACE */
0bc03378 11348
ed9b544e 11349
ed9b544e 11350
bcfc686d 11351/* The End */
11352
11353
ed9b544e 11354