]> git.saurik.com Git - redis.git/blame - redis.c
add thresholds for converting a ziplist to a real list
[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
560db612 124#define REDIS_VMPOINTER 8
f78fd11b 125
5234952b 126/* Objects encoding. Some kind of objects like Strings and Hashes can be
127 * internally represented in multiple ways. The 'encoding' field of the object
128 * is set to one of this fields for this object. */
c7d9d662
PN
129#define REDIS_ENCODING_RAW 0 /* Raw representation */
130#define REDIS_ENCODING_INT 1 /* Encoded as integer */
131#define REDIS_ENCODING_HT 2 /* Encoded as hash table */
132#define REDIS_ENCODING_ZIPMAP 3 /* Encoded as zipmap */
133#define REDIS_ENCODING_LIST 4 /* Encoded as zipmap */
134#define REDIS_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
942a3961 135
07efaf74 136static char* strencoding[] = {
846d8b3e 137 "raw", "int", "hashtable", "zipmap", "list", "ziplist"
07efaf74 138};
139
f78fd11b 140/* Object types only used for dumping to disk */
bb32ede5 141#define REDIS_EXPIRETIME 253
ed9b544e 142#define REDIS_SELECTDB 254
143#define REDIS_EOF 255
144
f78fd11b 145/* Defines related to the dump file format. To store 32 bits lengths for short
146 * keys requires a lot of space, so we check the most significant 2 bits of
147 * the first byte to interpreter the length:
148 *
149 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
150 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
151 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
a4d1ba9a 152 * 11|000000 this means: specially encoded object will follow. The six bits
153 * number specify the kind of object that follows.
154 * See the REDIS_RDB_ENC_* defines.
f78fd11b 155 *
10c43610 156 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
157 * values, will fit inside. */
f78fd11b 158#define REDIS_RDB_6BITLEN 0
159#define REDIS_RDB_14BITLEN 1
160#define REDIS_RDB_32BITLEN 2
17be1a4a 161#define REDIS_RDB_ENCVAL 3
f78fd11b 162#define REDIS_RDB_LENERR UINT_MAX
163
a4d1ba9a 164/* When a length of a string object stored on disk has the first two bits
165 * set, the remaining two bits specify a special encoding for the object
166 * accordingly to the following defines: */
167#define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
168#define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
169#define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
774e3047 170#define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
a4d1ba9a 171
75680a3c 172/* Virtual memory object->where field. */
173#define REDIS_VM_MEMORY 0 /* The object is on memory */
174#define REDIS_VM_SWAPPED 1 /* The object is on disk */
175#define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
176#define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
177
06224fec 178/* Virtual memory static configuration stuff.
179 * Check vmFindContiguousPages() to know more about this magic numbers. */
180#define REDIS_VM_MAX_NEAR_PAGES 65536
181#define REDIS_VM_MAX_RANDOM_JUMP 4096
92f8e882 182#define REDIS_VM_MAX_THREADS 32
bcaa7a4f 183#define REDIS_THREAD_STACK_SIZE (1024*1024*4)
f6c0bba8 184/* The following is the *percentage* of completed I/O jobs to process when the
185 * handelr is called. While Virtual Memory I/O operations are performed by
186 * threads, this operations must be processed by the main thread when completed
187 * in order to take effect. */
c953f24b 188#define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
06224fec 189
ed9b544e 190/* Client flags */
d5d55fc3 191#define REDIS_SLAVE 1 /* This client is a slave server */
192#define REDIS_MASTER 2 /* This client is a master server */
193#define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
194#define REDIS_MULTI 8 /* This client is in a MULTI context */
195#define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
196#define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
37ab76c9 197#define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
ed9b544e 198
40d224a9 199/* Slave replication state - slave side */
ed9b544e 200#define REDIS_REPL_NONE 0 /* No active replication */
201#define REDIS_REPL_CONNECT 1 /* Must connect to master */
202#define REDIS_REPL_CONNECTED 2 /* Connected to master */
203
40d224a9 204/* Slave replication state - from the point of view of master
205 * Note that in SEND_BULK and ONLINE state the slave receives new updates
206 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
207 * to start the next background saving in order to send updates to it. */
208#define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
209#define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
210#define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
211#define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
212
ed9b544e 213/* List related stuff */
214#define REDIS_HEAD 0
215#define REDIS_TAIL 1
216
217/* Sort operations */
218#define REDIS_SORT_GET 0
443c6409 219#define REDIS_SORT_ASC 1
220#define REDIS_SORT_DESC 2
ed9b544e 221#define REDIS_SORTKEY_MAX 1024
222
223/* Log levels */
224#define REDIS_DEBUG 0
f870935d 225#define REDIS_VERBOSE 1
226#define REDIS_NOTICE 2
227#define REDIS_WARNING 3
ed9b544e 228
229/* Anti-warning macro... */
230#define REDIS_NOTUSED(V) ((void) V)
231
6b47e12e 232#define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
233#define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
ed9b544e 234
48f0308a 235/* Append only defines */
236#define APPENDFSYNC_NO 0
237#define APPENDFSYNC_ALWAYS 1
238#define APPENDFSYNC_EVERYSEC 2
239
d0686e07 240/* Zip structure related defaults */
cbba7dd7 241#define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
242#define REDIS_HASH_MAX_ZIPMAP_VALUE 512
d0686e07
PN
243#define REDIS_LIST_MAX_ZIPLIST_ENTRIES 1024
244#define REDIS_LIST_MAX_ZIPLIST_VALUE 32
cbba7dd7 245
dfc5e96c 246/* We can print the stacktrace, so our assert is defined this way: */
478c2c6f 247#define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
c651fd9e 248#define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
6c96ba7d 249static void _redisAssert(char *estr, char *file, int line);
c651fd9e 250static void _redisPanic(char *msg, char *file, int line);
dfc5e96c 251
ed9b544e 252/*================================= Data types ============================== */
253
254/* A redis object, that is a type able to hold a string / list / set */
75680a3c 255
75680a3c 256/* The actual Redis Object */
ed9b544e 257typedef struct redisObject {
560db612 258 unsigned type:4;
259 unsigned storage:2; /* REDIS_VM_MEMORY or REDIS_VM_SWAPPING */
260 unsigned encoding:4;
261 unsigned lru:22; /* lru time (relative to server.lruclock) */
ed9b544e 262 int refcount;
560db612 263 void *ptr;
75680a3c 264 /* VM fields, this are only allocated if VM is active, otherwise the
265 * object allocation function will just allocate
266 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
267 * Redis without VM active will not have any overhead. */
ed9b544e 268} robj;
269
560db612 270/* The VM pointer structure - identifies an object in the swap file.
271 *
272 * This object is stored in place of the value
273 * object in the main key->value hash table representing a database.
274 * Note that the first fields (type, storage) are the same as the redisObject
275 * structure so that vmPointer strucuters can be accessed even when casted
276 * as redisObject structures.
277 *
278 * This is useful as we don't know if a value object is or not on disk, but we
169dd6b7 279 * are always able to read obj->storage to check this. For vmPointer
560db612 280 * structures "type" is set to REDIS_VMPOINTER (even if without this field
281 * is still possible to check the kind of object from the value of 'storage').*/
282typedef struct vmPointer {
283 unsigned type:4;
284 unsigned storage:2; /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
285 unsigned notused:26;
286 unsigned int vtype; /* type of the object stored in the swap file */
287 off_t page; /* the page at witch the object is stored on disk */
288 off_t usedpages; /* number of pages used on disk */
289} vmpointer;
290
dfc5e96c 291/* Macro used to initalize a Redis object allocated on the stack.
292 * Note that this macro is taken near the structure definition to make sure
293 * we'll update it when the structure is changed, to avoid bugs like
294 * bug #85 introduced exactly in this way. */
295#define initStaticStringObject(_var,_ptr) do { \
296 _var.refcount = 1; \
297 _var.type = REDIS_STRING; \
298 _var.encoding = REDIS_ENCODING_RAW; \
299 _var.ptr = _ptr; \
560db612 300 _var.storage = REDIS_VM_MEMORY; \
dfc5e96c 301} while(0);
302
3305306f 303typedef struct redisDb {
4409877e 304 dict *dict; /* The keyspace for this DB */
305 dict *expires; /* Timeout of keys with a timeout set */
37ab76c9 306 dict *blocking_keys; /* Keys with clients waiting for data (BLPOP) */
d5d55fc3 307 dict *io_keys; /* Keys with clients waiting for VM I/O */
37ab76c9 308 dict *watched_keys; /* WATCHED keys for MULTI/EXEC CAS */
3305306f 309 int id;
310} redisDb;
311
6e469882 312/* Client MULTI/EXEC state */
313typedef struct multiCmd {
314 robj **argv;
315 int argc;
316 struct redisCommand *cmd;
317} multiCmd;
318
319typedef struct multiState {
320 multiCmd *commands; /* Array of MULTI commands */
321 int count; /* Total number of MULTI commands */
322} multiState;
323
ed9b544e 324/* With multiplexing we need to take per-clinet state.
325 * Clients are taken in a liked list. */
326typedef struct redisClient {
327 int fd;
3305306f 328 redisDb *db;
ed9b544e 329 int dictid;
330 sds querybuf;
e8a74421 331 robj **argv, **mbargv;
332 int argc, mbargc;
40d224a9 333 int bulklen; /* bulk read len. -1 if not in bulk read mode */
e8a74421 334 int multibulk; /* multi bulk command format active */
ed9b544e 335 list *reply;
336 int sentlen;
337 time_t lastinteraction; /* time of the last interaction, used for timeout */
d5d55fc3 338 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
40d224a9 339 int slaveseldb; /* slave selected db, if this client is a slave */
340 int authenticated; /* when requirepass is non-NULL */
341 int replstate; /* replication state if this is a slave */
342 int repldbfd; /* replication DB file descriptor */
6e469882 343 long repldboff; /* replication DB file offset */
40d224a9 344 off_t repldbsize; /* replication DB file size */
6e469882 345 multiState mstate; /* MULTI/EXEC state */
37ab76c9 346 robj **blocking_keys; /* The key we are waiting to terminate a blocking
4409877e 347 * operation such as BLPOP. Otherwise NULL. */
37ab76c9 348 int blocking_keys_num; /* Number of blocking keys */
4409877e 349 time_t blockingto; /* Blocking operation timeout. If UNIX current time
350 * is >= blockingto then the operation timed out. */
92f8e882 351 list *io_keys; /* Keys this client is waiting to be loaded from the
352 * swap file in order to continue. */
37ab76c9 353 list *watched_keys; /* Keys WATCHED for MULTI/EXEC CAS */
ffc6b7f8 354 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
355 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
ed9b544e 356} redisClient;
357
358struct saveparam {
359 time_t seconds;
360 int changes;
361};
362
363/* Global server state structure */
364struct redisServer {
365 int port;
366 int fd;
3305306f 367 redisDb *db;
ed9b544e 368 long long dirty; /* changes to DB from the last save */
369 list *clients;
87eca727 370 list *slaves, *monitors;
ed9b544e 371 char neterr[ANET_ERR_LEN];
372 aeEventLoop *el;
373 int cronloops; /* number of times the cron function run */
374 list *objfreelist; /* A list of freed objects to avoid malloc() */
375 time_t lastsave; /* Unix time of last save succeeede */
ed9b544e 376 /* Fields used only for stats */
377 time_t stat_starttime; /* server start time */
378 long long stat_numcommands; /* number of processed commands */
379 long long stat_numconnections; /* number of connections received */
2a6a2ed1 380 long long stat_expiredkeys; /* number of expired keys */
ed9b544e 381 /* Configuration */
382 int verbosity;
383 int glueoutputbuf;
384 int maxidletime;
385 int dbnum;
386 int daemonize;
44b38ef4 387 int appendonly;
48f0308a 388 int appendfsync;
38db9171 389 int no_appendfsync_on_rewrite;
fab43727 390 int shutdown_asap;
48f0308a 391 time_t lastfsync;
44b38ef4 392 int appendfd;
393 int appendseldb;
ed329fcf 394 char *pidfile;
9f3c422c 395 pid_t bgsavechildpid;
9d65a1bb 396 pid_t bgrewritechildpid;
397 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
28ed1f33 398 sds aofbuf; /* AOF buffer, written before entering the event loop */
ed9b544e 399 struct saveparam *saveparams;
400 int saveparamslen;
401 char *logfile;
402 char *bindaddr;
403 char *dbfilename;
44b38ef4 404 char *appendfilename;
abcb223e 405 char *requirepass;
121f70cf 406 int rdbcompression;
8ca3e9d1 407 int activerehashing;
ed9b544e 408 /* Replication related */
409 int isslave;
d0ccebcf 410 char *masterauth;
ed9b544e 411 char *masterhost;
412 int masterport;
40d224a9 413 redisClient *master; /* client that is master for this slave */
ed9b544e 414 int replstate;
285add55 415 unsigned int maxclients;
4ef8de8a 416 unsigned long long maxmemory;
d5d55fc3 417 unsigned int blpop_blocked_clients;
418 unsigned int vm_blocked_clients;
ed9b544e 419 /* Sort parameters - qsort_r() is only available under BSD so we
420 * have to take this state global, in order to pass it to sortCompare() */
421 int sort_desc;
422 int sort_alpha;
423 int sort_bypattern;
75680a3c 424 /* Virtual memory configuration */
425 int vm_enabled;
054e426d 426 char *vm_swap_file;
75680a3c 427 off_t vm_page_size;
428 off_t vm_pages;
4ef8de8a 429 unsigned long long vm_max_memory;
d0686e07 430 /* Zip structure config */
cbba7dd7 431 size_t hash_max_zipmap_entries;
432 size_t hash_max_zipmap_value;
d0686e07
PN
433 size_t list_max_ziplist_entries;
434 size_t list_max_ziplist_value;
75680a3c 435 /* Virtual memory state */
436 FILE *vm_fp;
437 int vm_fd;
438 off_t vm_next_page; /* Next probably empty page */
439 off_t vm_near_pages; /* Number of pages allocated sequentially */
06224fec 440 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
3a66edc7 441 time_t unixtime; /* Unix time sampled every second. */
92f8e882 442 /* Virtual memory I/O threads stuff */
92f8e882 443 /* An I/O thread process an element taken from the io_jobs queue and
996cb5f7 444 * put the result of the operation in the io_done list. While the
445 * job is being processed, it's put on io_processing queue. */
446 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
447 list *io_processing; /* List of VM I/O jobs being processed */
448 list *io_processed; /* List of VM I/O jobs already processed */
d5d55fc3 449 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
996cb5f7 450 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
a5819310 451 pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
452 pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
bcaa7a4f 453 pthread_attr_t io_threads_attr; /* attributes for threads creation */
92f8e882 454 int io_active_threads; /* Number of running I/O threads */
455 int vm_max_threads; /* Max number of I/O threads running at the same time */
996cb5f7 456 /* Our main thread is blocked on the event loop, locking for sockets ready
457 * to be read or written, so when a threaded I/O operation is ready to be
458 * processed by the main thread, the I/O thread will use a unix pipe to
459 * awake the main thread. The followings are the two pipe FDs. */
460 int io_ready_pipe_read;
461 int io_ready_pipe_write;
7d98e08c 462 /* Virtual memory stats */
463 unsigned long long vm_stats_used_pages;
464 unsigned long long vm_stats_swapped_objects;
465 unsigned long long vm_stats_swapouts;
466 unsigned long long vm_stats_swapins;
befec3cd 467 /* Pubsub */
ffc6b7f8 468 dict *pubsub_channels; /* Map channels to list of subscribed clients */
469 list *pubsub_patterns; /* A list of pubsub_patterns */
befec3cd 470 /* Misc */
b9bc0eef 471 FILE *devnull;
560db612 472 unsigned lruclock:22; /* clock incrementing every minute, for LRU */
473 unsigned lruclock_padding:10;
ed9b544e 474};
475
ffc6b7f8 476typedef struct pubsubPattern {
477 redisClient *client;
478 robj *pattern;
479} pubsubPattern;
480
ed9b544e 481typedef void redisCommandProc(redisClient *c);
ca1788b5 482typedef void redisVmPreloadProc(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
ed9b544e 483struct redisCommand {
484 char *name;
485 redisCommandProc *proc;
486 int arity;
487 int flags;
76583ea4
PN
488 /* Use a function to determine which keys need to be loaded
489 * in the background prior to executing this command. Takes precedence
490 * over vm_firstkey and others, ignored when NULL */
ca1788b5 491 redisVmPreloadProc *vm_preload_proc;
7c775e09 492 /* What keys should be loaded in background when calling this command? */
493 int vm_firstkey; /* The first argument that's a key (0 = no keys) */
494 int vm_lastkey; /* THe last argument that's a key */
495 int vm_keystep; /* The step between first and last key */
ed9b544e 496};
497
de96dbfe 498struct redisFunctionSym {
499 char *name;
56906eef 500 unsigned long pointer;
de96dbfe 501};
502
ed9b544e 503typedef struct _redisSortObject {
504 robj *obj;
505 union {
506 double score;
507 robj *cmpobj;
508 } u;
509} redisSortObject;
510
511typedef struct _redisSortOperation {
512 int type;
513 robj *pattern;
514} redisSortOperation;
515
6b47e12e 516/* ZSETs use a specialized version of Skiplists */
517
518typedef struct zskiplistNode {
519 struct zskiplistNode **forward;
e3870fab 520 struct zskiplistNode *backward;
912b9165 521 unsigned int *span;
6b47e12e 522 double score;
523 robj *obj;
524} zskiplistNode;
525
526typedef struct zskiplist {
e3870fab 527 struct zskiplistNode *header, *tail;
d13f767c 528 unsigned long length;
6b47e12e 529 int level;
530} zskiplist;
531
1812e024 532typedef struct zset {
533 dict *dict;
6b47e12e 534 zskiplist *zsl;
1812e024 535} zset;
536
6b47e12e 537/* Our shared "common" objects */
538
05df7621 539#define REDIS_SHARED_INTEGERS 10000
ed9b544e 540struct sharedObjectsStruct {
c937aa89 541 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
6e469882 542 *colon, *nullbulk, *nullmultibulk, *queued,
c937aa89 543 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
544 *outofrangeerr, *plus,
ed9b544e 545 *select0, *select1, *select2, *select3, *select4,
befec3cd 546 *select5, *select6, *select7, *select8, *select9,
c8d0ea0e 547 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk, *mbulk3,
548 *mbulk4, *psubscribebulk, *punsubscribebulk,
549 *integers[REDIS_SHARED_INTEGERS];
ed9b544e 550} shared;
551
a7866db6 552/* Global vars that are actally used as constants. The following double
553 * values are used for double on-disk serialization, and are initialized
554 * at runtime to avoid strange compiler optimizations. */
555
556static double R_Zero, R_PosInf, R_NegInf, R_Nan;
557
92f8e882 558/* VM threaded I/O request message */
b9bc0eef 559#define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
560#define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
561#define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
d5d55fc3 562typedef struct iojob {
996cb5f7 563 int type; /* Request type, REDIS_IOJOB_* */
b9bc0eef 564 redisDb *db;/* Redis database */
92f8e882 565 robj *key; /* This I/O request is about swapping this key */
560db612 566 robj *id; /* Unique identifier of this job:
567 this is the object to swap for REDIS_IOREQ_*_SWAP, or the
568 vmpointer objct for REDIS_IOREQ_LOAD. */
b9bc0eef 569 robj *val; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
92f8e882 570 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
571 off_t page; /* Swap page where to read/write the object */
248ea310 572 off_t pages; /* Swap pages needed to save object. PREPARE_SWAP return val */
996cb5f7 573 int canceled; /* True if this command was canceled by blocking side of VM */
574 pthread_t thread; /* ID of the thread processing this entry */
575} iojob;
92f8e882 576
ed9b544e 577/*================================ Prototypes =============================== */
578
579static void freeStringObject(robj *o);
580static void freeListObject(robj *o);
581static void freeSetObject(robj *o);
582static void decrRefCount(void *o);
583static robj *createObject(int type, void *ptr);
584static void freeClient(redisClient *c);
f78fd11b 585static int rdbLoad(char *filename);
ed9b544e 586static void addReply(redisClient *c, robj *obj);
587static void addReplySds(redisClient *c, sds s);
588static void incrRefCount(robj *o);
f78fd11b 589static int rdbSaveBackground(char *filename);
ed9b544e 590static robj *createStringObject(char *ptr, size_t len);
4ef8de8a 591static robj *dupStringObject(robj *o);
248ea310 592static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
dd142b9c 593static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
28ed1f33 594static void flushAppendOnlyFile(void);
44b38ef4 595static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
ed9b544e 596static int syncWithMaster(void);
05df7621 597static robj *tryObjectEncoding(robj *o);
9d65a1bb 598static robj *getDecodedObject(robj *o);
3305306f 599static int removeExpire(redisDb *db, robj *key);
600static int expireIfNeeded(redisDb *db, robj *key);
601static int deleteIfVolatile(redisDb *db, robj *key);
09241813 602static int dbDelete(redisDb *db, robj *key);
bb32ede5 603static time_t getExpire(redisDb *db, robj *key);
604static int setExpire(redisDb *db, robj *key, time_t when);
a3b21203 605static void updateSlavesWaitingBgsave(int bgsaveerr);
3fd78bcd 606static void freeMemoryIfNeeded(void);
de96dbfe 607static int processCommand(redisClient *c);
56906eef 608static void setupSigSegvAction(void);
a3b21203 609static void rdbRemoveTempFile(pid_t childpid);
9d65a1bb 610static void aofRemoveTempFile(pid_t childpid);
0ea663ea 611static size_t stringObjectLen(robj *o);
638e42ac 612static void processInputBuffer(redisClient *c);
6b47e12e 613static zskiplist *zslCreate(void);
fd8ccf44 614static void zslFree(zskiplist *zsl);
2b59cfdf 615static void zslInsert(zskiplist *zsl, double score, robj *obj);
2895e862 616static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
6e469882 617static void initClientMultiState(redisClient *c);
618static void freeClientMultiState(redisClient *c);
619static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
b0d8747d 620static void unblockClientWaitingData(redisClient *c);
4409877e 621static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
75680a3c 622static void vmInit(void);
a35ddf12 623static void vmMarkPagesFree(off_t page, off_t count);
560db612 624static robj *vmLoadObject(robj *o);
625static robj *vmPreviewObject(robj *o);
a69a0c9c 626static int vmSwapOneObjectBlocking(void);
627static int vmSwapOneObjectThreaded(void);
7e69548d 628static int vmCanSwapOut(void);
a5819310 629static int tryFreeOneObjectFromFreelist(void);
996cb5f7 630static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
631static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
632static void vmCancelThreadedIOJob(robj *o);
b9bc0eef 633static void lockThreadedIO(void);
634static void unlockThreadedIO(void);
635static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
636static void freeIOJob(iojob *j);
637static void queueIOJob(iojob *j);
a5819310 638static int vmWriteObjectOnSwap(robj *o, off_t page);
639static robj *vmReadObjectFromSwap(off_t page, int type);
054e426d 640static void waitEmptyIOJobsQueue(void);
641static void vmReopenSwapFile(void);
970e10bb 642static int vmFreePage(off_t page);
ca1788b5 643static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
3805e04f 644static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
0a6f3f0f 645static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd);
d5d55fc3 646static int dontWaitForSwappedKey(redisClient *c, robj *key);
647static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
648static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
649static struct redisCommand *lookupCommand(char *name);
650static void call(redisClient *c, struct redisCommand *cmd);
651static void resetClient(redisClient *c);
ada386b2 652static void convertToRealHash(robj *o);
d0686e07 653static void convertList(robj *o, int enc);
ffc6b7f8 654static int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
655static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
656static void freePubsubPattern(void *p);
657static int listMatchPubsubPattern(void *a, void *b);
658static int compareStringObjects(robj *a, robj *b);
bf028098 659static int equalStringObjects(robj *a, robj *b);
befec3cd 660static void usage();
8f63ddca 661static int rewriteAppendOnlyFileBackground(void);
560db612 662static vmpointer *vmSwapObjectBlocking(robj *val);
fab43727 663static int prepareForShutdown();
37ab76c9 664static void touchWatchedKey(redisDb *db, robj *key);
9b30e1a2 665static void touchWatchedKeysOnFlush(int dbid);
37ab76c9 666static void unwatchAllKeys(redisClient *c);
ed9b544e 667
abcb223e 668static void authCommand(redisClient *c);
ed9b544e 669static void pingCommand(redisClient *c);
670static void echoCommand(redisClient *c);
671static void setCommand(redisClient *c);
672static void setnxCommand(redisClient *c);
526d00a5 673static void setexCommand(redisClient *c);
ed9b544e 674static void getCommand(redisClient *c);
675static void delCommand(redisClient *c);
676static void existsCommand(redisClient *c);
677static void incrCommand(redisClient *c);
678static void decrCommand(redisClient *c);
679static void incrbyCommand(redisClient *c);
680static void decrbyCommand(redisClient *c);
681static void selectCommand(redisClient *c);
682static void randomkeyCommand(redisClient *c);
683static void keysCommand(redisClient *c);
684static void dbsizeCommand(redisClient *c);
685static void lastsaveCommand(redisClient *c);
686static void saveCommand(redisClient *c);
687static void bgsaveCommand(redisClient *c);
9d65a1bb 688static void bgrewriteaofCommand(redisClient *c);
ed9b544e 689static void shutdownCommand(redisClient *c);
690static void moveCommand(redisClient *c);
691static void renameCommand(redisClient *c);
692static void renamenxCommand(redisClient *c);
693static void lpushCommand(redisClient *c);
694static void rpushCommand(redisClient *c);
695static void lpopCommand(redisClient *c);
696static void rpopCommand(redisClient *c);
697static void llenCommand(redisClient *c);
698static void lindexCommand(redisClient *c);
699static void lrangeCommand(redisClient *c);
700static void ltrimCommand(redisClient *c);
701static void typeCommand(redisClient *c);
702static void lsetCommand(redisClient *c);
703static void saddCommand(redisClient *c);
704static void sremCommand(redisClient *c);
a4460ef4 705static void smoveCommand(redisClient *c);
ed9b544e 706static void sismemberCommand(redisClient *c);
707static void scardCommand(redisClient *c);
12fea928 708static void spopCommand(redisClient *c);
2abb95a9 709static void srandmemberCommand(redisClient *c);
ed9b544e 710static void sinterCommand(redisClient *c);
711static void sinterstoreCommand(redisClient *c);
40d224a9 712static void sunionCommand(redisClient *c);
713static void sunionstoreCommand(redisClient *c);
f4f56e1d 714static void sdiffCommand(redisClient *c);
715static void sdiffstoreCommand(redisClient *c);
ed9b544e 716static void syncCommand(redisClient *c);
717static void flushdbCommand(redisClient *c);
718static void flushallCommand(redisClient *c);
719static void sortCommand(redisClient *c);
720static void lremCommand(redisClient *c);
0f5f7e9a 721static void rpoplpushcommand(redisClient *c);
ed9b544e 722static void infoCommand(redisClient *c);
70003d28 723static void mgetCommand(redisClient *c);
87eca727 724static void monitorCommand(redisClient *c);
3305306f 725static void expireCommand(redisClient *c);
802e8373 726static void expireatCommand(redisClient *c);
f6b141c5 727static void getsetCommand(redisClient *c);
fd88489a 728static void ttlCommand(redisClient *c);
321b0e13 729static void slaveofCommand(redisClient *c);
7f957c92 730static void debugCommand(redisClient *c);
f6b141c5 731static void msetCommand(redisClient *c);
732static void msetnxCommand(redisClient *c);
fd8ccf44 733static void zaddCommand(redisClient *c);
7db723ad 734static void zincrbyCommand(redisClient *c);
cc812361 735static void zrangeCommand(redisClient *c);
50c55df5 736static void zrangebyscoreCommand(redisClient *c);
f44dd428 737static void zcountCommand(redisClient *c);
e3870fab 738static void zrevrangeCommand(redisClient *c);
3c41331e 739static void zcardCommand(redisClient *c);
1b7106e7 740static void zremCommand(redisClient *c);
6e333bbe 741static void zscoreCommand(redisClient *c);
1807985b 742static void zremrangebyscoreCommand(redisClient *c);
6e469882 743static void multiCommand(redisClient *c);
744static void execCommand(redisClient *c);
18b6cb76 745static void discardCommand(redisClient *c);
4409877e 746static void blpopCommand(redisClient *c);
747static void brpopCommand(redisClient *c);
4b00bebd 748static void appendCommand(redisClient *c);
39191553 749static void substrCommand(redisClient *c);
69d95c3e 750static void zrankCommand(redisClient *c);
798d9e55 751static void zrevrankCommand(redisClient *c);
978c2c94 752static void hsetCommand(redisClient *c);
1f1c7695 753static void hsetnxCommand(redisClient *c);
978c2c94 754static void hgetCommand(redisClient *c);
09aeb579
PN
755static void hmsetCommand(redisClient *c);
756static void hmgetCommand(redisClient *c);
07efaf74 757static void hdelCommand(redisClient *c);
92b27fe9 758static void hlenCommand(redisClient *c);
9212eafd 759static void zremrangebyrankCommand(redisClient *c);
5d373da9 760static void zunionstoreCommand(redisClient *c);
761static void zinterstoreCommand(redisClient *c);
78409a0f 762static void hkeysCommand(redisClient *c);
763static void hvalsCommand(redisClient *c);
764static void hgetallCommand(redisClient *c);
a86f14b1 765static void hexistsCommand(redisClient *c);
500ece7c 766static void configCommand(redisClient *c);
01426b05 767static void hincrbyCommand(redisClient *c);
befec3cd 768static void subscribeCommand(redisClient *c);
769static void unsubscribeCommand(redisClient *c);
ffc6b7f8 770static void psubscribeCommand(redisClient *c);
771static void punsubscribeCommand(redisClient *c);
befec3cd 772static void publishCommand(redisClient *c);
37ab76c9 773static void watchCommand(redisClient *c);
774static void unwatchCommand(redisClient *c);
f6b141c5 775
ed9b544e 776/*================================= Globals ================================= */
777
778/* Global vars */
779static struct redisServer server; /* server global state */
1a132bbc 780static struct redisCommand *commandTable;
1a132bbc 781static struct redisCommand readonlyCommandTable[] = {
76583ea4
PN
782 {"get",getCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
783 {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
784 {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
526d00a5 785 {"setex",setexCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
76583ea4
PN
786 {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
787 {"substr",substrCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
788 {"del",delCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
789 {"exists",existsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
790 {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
791 {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
792 {"mget",mgetCommand,-2,REDIS_CMD_INLINE,NULL,1,-1,1},
793 {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
794 {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
795 {"rpop",rpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
796 {"lpop",lpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
797 {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
798 {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
799 {"llen",llenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
800 {"lindex",lindexCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
801 {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
802 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
803 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
804 {"lrem",lremCommand,4,REDIS_CMD_BULK,NULL,1,1,1},
805 {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,2,1},
806 {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
807 {"srem",sremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
808 {"smove",smoveCommand,4,REDIS_CMD_BULK,NULL,1,2,1},
809 {"sismember",sismemberCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
810 {"scard",scardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
811 {"spop",spopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
812 {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
813 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
814 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
815 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
816 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
817 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
818 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
819 {"smembers",sinterCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
820 {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
821 {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
822 {"zrem",zremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
823 {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
824 {"zremrangebyrank",zremrangebyrankCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
5d373da9 825 {"zunionstore",zunionstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
826 {"zinterstore",zinterstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
76583ea4
PN
827 {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
828 {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
829 {"zcount",zcountCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
830 {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
831 {"zcard",zcardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
832 {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
833 {"zrank",zrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
834 {"zrevrank",zrevrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
835 {"hset",hsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
1f1c7695 836 {"hsetnx",hsetnxCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
09aeb579 837 {"hget",hgetCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
d33278d1 838 {"hmset",hmsetCommand,-4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
09aeb579 839 {"hmget",hmgetCommand,-3,REDIS_CMD_BULK,NULL,1,1,1},
01426b05 840 {"hincrby",hincrbyCommand,4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
76583ea4
PN
841 {"hdel",hdelCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
842 {"hlen",hlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
843 {"hkeys",hkeysCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
844 {"hvals",hvalsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
845 {"hgetall",hgetallCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
4583c4f0 846 {"hexists",hexistsCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
76583ea4
PN
847 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
848 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
849 {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
850 {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
851 {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
852 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
853 {"select",selectCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
854 {"move",moveCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
855 {"rename",renameCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
856 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
857 {"expire",expireCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
858 {"expireat",expireatCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
859 {"keys",keysCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
860 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
861 {"auth",authCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
862 {"ping",pingCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
863 {"echo",echoCommand,2,REDIS_CMD_BULK,NULL,0,0,0},
864 {"save",saveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
865 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
866 {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
867 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
868 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
869 {"type",typeCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
870 {"multi",multiCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
3805e04f 871 {"exec",execCommand,1,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0},
76583ea4
PN
872 {"discard",discardCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
873 {"sync",syncCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
874 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
875 {"flushall",flushallCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
876 {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
877 {"info",infoCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
878 {"monitor",monitorCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
879 {"ttl",ttlCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
880 {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
881 {"debug",debugCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
500ece7c 882 {"config",configCommand,-2,REDIS_CMD_BULK,NULL,0,0,0},
befec3cd 883 {"subscribe",subscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
884 {"unsubscribe",unsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
ffc6b7f8 885 {"psubscribe",psubscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
886 {"punsubscribe",punsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
4005fef1 887 {"publish",publishCommand,3,REDIS_CMD_BULK|REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0},
37ab76c9 888 {"watch",watchCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
d55d5c5d 889 {"unwatch",unwatchCommand,1,REDIS_CMD_INLINE,NULL,0,0,0}
ed9b544e 890};
bcfc686d 891
ed9b544e 892/*============================ Utility functions ============================ */
893
894/* Glob-style pattern matching. */
500ece7c 895static int stringmatchlen(const char *pattern, int patternLen,
ed9b544e 896 const char *string, int stringLen, int nocase)
897{
898 while(patternLen) {
899 switch(pattern[0]) {
900 case '*':
901 while (pattern[1] == '*') {
902 pattern++;
903 patternLen--;
904 }
905 if (patternLen == 1)
906 return 1; /* match */
907 while(stringLen) {
908 if (stringmatchlen(pattern+1, patternLen-1,
909 string, stringLen, nocase))
910 return 1; /* match */
911 string++;
912 stringLen--;
913 }
914 return 0; /* no match */
915 break;
916 case '?':
917 if (stringLen == 0)
918 return 0; /* no match */
919 string++;
920 stringLen--;
921 break;
922 case '[':
923 {
924 int not, match;
925
926 pattern++;
927 patternLen--;
928 not = pattern[0] == '^';
929 if (not) {
930 pattern++;
931 patternLen--;
932 }
933 match = 0;
934 while(1) {
935 if (pattern[0] == '\\') {
936 pattern++;
937 patternLen--;
938 if (pattern[0] == string[0])
939 match = 1;
940 } else if (pattern[0] == ']') {
941 break;
942 } else if (patternLen == 0) {
943 pattern--;
944 patternLen++;
945 break;
946 } else if (pattern[1] == '-' && patternLen >= 3) {
947 int start = pattern[0];
948 int end = pattern[2];
949 int c = string[0];
950 if (start > end) {
951 int t = start;
952 start = end;
953 end = t;
954 }
955 if (nocase) {
956 start = tolower(start);
957 end = tolower(end);
958 c = tolower(c);
959 }
960 pattern += 2;
961 patternLen -= 2;
962 if (c >= start && c <= end)
963 match = 1;
964 } else {
965 if (!nocase) {
966 if (pattern[0] == string[0])
967 match = 1;
968 } else {
969 if (tolower((int)pattern[0]) == tolower((int)string[0]))
970 match = 1;
971 }
972 }
973 pattern++;
974 patternLen--;
975 }
976 if (not)
977 match = !match;
978 if (!match)
979 return 0; /* no match */
980 string++;
981 stringLen--;
982 break;
983 }
984 case '\\':
985 if (patternLen >= 2) {
986 pattern++;
987 patternLen--;
988 }
989 /* fall through */
990 default:
991 if (!nocase) {
992 if (pattern[0] != string[0])
993 return 0; /* no match */
994 } else {
995 if (tolower((int)pattern[0]) != tolower((int)string[0]))
996 return 0; /* no match */
997 }
998 string++;
999 stringLen--;
1000 break;
1001 }
1002 pattern++;
1003 patternLen--;
1004 if (stringLen == 0) {
1005 while(*pattern == '*') {
1006 pattern++;
1007 patternLen--;
1008 }
1009 break;
1010 }
1011 }
1012 if (patternLen == 0 && stringLen == 0)
1013 return 1;
1014 return 0;
1015}
1016
500ece7c 1017static int stringmatch(const char *pattern, const char *string, int nocase) {
1018 return stringmatchlen(pattern,strlen(pattern),string,strlen(string),nocase);
1019}
1020
2b619329 1021/* Convert a string representing an amount of memory into the number of
1022 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
1023 * (1024*1024*1024).
1024 *
1025 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
1026 * set to 0 */
1027static long long memtoll(const char *p, int *err) {
1028 const char *u;
1029 char buf[128];
1030 long mul; /* unit multiplier */
1031 long long val;
1032 unsigned int digits;
1033
1034 if (err) *err = 0;
1035 /* Search the first non digit character. */
1036 u = p;
1037 if (*u == '-') u++;
1038 while(*u && isdigit(*u)) u++;
1039 if (*u == '\0' || !strcasecmp(u,"b")) {
1040 mul = 1;
72324005 1041 } else if (!strcasecmp(u,"k")) {
2b619329 1042 mul = 1000;
72324005 1043 } else if (!strcasecmp(u,"kb")) {
2b619329 1044 mul = 1024;
72324005 1045 } else if (!strcasecmp(u,"m")) {
2b619329 1046 mul = 1000*1000;
72324005 1047 } else if (!strcasecmp(u,"mb")) {
2b619329 1048 mul = 1024*1024;
72324005 1049 } else if (!strcasecmp(u,"g")) {
2b619329 1050 mul = 1000L*1000*1000;
72324005 1051 } else if (!strcasecmp(u,"gb")) {
2b619329 1052 mul = 1024L*1024*1024;
1053 } else {
1054 if (err) *err = 1;
1055 mul = 1;
1056 }
1057 digits = u-p;
1058 if (digits >= sizeof(buf)) {
1059 if (err) *err = 1;
1060 return LLONG_MAX;
1061 }
1062 memcpy(buf,p,digits);
1063 buf[digits] = '\0';
1064 val = strtoll(buf,NULL,10);
1065 return val*mul;
1066}
1067
ee14da56 1068/* Convert a long long into a string. Returns the number of
1069 * characters needed to represent the number, that can be shorter if passed
1070 * buffer length is not enough to store the whole number. */
1071static int ll2string(char *s, size_t len, long long value) {
1072 char buf[32], *p;
1073 unsigned long long v;
1074 size_t l;
1075
1076 if (len == 0) return 0;
1077 v = (value < 0) ? -value : value;
1078 p = buf+31; /* point to the last character */
1079 do {
1080 *p-- = '0'+(v%10);
1081 v /= 10;
1082 } while(v);
1083 if (value < 0) *p-- = '-';
1084 p++;
1085 l = 32-(p-buf);
1086 if (l+1 > len) l = len-1; /* Make sure it fits, including the nul term */
1087 memcpy(s,p,l);
1088 s[l] = '\0';
1089 return l;
1090}
1091
56906eef 1092static void redisLog(int level, const char *fmt, ...) {
ed9b544e 1093 va_list ap;
1094 FILE *fp;
1095
1096 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
1097 if (!fp) return;
1098
1099 va_start(ap, fmt);
1100 if (level >= server.verbosity) {
6766f45e 1101 char *c = ".-*#";
1904ecc1 1102 char buf[64];
1103 time_t now;
1104
1105 now = time(NULL);
6c9385e0 1106 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
054e426d 1107 fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
ed9b544e 1108 vfprintf(fp, fmt, ap);
1109 fprintf(fp,"\n");
1110 fflush(fp);
1111 }
1112 va_end(ap);
1113
1114 if (server.logfile) fclose(fp);
1115}
1116
1117/*====================== Hash table type implementation ==================== */
1118
1119/* This is an hash table type that uses the SDS dynamic strings libary as
1120 * keys and radis objects as values (objects can hold SDS strings,
1121 * lists, sets). */
1122
1812e024 1123static void dictVanillaFree(void *privdata, void *val)
1124{
1125 DICT_NOTUSED(privdata);
1126 zfree(val);
1127}
1128
4409877e 1129static void dictListDestructor(void *privdata, void *val)
1130{
1131 DICT_NOTUSED(privdata);
1132 listRelease((list*)val);
1133}
1134
09241813 1135static int dictSdsKeyCompare(void *privdata, const void *key1,
ed9b544e 1136 const void *key2)
1137{
1138 int l1,l2;
1139 DICT_NOTUSED(privdata);
1140
1141 l1 = sdslen((sds)key1);
1142 l2 = sdslen((sds)key2);
1143 if (l1 != l2) return 0;
1144 return memcmp(key1, key2, l1) == 0;
1145}
1146
1147static void dictRedisObjectDestructor(void *privdata, void *val)
1148{
1149 DICT_NOTUSED(privdata);
1150
a35ddf12 1151 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
ed9b544e 1152 decrRefCount(val);
1153}
1154
09241813 1155static void dictSdsDestructor(void *privdata, void *val)
1156{
1157 DICT_NOTUSED(privdata);
1158
1159 sdsfree(val);
1160}
1161
942a3961 1162static int dictObjKeyCompare(void *privdata, const void *key1,
ed9b544e 1163 const void *key2)
1164{
1165 const robj *o1 = key1, *o2 = key2;
09241813 1166 return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
ed9b544e 1167}
1168
942a3961 1169static unsigned int dictObjHash(const void *key) {
ed9b544e 1170 const robj *o = key;
1171 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1172}
1173
09241813 1174static unsigned int dictSdsHash(const void *key) {
1175 return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
1176}
1177
942a3961 1178static int dictEncObjKeyCompare(void *privdata, const void *key1,
1179 const void *key2)
1180{
9d65a1bb 1181 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
1182 int cmp;
942a3961 1183
2a1198b4 1184 if (o1->encoding == REDIS_ENCODING_INT &&
dc05abde 1185 o2->encoding == REDIS_ENCODING_INT)
1186 return o1->ptr == o2->ptr;
2a1198b4 1187
9d65a1bb 1188 o1 = getDecodedObject(o1);
1189 o2 = getDecodedObject(o2);
09241813 1190 cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
9d65a1bb 1191 decrRefCount(o1);
1192 decrRefCount(o2);
1193 return cmp;
942a3961 1194}
1195
1196static unsigned int dictEncObjHash(const void *key) {
9d65a1bb 1197 robj *o = (robj*) key;
942a3961 1198
ed9e4966 1199 if (o->encoding == REDIS_ENCODING_RAW) {
1200 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1201 } else {
1202 if (o->encoding == REDIS_ENCODING_INT) {
1203 char buf[32];
1204 int len;
1205
ee14da56 1206 len = ll2string(buf,32,(long)o->ptr);
ed9e4966 1207 return dictGenHashFunction((unsigned char*)buf, len);
1208 } else {
1209 unsigned int hash;
1210
1211 o = getDecodedObject(o);
1212 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1213 decrRefCount(o);
1214 return hash;
1215 }
1216 }
942a3961 1217}
1218
09241813 1219/* Sets type */
ed9b544e 1220static dictType setDictType = {
942a3961 1221 dictEncObjHash, /* hash function */
ed9b544e 1222 NULL, /* key dup */
1223 NULL, /* val dup */
942a3961 1224 dictEncObjKeyCompare, /* key compare */
ed9b544e 1225 dictRedisObjectDestructor, /* key destructor */
1226 NULL /* val destructor */
1227};
1228
f2d9f50f 1229/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1812e024 1230static dictType zsetDictType = {
1231 dictEncObjHash, /* hash function */
1232 NULL, /* key dup */
1233 NULL, /* val dup */
1234 dictEncObjKeyCompare, /* key compare */
1235 dictRedisObjectDestructor, /* key destructor */
da0a1620 1236 dictVanillaFree /* val destructor of malloc(sizeof(double)) */
1812e024 1237};
1238
09241813 1239/* Db->dict, keys are sds strings, vals are Redis objects. */
5234952b 1240static dictType dbDictType = {
09241813 1241 dictSdsHash, /* hash function */
ed9b544e 1242 NULL, /* key dup */
1243 NULL, /* val dup */
09241813 1244 dictSdsKeyCompare, /* key compare */
1245 dictSdsDestructor, /* key destructor */
ed9b544e 1246 dictRedisObjectDestructor /* val destructor */
1247};
1248
f2d9f50f 1249/* Db->expires */
1250static dictType keyptrDictType = {
09241813 1251 dictSdsHash, /* hash function */
f2d9f50f 1252 NULL, /* key dup */
1253 NULL, /* val dup */
09241813 1254 dictSdsKeyCompare, /* key compare */
1255 dictSdsDestructor, /* key destructor */
f2d9f50f 1256 NULL /* val destructor */
1257};
1258
5234952b 1259/* Hash type hash table (note that small hashes are represented with zimpaps) */
1260static dictType hashDictType = {
1261 dictEncObjHash, /* hash function */
1262 NULL, /* key dup */
1263 NULL, /* val dup */
1264 dictEncObjKeyCompare, /* key compare */
1265 dictRedisObjectDestructor, /* key destructor */
1266 dictRedisObjectDestructor /* val destructor */
1267};
1268
4409877e 1269/* Keylist hash table type has unencoded redis objects as keys and
d5d55fc3 1270 * lists as values. It's used for blocking operations (BLPOP) and to
1271 * map swapped keys to a list of clients waiting for this keys to be loaded. */
4409877e 1272static dictType keylistDictType = {
1273 dictObjHash, /* hash function */
1274 NULL, /* key dup */
1275 NULL, /* val dup */
1276 dictObjKeyCompare, /* key compare */
1277 dictRedisObjectDestructor, /* key destructor */
1278 dictListDestructor /* val destructor */
1279};
1280
42ab0172
AO
1281static void version();
1282
ed9b544e 1283/* ========================= Random utility functions ======================= */
1284
1285/* Redis generally does not try to recover from out of memory conditions
1286 * when allocating objects or strings, it is not clear if it will be possible
1287 * to report this condition to the client since the networking layer itself
1288 * is based on heap allocation for send buffers, so we simply abort.
1289 * At least the code will be simpler to read... */
1290static void oom(const char *msg) {
71c54b21 1291 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
ed9b544e 1292 sleep(1);
1293 abort();
1294}
1295
1296/* ====================== Redis server networking stuff ===================== */
56906eef 1297static void closeTimedoutClients(void) {
ed9b544e 1298 redisClient *c;
ed9b544e 1299 listNode *ln;
1300 time_t now = time(NULL);
c7df85a4 1301 listIter li;
ed9b544e 1302
c7df85a4 1303 listRewind(server.clients,&li);
1304 while ((ln = listNext(&li)) != NULL) {
ed9b544e 1305 c = listNodeValue(ln);
f86a74e9 1306 if (server.maxidletime &&
1307 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
c7cf2ec9 1308 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
ffc6b7f8 1309 dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
1310 listLength(c->pubsub_patterns) == 0 &&
d6cc8867 1311 (now - c->lastinteraction > server.maxidletime))
f86a74e9 1312 {
f870935d 1313 redisLog(REDIS_VERBOSE,"Closing idle client");
ed9b544e 1314 freeClient(c);
f86a74e9 1315 } else if (c->flags & REDIS_BLOCKED) {
58d976b8 1316 if (c->blockingto != 0 && c->blockingto < now) {
b177fd30 1317 addReply(c,shared.nullmultibulk);
b0d8747d 1318 unblockClientWaitingData(c);
f86a74e9 1319 }
ed9b544e 1320 }
1321 }
ed9b544e 1322}
1323
12fea928 1324static int htNeedsResize(dict *dict) {
1325 long long size, used;
1326
1327 size = dictSlots(dict);
1328 used = dictSize(dict);
1329 return (size && used && size > DICT_HT_INITIAL_SIZE &&
1330 (used*100/size < REDIS_HT_MINFILL));
1331}
1332
0bc03378 1333/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1334 * we resize the hash table to save memory */
56906eef 1335static void tryResizeHashTables(void) {
0bc03378 1336 int j;
1337
1338 for (j = 0; j < server.dbnum; j++) {
5413c40d 1339 if (htNeedsResize(server.db[j].dict))
0bc03378 1340 dictResize(server.db[j].dict);
12fea928 1341 if (htNeedsResize(server.db[j].expires))
1342 dictResize(server.db[j].expires);
0bc03378 1343 }
1344}
1345
8ca3e9d1 1346/* Our hash table implementation performs rehashing incrementally while
1347 * we write/read from the hash table. Still if the server is idle, the hash
1348 * table will use two tables for a long time. So we try to use 1 millisecond
1349 * of CPU time at every serverCron() loop in order to rehash some key. */
1350static void incrementallyRehash(void) {
1351 int j;
1352
1353 for (j = 0; j < server.dbnum; j++) {
1354 if (dictIsRehashing(server.db[j].dict)) {
1355 dictRehashMilliseconds(server.db[j].dict,1);
1356 break; /* already used our millisecond for this loop... */
1357 }
1358 }
1359}
1360
9d65a1bb 1361/* A background saving child (BGSAVE) terminated its work. Handle this. */
1362void backgroundSaveDoneHandler(int statloc) {
1363 int exitcode = WEXITSTATUS(statloc);
1364 int bysignal = WIFSIGNALED(statloc);
1365
1366 if (!bysignal && exitcode == 0) {
1367 redisLog(REDIS_NOTICE,
1368 "Background saving terminated with success");
1369 server.dirty = 0;
1370 server.lastsave = time(NULL);
1371 } else if (!bysignal && exitcode != 0) {
1372 redisLog(REDIS_WARNING, "Background saving error");
1373 } else {
1374 redisLog(REDIS_WARNING,
454eea7c 1375 "Background saving terminated by signal %d", WTERMSIG(statloc));
9d65a1bb 1376 rdbRemoveTempFile(server.bgsavechildpid);
1377 }
1378 server.bgsavechildpid = -1;
1379 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1380 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1381 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1382}
1383
1384/* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1385 * Handle this. */
1386void backgroundRewriteDoneHandler(int statloc) {
1387 int exitcode = WEXITSTATUS(statloc);
1388 int bysignal = WIFSIGNALED(statloc);
1389
1390 if (!bysignal && exitcode == 0) {
1391 int fd;
1392 char tmpfile[256];
1393
1394 redisLog(REDIS_NOTICE,
1395 "Background append only file rewriting terminated with success");
1396 /* Now it's time to flush the differences accumulated by the parent */
1397 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
1398 fd = open(tmpfile,O_WRONLY|O_APPEND);
1399 if (fd == -1) {
1400 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
1401 goto cleanup;
1402 }
1403 /* Flush our data... */
1404 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
1405 (signed) sdslen(server.bgrewritebuf)) {
1406 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));
1407 close(fd);
1408 goto cleanup;
1409 }
b32627cd 1410 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
9d65a1bb 1411 /* Now our work is to rename the temp file into the stable file. And
1412 * switch the file descriptor used by the server for append only. */
1413 if (rename(tmpfile,server.appendfilename) == -1) {
1414 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
1415 close(fd);
1416 goto cleanup;
1417 }
1418 /* Mission completed... almost */
1419 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
1420 if (server.appendfd != -1) {
1421 /* If append only is actually enabled... */
1422 close(server.appendfd);
1423 server.appendfd = fd;
d5d23dab 1424 if (server.appendfsync != APPENDFSYNC_NO) aof_fsync(fd);
85a83172 1425 server.appendseldb = -1; /* Make sure it will issue SELECT */
9d65a1bb 1426 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
1427 } else {
1428 /* If append only is disabled we just generate a dump in this
1429 * format. Why not? */
1430 close(fd);
1431 }
1432 } else if (!bysignal && exitcode != 0) {
1433 redisLog(REDIS_WARNING, "Background append only file rewriting error");
1434 } else {
1435 redisLog(REDIS_WARNING,
454eea7c 1436 "Background append only file rewriting terminated by signal %d",
1437 WTERMSIG(statloc));
9d65a1bb 1438 }
1439cleanup:
1440 sdsfree(server.bgrewritebuf);
1441 server.bgrewritebuf = sdsempty();
1442 aofRemoveTempFile(server.bgrewritechildpid);
1443 server.bgrewritechildpid = -1;
1444}
1445
884d4b39 1446/* This function is called once a background process of some kind terminates,
1447 * as we want to avoid resizing the hash tables when there is a child in order
1448 * to play well with copy-on-write (otherwise when a resize happens lots of
1449 * memory pages are copied). The goal of this function is to update the ability
1450 * for dict.c to resize the hash tables accordingly to the fact we have o not
1451 * running childs. */
1452static void updateDictResizePolicy(void) {
1453 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
1454 dictEnableResize();
1455 else
1456 dictDisableResize();
1457}
1458
56906eef 1459static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
94754ccc 1460 int j, loops = server.cronloops++;
ed9b544e 1461 REDIS_NOTUSED(eventLoop);
1462 REDIS_NOTUSED(id);
1463 REDIS_NOTUSED(clientData);
1464
3a66edc7 1465 /* We take a cached value of the unix time in the global state because
1466 * with virtual memory and aging there is to store the current time
1467 * in objects at every object access, and accuracy is not needed.
1468 * To access a global var is faster than calling time(NULL) */
1469 server.unixtime = time(NULL);
560db612 1470 /* We have just 21 bits per object for LRU information.
1471 * So we use an (eventually wrapping) LRU clock with minutes resolution.
1472 *
1473 * When we need to select what object to swap, we compute the minimum
1474 * time distance between the current lruclock and the object last access
1475 * lruclock info. Even if clocks will wrap on overflow, there is
1476 * the interesting property that we are sure that at least
1477 * ABS(A-B) minutes passed between current time and timestamp B.
1478 *
1479 * This is not precise but we don't need at all precision, but just
1480 * something statistically reasonable.
1481 */
1482 server.lruclock = (time(NULL)/60)&((1<<21)-1);
3a66edc7 1483
fab43727 1484 /* We received a SIGTERM, shutting down here in a safe way, as it is
1485 * not ok doing so inside the signal handler. */
1486 if (server.shutdown_asap) {
1487 if (prepareForShutdown() == REDIS_OK) exit(0);
1488 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
1489 }
1490
0bc03378 1491 /* Show some info about non-empty databases */
ed9b544e 1492 for (j = 0; j < server.dbnum; j++) {
dec423d9 1493 long long size, used, vkeys;
94754ccc 1494
3305306f 1495 size = dictSlots(server.db[j].dict);
1496 used = dictSize(server.db[j].dict);
94754ccc 1497 vkeys = dictSize(server.db[j].expires);
1763929f 1498 if (!(loops % 50) && (used || vkeys)) {
f870935d 1499 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
a4d1ba9a 1500 /* dictPrintStats(server.dict); */
ed9b544e 1501 }
ed9b544e 1502 }
1503
0bc03378 1504 /* We don't want to resize the hash tables while a bacground saving
1505 * is in progress: the saving child is created using fork() that is
1506 * implemented with a copy-on-write semantic in most modern systems, so
1507 * if we resize the HT while there is the saving child at work actually
1508 * a lot of memory movements in the parent will cause a lot of pages
1509 * copied. */
8ca3e9d1 1510 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
1511 if (!(loops % 10)) tryResizeHashTables();
1512 if (server.activerehashing) incrementallyRehash();
884d4b39 1513 }
0bc03378 1514
ed9b544e 1515 /* Show information about connected clients */
1763929f 1516 if (!(loops % 50)) {
bdcb92f2 1517 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
ed9b544e 1518 listLength(server.clients)-listLength(server.slaves),
1519 listLength(server.slaves),
bdcb92f2 1520 zmalloc_used_memory());
ed9b544e 1521 }
1522
1523 /* Close connections of timedout clients */
1763929f 1524 if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients)
ed9b544e 1525 closeTimedoutClients();
1526
9d65a1bb 1527 /* Check if a background saving or AOF rewrite in progress terminated */
1528 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
ed9b544e 1529 int statloc;
9d65a1bb 1530 pid_t pid;
1531
1532 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
1533 if (pid == server.bgsavechildpid) {
1534 backgroundSaveDoneHandler(statloc);
ed9b544e 1535 } else {
9d65a1bb 1536 backgroundRewriteDoneHandler(statloc);
ed9b544e 1537 }
884d4b39 1538 updateDictResizePolicy();
ed9b544e 1539 }
1540 } else {
1541 /* If there is not a background saving in progress check if
1542 * we have to save now */
1543 time_t now = time(NULL);
1544 for (j = 0; j < server.saveparamslen; j++) {
1545 struct saveparam *sp = server.saveparams+j;
1546
1547 if (server.dirty >= sp->changes &&
1548 now-server.lastsave > sp->seconds) {
1549 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
1550 sp->changes, sp->seconds);
f78fd11b 1551 rdbSaveBackground(server.dbfilename);
ed9b544e 1552 break;
1553 }
1554 }
1555 }
94754ccc 1556
f2324293 1557 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1558 * will use few CPU cycles if there are few expiring keys, otherwise
1559 * it will get more aggressive to avoid that too much memory is used by
1560 * keys that can be removed from the keyspace. */
94754ccc 1561 for (j = 0; j < server.dbnum; j++) {
f2324293 1562 int expired;
94754ccc 1563 redisDb *db = server.db+j;
94754ccc 1564
f2324293 1565 /* Continue to expire if at the end of the cycle more than 25%
1566 * of the keys were expired. */
1567 do {
4ef8de8a 1568 long num = dictSize(db->expires);
94754ccc 1569 time_t now = time(NULL);
1570
f2324293 1571 expired = 0;
94754ccc 1572 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
1573 num = REDIS_EXPIRELOOKUPS_PER_CRON;
1574 while (num--) {
1575 dictEntry *de;
1576 time_t t;
1577
1578 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
1579 t = (time_t) dictGetEntryVal(de);
1580 if (now > t) {
09241813 1581 sds key = dictGetEntryKey(de);
1582 robj *keyobj = createStringObject(key,sdslen(key));
1583
1584 dbDelete(db,keyobj);
1585 decrRefCount(keyobj);
f2324293 1586 expired++;
2a6a2ed1 1587 server.stat_expiredkeys++;
94754ccc 1588 }
1589 }
f2324293 1590 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
94754ccc 1591 }
1592
4ef8de8a 1593 /* Swap a few keys on disk if we are over the memory limit and VM
f870935d 1594 * is enbled. Try to free objects from the free list first. */
7e69548d 1595 if (vmCanSwapOut()) {
1596 while (server.vm_enabled && zmalloc_used_memory() >
f870935d 1597 server.vm_max_memory)
1598 {
72e9fd40 1599 int retval;
1600
a5819310 1601 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
72e9fd40 1602 retval = (server.vm_max_threads == 0) ?
1603 vmSwapOneObjectBlocking() :
1604 vmSwapOneObjectThreaded();
1763929f 1605 if (retval == REDIS_ERR && !(loops % 300) &&
72e9fd40 1606 zmalloc_used_memory() >
1607 (server.vm_max_memory+server.vm_max_memory/10))
1608 {
1609 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
7e69548d 1610 }
72e9fd40 1611 /* Note that when using threade I/O we free just one object,
1612 * because anyway when the I/O thread in charge to swap this
1613 * object out will finish, the handler of completed jobs
1614 * will try to swap more objects if we are still out of memory. */
1615 if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
4ef8de8a 1616 }
1617 }
1618
ed9b544e 1619 /* Check if we should connect to a MASTER */
1763929f 1620 if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) {
ed9b544e 1621 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
1622 if (syncWithMaster() == REDIS_OK) {
1623 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
8f63ddca 1624 if (server.appendonly) rewriteAppendOnlyFileBackground();
ed9b544e 1625 }
1626 }
1763929f 1627 return 100;
ed9b544e 1628}
1629
d5d55fc3 1630/* This function gets called every time Redis is entering the
1631 * main loop of the event driven library, that is, before to sleep
1632 * for ready file descriptors. */
1633static void beforeSleep(struct aeEventLoop *eventLoop) {
1634 REDIS_NOTUSED(eventLoop);
1635
28ed1f33 1636 /* Awake clients that got all the swapped keys they requested */
d5d55fc3 1637 if (server.vm_enabled && listLength(server.io_ready_clients)) {
1638 listIter li;
1639 listNode *ln;
1640
1641 listRewind(server.io_ready_clients,&li);
1642 while((ln = listNext(&li))) {
1643 redisClient *c = ln->value;
1644 struct redisCommand *cmd;
1645
1646 /* Resume the client. */
1647 listDelNode(server.io_ready_clients,ln);
1648 c->flags &= (~REDIS_IO_WAIT);
1649 server.vm_blocked_clients--;
1650 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1651 readQueryFromClient, c);
1652 cmd = lookupCommand(c->argv[0]->ptr);
1653 assert(cmd != NULL);
1654 call(c,cmd);
1655 resetClient(c);
1656 /* There may be more data to process in the input buffer. */
1657 if (c->querybuf && sdslen(c->querybuf) > 0)
1658 processInputBuffer(c);
1659 }
1660 }
28ed1f33 1661 /* Write the AOF buffer on disk */
1662 flushAppendOnlyFile();
d5d55fc3 1663}
1664
ed9b544e 1665static void createSharedObjects(void) {
05df7621 1666 int j;
1667
ed9b544e 1668 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
1669 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
1670 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
c937aa89 1671 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
1672 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
1673 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
1674 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
1675 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
1676 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
ed9b544e 1677 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
6e469882 1678 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
ed9b544e 1679 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
1680 "-ERR Operation against a key holding the wrong kind of value\r\n"));
ed9b544e 1681 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
1682 "-ERR no such key\r\n"));
ed9b544e 1683 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
1684 "-ERR syntax error\r\n"));
c937aa89 1685 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
1686 "-ERR source and destination objects are the same\r\n"));
1687 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
1688 "-ERR index out of range\r\n"));
ed9b544e 1689 shared.space = createObject(REDIS_STRING,sdsnew(" "));
c937aa89 1690 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
1691 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
ed9b544e 1692 shared.select0 = createStringObject("select 0\r\n",10);
1693 shared.select1 = createStringObject("select 1\r\n",10);
1694 shared.select2 = createStringObject("select 2\r\n",10);
1695 shared.select3 = createStringObject("select 3\r\n",10);
1696 shared.select4 = createStringObject("select 4\r\n",10);
1697 shared.select5 = createStringObject("select 5\r\n",10);
1698 shared.select6 = createStringObject("select 6\r\n",10);
1699 shared.select7 = createStringObject("select 7\r\n",10);
1700 shared.select8 = createStringObject("select 8\r\n",10);
1701 shared.select9 = createStringObject("select 9\r\n",10);
befec3cd 1702 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
c8d0ea0e 1703 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
befec3cd 1704 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
fc46bb71 1705 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
ffc6b7f8 1706 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
1707 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
befec3cd 1708 shared.mbulk3 = createStringObject("*3\r\n",4);
c8d0ea0e 1709 shared.mbulk4 = createStringObject("*4\r\n",4);
05df7621 1710 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
1711 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
1712 shared.integers[j]->encoding = REDIS_ENCODING_INT;
1713 }
ed9b544e 1714}
1715
1716static void appendServerSaveParams(time_t seconds, int changes) {
1717 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
ed9b544e 1718 server.saveparams[server.saveparamslen].seconds = seconds;
1719 server.saveparams[server.saveparamslen].changes = changes;
1720 server.saveparamslen++;
1721}
1722
bcfc686d 1723static void resetServerSaveParams() {
ed9b544e 1724 zfree(server.saveparams);
1725 server.saveparams = NULL;
1726 server.saveparamslen = 0;
1727}
1728
1729static void initServerConfig() {
1730 server.dbnum = REDIS_DEFAULT_DBNUM;
1731 server.port = REDIS_SERVERPORT;
f870935d 1732 server.verbosity = REDIS_VERBOSE;
ed9b544e 1733 server.maxidletime = REDIS_MAXIDLETIME;
1734 server.saveparams = NULL;
1735 server.logfile = NULL; /* NULL = log on standard output */
1736 server.bindaddr = NULL;
1737 server.glueoutputbuf = 1;
1738 server.daemonize = 0;
44b38ef4 1739 server.appendonly = 0;
1b677732 1740 server.appendfsync = APPENDFSYNC_EVERYSEC;
38db9171 1741 server.no_appendfsync_on_rewrite = 0;
48f0308a 1742 server.lastfsync = time(NULL);
44b38ef4 1743 server.appendfd = -1;
1744 server.appendseldb = -1; /* Make sure the first time will not match */
500ece7c 1745 server.pidfile = zstrdup("/var/run/redis.pid");
1746 server.dbfilename = zstrdup("dump.rdb");
1747 server.appendfilename = zstrdup("appendonly.aof");
abcb223e 1748 server.requirepass = NULL;
b0553789 1749 server.rdbcompression = 1;
8ca3e9d1 1750 server.activerehashing = 1;
285add55 1751 server.maxclients = 0;
d5d55fc3 1752 server.blpop_blocked_clients = 0;
3fd78bcd 1753 server.maxmemory = 0;
75680a3c 1754 server.vm_enabled = 0;
054e426d 1755 server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
75680a3c 1756 server.vm_page_size = 256; /* 256 bytes per page */
1757 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
1758 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
92f8e882 1759 server.vm_max_threads = 4;
d5d55fc3 1760 server.vm_blocked_clients = 0;
cbba7dd7 1761 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
1762 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
d0686e07
PN
1763 server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
1764 server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
fab43727 1765 server.shutdown_asap = 0;
75680a3c 1766
bcfc686d 1767 resetServerSaveParams();
ed9b544e 1768
1769 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1770 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1771 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1772 /* Replication related */
1773 server.isslave = 0;
d0ccebcf 1774 server.masterauth = NULL;
ed9b544e 1775 server.masterhost = NULL;
1776 server.masterport = 6379;
1777 server.master = NULL;
1778 server.replstate = REDIS_REPL_NONE;
a7866db6 1779
1780 /* Double constants initialization */
1781 R_Zero = 0.0;
1782 R_PosInf = 1.0/R_Zero;
1783 R_NegInf = -1.0/R_Zero;
1784 R_Nan = R_Zero/R_Zero;
ed9b544e 1785}
1786
1787static void initServer() {
1788 int j;
1789
1790 signal(SIGHUP, SIG_IGN);
1791 signal(SIGPIPE, SIG_IGN);
fe3bbfbe 1792 setupSigSegvAction();
ed9b544e 1793
b9bc0eef 1794 server.devnull = fopen("/dev/null","w");
1795 if (server.devnull == NULL) {
1796 redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr);
1797 exit(1);
1798 }
ed9b544e 1799 server.clients = listCreate();
1800 server.slaves = listCreate();
87eca727 1801 server.monitors = listCreate();
ed9b544e 1802 server.objfreelist = listCreate();
1803 createSharedObjects();
1804 server.el = aeCreateEventLoop();
3305306f 1805 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
ed9b544e 1806 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
1807 if (server.fd == -1) {
1808 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
1809 exit(1);
1810 }
3305306f 1811 for (j = 0; j < server.dbnum; j++) {
5234952b 1812 server.db[j].dict = dictCreate(&dbDictType,NULL);
f2d9f50f 1813 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
37ab76c9 1814 server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
1815 server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
d5d55fc3 1816 if (server.vm_enabled)
1817 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
3305306f 1818 server.db[j].id = j;
1819 }
ffc6b7f8 1820 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1821 server.pubsub_patterns = listCreate();
1822 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1823 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
ed9b544e 1824 server.cronloops = 0;
9f3c422c 1825 server.bgsavechildpid = -1;
9d65a1bb 1826 server.bgrewritechildpid = -1;
1827 server.bgrewritebuf = sdsempty();
28ed1f33 1828 server.aofbuf = sdsempty();
ed9b544e 1829 server.lastsave = time(NULL);
1830 server.dirty = 0;
ed9b544e 1831 server.stat_numcommands = 0;
1832 server.stat_numconnections = 0;
2a6a2ed1 1833 server.stat_expiredkeys = 0;
ed9b544e 1834 server.stat_starttime = time(NULL);
3a66edc7 1835 server.unixtime = time(NULL);
d8f8b666 1836 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
996cb5f7 1837 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
1838 acceptHandler, NULL) == AE_ERR) oom("creating file event");
44b38ef4 1839
1840 if (server.appendonly) {
3bb225d6 1841 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
44b38ef4 1842 if (server.appendfd == -1) {
1843 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1844 strerror(errno));
1845 exit(1);
1846 }
1847 }
75680a3c 1848
1849 if (server.vm_enabled) vmInit();
ed9b544e 1850}
1851
1852/* Empty the whole database */
ca37e9cd 1853static long long emptyDb() {
ed9b544e 1854 int j;
ca37e9cd 1855 long long removed = 0;
ed9b544e 1856
3305306f 1857 for (j = 0; j < server.dbnum; j++) {
ca37e9cd 1858 removed += dictSize(server.db[j].dict);
3305306f 1859 dictEmpty(server.db[j].dict);
1860 dictEmpty(server.db[j].expires);
1861 }
ca37e9cd 1862 return removed;
ed9b544e 1863}
1864
85dd2f3a 1865static int yesnotoi(char *s) {
1866 if (!strcasecmp(s,"yes")) return 1;
1867 else if (!strcasecmp(s,"no")) return 0;
1868 else return -1;
1869}
1870
ed9b544e 1871/* I agree, this is a very rudimental way to load a configuration...
1872 will improve later if the config gets more complex */
1873static void loadServerConfig(char *filename) {
c9a111ac 1874 FILE *fp;
ed9b544e 1875 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
1876 int linenum = 0;
1877 sds line = NULL;
c9a111ac 1878
1879 if (filename[0] == '-' && filename[1] == '\0')
1880 fp = stdin;
1881 else {
1882 if ((fp = fopen(filename,"r")) == NULL) {
9a22de82 1883 redisLog(REDIS_WARNING, "Fatal error, can't open config file '%s'", filename);
c9a111ac 1884 exit(1);
1885 }
ed9b544e 1886 }
c9a111ac 1887
ed9b544e 1888 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1889 sds *argv;
1890 int argc, j;
1891
1892 linenum++;
1893 line = sdsnew(buf);
1894 line = sdstrim(line," \t\r\n");
1895
1896 /* Skip comments and blank lines*/
1897 if (line[0] == '#' || line[0] == '\0') {
1898 sdsfree(line);
1899 continue;
1900 }
1901
1902 /* Split into arguments */
1903 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
1904 sdstolower(argv[0]);
1905
1906 /* Execute config directives */
bb0b03a3 1907 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
ed9b544e 1908 server.maxidletime = atoi(argv[1]);
0150db36 1909 if (server.maxidletime < 0) {
ed9b544e 1910 err = "Invalid timeout value"; goto loaderr;
1911 }
bb0b03a3 1912 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
ed9b544e 1913 server.port = atoi(argv[1]);
1914 if (server.port < 1 || server.port > 65535) {
1915 err = "Invalid port"; goto loaderr;
1916 }
bb0b03a3 1917 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
ed9b544e 1918 server.bindaddr = zstrdup(argv[1]);
bb0b03a3 1919 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
ed9b544e 1920 int seconds = atoi(argv[1]);
1921 int changes = atoi(argv[2]);
1922 if (seconds < 1 || changes < 0) {
1923 err = "Invalid save parameters"; goto loaderr;
1924 }
1925 appendServerSaveParams(seconds,changes);
bb0b03a3 1926 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
ed9b544e 1927 if (chdir(argv[1]) == -1) {
1928 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
1929 argv[1], strerror(errno));
1930 exit(1);
1931 }
bb0b03a3 1932 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
1933 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
f870935d 1934 else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
bb0b03a3 1935 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
1936 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
ed9b544e 1937 else {
1938 err = "Invalid log level. Must be one of debug, notice, warning";
1939 goto loaderr;
1940 }
bb0b03a3 1941 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
c9a111ac 1942 FILE *logfp;
ed9b544e 1943
1944 server.logfile = zstrdup(argv[1]);
bb0b03a3 1945 if (!strcasecmp(server.logfile,"stdout")) {
ed9b544e 1946 zfree(server.logfile);
1947 server.logfile = NULL;
1948 }
1949 if (server.logfile) {
1950 /* Test if we are able to open the file. The server will not
1951 * be able to abort just for this problem later... */
c9a111ac 1952 logfp = fopen(server.logfile,"a");
1953 if (logfp == NULL) {
ed9b544e 1954 err = sdscatprintf(sdsempty(),
1955 "Can't open the log file: %s", strerror(errno));
1956 goto loaderr;
1957 }
c9a111ac 1958 fclose(logfp);
ed9b544e 1959 }
bb0b03a3 1960 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
ed9b544e 1961 server.dbnum = atoi(argv[1]);
1962 if (server.dbnum < 1) {
1963 err = "Invalid number of databases"; goto loaderr;
1964 }
b3f83f12
JZ
1965 } else if (!strcasecmp(argv[0],"include") && argc == 2) {
1966 loadServerConfig(argv[1]);
285add55 1967 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
1968 server.maxclients = atoi(argv[1]);
3fd78bcd 1969 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
2b619329 1970 server.maxmemory = memtoll(argv[1],NULL);
bb0b03a3 1971 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
ed9b544e 1972 server.masterhost = sdsnew(argv[1]);
1973 server.masterport = atoi(argv[2]);
1974 server.replstate = REDIS_REPL_CONNECT;
d0ccebcf 1975 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
1976 server.masterauth = zstrdup(argv[1]);
bb0b03a3 1977 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
85dd2f3a 1978 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
ed9b544e 1979 err = "argument must be 'yes' or 'no'"; goto loaderr;
1980 }
121f70cf 1981 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
1982 if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
8ca3e9d1 1983 err = "argument must be 'yes' or 'no'"; goto loaderr;
1984 }
1985 } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
1986 if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
121f70cf 1987 err = "argument must be 'yes' or 'no'"; goto loaderr;
1988 }
bb0b03a3 1989 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
85dd2f3a 1990 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
ed9b544e 1991 err = "argument must be 'yes' or 'no'"; goto loaderr;
1992 }
44b38ef4 1993 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
1994 if ((server.appendonly = yesnotoi(argv[1])) == -1) {
1995 err = "argument must be 'yes' or 'no'"; goto loaderr;
1996 }
f3b52411
PN
1997 } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
1998 zfree(server.appendfilename);
1999 server.appendfilename = zstrdup(argv[1]);
38db9171 2000 } else if (!strcasecmp(argv[0],"no-appendfsync-on-rewrite")
2001 && argc == 2) {
2002 if ((server.no_appendfsync_on_rewrite= yesnotoi(argv[1])) == -1) {
2003 err = "argument must be 'yes' or 'no'"; goto loaderr;
2004 }
48f0308a 2005 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
1766c6da 2006 if (!strcasecmp(argv[1],"no")) {
48f0308a 2007 server.appendfsync = APPENDFSYNC_NO;
1766c6da 2008 } else if (!strcasecmp(argv[1],"always")) {
48f0308a 2009 server.appendfsync = APPENDFSYNC_ALWAYS;
1766c6da 2010 } else if (!strcasecmp(argv[1],"everysec")) {
48f0308a 2011 server.appendfsync = APPENDFSYNC_EVERYSEC;
2012 } else {
2013 err = "argument must be 'no', 'always' or 'everysec'";
2014 goto loaderr;
2015 }
bb0b03a3 2016 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
054e426d 2017 server.requirepass = zstrdup(argv[1]);
bb0b03a3 2018 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
500ece7c 2019 zfree(server.pidfile);
054e426d 2020 server.pidfile = zstrdup(argv[1]);
bb0b03a3 2021 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
500ece7c 2022 zfree(server.dbfilename);
054e426d 2023 server.dbfilename = zstrdup(argv[1]);
75680a3c 2024 } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
2025 if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
2026 err = "argument must be 'yes' or 'no'"; goto loaderr;
2027 }
054e426d 2028 } else if (!strcasecmp(argv[0],"vm-swap-file") && argc == 2) {
fefed597 2029 zfree(server.vm_swap_file);
054e426d 2030 server.vm_swap_file = zstrdup(argv[1]);
4ef8de8a 2031 } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
2b619329 2032 server.vm_max_memory = memtoll(argv[1],NULL);
4ef8de8a 2033 } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
2b619329 2034 server.vm_page_size = memtoll(argv[1], NULL);
4ef8de8a 2035 } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
2b619329 2036 server.vm_pages = memtoll(argv[1], NULL);
92f8e882 2037 } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
2038 server.vm_max_threads = strtoll(argv[1], NULL, 10);
cbba7dd7 2039 } else if (!strcasecmp(argv[0],"hash-max-zipmap-entries") && argc == 2){
2b619329 2040 server.hash_max_zipmap_entries = memtoll(argv[1], NULL);
cbba7dd7 2041 } else if (!strcasecmp(argv[0],"hash-max-zipmap-value") && argc == 2){
2b619329 2042 server.hash_max_zipmap_value = memtoll(argv[1], NULL);
d0686e07
PN
2043 } else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){
2044 server.list_max_ziplist_entries = memtoll(argv[1], NULL);
2045 } else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2){
2046 server.list_max_ziplist_value = memtoll(argv[1], NULL);
ed9b544e 2047 } else {
2048 err = "Bad directive or wrong number of arguments"; goto loaderr;
2049 }
2050 for (j = 0; j < argc; j++)
2051 sdsfree(argv[j]);
2052 zfree(argv);
2053 sdsfree(line);
2054 }
c9a111ac 2055 if (fp != stdin) fclose(fp);
ed9b544e 2056 return;
2057
2058loaderr:
2059 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
2060 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
2061 fprintf(stderr, ">>> '%s'\n", line);
2062 fprintf(stderr, "%s\n", err);
2063 exit(1);
2064}
2065
2066static void freeClientArgv(redisClient *c) {
2067 int j;
2068
2069 for (j = 0; j < c->argc; j++)
2070 decrRefCount(c->argv[j]);
e8a74421 2071 for (j = 0; j < c->mbargc; j++)
2072 decrRefCount(c->mbargv[j]);
ed9b544e 2073 c->argc = 0;
e8a74421 2074 c->mbargc = 0;
ed9b544e 2075}
2076
2077static void freeClient(redisClient *c) {
2078 listNode *ln;
2079
4409877e 2080 /* Note that if the client we are freeing is blocked into a blocking
b0d8747d 2081 * call, we have to set querybuf to NULL *before* to call
2082 * unblockClientWaitingData() to avoid processInputBuffer() will get
2083 * called. Also it is important to remove the file events after
2084 * this, because this call adds the READABLE event. */
4409877e 2085 sdsfree(c->querybuf);
2086 c->querybuf = NULL;
2087 if (c->flags & REDIS_BLOCKED)
b0d8747d 2088 unblockClientWaitingData(c);
4409877e 2089
37ab76c9 2090 /* UNWATCH all the keys */
2091 unwatchAllKeys(c);
2092 listRelease(c->watched_keys);
ffc6b7f8 2093 /* Unsubscribe from all the pubsub channels */
2094 pubsubUnsubscribeAllChannels(c,0);
2095 pubsubUnsubscribeAllPatterns(c,0);
2096 dictRelease(c->pubsub_channels);
2097 listRelease(c->pubsub_patterns);
befec3cd 2098 /* Obvious cleanup */
ed9b544e 2099 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
2100 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
ed9b544e 2101 listRelease(c->reply);
2102 freeClientArgv(c);
2103 close(c->fd);
92f8e882 2104 /* Remove from the list of clients */
ed9b544e 2105 ln = listSearchKey(server.clients,c);
dfc5e96c 2106 redisAssert(ln != NULL);
ed9b544e 2107 listDelNode(server.clients,ln);
37ab76c9 2108 /* Remove from the list of clients that are now ready to be restarted
2109 * after waiting for swapped keys */
d5d55fc3 2110 if (c->flags & REDIS_IO_WAIT && listLength(c->io_keys) == 0) {
2111 ln = listSearchKey(server.io_ready_clients,c);
2112 if (ln) {
2113 listDelNode(server.io_ready_clients,ln);
2114 server.vm_blocked_clients--;
2115 }
2116 }
37ab76c9 2117 /* Remove from the list of clients waiting for swapped keys */
d5d55fc3 2118 while (server.vm_enabled && listLength(c->io_keys)) {
2119 ln = listFirst(c->io_keys);
2120 dontWaitForSwappedKey(c,ln->value);
92f8e882 2121 }
b3e3d0d7 2122 listRelease(c->io_keys);
befec3cd 2123 /* Master/slave cleanup */
ed9b544e 2124 if (c->flags & REDIS_SLAVE) {
6208b3a7 2125 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
2126 close(c->repldbfd);
87eca727 2127 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
2128 ln = listSearchKey(l,c);
dfc5e96c 2129 redisAssert(ln != NULL);
87eca727 2130 listDelNode(l,ln);
ed9b544e 2131 }
2132 if (c->flags & REDIS_MASTER) {
2133 server.master = NULL;
2134 server.replstate = REDIS_REPL_CONNECT;
2135 }
befec3cd 2136 /* Release memory */
93ea3759 2137 zfree(c->argv);
e8a74421 2138 zfree(c->mbargv);
6e469882 2139 freeClientMultiState(c);
ed9b544e 2140 zfree(c);
2141}
2142
cc30e368 2143#define GLUEREPLY_UP_TO (1024)
ed9b544e 2144static void glueReplyBuffersIfNeeded(redisClient *c) {
c28b42ac 2145 int copylen = 0;
2146 char buf[GLUEREPLY_UP_TO];
6208b3a7 2147 listNode *ln;
c7df85a4 2148 listIter li;
ed9b544e 2149 robj *o;
2150
c7df85a4 2151 listRewind(c->reply,&li);
2152 while((ln = listNext(&li))) {
c28b42ac 2153 int objlen;
2154
ed9b544e 2155 o = ln->value;
c28b42ac 2156 objlen = sdslen(o->ptr);
2157 if (copylen + objlen <= GLUEREPLY_UP_TO) {
2158 memcpy(buf+copylen,o->ptr,objlen);
2159 copylen += objlen;
ed9b544e 2160 listDelNode(c->reply,ln);
c28b42ac 2161 } else {
2162 if (copylen == 0) return;
2163 break;
ed9b544e 2164 }
ed9b544e 2165 }
c28b42ac 2166 /* Now the output buffer is empty, add the new single element */
2167 o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
2168 listAddNodeHead(c->reply,o);
ed9b544e 2169}
2170
2171static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2172 redisClient *c = privdata;
2173 int nwritten = 0, totwritten = 0, objlen;
2174 robj *o;
2175 REDIS_NOTUSED(el);
2176 REDIS_NOTUSED(mask);
2177
2895e862 2178 /* Use writev() if we have enough buffers to send */
7ea870c0 2179 if (!server.glueoutputbuf &&
e0a62c7f 2180 listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
7ea870c0 2181 !(c->flags & REDIS_MASTER))
2895e862 2182 {
2183 sendReplyToClientWritev(el, fd, privdata, mask);
2184 return;
2185 }
2895e862 2186
ed9b544e 2187 while(listLength(c->reply)) {
c28b42ac 2188 if (server.glueoutputbuf && listLength(c->reply) > 1)
2189 glueReplyBuffersIfNeeded(c);
2190
ed9b544e 2191 o = listNodeValue(listFirst(c->reply));
2192 objlen = sdslen(o->ptr);
2193
2194 if (objlen == 0) {
2195 listDelNode(c->reply,listFirst(c->reply));
2196 continue;
2197 }
2198
2199 if (c->flags & REDIS_MASTER) {
6f376729 2200 /* Don't reply to a master */
ed9b544e 2201 nwritten = objlen - c->sentlen;
2202 } else {
a4d1ba9a 2203 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
ed9b544e 2204 if (nwritten <= 0) break;
2205 }
2206 c->sentlen += nwritten;
2207 totwritten += nwritten;
2208 /* If we fully sent the object on head go to the next one */
2209 if (c->sentlen == objlen) {
2210 listDelNode(c->reply,listFirst(c->reply));
2211 c->sentlen = 0;
2212 }
6f376729 2213 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
12f9d551 2214 * bytes, in a single threaded server it's a good idea to serve
6f376729 2215 * other clients as well, even if a very large request comes from
2216 * super fast link that is always able to accept data (in real world
12f9d551 2217 * scenario think about 'KEYS *' against the loopback interfae) */
6f376729 2218 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
ed9b544e 2219 }
2220 if (nwritten == -1) {
2221 if (errno == EAGAIN) {
2222 nwritten = 0;
2223 } else {
f870935d 2224 redisLog(REDIS_VERBOSE,
ed9b544e 2225 "Error writing to client: %s", strerror(errno));
2226 freeClient(c);
2227 return;
2228 }
2229 }
2230 if (totwritten > 0) c->lastinteraction = time(NULL);
2231 if (listLength(c->reply) == 0) {
2232 c->sentlen = 0;
2233 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2234 }
2235}
2236
2895e862 2237static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
2238{
2239 redisClient *c = privdata;
2240 int nwritten = 0, totwritten = 0, objlen, willwrite;
2241 robj *o;
2242 struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
2243 int offset, ion = 0;
2244 REDIS_NOTUSED(el);
2245 REDIS_NOTUSED(mask);
2246
2247 listNode *node;
2248 while (listLength(c->reply)) {
2249 offset = c->sentlen;
2250 ion = 0;
2251 willwrite = 0;
2252
2253 /* fill-in the iov[] array */
2254 for(node = listFirst(c->reply); node; node = listNextNode(node)) {
2255 o = listNodeValue(node);
2256 objlen = sdslen(o->ptr);
2257
e0a62c7f 2258 if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
2895e862 2259 break;
2260
2261 if(ion == REDIS_WRITEV_IOVEC_COUNT)
2262 break; /* no more iovecs */
2263
2264 iov[ion].iov_base = ((char*)o->ptr) + offset;
2265 iov[ion].iov_len = objlen - offset;
2266 willwrite += objlen - offset;
2267 offset = 0; /* just for the first item */
2268 ion++;
2269 }
2270
2271 if(willwrite == 0)
2272 break;
2273
2274 /* write all collected blocks at once */
2275 if((nwritten = writev(fd, iov, ion)) < 0) {
2276 if (errno != EAGAIN) {
f870935d 2277 redisLog(REDIS_VERBOSE,
2895e862 2278 "Error writing to client: %s", strerror(errno));
2279 freeClient(c);
2280 return;
2281 }
2282 break;
2283 }
2284
2285 totwritten += nwritten;
2286 offset = c->sentlen;
2287
2288 /* remove written robjs from c->reply */
2289 while (nwritten && listLength(c->reply)) {
2290 o = listNodeValue(listFirst(c->reply));
2291 objlen = sdslen(o->ptr);
2292
2293 if(nwritten >= objlen - offset) {
2294 listDelNode(c->reply, listFirst(c->reply));
2295 nwritten -= objlen - offset;
2296 c->sentlen = 0;
2297 } else {
2298 /* partial write */
2299 c->sentlen += nwritten;
2300 break;
2301 }
2302 offset = 0;
2303 }
2304 }
2305
e0a62c7f 2306 if (totwritten > 0)
2895e862 2307 c->lastinteraction = time(NULL);
2308
2309 if (listLength(c->reply) == 0) {
2310 c->sentlen = 0;
2311 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2312 }
2313}
2314
1a132bbc
PN
2315static int qsortRedisCommands(const void *r1, const void *r2) {
2316 return strcasecmp(
2317 ((struct redisCommand*)r1)->name,
2318 ((struct redisCommand*)r2)->name);
2319}
2320
2321static void sortCommandTable() {
1a132bbc
PN
2322 /* Copy and sort the read-only version of the command table */
2323 commandTable = (struct redisCommand*)malloc(sizeof(readonlyCommandTable));
2324 memcpy(commandTable,readonlyCommandTable,sizeof(readonlyCommandTable));
d55d5c5d 2325 qsort(commandTable,
2326 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
2327 sizeof(struct redisCommand),qsortRedisCommands);
1a132bbc
PN
2328}
2329
ed9b544e 2330static struct redisCommand *lookupCommand(char *name) {
1a132bbc
PN
2331 struct redisCommand tmp = {name,NULL,0,0,NULL,0,0,0};
2332 return bsearch(
2333 &tmp,
2334 commandTable,
d55d5c5d 2335 sizeof(readonlyCommandTable)/sizeof(struct redisCommand),
1a132bbc
PN
2336 sizeof(struct redisCommand),
2337 qsortRedisCommands);
ed9b544e 2338}
2339
2340/* resetClient prepare the client to process the next command */
2341static void resetClient(redisClient *c) {
2342 freeClientArgv(c);
2343 c->bulklen = -1;
e8a74421 2344 c->multibulk = 0;
ed9b544e 2345}
2346
6e469882 2347/* Call() is the core of Redis execution of a command */
2348static void call(redisClient *c, struct redisCommand *cmd) {
2349 long long dirty;
2350
2351 dirty = server.dirty;
2352 cmd->proc(c);
4005fef1 2353 dirty = server.dirty-dirty;
2354
2355 if (server.appendonly && dirty)
6e469882 2356 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
4005fef1 2357 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
2358 listLength(server.slaves))
248ea310 2359 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
6e469882 2360 if (listLength(server.monitors))
dd142b9c 2361 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
6e469882 2362 server.stat_numcommands++;
2363}
2364
ed9b544e 2365/* If this function gets called we already read a whole
2366 * command, argments are in the client argv/argc fields.
2367 * processCommand() execute the command or prepare the
2368 * server for a bulk read from the client.
2369 *
2370 * If 1 is returned the client is still alive and valid and
2371 * and other operations can be performed by the caller. Otherwise
2372 * if 0 is returned the client was destroied (i.e. after QUIT). */
2373static int processCommand(redisClient *c) {
2374 struct redisCommand *cmd;
ed9b544e 2375
3fd78bcd 2376 /* Free some memory if needed (maxmemory setting) */
2377 if (server.maxmemory) freeMemoryIfNeeded();
2378
e8a74421 2379 /* Handle the multi bulk command type. This is an alternative protocol
2380 * supported by Redis in order to receive commands that are composed of
2381 * multiple binary-safe "bulk" arguments. The latency of processing is
2382 * a bit higher but this allows things like multi-sets, so if this
2383 * protocol is used only for MSET and similar commands this is a big win. */
2384 if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
2385 c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
2386 if (c->multibulk <= 0) {
2387 resetClient(c);
2388 return 1;
2389 } else {
2390 decrRefCount(c->argv[c->argc-1]);
2391 c->argc--;
2392 return 1;
2393 }
2394 } else if (c->multibulk) {
2395 if (c->bulklen == -1) {
2396 if (((char*)c->argv[0]->ptr)[0] != '$') {
2397 addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
2398 resetClient(c);
2399 return 1;
2400 } else {
2401 int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
2402 decrRefCount(c->argv[0]);
2403 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2404 c->argc--;
2405 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2406 resetClient(c);
2407 return 1;
2408 }
2409 c->argc--;
2410 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2411 return 1;
2412 }
2413 } else {
2414 c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
2415 c->mbargv[c->mbargc] = c->argv[0];
2416 c->mbargc++;
2417 c->argc--;
2418 c->multibulk--;
2419 if (c->multibulk == 0) {
2420 robj **auxargv;
2421 int auxargc;
2422
2423 /* Here we need to swap the multi-bulk argc/argv with the
2424 * normal argc/argv of the client structure. */
2425 auxargv = c->argv;
2426 c->argv = c->mbargv;
2427 c->mbargv = auxargv;
2428
2429 auxargc = c->argc;
2430 c->argc = c->mbargc;
2431 c->mbargc = auxargc;
2432
2433 /* We need to set bulklen to something different than -1
2434 * in order for the code below to process the command without
2435 * to try to read the last argument of a bulk command as
2436 * a special argument. */
2437 c->bulklen = 0;
2438 /* continue below and process the command */
2439 } else {
2440 c->bulklen = -1;
2441 return 1;
2442 }
2443 }
2444 }
2445 /* -- end of multi bulk commands processing -- */
2446
ed9b544e 2447 /* The QUIT command is handled as a special case. Normal command
2448 * procs are unable to close the client connection safely */
bb0b03a3 2449 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
ed9b544e 2450 freeClient(c);
2451 return 0;
2452 }
d5d55fc3 2453
2454 /* Now lookup the command and check ASAP about trivial error conditions
2455 * such wrong arity, bad command name and so forth. */
ed9b544e 2456 cmd = lookupCommand(c->argv[0]->ptr);
2457 if (!cmd) {
2c14807b 2458 addReplySds(c,
2459 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2460 (char*)c->argv[0]->ptr));
ed9b544e 2461 resetClient(c);
2462 return 1;
2463 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
2464 (c->argc < -cmd->arity)) {
454d4e43 2465 addReplySds(c,
2466 sdscatprintf(sdsempty(),
2467 "-ERR wrong number of arguments for '%s' command\r\n",
2468 cmd->name));
ed9b544e 2469 resetClient(c);
2470 return 1;
2471 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
d5d55fc3 2472 /* This is a bulk command, we have to read the last argument yet. */
ed9b544e 2473 int bulklen = atoi(c->argv[c->argc-1]->ptr);
2474
2475 decrRefCount(c->argv[c->argc-1]);
2476 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2477 c->argc--;
2478 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2479 resetClient(c);
2480 return 1;
2481 }
2482 c->argc--;
2483 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2484 /* It is possible that the bulk read is already in the
8d0490e7 2485 * buffer. Check this condition and handle it accordingly.
2486 * This is just a fast path, alternative to call processInputBuffer().
2487 * It's a good idea since the code is small and this condition
2488 * happens most of the times. */
ed9b544e 2489 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
2490 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2491 c->argc++;
2492 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2493 } else {
d5d55fc3 2494 /* Otherwise return... there is to read the last argument
2495 * from the socket. */
ed9b544e 2496 return 1;
2497 }
2498 }
942a3961 2499 /* Let's try to encode the bulk object to save space. */
2500 if (cmd->flags & REDIS_CMD_BULK)
05df7621 2501 c->argv[c->argc-1] = tryObjectEncoding(c->argv[c->argc-1]);
942a3961 2502
e63943a4 2503 /* Check if the user is authenticated */
2504 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
2505 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
2506 resetClient(c);
2507 return 1;
2508 }
2509
b61a28fe 2510 /* Handle the maxmemory directive */
2511 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
2512 zmalloc_used_memory() > server.maxmemory)
2513 {
2514 addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2515 resetClient(c);
2516 return 1;
2517 }
2518
d6cc8867 2519 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
e6cca5db 2520 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
2521 &&
ffc6b7f8 2522 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
2523 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
2524 addReplySds(c,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
d6cc8867 2525 resetClient(c);
2526 return 1;
2527 }
2528
ed9b544e 2529 /* Exec the command */
6531c94d 2530 if (c->flags & REDIS_MULTI &&
2531 cmd->proc != execCommand && cmd->proc != discardCommand &&
2532 cmd->proc != multiCommand && cmd->proc != watchCommand)
2533 {
6e469882 2534 queueMultiCommand(c,cmd);
2535 addReply(c,shared.queued);
2536 } else {
d5d55fc3 2537 if (server.vm_enabled && server.vm_max_threads > 0 &&
0a6f3f0f 2538 blockClientOnSwappedKeys(c,cmd)) return 1;
6e469882 2539 call(c,cmd);
2540 }
ed9b544e 2541
2542 /* Prepare the client for the next command */
ed9b544e 2543 resetClient(c);
2544 return 1;
2545}
2546
248ea310 2547static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
6208b3a7 2548 listNode *ln;
c7df85a4 2549 listIter li;
ed9b544e 2550 int outc = 0, j;
93ea3759 2551 robj **outv;
248ea310 2552 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2553 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2554 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2555 robj *static_outv[REDIS_STATIC_ARGS*3+1];
2556 robj *lenobj;
93ea3759 2557
2558 if (argc <= REDIS_STATIC_ARGS) {
2559 outv = static_outv;
2560 } else {
248ea310 2561 outv = zmalloc(sizeof(robj*)*(argc*3+1));
93ea3759 2562 }
248ea310 2563
2564 lenobj = createObject(REDIS_STRING,
2565 sdscatprintf(sdsempty(), "*%d\r\n", argc));
2566 lenobj->refcount = 0;
2567 outv[outc++] = lenobj;
ed9b544e 2568 for (j = 0; j < argc; j++) {
248ea310 2569 lenobj = createObject(REDIS_STRING,
2570 sdscatprintf(sdsempty(),"$%lu\r\n",
2571 (unsigned long) stringObjectLen(argv[j])));
2572 lenobj->refcount = 0;
2573 outv[outc++] = lenobj;
ed9b544e 2574 outv[outc++] = argv[j];
248ea310 2575 outv[outc++] = shared.crlf;
ed9b544e 2576 }
ed9b544e 2577
40d224a9 2578 /* Increment all the refcounts at start and decrement at end in order to
2579 * be sure to free objects if there is no slave in a replication state
2580 * able to be feed with commands */
2581 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
c7df85a4 2582 listRewind(slaves,&li);
2583 while((ln = listNext(&li))) {
ed9b544e 2584 redisClient *slave = ln->value;
40d224a9 2585
2586 /* Don't feed slaves that are still waiting for BGSAVE to start */
6208b3a7 2587 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
40d224a9 2588
2589 /* Feed all the other slaves, MONITORs and so on */
ed9b544e 2590 if (slave->slaveseldb != dictid) {
2591 robj *selectcmd;
2592
2593 switch(dictid) {
2594 case 0: selectcmd = shared.select0; break;
2595 case 1: selectcmd = shared.select1; break;
2596 case 2: selectcmd = shared.select2; break;
2597 case 3: selectcmd = shared.select3; break;
2598 case 4: selectcmd = shared.select4; break;
2599 case 5: selectcmd = shared.select5; break;
2600 case 6: selectcmd = shared.select6; break;
2601 case 7: selectcmd = shared.select7; break;
2602 case 8: selectcmd = shared.select8; break;
2603 case 9: selectcmd = shared.select9; break;
2604 default:
2605 selectcmd = createObject(REDIS_STRING,
2606 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
2607 selectcmd->refcount = 0;
2608 break;
2609 }
2610 addReply(slave,selectcmd);
2611 slave->slaveseldb = dictid;
2612 }
2613 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
ed9b544e 2614 }
40d224a9 2615 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
93ea3759 2616 if (outv != static_outv) zfree(outv);
ed9b544e 2617}
2618
dd142b9c 2619static sds sdscatrepr(sds s, char *p, size_t len) {
2620 s = sdscatlen(s,"\"",1);
2621 while(len--) {
2622 switch(*p) {
2623 case '\\':
2624 case '"':
2625 s = sdscatprintf(s,"\\%c",*p);
2626 break;
2627 case '\n': s = sdscatlen(s,"\\n",1); break;
2628 case '\r': s = sdscatlen(s,"\\r",1); break;
2629 case '\t': s = sdscatlen(s,"\\t",1); break;
2630 case '\a': s = sdscatlen(s,"\\a",1); break;
2631 case '\b': s = sdscatlen(s,"\\b",1); break;
2632 default:
2633 if (isprint(*p))
2634 s = sdscatprintf(s,"%c",*p);
2635 else
2636 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
2637 break;
2638 }
2639 p++;
2640 }
2641 return sdscatlen(s,"\"",1);
2642}
2643
2644static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc) {
2645 listNode *ln;
2646 listIter li;
2647 int j;
2648 sds cmdrepr = sdsnew("+");
2649 robj *cmdobj;
2650 struct timeval tv;
2651
2652 gettimeofday(&tv,NULL);
2653 cmdrepr = sdscatprintf(cmdrepr,"%ld.%ld ",(long)tv.tv_sec,(long)tv.tv_usec);
2654 if (dictid != 0) cmdrepr = sdscatprintf(cmdrepr,"(db %d) ", dictid);
2655
2656 for (j = 0; j < argc; j++) {
2657 if (argv[j]->encoding == REDIS_ENCODING_INT) {
2658 cmdrepr = sdscatprintf(cmdrepr, "%ld", (long)argv[j]->ptr);
2659 } else {
2660 cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
2661 sdslen(argv[j]->ptr));
2662 }
2663 if (j != argc-1)
2664 cmdrepr = sdscatlen(cmdrepr," ",1);
2665 }
2666 cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
2667 cmdobj = createObject(REDIS_STRING,cmdrepr);
2668
2669 listRewind(monitors,&li);
2670 while((ln = listNext(&li))) {
2671 redisClient *monitor = ln->value;
2672 addReply(monitor,cmdobj);
2673 }
2674 decrRefCount(cmdobj);
2675}
2676
638e42ac 2677static void processInputBuffer(redisClient *c) {
ed9b544e 2678again:
4409877e 2679 /* Before to process the input buffer, make sure the client is not
2680 * waitig for a blocking operation such as BLPOP. Note that the first
2681 * iteration the client is never blocked, otherwise the processInputBuffer
2682 * would not be called at all, but after the execution of the first commands
2683 * in the input buffer the client may be blocked, and the "goto again"
2684 * will try to reiterate. The following line will make it return asap. */
92f8e882 2685 if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
ed9b544e 2686 if (c->bulklen == -1) {
2687 /* Read the first line of the query */
2688 char *p = strchr(c->querybuf,'\n');
2689 size_t querylen;
644fafa3 2690
ed9b544e 2691 if (p) {
2692 sds query, *argv;
2693 int argc, j;
e0a62c7f 2694
ed9b544e 2695 query = c->querybuf;
2696 c->querybuf = sdsempty();
2697 querylen = 1+(p-(query));
2698 if (sdslen(query) > querylen) {
2699 /* leave data after the first line of the query in the buffer */
2700 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
2701 }
2702 *p = '\0'; /* remove "\n" */
2703 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
2704 sdsupdatelen(query);
2705
2706 /* Now we can split the query in arguments */
ed9b544e 2707 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
93ea3759 2708 sdsfree(query);
2709
2710 if (c->argv) zfree(c->argv);
2711 c->argv = zmalloc(sizeof(robj*)*argc);
93ea3759 2712
2713 for (j = 0; j < argc; j++) {
ed9b544e 2714 if (sdslen(argv[j])) {
2715 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
2716 c->argc++;
2717 } else {
2718 sdsfree(argv[j]);
2719 }
2720 }
2721 zfree(argv);
7c49733c 2722 if (c->argc) {
2723 /* Execute the command. If the client is still valid
2724 * after processCommand() return and there is something
2725 * on the query buffer try to process the next command. */
2726 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2727 } else {
2728 /* Nothing to process, argc == 0. Just process the query
2729 * buffer if it's not empty or return to the caller */
2730 if (sdslen(c->querybuf)) goto again;
2731 }
ed9b544e 2732 return;
644fafa3 2733 } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
f870935d 2734 redisLog(REDIS_VERBOSE, "Client protocol error");
ed9b544e 2735 freeClient(c);
2736 return;
2737 }
2738 } else {
2739 /* Bulk read handling. Note that if we are at this point
2740 the client already sent a command terminated with a newline,
2741 we are reading the bulk data that is actually the last
2742 argument of the command. */
2743 int qbl = sdslen(c->querybuf);
2744
2745 if (c->bulklen <= qbl) {
2746 /* Copy everything but the final CRLF as final argument */
2747 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2748 c->argc++;
2749 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
638e42ac 2750 /* Process the command. If the client is still valid after
2751 * the processing and there is more data in the buffer
2752 * try to parse it. */
2753 if (processCommand(c) && sdslen(c->querybuf)) goto again;
ed9b544e 2754 return;
2755 }
2756 }
2757}
2758
638e42ac 2759static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2760 redisClient *c = (redisClient*) privdata;
2761 char buf[REDIS_IOBUF_LEN];
2762 int nread;
2763 REDIS_NOTUSED(el);
2764 REDIS_NOTUSED(mask);
2765
2766 nread = read(fd, buf, REDIS_IOBUF_LEN);
2767 if (nread == -1) {
2768 if (errno == EAGAIN) {
2769 nread = 0;
2770 } else {
f870935d 2771 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
638e42ac 2772 freeClient(c);
2773 return;
2774 }
2775 } else if (nread == 0) {
f870935d 2776 redisLog(REDIS_VERBOSE, "Client closed connection");
638e42ac 2777 freeClient(c);
2778 return;
2779 }
2780 if (nread) {
2781 c->querybuf = sdscatlen(c->querybuf, buf, nread);
2782 c->lastinteraction = time(NULL);
2783 } else {
2784 return;
2785 }
168ac5c6 2786 processInputBuffer(c);
638e42ac 2787}
2788
ed9b544e 2789static int selectDb(redisClient *c, int id) {
2790 if (id < 0 || id >= server.dbnum)
2791 return REDIS_ERR;
3305306f 2792 c->db = &server.db[id];
ed9b544e 2793 return REDIS_OK;
2794}
2795
40d224a9 2796static void *dupClientReplyValue(void *o) {
2797 incrRefCount((robj*)o);
12d090d2 2798 return o;
40d224a9 2799}
2800
ffc6b7f8 2801static int listMatchObjects(void *a, void *b) {
bf028098 2802 return equalStringObjects(a,b);
ffc6b7f8 2803}
2804
ed9b544e 2805static redisClient *createClient(int fd) {
2806 redisClient *c = zmalloc(sizeof(*c));
2807
2808 anetNonBlock(NULL,fd);
2809 anetTcpNoDelay(NULL,fd);
2810 if (!c) return NULL;
2811 selectDb(c,0);
2812 c->fd = fd;
2813 c->querybuf = sdsempty();
2814 c->argc = 0;
93ea3759 2815 c->argv = NULL;
ed9b544e 2816 c->bulklen = -1;
e8a74421 2817 c->multibulk = 0;
2818 c->mbargc = 0;
2819 c->mbargv = NULL;
ed9b544e 2820 c->sentlen = 0;
2821 c->flags = 0;
2822 c->lastinteraction = time(NULL);
abcb223e 2823 c->authenticated = 0;
40d224a9 2824 c->replstate = REDIS_REPL_NONE;
6b47e12e 2825 c->reply = listCreate();
ed9b544e 2826 listSetFreeMethod(c->reply,decrRefCount);
40d224a9 2827 listSetDupMethod(c->reply,dupClientReplyValue);
37ab76c9 2828 c->blocking_keys = NULL;
2829 c->blocking_keys_num = 0;
92f8e882 2830 c->io_keys = listCreate();
87c68815 2831 c->watched_keys = listCreate();
92f8e882 2832 listSetFreeMethod(c->io_keys,decrRefCount);
ffc6b7f8 2833 c->pubsub_channels = dictCreate(&setDictType,NULL);
2834 c->pubsub_patterns = listCreate();
2835 listSetFreeMethod(c->pubsub_patterns,decrRefCount);
2836 listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
ed9b544e 2837 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
266373b2 2838 readQueryFromClient, c) == AE_ERR) {
ed9b544e 2839 freeClient(c);
2840 return NULL;
2841 }
6b47e12e 2842 listAddNodeTail(server.clients,c);
6e469882 2843 initClientMultiState(c);
ed9b544e 2844 return c;
2845}
2846
2847static void addReply(redisClient *c, robj *obj) {
2848 if (listLength(c->reply) == 0 &&
6208b3a7 2849 (c->replstate == REDIS_REPL_NONE ||
2850 c->replstate == REDIS_REPL_ONLINE) &&
ed9b544e 2851 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
266373b2 2852 sendReplyToClient, c) == AE_ERR) return;
e3cadb8a 2853
2854 if (server.vm_enabled && obj->storage != REDIS_VM_MEMORY) {
2855 obj = dupStringObject(obj);
2856 obj->refcount = 0; /* getDecodedObject() will increment the refcount */
2857 }
9d65a1bb 2858 listAddNodeTail(c->reply,getDecodedObject(obj));
ed9b544e 2859}
2860
2861static void addReplySds(redisClient *c, sds s) {
2862 robj *o = createObject(REDIS_STRING,s);
2863 addReply(c,o);
2864 decrRefCount(o);
2865}
2866
e2665397 2867static void addReplyDouble(redisClient *c, double d) {
2868 char buf[128];
2869
2870 snprintf(buf,sizeof(buf),"%.17g",d);
682ac724 2871 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
83c6a618 2872 (unsigned long) strlen(buf),buf));
e2665397 2873}
2874
aa7c2934
PN
2875static void addReplyLongLong(redisClient *c, long long ll) {
2876 char buf[128];
2877 size_t len;
2878
2879 if (ll == 0) {
2880 addReply(c,shared.czero);
2881 return;
2882 } else if (ll == 1) {
2883 addReply(c,shared.cone);
2884 return;
2885 }
482b672d 2886 buf[0] = ':';
2887 len = ll2string(buf+1,sizeof(buf)-1,ll);
2888 buf[len+1] = '\r';
2889 buf[len+2] = '\n';
2890 addReplySds(c,sdsnewlen(buf,len+3));
aa7c2934
PN
2891}
2892
92b27fe9 2893static void addReplyUlong(redisClient *c, unsigned long ul) {
2894 char buf[128];
2895 size_t len;
2896
dd88747b 2897 if (ul == 0) {
2898 addReply(c,shared.czero);
2899 return;
2900 } else if (ul == 1) {
2901 addReply(c,shared.cone);
2902 return;
2903 }
92b27fe9 2904 len = snprintf(buf,sizeof(buf),":%lu\r\n",ul);
2905 addReplySds(c,sdsnewlen(buf,len));
2906}
2907
942a3961 2908static void addReplyBulkLen(redisClient *c, robj *obj) {
482b672d 2909 size_t len, intlen;
2910 char buf[128];
942a3961 2911
2912 if (obj->encoding == REDIS_ENCODING_RAW) {
2913 len = sdslen(obj->ptr);
2914 } else {
2915 long n = (long)obj->ptr;
2916
e054afda 2917 /* Compute how many bytes will take this integer as a radix 10 string */
942a3961 2918 len = 1;
2919 if (n < 0) {
2920 len++;
2921 n = -n;
2922 }
2923 while((n = n/10) != 0) {
2924 len++;
2925 }
2926 }
482b672d 2927 buf[0] = '$';
2928 intlen = ll2string(buf+1,sizeof(buf)-1,(long long)len);
2929 buf[intlen+1] = '\r';
2930 buf[intlen+2] = '\n';
2931 addReplySds(c,sdsnewlen(buf,intlen+3));
942a3961 2932}
2933
dd88747b 2934static void addReplyBulk(redisClient *c, robj *obj) {
2935 addReplyBulkLen(c,obj);
2936 addReply(c,obj);
2937 addReply(c,shared.crlf);
2938}
2939
09241813 2940static void addReplyBulkSds(redisClient *c, sds s) {
2941 robj *o = createStringObject(s, sdslen(s));
2942 addReplyBulk(c,o);
2943 decrRefCount(o);
2944}
2945
500ece7c 2946/* In the CONFIG command we need to add vanilla C string as bulk replies */
2947static void addReplyBulkCString(redisClient *c, char *s) {
2948 if (s == NULL) {
2949 addReply(c,shared.nullbulk);
2950 } else {
2951 robj *o = createStringObject(s,strlen(s));
2952 addReplyBulk(c,o);
2953 decrRefCount(o);
2954 }
2955}
2956
ed9b544e 2957static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2958 int cport, cfd;
2959 char cip[128];
285add55 2960 redisClient *c;
ed9b544e 2961 REDIS_NOTUSED(el);
2962 REDIS_NOTUSED(mask);
2963 REDIS_NOTUSED(privdata);
2964
2965 cfd = anetAccept(server.neterr, fd, cip, &cport);
2966 if (cfd == AE_ERR) {
f870935d 2967 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
ed9b544e 2968 return;
2969 }
f870935d 2970 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
285add55 2971 if ((c = createClient(cfd)) == NULL) {
ed9b544e 2972 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2973 close(cfd); /* May be already closed, just ingore errors */
2974 return;
2975 }
285add55 2976 /* If maxclient directive is set and this is one client more... close the
2977 * connection. Note that we create the client instead to check before
2978 * for this condition, since now the socket is already set in nonblocking
2979 * mode and we can send an error for free using the Kernel I/O */
2980 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2981 char *err = "-ERR max number of clients reached\r\n";
2982
2983 /* That's a best effort error message, don't check write errors */
fee803ba 2984 if (write(c->fd,err,strlen(err)) == -1) {
2985 /* Nothing to do, Just to avoid the warning... */
2986 }
285add55 2987 freeClient(c);
2988 return;
2989 }
ed9b544e 2990 server.stat_numconnections++;
2991}
2992
2993/* ======================= Redis objects implementation ===================== */
2994
2995static robj *createObject(int type, void *ptr) {
2996 robj *o;
2997
a5819310 2998 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
ed9b544e 2999 if (listLength(server.objfreelist)) {
3000 listNode *head = listFirst(server.objfreelist);
3001 o = listNodeValue(head);
3002 listDelNode(server.objfreelist,head);
a5819310 3003 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
ed9b544e 3004 } else {
560db612 3005 if (server.vm_enabled)
a5819310 3006 pthread_mutex_unlock(&server.obj_freelist_mutex);
560db612 3007 o = zmalloc(sizeof(*o));
ed9b544e 3008 }
ed9b544e 3009 o->type = type;
942a3961 3010 o->encoding = REDIS_ENCODING_RAW;
ed9b544e 3011 o->ptr = ptr;
3012 o->refcount = 1;
3a66edc7 3013 if (server.vm_enabled) {
1064ef87 3014 /* Note that this code may run in the context of an I/O thread
560db612 3015 * and accessing server.lruclock in theory is an error
1064ef87 3016 * (no locks). But in practice this is safe, and even if we read
560db612 3017 * garbage Redis will not fail. */
3018 o->lru = server.lruclock;
3a66edc7 3019 o->storage = REDIS_VM_MEMORY;
3020 }
ed9b544e 3021 return o;
3022}
3023
3024static robj *createStringObject(char *ptr, size_t len) {
3025 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
3026}
3027
3f973463
PN
3028static robj *createStringObjectFromLongLong(long long value) {
3029 robj *o;
3030 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3031 incrRefCount(shared.integers[value]);
3032 o = shared.integers[value];
3033 } else {
3f973463 3034 if (value >= LONG_MIN && value <= LONG_MAX) {
10dea8dc 3035 o = createObject(REDIS_STRING, NULL);
3f973463
PN
3036 o->encoding = REDIS_ENCODING_INT;
3037 o->ptr = (void*)((long)value);
3038 } else {
ee14da56 3039 o = createObject(REDIS_STRING,sdsfromlonglong(value));
3f973463
PN
3040 }
3041 }
3042 return o;
3043}
3044
4ef8de8a 3045static robj *dupStringObject(robj *o) {
b9bc0eef 3046 assert(o->encoding == REDIS_ENCODING_RAW);
4ef8de8a 3047 return createStringObject(o->ptr,sdslen(o->ptr));
3048}
3049
ed9b544e 3050static robj *createListObject(void) {
3051 list *l = listCreate();
1cd92e7f 3052 robj *o = createObject(REDIS_LIST,l);
ed9b544e 3053 listSetFreeMethod(l,decrRefCount);
1cd92e7f
PN
3054 o->encoding = REDIS_ENCODING_LIST;
3055 return o;
3056}
3057
3058static robj *createZiplistObject(void) {
3059 unsigned char *zl = ziplistNew();
3060 robj *o = createObject(REDIS_LIST,zl);
3061 o->encoding = REDIS_ENCODING_ZIPLIST;
3062 return o;
ed9b544e 3063}
3064
3065static robj *createSetObject(void) {
3066 dict *d = dictCreate(&setDictType,NULL);
ed9b544e 3067 return createObject(REDIS_SET,d);
3068}
3069
5234952b 3070static robj *createHashObject(void) {
3071 /* All the Hashes start as zipmaps. Will be automatically converted
3072 * into hash tables if there are enough elements or big elements
3073 * inside. */
3074 unsigned char *zm = zipmapNew();
3075 robj *o = createObject(REDIS_HASH,zm);
3076 o->encoding = REDIS_ENCODING_ZIPMAP;
3077 return o;
3078}
3079
1812e024 3080static robj *createZsetObject(void) {
6b47e12e 3081 zset *zs = zmalloc(sizeof(*zs));
3082
3083 zs->dict = dictCreate(&zsetDictType,NULL);
3084 zs->zsl = zslCreate();
3085 return createObject(REDIS_ZSET,zs);
1812e024 3086}
3087
ed9b544e 3088static void freeStringObject(robj *o) {
942a3961 3089 if (o->encoding == REDIS_ENCODING_RAW) {
3090 sdsfree(o->ptr);
3091 }
ed9b544e 3092}
3093
3094static void freeListObject(robj *o) {
c7d9d662
PN
3095 switch (o->encoding) {
3096 case REDIS_ENCODING_LIST:
3097 listRelease((list*) o->ptr);
3098 break;
3099 case REDIS_ENCODING_ZIPLIST:
3100 zfree(o->ptr);
3101 break;
3102 default:
3103 redisPanic("Unknown list encoding type");
3104 }
ed9b544e 3105}
3106
3107static void freeSetObject(robj *o) {
3108 dictRelease((dict*) o->ptr);
3109}
3110
fd8ccf44 3111static void freeZsetObject(robj *o) {
3112 zset *zs = o->ptr;
3113
3114 dictRelease(zs->dict);
3115 zslFree(zs->zsl);
3116 zfree(zs);
3117}
3118
ed9b544e 3119static void freeHashObject(robj *o) {
cbba7dd7 3120 switch (o->encoding) {
3121 case REDIS_ENCODING_HT:
3122 dictRelease((dict*) o->ptr);
3123 break;
3124 case REDIS_ENCODING_ZIPMAP:
3125 zfree(o->ptr);
3126 break;
3127 default:
f83c6cb5 3128 redisPanic("Unknown hash encoding type");
cbba7dd7 3129 break;
3130 }
ed9b544e 3131}
3132
3133static void incrRefCount(robj *o) {
3134 o->refcount++;
3135}
3136
3137static void decrRefCount(void *obj) {
3138 robj *o = obj;
94754ccc 3139
560db612 3140 /* Object is a swapped out value, or in the process of being loaded. */
996cb5f7 3141 if (server.vm_enabled &&
3142 (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
3143 {
560db612 3144 vmpointer *vp = obj;
3145 if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(o);
3146 vmMarkPagesFree(vp->page,vp->usedpages);
7d98e08c 3147 server.vm_stats_swapped_objects--;
560db612 3148 zfree(vp);
a35ddf12 3149 return;
3150 }
560db612 3151
3152 if (o->refcount <= 0) redisPanic("decrRefCount against refcount <= 0");
e4ed181d 3153 /* Object is in memory, or in the process of being swapped out.
3154 *
3155 * If the object is being swapped out, abort the operation on
3156 * decrRefCount even if the refcount does not drop to 0: the object
3157 * is referenced at least two times, as value of the key AND as
3158 * job->val in the iojob. So if we don't invalidate the iojob, when it is
3159 * done but the relevant key was removed in the meantime, the
3160 * complete jobs handler will not find the key about the job and the
3161 * assert will fail. */
3162 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
3163 vmCancelThreadedIOJob(o);
ed9b544e 3164 if (--(o->refcount) == 0) {
3165 switch(o->type) {
3166 case REDIS_STRING: freeStringObject(o); break;
3167 case REDIS_LIST: freeListObject(o); break;
3168 case REDIS_SET: freeSetObject(o); break;
fd8ccf44 3169 case REDIS_ZSET: freeZsetObject(o); break;
ed9b544e 3170 case REDIS_HASH: freeHashObject(o); break;
f83c6cb5 3171 default: redisPanic("Unknown object type"); break;
ed9b544e 3172 }
a5819310 3173 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
ed9b544e 3174 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3175 !listAddNodeHead(server.objfreelist,o))
3176 zfree(o);
a5819310 3177 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
ed9b544e 3178 }
3179}
3180
92b27fe9 3181static int checkType(redisClient *c, robj *o, int type) {
3182 if (o->type != type) {
3183 addReply(c,shared.wrongtypeerr);
3184 return 1;
3185 }
3186 return 0;
3187}
3188
724a51b1 3189/* Check if the nul-terminated string 's' can be represented by a long
3190 * (that is, is a number that fits into long without any other space or
3191 * character before or after the digits).
3192 *
3193 * If so, the function returns REDIS_OK and *longval is set to the value
3194 * of the number. Otherwise REDIS_ERR is returned */
f69f2cba 3195static int isStringRepresentableAsLong(sds s, long *longval) {
724a51b1 3196 char buf[32], *endptr;
3197 long value;
3198 int slen;
e0a62c7f 3199
724a51b1 3200 value = strtol(s, &endptr, 10);
3201 if (endptr[0] != '\0') return REDIS_ERR;
ee14da56 3202 slen = ll2string(buf,32,value);
724a51b1 3203
3204 /* If the number converted back into a string is not identical
3205 * then it's not possible to encode the string as integer */
f69f2cba 3206 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
724a51b1 3207 if (longval) *longval = value;
3208 return REDIS_OK;
3209}
3210
942a3961 3211/* Try to encode a string object in order to save space */
05df7621 3212static robj *tryObjectEncoding(robj *o) {
942a3961 3213 long value;
942a3961 3214 sds s = o->ptr;
3305306f 3215
942a3961 3216 if (o->encoding != REDIS_ENCODING_RAW)
05df7621 3217 return o; /* Already encoded */
3305306f 3218
05df7621 3219 /* It's not safe to encode shared objects: shared objects can be shared
942a3961 3220 * everywhere in the "object space" of Redis. Encoded objects can only
3221 * appear as "values" (and not, for instance, as keys) */
05df7621 3222 if (o->refcount > 1) return o;
3305306f 3223
942a3961 3224 /* Currently we try to encode only strings */
dfc5e96c 3225 redisAssert(o->type == REDIS_STRING);
94754ccc 3226
724a51b1 3227 /* Check if we can represent this string as a long integer */
05df7621 3228 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return o;
942a3961 3229
3230 /* Ok, this object can be encoded */
05df7621 3231 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3232 decrRefCount(o);
3233 incrRefCount(shared.integers[value]);
3234 return shared.integers[value];
3235 } else {
3236 o->encoding = REDIS_ENCODING_INT;
3237 sdsfree(o->ptr);
3238 o->ptr = (void*) value;
3239 return o;
3240 }
942a3961 3241}
3242
9d65a1bb 3243/* Get a decoded version of an encoded object (returned as a new object).
3244 * If the object is already raw-encoded just increment the ref count. */
3245static robj *getDecodedObject(robj *o) {
942a3961 3246 robj *dec;
e0a62c7f 3247
9d65a1bb 3248 if (o->encoding == REDIS_ENCODING_RAW) {
3249 incrRefCount(o);
3250 return o;
3251 }
942a3961 3252 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
3253 char buf[32];
3254
ee14da56 3255 ll2string(buf,32,(long)o->ptr);
942a3961 3256 dec = createStringObject(buf,strlen(buf));
3257 return dec;
3258 } else {
08ee9b57 3259 redisPanic("Unknown encoding type");
942a3961 3260 }
3305306f 3261}
3262
d7f43c08 3263/* Compare two string objects via strcmp() or alike.
3264 * Note that the objects may be integer-encoded. In such a case we
ee14da56 3265 * use ll2string() to get a string representation of the numbers on the stack
1fd9bc8a 3266 * and compare the strings, it's much faster than calling getDecodedObject().
3267 *
3268 * Important note: if objects are not integer encoded, but binary-safe strings,
3269 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3270 * binary safe. */
724a51b1 3271static int compareStringObjects(robj *a, robj *b) {
dfc5e96c 3272 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
d7f43c08 3273 char bufa[128], bufb[128], *astr, *bstr;
3274 int bothsds = 1;
724a51b1 3275
e197b441 3276 if (a == b) return 0;
d7f43c08 3277 if (a->encoding != REDIS_ENCODING_RAW) {
ee14da56 3278 ll2string(bufa,sizeof(bufa),(long) a->ptr);
d7f43c08 3279 astr = bufa;
3280 bothsds = 0;
724a51b1 3281 } else {
d7f43c08 3282 astr = a->ptr;
724a51b1 3283 }
d7f43c08 3284 if (b->encoding != REDIS_ENCODING_RAW) {
ee14da56 3285 ll2string(bufb,sizeof(bufb),(long) b->ptr);
d7f43c08 3286 bstr = bufb;
3287 bothsds = 0;
3288 } else {
3289 bstr = b->ptr;
3290 }
3291 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
724a51b1 3292}
3293
bf028098 3294/* Equal string objects return 1 if the two objects are the same from the
3295 * point of view of a string comparison, otherwise 0 is returned. Note that
3296 * this function is faster then checking for (compareStringObject(a,b) == 0)
3297 * because it can perform some more optimization. */
3298static int equalStringObjects(robj *a, robj *b) {
3299 if (a->encoding != REDIS_ENCODING_RAW && b->encoding != REDIS_ENCODING_RAW){
3300 return a->ptr == b->ptr;
3301 } else {
3302 return compareStringObjects(a,b) == 0;
3303 }
3304}
3305
0ea663ea 3306static size_t stringObjectLen(robj *o) {
dfc5e96c 3307 redisAssert(o->type == REDIS_STRING);
0ea663ea 3308 if (o->encoding == REDIS_ENCODING_RAW) {
3309 return sdslen(o->ptr);
3310 } else {
3311 char buf[32];
3312
ee14da56 3313 return ll2string(buf,32,(long)o->ptr);
0ea663ea 3314 }
3315}
3316
bd79a6bd
PN
3317static int getDoubleFromObject(robj *o, double *target) {
3318 double value;
682c73e8 3319 char *eptr;
bbe025e0 3320
bd79a6bd
PN
3321 if (o == NULL) {
3322 value = 0;
3323 } else {
3324 redisAssert(o->type == REDIS_STRING);
3325 if (o->encoding == REDIS_ENCODING_RAW) {
3326 value = strtod(o->ptr, &eptr);
682c73e8 3327 if (eptr[0] != '\0') return REDIS_ERR;
bd79a6bd
PN
3328 } else if (o->encoding == REDIS_ENCODING_INT) {
3329 value = (long)o->ptr;
3330 } else {
946342c1 3331 redisPanic("Unknown string encoding");
bd79a6bd
PN
3332 }
3333 }
3334
bd79a6bd
PN
3335 *target = value;
3336 return REDIS_OK;
3337}
bbe025e0 3338
bd79a6bd
PN
3339static int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg) {
3340 double value;
3341 if (getDoubleFromObject(o, &value) != REDIS_OK) {
3342 if (msg != NULL) {
3343 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3344 } else {
3345 addReplySds(c, sdsnew("-ERR value is not a double\r\n"));
3346 }
bbe025e0
AM
3347 return REDIS_ERR;
3348 }
3349
bd79a6bd 3350 *target = value;
bbe025e0
AM
3351 return REDIS_OK;
3352}
3353
bd79a6bd
PN
3354static int getLongLongFromObject(robj *o, long long *target) {
3355 long long value;
682c73e8 3356 char *eptr;
bbe025e0 3357
bd79a6bd
PN
3358 if (o == NULL) {
3359 value = 0;
3360 } else {
3361 redisAssert(o->type == REDIS_STRING);
3362 if (o->encoding == REDIS_ENCODING_RAW) {
3363 value = strtoll(o->ptr, &eptr, 10);
682c73e8 3364 if (eptr[0] != '\0') return REDIS_ERR;
bd79a6bd
PN
3365 } else if (o->encoding == REDIS_ENCODING_INT) {
3366 value = (long)o->ptr;
3367 } else {
946342c1 3368 redisPanic("Unknown string encoding");
bd79a6bd
PN
3369 }
3370 }
3371
bd79a6bd
PN
3372 *target = value;
3373 return REDIS_OK;
3374}
bbe025e0 3375
bd79a6bd
PN
3376static int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg) {
3377 long long value;
3378 if (getLongLongFromObject(o, &value) != REDIS_OK) {
3379 if (msg != NULL) {
3380 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3381 } else {
3382 addReplySds(c, sdsnew("-ERR value is not an integer\r\n"));
3383 }
bbe025e0
AM
3384 return REDIS_ERR;
3385 }
3386
bd79a6bd 3387 *target = value;
bbe025e0
AM
3388 return REDIS_OK;
3389}
3390
bd79a6bd
PN
3391static int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg) {
3392 long long value;
bbe025e0 3393
bd79a6bd
PN
3394 if (getLongLongFromObjectOrReply(c, o, &value, msg) != REDIS_OK) return REDIS_ERR;
3395 if (value < LONG_MIN || value > LONG_MAX) {
3396 if (msg != NULL) {
3397 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3398 } else {
3399 addReplySds(c, sdsnew("-ERR value is out of range\r\n"));
3400 }
bbe025e0
AM
3401 return REDIS_ERR;
3402 }
3403
bd79a6bd 3404 *target = value;
bbe025e0
AM
3405 return REDIS_OK;
3406}
3407
612e4de8 3408/* =========================== Keyspace access API ========================== */
3409
3410static robj *lookupKey(redisDb *db, robj *key) {
09241813 3411 dictEntry *de = dictFind(db->dict,key->ptr);
612e4de8 3412 if (de) {
612e4de8 3413 robj *val = dictGetEntryVal(de);
3414
3415 if (server.vm_enabled) {
3416 if (val->storage == REDIS_VM_MEMORY ||
3417 val->storage == REDIS_VM_SWAPPING)
3418 {
3419 /* If we were swapping the object out, cancel the operation */
3420 if (val->storage == REDIS_VM_SWAPPING)
3421 vmCancelThreadedIOJob(val);
09241813 3422 /* Update the access time for the aging algorithm. */
612e4de8 3423 val->lru = server.lruclock;
3424 } else {
3425 int notify = (val->storage == REDIS_VM_LOADING);
3426
3427 /* Our value was swapped on disk. Bring it at home. */
3428 redisAssert(val->type == REDIS_VMPOINTER);
3429 val = vmLoadObject(val);
3430 dictGetEntryVal(de) = val;
3431
3432 /* Clients blocked by the VM subsystem may be waiting for
3433 * this key... */
3434 if (notify) handleClientsBlockedOnSwappedKey(db,key);
3435 }
3436 }
3437 return val;
3438 } else {
3439 return NULL;
3440 }
3441}
3442
3443static robj *lookupKeyRead(redisDb *db, robj *key) {
3444 expireIfNeeded(db,key);
3445 return lookupKey(db,key);
3446}
3447
3448static robj *lookupKeyWrite(redisDb *db, robj *key) {
3449 deleteIfVolatile(db,key);
3450 touchWatchedKey(db,key);
3451 return lookupKey(db,key);
3452}
3453
3454static robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
3455 robj *o = lookupKeyRead(c->db, key);
3456 if (!o) addReply(c,reply);
3457 return o;
3458}
3459
3460static robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
3461 robj *o = lookupKeyWrite(c->db, key);
3462 if (!o) addReply(c,reply);
3463 return o;
3464}
3465
09241813 3466/* Add the key to the DB. If the key already exists REDIS_ERR is returned,
3467 * otherwise REDIS_OK is returned, and the caller should increment the
3468 * refcount of 'val'. */
3469static int dbAdd(redisDb *db, robj *key, robj *val) {
3470 /* Perform a lookup before adding the key, as we need to copy the
3471 * key value. */
3472 if (dictFind(db->dict, key->ptr) != NULL) {
3473 return REDIS_ERR;
3474 } else {
3475 sds copy = sdsdup(key->ptr);
3476 dictAdd(db->dict, copy, val);
3477 return REDIS_OK;
3478 }
3479}
3480
3481/* If the key does not exist, this is just like dbAdd(). Otherwise
3482 * the value associated to the key is replaced with the new one.
3483 *
3484 * On update (key already existed) 0 is returned. Otherwise 1. */
3485static int dbReplace(redisDb *db, robj *key, robj *val) {
3486 if (dictFind(db->dict,key->ptr) == NULL) {
3487 sds copy = sdsdup(key->ptr);
3488 dictAdd(db->dict, copy, val);
3489 return 1;
3490 } else {
3491 dictReplace(db->dict, key->ptr, val);
3492 return 0;
3493 }
3494}
3495
3496static int dbExists(redisDb *db, robj *key) {
3497 return dictFind(db->dict,key->ptr) != NULL;
3498}
3499
3500/* Return a random key, in form of a Redis object.
3501 * If there are no keys, NULL is returned.
3502 *
3503 * The function makes sure to return keys not already expired. */
3504static robj *dbRandomKey(redisDb *db) {
3505 struct dictEntry *de;
3506
3507 while(1) {
3508 sds key;
3509 robj *keyobj;
3510
3511 de = dictGetRandomKey(db->dict);
3512 if (de == NULL) return NULL;
3513
3514 key = dictGetEntryKey(de);
3515 keyobj = createStringObject(key,sdslen(key));
3516 if (dictFind(db->expires,key)) {
3517 if (expireIfNeeded(db,keyobj)) {
3518 decrRefCount(keyobj);
3519 continue; /* search for another key. This expired. */
3520 }
3521 }
3522 return keyobj;
3523 }
3524}
3525
3526/* Delete a key, value, and associated expiration entry if any, from the DB */
3527static int dbDelete(redisDb *db, robj *key) {
612e4de8 3528 int retval;
3529
09241813 3530 if (dictSize(db->expires)) dictDelete(db->expires,key->ptr);
3531 retval = dictDelete(db->dict,key->ptr);
612e4de8 3532
3533 return retval == DICT_OK;
3534}
3535
06233c45 3536/*============================ RDB saving/loading =========================== */
ed9b544e 3537
f78fd11b 3538static int rdbSaveType(FILE *fp, unsigned char type) {
3539 if (fwrite(&type,1,1,fp) == 0) return -1;
3540 return 0;
3541}
3542
bb32ede5 3543static int rdbSaveTime(FILE *fp, time_t t) {
3544 int32_t t32 = (int32_t) t;
3545 if (fwrite(&t32,4,1,fp) == 0) return -1;
3546 return 0;
3547}
3548
e3566d4b 3549/* check rdbLoadLen() comments for more info */
f78fd11b 3550static int rdbSaveLen(FILE *fp, uint32_t len) {
3551 unsigned char buf[2];
3552
3553 if (len < (1<<6)) {
3554 /* Save a 6 bit len */
10c43610 3555 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
f78fd11b 3556 if (fwrite(buf,1,1,fp) == 0) return -1;
3557 } else if (len < (1<<14)) {
3558 /* Save a 14 bit len */
10c43610 3559 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
f78fd11b 3560 buf[1] = len&0xFF;
17be1a4a 3561 if (fwrite(buf,2,1,fp) == 0) return -1;
f78fd11b 3562 } else {
3563 /* Save a 32 bit len */
10c43610 3564 buf[0] = (REDIS_RDB_32BITLEN<<6);
f78fd11b 3565 if (fwrite(buf,1,1,fp) == 0) return -1;
3566 len = htonl(len);
3567 if (fwrite(&len,4,1,fp) == 0) return -1;
3568 }
3569 return 0;
3570}
3571
32a66513 3572/* Encode 'value' as an integer if possible (if integer will fit the
3573 * supported range). If the function sucessful encoded the integer
3574 * then the (up to 5 bytes) encoded representation is written in the
3575 * string pointed by 'enc' and the length is returned. Otherwise
3576 * 0 is returned. */
3577static int rdbEncodeInteger(long long value, unsigned char *enc) {
e3566d4b 3578 /* Finally check if it fits in our ranges */
3579 if (value >= -(1<<7) && value <= (1<<7)-1) {
3580 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
3581 enc[1] = value&0xFF;
3582 return 2;
3583 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
3584 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
3585 enc[1] = value&0xFF;
3586 enc[2] = (value>>8)&0xFF;
3587 return 3;
3588 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
3589 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
3590 enc[1] = value&0xFF;
3591 enc[2] = (value>>8)&0xFF;
3592 enc[3] = (value>>16)&0xFF;
3593 enc[4] = (value>>24)&0xFF;
3594 return 5;
3595 } else {
3596 return 0;
3597 }
3598}
3599
32a66513 3600/* String objects in the form "2391" "-100" without any space and with a
3601 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3602 * encoded as integers to save space */
3603static int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
3604 long long value;
3605 char *endptr, buf[32];
3606
3607 /* Check if it's possible to encode this value as a number */
3608 value = strtoll(s, &endptr, 10);
3609 if (endptr[0] != '\0') return 0;
3610 ll2string(buf,32,value);
3611
3612 /* If the number converted back into a string is not identical
3613 * then it's not possible to encode the string as integer */
3614 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
3615
3616 return rdbEncodeInteger(value,enc);
3617}
3618
b1befe6a 3619static int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
3620 size_t comprlen, outlen;
774e3047 3621 unsigned char byte;
3622 void *out;
3623
3624 /* We require at least four bytes compression for this to be worth it */
b1befe6a 3625 if (len <= 4) return 0;
3626 outlen = len-4;
3a2694c4 3627 if ((out = zmalloc(outlen+1)) == NULL) return 0;
b1befe6a 3628 comprlen = lzf_compress(s, len, out, outlen);
774e3047 3629 if (comprlen == 0) {
88e85998 3630 zfree(out);
774e3047 3631 return 0;
3632 }
3633 /* Data compressed! Let's save it on disk */
3634 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
3635 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
3636 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
b1befe6a 3637 if (rdbSaveLen(fp,len) == -1) goto writeerr;
774e3047 3638 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
88e85998 3639 zfree(out);
774e3047 3640 return comprlen;
3641
3642writeerr:
88e85998 3643 zfree(out);
774e3047 3644 return -1;
3645}
3646
e3566d4b 3647/* Save a string objet as [len][data] on disk. If the object is a string
3648 * representation of an integer value we try to safe it in a special form */
b1befe6a 3649static int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
e3566d4b 3650 int enclen;
10c43610 3651
774e3047 3652 /* Try integer encoding */
e3566d4b 3653 if (len <= 11) {
3654 unsigned char buf[5];
b1befe6a 3655 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
e3566d4b 3656 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3657 return 0;
3658 }
3659 }
774e3047 3660
3661 /* Try LZF compression - under 20 bytes it's unable to compress even
88e85998 3662 * aaaaaaaaaaaaaaaaaa so skip it */
121f70cf 3663 if (server.rdbcompression && len > 20) {
774e3047 3664 int retval;
3665
b1befe6a 3666 retval = rdbSaveLzfStringObject(fp,s,len);
774e3047 3667 if (retval == -1) return -1;
3668 if (retval > 0) return 0;
3669 /* retval == 0 means data can't be compressed, save the old way */
3670 }
3671
3672 /* Store verbatim */
10c43610 3673 if (rdbSaveLen(fp,len) == -1) return -1;
b1befe6a 3674 if (len && fwrite(s,len,1,fp) == 0) return -1;
10c43610 3675 return 0;
3676}
3677
2796f6da
PN
3678/* Save a long long value as either an encoded string or a string. */
3679static int rdbSaveLongLongAsStringObject(FILE *fp, long long value) {
3680 unsigned char buf[32];
3681 int enclen = rdbEncodeInteger(value,buf);
3682 if (enclen > 0) {
3683 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3684 } else {
3685 /* Encode as string */
3686 enclen = ll2string((char*)buf,32,value);
3687 redisAssert(enclen < 32);
3688 if (rdbSaveLen(fp,enclen) == -1) return -1;
3689 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3690 }
3691 return 0;
3692}
3693
942a3961 3694/* Like rdbSaveStringObjectRaw() but handle encoded objects */
3695static int rdbSaveStringObject(FILE *fp, robj *obj) {
32a66513 3696 /* Avoid to decode the object, then encode it again, if the
3697 * object is alrady integer encoded. */
3698 if (obj->encoding == REDIS_ENCODING_INT) {
2796f6da 3699 return rdbSaveLongLongAsStringObject(fp,(long)obj->ptr);
996cb5f7 3700 } else {
2796f6da
PN
3701 redisAssert(obj->encoding == REDIS_ENCODING_RAW);
3702 return rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
996cb5f7 3703 }
942a3961 3704}
3705
a7866db6 3706/* Save a double value. Doubles are saved as strings prefixed by an unsigned
3707 * 8 bit integer specifing the length of the representation.
3708 * This 8 bit integer has special values in order to specify the following
3709 * conditions:
3710 * 253: not a number
3711 * 254: + inf
3712 * 255: - inf
3713 */
3714static int rdbSaveDoubleValue(FILE *fp, double val) {
3715 unsigned char buf[128];
3716 int len;
3717
3718 if (isnan(val)) {
3719 buf[0] = 253;
3720 len = 1;
3721 } else if (!isfinite(val)) {
3722 len = 1;
3723 buf[0] = (val < 0) ? 255 : 254;
3724 } else {
88e8d89f 3725#if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
fe244589 3726 /* Check if the float is in a safe range to be casted into a
3727 * long long. We are assuming that long long is 64 bit here.
3728 * Also we are assuming that there are no implementations around where
3729 * double has precision < 52 bit.
3730 *
3731 * Under this assumptions we test if a double is inside an interval
3732 * where casting to long long is safe. Then using two castings we
3733 * make sure the decimal part is zero. If all this is true we use
3734 * integer printing function that is much faster. */
fb82e75c 3735 double min = -4503599627370495; /* (2^52)-1 */
3736 double max = 4503599627370496; /* -(2^52) */
fe244589 3737 if (val > min && val < max && val == ((double)((long long)val)))
8c096b16 3738 ll2string((char*)buf+1,sizeof(buf),(long long)val);
3739 else
88e8d89f 3740#endif
8c096b16 3741 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
6c446631 3742 buf[0] = strlen((char*)buf+1);
a7866db6 3743 len = buf[0]+1;
3744 }
3745 if (fwrite(buf,len,1,fp) == 0) return -1;
3746 return 0;
3747}
3748
06233c45 3749/* Save a Redis object. */
3750static int rdbSaveObject(FILE *fp, robj *o) {
3751 if (o->type == REDIS_STRING) {
3752 /* Save a string value */
3753 if (rdbSaveStringObject(fp,o) == -1) return -1;
3754 } else if (o->type == REDIS_LIST) {
3755 /* Save a list value */
23f96494
PN
3756 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
3757 unsigned char *p;
3758 unsigned char *vstr;
3759 unsigned int vlen;
3760 long long vlong;
3761
3762 if (rdbSaveLen(fp,ziplistLen(o->ptr)) == -1) return -1;
3763 p = ziplistIndex(o->ptr,0);
3764 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
3765 if (vstr) {
3766 if (rdbSaveRawString(fp,vstr,vlen) == -1)
3767 return -1;
3768 } else {
3769 if (rdbSaveLongLongAsStringObject(fp,vlong) == -1)
3770 return -1;
3771 }
3772 p = ziplistNext(o->ptr,p);
3773 }
3774 } else if (o->encoding == REDIS_ENCODING_LIST) {
3775 list *list = o->ptr;
3776 listIter li;
3777 listNode *ln;
3778
3779 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
3780 listRewind(list,&li);
3781 while((ln = listNext(&li))) {
3782 robj *eleobj = listNodeValue(ln);
3783 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3784 }
3785 } else {
3786 redisPanic("Unknown list encoding");
06233c45 3787 }
3788 } else if (o->type == REDIS_SET) {
3789 /* Save a set value */
3790 dict *set = o->ptr;
3791 dictIterator *di = dictGetIterator(set);
3792 dictEntry *de;
3793
3794 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
3795 while((de = dictNext(di)) != NULL) {
3796 robj *eleobj = dictGetEntryKey(de);
3797
3798 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3799 }
3800 dictReleaseIterator(di);
3801 } else if (o->type == REDIS_ZSET) {
3802 /* Save a set value */
3803 zset *zs = o->ptr;
3804 dictIterator *di = dictGetIterator(zs->dict);
3805 dictEntry *de;
3806
3807 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
3808 while((de = dictNext(di)) != NULL) {
3809 robj *eleobj = dictGetEntryKey(de);
3810 double *score = dictGetEntryVal(de);
3811
3812 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3813 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
3814 }
3815 dictReleaseIterator(di);
b1befe6a 3816 } else if (o->type == REDIS_HASH) {
3817 /* Save a hash value */
3818 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3819 unsigned char *p = zipmapRewind(o->ptr);
3820 unsigned int count = zipmapLen(o->ptr);
3821 unsigned char *key, *val;
3822 unsigned int klen, vlen;
3823
3824 if (rdbSaveLen(fp,count) == -1) return -1;
3825 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
3826 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
3827 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
3828 }
3829 } else {
3830 dictIterator *di = dictGetIterator(o->ptr);
3831 dictEntry *de;
3832
3833 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
3834 while((de = dictNext(di)) != NULL) {
3835 robj *key = dictGetEntryKey(de);
3836 robj *val = dictGetEntryVal(de);
3837
3838 if (rdbSaveStringObject(fp,key) == -1) return -1;
3839 if (rdbSaveStringObject(fp,val) == -1) return -1;
3840 }
3841 dictReleaseIterator(di);
3842 }
06233c45 3843 } else {
f83c6cb5 3844 redisPanic("Unknown object type");
06233c45 3845 }
3846 return 0;
3847}
3848
3849/* Return the length the object will have on disk if saved with
3850 * the rdbSaveObject() function. Currently we use a trick to get
3851 * this length with very little changes to the code. In the future
3852 * we could switch to a faster solution. */
b9bc0eef 3853static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
3854 if (fp == NULL) fp = server.devnull;
06233c45 3855 rewind(fp);
3856 assert(rdbSaveObject(fp,o) != 1);
3857 return ftello(fp);
3858}
3859
06224fec 3860/* Return the number of pages required to save this object in the swap file */
b9bc0eef 3861static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
3862 off_t bytes = rdbSavedObjectLen(o,fp);
e0a62c7f 3863
06224fec 3864 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
3865}
3866
ed9b544e 3867/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
f78fd11b 3868static int rdbSave(char *filename) {
ed9b544e 3869 dictIterator *di = NULL;
3870 dictEntry *de;
ed9b544e 3871 FILE *fp;
3872 char tmpfile[256];
3873 int j;
bb32ede5 3874 time_t now = time(NULL);
ed9b544e 3875
2316bb3b 3876 /* Wait for I/O therads to terminate, just in case this is a
3877 * foreground-saving, to avoid seeking the swap file descriptor at the
3878 * same time. */
3879 if (server.vm_enabled)
3880 waitEmptyIOJobsQueue();
3881
a3b21203 3882 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
ed9b544e 3883 fp = fopen(tmpfile,"w");
3884 if (!fp) {
3885 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
3886 return REDIS_ERR;
3887 }
f78fd11b 3888 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
ed9b544e 3889 for (j = 0; j < server.dbnum; j++) {
bb32ede5 3890 redisDb *db = server.db+j;
3891 dict *d = db->dict;
3305306f 3892 if (dictSize(d) == 0) continue;
ed9b544e 3893 di = dictGetIterator(d);
3894 if (!di) {
3895 fclose(fp);
3896 return REDIS_ERR;
3897 }
3898
3899 /* Write the SELECT DB opcode */
f78fd11b 3900 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
3901 if (rdbSaveLen(fp,j) == -1) goto werr;
ed9b544e 3902
3903 /* Iterate this DB writing every entry */
3904 while((de = dictNext(di)) != NULL) {
09241813 3905 sds keystr = dictGetEntryKey(de);
3906 robj key, *o = dictGetEntryVal(de);
3907 time_t expiretime;
3908
3909 initStaticStringObject(key,keystr);
3910 expiretime = getExpire(db,&key);
bb32ede5 3911
3912 /* Save the expire time */
3913 if (expiretime != -1) {
3914 /* If this key is already expired skip it */
3915 if (expiretime < now) continue;
3916 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
3917 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
3918 }
7e69548d 3919 /* Save the key and associated value. This requires special
3920 * handling if the value is swapped out. */
560db612 3921 if (!server.vm_enabled || o->storage == REDIS_VM_MEMORY ||
3922 o->storage == REDIS_VM_SWAPPING) {
7e69548d 3923 /* Save type, key, value */
3924 if (rdbSaveType(fp,o->type) == -1) goto werr;
09241813 3925 if (rdbSaveStringObject(fp,&key) == -1) goto werr;
7e69548d 3926 if (rdbSaveObject(fp,o) == -1) goto werr;
3927 } else {
996cb5f7 3928 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
b9bc0eef 3929 robj *po;
7e69548d 3930 /* Get a preview of the object in memory */
560db612 3931 po = vmPreviewObject(o);
7e69548d 3932 /* Save type, key, value */
560db612 3933 if (rdbSaveType(fp,po->type) == -1) goto werr;
09241813 3934 if (rdbSaveStringObject(fp,&key) == -1) goto werr;
7e69548d 3935 if (rdbSaveObject(fp,po) == -1) goto werr;
3936 /* Remove the loaded object from memory */
3937 decrRefCount(po);
7e69548d 3938 }
ed9b544e 3939 }
3940 dictReleaseIterator(di);
3941 }
3942 /* EOF opcode */
f78fd11b 3943 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
3944
3945 /* Make sure data will not remain on the OS's output buffers */
ed9b544e 3946 fflush(fp);
3947 fsync(fileno(fp));
3948 fclose(fp);
e0a62c7f 3949
ed9b544e 3950 /* Use RENAME to make sure the DB file is changed atomically only
3951 * if the generate DB file is ok. */
3952 if (rename(tmpfile,filename) == -1) {
325d1eb4 3953 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
ed9b544e 3954 unlink(tmpfile);
3955 return REDIS_ERR;
3956 }
3957 redisLog(REDIS_NOTICE,"DB saved on disk");
3958 server.dirty = 0;
3959 server.lastsave = time(NULL);
3960 return REDIS_OK;
3961
3962werr:
3963 fclose(fp);
3964 unlink(tmpfile);
3965 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
3966 if (di) dictReleaseIterator(di);
3967 return REDIS_ERR;
3968}
3969
f78fd11b 3970static int rdbSaveBackground(char *filename) {
ed9b544e 3971 pid_t childpid;
3972
9d65a1bb 3973 if (server.bgsavechildpid != -1) return REDIS_ERR;
054e426d 3974 if (server.vm_enabled) waitEmptyIOJobsQueue();
ed9b544e 3975 if ((childpid = fork()) == 0) {
3976 /* Child */
054e426d 3977 if (server.vm_enabled) vmReopenSwapFile();
ed9b544e 3978 close(server.fd);
f78fd11b 3979 if (rdbSave(filename) == REDIS_OK) {
478c2c6f 3980 _exit(0);
ed9b544e 3981 } else {
478c2c6f 3982 _exit(1);
ed9b544e 3983 }
3984 } else {
3985 /* Parent */
5a7c647e 3986 if (childpid == -1) {
3987 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
3988 strerror(errno));
3989 return REDIS_ERR;
3990 }
ed9b544e 3991 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
9f3c422c 3992 server.bgsavechildpid = childpid;
884d4b39 3993 updateDictResizePolicy();
ed9b544e 3994 return REDIS_OK;
3995 }
3996 return REDIS_OK; /* unreached */
3997}
3998
a3b21203 3999static void rdbRemoveTempFile(pid_t childpid) {
4000 char tmpfile[256];
4001
4002 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
4003 unlink(tmpfile);
4004}
4005
f78fd11b 4006static int rdbLoadType(FILE *fp) {
4007 unsigned char type;
7b45bfb2 4008 if (fread(&type,1,1,fp) == 0) return -1;
4009 return type;
4010}
4011
bb32ede5 4012static time_t rdbLoadTime(FILE *fp) {
4013 int32_t t32;
4014 if (fread(&t32,4,1,fp) == 0) return -1;
4015 return (time_t) t32;
4016}
4017
e3566d4b 4018/* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
4019 * of this file for a description of how this are stored on disk.
4020 *
4021 * isencoded is set to 1 if the readed length is not actually a length but
4022 * an "encoding type", check the above comments for more info */
c78a8ccc 4023static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
f78fd11b 4024 unsigned char buf[2];
4025 uint32_t len;
c78a8ccc 4026 int type;
f78fd11b 4027
e3566d4b 4028 if (isencoded) *isencoded = 0;
c78a8ccc 4029 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
4030 type = (buf[0]&0xC0)>>6;
4031 if (type == REDIS_RDB_6BITLEN) {
4032 /* Read a 6 bit len */
4033 return buf[0]&0x3F;
4034 } else if (type == REDIS_RDB_ENCVAL) {
4035 /* Read a 6 bit len encoding type */
4036 if (isencoded) *isencoded = 1;
4037 return buf[0]&0x3F;
4038 } else if (type == REDIS_RDB_14BITLEN) {
4039 /* Read a 14 bit len */
4040 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
4041 return ((buf[0]&0x3F)<<8)|buf[1];
4042 } else {
4043 /* Read a 32 bit len */
f78fd11b 4044 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
4045 return ntohl(len);
f78fd11b 4046 }
f78fd11b 4047}
4048
ad30aa60 4049/* Load an integer-encoded object from file 'fp', with the specified
4050 * encoding type 'enctype'. If encode is true the function may return
4051 * an integer-encoded object as reply, otherwise the returned object
4052 * will always be encoded as a raw string. */
4053static robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
e3566d4b 4054 unsigned char enc[4];
4055 long long val;
4056
4057 if (enctype == REDIS_RDB_ENC_INT8) {
4058 if (fread(enc,1,1,fp) == 0) return NULL;
4059 val = (signed char)enc[0];
4060 } else if (enctype == REDIS_RDB_ENC_INT16) {
4061 uint16_t v;
4062 if (fread(enc,2,1,fp) == 0) return NULL;
4063 v = enc[0]|(enc[1]<<8);
4064 val = (int16_t)v;
4065 } else if (enctype == REDIS_RDB_ENC_INT32) {
4066 uint32_t v;
4067 if (fread(enc,4,1,fp) == 0) return NULL;
4068 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
4069 val = (int32_t)v;
4070 } else {
4071 val = 0; /* anti-warning */
f83c6cb5 4072 redisPanic("Unknown RDB integer encoding type");
e3566d4b 4073 }
ad30aa60 4074 if (encode)
4075 return createStringObjectFromLongLong(val);
4076 else
4077 return createObject(REDIS_STRING,sdsfromlonglong(val));
e3566d4b 4078}
4079
c78a8ccc 4080static robj *rdbLoadLzfStringObject(FILE*fp) {
88e85998 4081 unsigned int len, clen;
4082 unsigned char *c = NULL;
4083 sds val = NULL;
4084
c78a8ccc 4085 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4086 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
88e85998 4087 if ((c = zmalloc(clen)) == NULL) goto err;
4088 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
4089 if (fread(c,clen,1,fp) == 0) goto err;
4090 if (lzf_decompress(c,clen,val,len) == 0) goto err;
5109cdff 4091 zfree(c);
88e85998 4092 return createObject(REDIS_STRING,val);
4093err:
4094 zfree(c);
4095 sdsfree(val);
4096 return NULL;
4097}
4098
ad30aa60 4099static robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
e3566d4b 4100 int isencoded;
4101 uint32_t len;
f78fd11b 4102 sds val;
4103
c78a8ccc 4104 len = rdbLoadLen(fp,&isencoded);
e3566d4b 4105 if (isencoded) {
4106 switch(len) {
4107 case REDIS_RDB_ENC_INT8:
4108 case REDIS_RDB_ENC_INT16:
4109 case REDIS_RDB_ENC_INT32:
ad30aa60 4110 return rdbLoadIntegerObject(fp,len,encode);
88e85998 4111 case REDIS_RDB_ENC_LZF:
bdcb92f2 4112 return rdbLoadLzfStringObject(fp);
e3566d4b 4113 default:
f83c6cb5 4114 redisPanic("Unknown RDB encoding type");
e3566d4b 4115 }
4116 }
4117
f78fd11b 4118 if (len == REDIS_RDB_LENERR) return NULL;
4119 val = sdsnewlen(NULL,len);
4120 if (len && fread(val,len,1,fp) == 0) {
4121 sdsfree(val);
4122 return NULL;
4123 }
bdcb92f2 4124 return createObject(REDIS_STRING,val);
f78fd11b 4125}
4126
ad30aa60 4127static robj *rdbLoadStringObject(FILE *fp) {
4128 return rdbGenericLoadStringObject(fp,0);
4129}
4130
4131static robj *rdbLoadEncodedStringObject(FILE *fp) {
4132 return rdbGenericLoadStringObject(fp,1);
4133}
4134
a7866db6 4135/* For information about double serialization check rdbSaveDoubleValue() */
4136static int rdbLoadDoubleValue(FILE *fp, double *val) {
4137 char buf[128];
4138 unsigned char len;
4139
4140 if (fread(&len,1,1,fp) == 0) return -1;
4141 switch(len) {
4142 case 255: *val = R_NegInf; return 0;
4143 case 254: *val = R_PosInf; return 0;
4144 case 253: *val = R_Nan; return 0;
4145 default:
4146 if (fread(buf,len,1,fp) == 0) return -1;
231d758e 4147 buf[len] = '\0';
a7866db6 4148 sscanf(buf, "%lg", val);
4149 return 0;
4150 }
4151}
4152
c78a8ccc 4153/* Load a Redis object of the specified type from the specified file.
4154 * On success a newly allocated object is returned, otherwise NULL. */
4155static robj *rdbLoadObject(int type, FILE *fp) {
23f96494
PN
4156 robj *o, *ele, *dec;
4157 size_t len;
c78a8ccc 4158
bcd11906 4159 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
c78a8ccc 4160 if (type == REDIS_STRING) {
4161 /* Read string value */
ad30aa60 4162 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 4163 o = tryObjectEncoding(o);
23f96494
PN
4164 } else if (type == REDIS_LIST) {
4165 /* Read list value */
4166 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4167
d0686e07
PN
4168 /* Use a real list when there are too many entries */
4169 if (len > server.list_max_ziplist_entries) {
4170 o = createListObject();
4171 } else {
4172 o = createZiplistObject();
4173 }
c78a8ccc 4174
23f96494
PN
4175 /* Load every single element of the list */
4176 while(len--) {
4177 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
4178
d0686e07
PN
4179 /* If we are using a ziplist and the value is too big, convert
4180 * the object to a real list. */
4181 if (o->encoding == REDIS_ENCODING_ZIPLIST &&
4182 ele->encoding == REDIS_ENCODING_RAW &&
4183 sdslen(ele->ptr) > server.list_max_ziplist_value)
4184 convertList(o,REDIS_ENCODING_LIST);
4185
23f96494
PN
4186 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
4187 dec = getDecodedObject(ele);
4188 o->ptr = ziplistPush(o->ptr,dec->ptr,sdslen(dec->ptr),REDIS_TAIL);
4189 decrRefCount(dec);
4190 decrRefCount(ele);
4191 } else {
4192 ele = tryObjectEncoding(ele);
4193 listAddNodeTail(o->ptr,ele);
4194 incrRefCount(ele);
4195 }
4196 }
4197 } else if (type == REDIS_SET) {
4198 /* Read list/set value */
4199 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4200 o = createSetObject();
3c68de9b 4201 /* It's faster to expand the dict to the right size asap in order
4202 * to avoid rehashing */
23f96494
PN
4203 if (len > DICT_HT_INITIAL_SIZE)
4204 dictExpand(o->ptr,len);
c78a8ccc 4205 /* Load every single element of the list/set */
23f96494 4206 while(len--) {
ad30aa60 4207 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 4208 ele = tryObjectEncoding(ele);
23f96494 4209 dictAdd((dict*)o->ptr,ele,NULL);
c78a8ccc 4210 }
4211 } else if (type == REDIS_ZSET) {
4212 /* Read list/set value */
ada386b2 4213 size_t zsetlen;
c78a8ccc 4214 zset *zs;
4215
4216 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4217 o = createZsetObject();
4218 zs = o->ptr;
4219 /* Load every single element of the list/set */
4220 while(zsetlen--) {
4221 robj *ele;
4222 double *score = zmalloc(sizeof(double));
4223
ad30aa60 4224 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 4225 ele = tryObjectEncoding(ele);
c78a8ccc 4226 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
4227 dictAdd(zs->dict,ele,score);
4228 zslInsert(zs->zsl,*score,ele);
4229 incrRefCount(ele); /* added to skiplist */
4230 }
ada386b2 4231 } else if (type == REDIS_HASH) {
4232 size_t hashlen;
4233
4234 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4235 o = createHashObject();
4236 /* Too many entries? Use an hash table. */
4237 if (hashlen > server.hash_max_zipmap_entries)
4238 convertToRealHash(o);
4239 /* Load every key/value, then set it into the zipmap or hash
4240 * table, as needed. */
4241 while(hashlen--) {
4242 robj *key, *val;
4243
4244 if ((key = rdbLoadStringObject(fp)) == NULL) return NULL;
4245 if ((val = rdbLoadStringObject(fp)) == NULL) return NULL;
4246 /* If we are using a zipmap and there are too big values
4247 * the object is converted to real hash table encoding. */
4248 if (o->encoding != REDIS_ENCODING_HT &&
4249 (sdslen(key->ptr) > server.hash_max_zipmap_value ||
4250 sdslen(val->ptr) > server.hash_max_zipmap_value))
4251 {
4252 convertToRealHash(o);
4253 }
4254
4255 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
4256 unsigned char *zm = o->ptr;
4257
4258 zm = zipmapSet(zm,key->ptr,sdslen(key->ptr),
4259 val->ptr,sdslen(val->ptr),NULL);
4260 o->ptr = zm;
4261 decrRefCount(key);
4262 decrRefCount(val);
4263 } else {
05df7621 4264 key = tryObjectEncoding(key);
4265 val = tryObjectEncoding(val);
ada386b2 4266 dictAdd((dict*)o->ptr,key,val);
ada386b2 4267 }
4268 }
c78a8ccc 4269 } else {
f83c6cb5 4270 redisPanic("Unknown object type");
c78a8ccc 4271 }
4272 return o;
4273}
4274
f78fd11b 4275static int rdbLoad(char *filename) {
ed9b544e 4276 FILE *fp;
f78fd11b 4277 uint32_t dbid;
bb32ede5 4278 int type, retval, rdbver;
585af7e2 4279 int swap_all_values = 0;
bb32ede5 4280 redisDb *db = server.db+0;
f78fd11b 4281 char buf[1024];
242a64f3 4282 time_t expiretime, now = time(NULL);
bb32ede5 4283
ed9b544e 4284 fp = fopen(filename,"r");
4285 if (!fp) return REDIS_ERR;
4286 if (fread(buf,9,1,fp) == 0) goto eoferr;
f78fd11b 4287 buf[9] = '\0';
4288 if (memcmp(buf,"REDIS",5) != 0) {
ed9b544e 4289 fclose(fp);
4290 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
4291 return REDIS_ERR;
4292 }
f78fd11b 4293 rdbver = atoi(buf+5);
c78a8ccc 4294 if (rdbver != 1) {
f78fd11b 4295 fclose(fp);
4296 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
4297 return REDIS_ERR;
4298 }
ed9b544e 4299 while(1) {
585af7e2 4300 robj *key, *val;
7e02fe32 4301 int force_swapout;
ed9b544e 4302
585af7e2 4303 expiretime = -1;
ed9b544e 4304 /* Read type. */
f78fd11b 4305 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
bb32ede5 4306 if (type == REDIS_EXPIRETIME) {
4307 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
4308 /* We read the time so we need to read the object type again */
4309 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4310 }
ed9b544e 4311 if (type == REDIS_EOF) break;
4312 /* Handle SELECT DB opcode as a special case */
4313 if (type == REDIS_SELECTDB) {
c78a8ccc 4314 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
e3566d4b 4315 goto eoferr;
ed9b544e 4316 if (dbid >= (unsigned)server.dbnum) {
f78fd11b 4317 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
ed9b544e 4318 exit(1);
4319 }
bb32ede5 4320 db = server.db+dbid;
ed9b544e 4321 continue;
4322 }
4323 /* Read key */
585af7e2 4324 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
c78a8ccc 4325 /* Read value */
585af7e2 4326 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
89e689c5 4327 /* Check if the key already expired */
4328 if (expiretime != -1 && expiretime < now) {
4329 decrRefCount(key);
4330 decrRefCount(val);
4331 continue;
4332 }
ed9b544e 4333 /* Add the new object in the hash table */
09241813 4334 retval = dbAdd(db,key,val);
4335 if (retval == REDIS_ERR) {
585af7e2 4336 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
ed9b544e 4337 exit(1);
4338 }
bb32ede5 4339 /* Set the expire time if needed */
89e689c5 4340 if (expiretime != -1) setExpire(db,key,expiretime);
242a64f3 4341
b492cf00 4342 /* Handle swapping while loading big datasets when VM is on */
242a64f3 4343
4344 /* If we detecter we are hopeless about fitting something in memory
4345 * we just swap every new key on disk. Directly...
4346 * Note that's important to check for this condition before resorting
4347 * to random sampling, otherwise we may try to swap already
4348 * swapped keys. */
585af7e2 4349 if (swap_all_values) {
09241813 4350 dictEntry *de = dictFind(db->dict,key->ptr);
242a64f3 4351
4352 /* de may be NULL since the key already expired */
4353 if (de) {
560db612 4354 vmpointer *vp;
585af7e2 4355 val = dictGetEntryVal(de);
242a64f3 4356
560db612 4357 if (val->refcount == 1 &&
4358 (vp = vmSwapObjectBlocking(val)) != NULL)
4359 dictGetEntryVal(de) = vp;
242a64f3 4360 }
09241813 4361 decrRefCount(key);
242a64f3 4362 continue;
4363 }
09241813 4364 decrRefCount(key);
242a64f3 4365
a89b7013 4366 /* Flush data on disk once 32 MB of additional RAM are used... */
7e02fe32 4367 force_swapout = 0;
4368 if ((zmalloc_used_memory() - server.vm_max_memory) > 1024*1024*32)
4369 force_swapout = 1;
242a64f3 4370
4371 /* If we have still some hope of having some value fitting memory
4372 * then we try random sampling. */
7e02fe32 4373 if (!swap_all_values && server.vm_enabled && force_swapout) {
b492cf00 4374 while (zmalloc_used_memory() > server.vm_max_memory) {
a69a0c9c 4375 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
b492cf00 4376 }
242a64f3 4377 if (zmalloc_used_memory() > server.vm_max_memory)
585af7e2 4378 swap_all_values = 1; /* We are already using too much mem */
b492cf00 4379 }
ed9b544e 4380 }
4381 fclose(fp);
4382 return REDIS_OK;
4383
4384eoferr: /* unexpected end of file is handled here with a fatal exit */
f80dff62 4385 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
ed9b544e 4386 exit(1);
4387 return REDIS_ERR; /* Just to avoid warning */
4388}
4389
b58ba105 4390/*================================== Shutdown =============================== */
fab43727 4391static int prepareForShutdown() {
b58ba105
AM
4392 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
4393 /* Kill the saving child if there is a background saving in progress.
4394 We want to avoid race conditions, for instance our saving child may
4395 overwrite the synchronous saving did by SHUTDOWN. */
4396 if (server.bgsavechildpid != -1) {
4397 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
4398 kill(server.bgsavechildpid,SIGKILL);
4399 rdbRemoveTempFile(server.bgsavechildpid);
4400 }
4401 if (server.appendonly) {
4402 /* Append only file: fsync() the AOF and exit */
b0bd87f6 4403 aof_fsync(server.appendfd);
b58ba105 4404 if (server.vm_enabled) unlink(server.vm_swap_file);
b58ba105
AM
4405 } else {
4406 /* Snapshotting. Perform a SYNC SAVE and exit */
4407 if (rdbSave(server.dbfilename) == REDIS_OK) {
4408 if (server.daemonize)
4409 unlink(server.pidfile);
4410 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
b58ba105
AM
4411 } else {
4412 /* Ooops.. error saving! The best we can do is to continue
4413 * operating. Note that if there was a background saving process,
4414 * in the next cron() Redis will be notified that the background
4415 * saving aborted, handling special stuff like slaves pending for
4416 * synchronization... */
4417 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
fab43727 4418 return REDIS_ERR;
b58ba105
AM
4419 }
4420 }
8513a757 4421 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
fab43727 4422 return REDIS_OK;
b58ba105
AM
4423}
4424
ed9b544e 4425/*================================== Commands =============================== */
4426
abcb223e 4427static void authCommand(redisClient *c) {
2e77c2ee 4428 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
abcb223e
BH
4429 c->authenticated = 1;
4430 addReply(c,shared.ok);
4431 } else {
4432 c->authenticated = 0;
fa4c0aba 4433 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
abcb223e
BH
4434 }
4435}
4436
ed9b544e 4437static void pingCommand(redisClient *c) {
4438 addReply(c,shared.pong);
4439}
4440
4441static void echoCommand(redisClient *c) {
dd88747b 4442 addReplyBulk(c,c->argv[1]);
ed9b544e 4443}
4444
4445/*=================================== Strings =============================== */
4446
526d00a5 4447static void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
ed9b544e 4448 int retval;
10ce1276 4449 long seconds = 0; /* initialized to avoid an harmness warning */
ed9b544e 4450
526d00a5 4451 if (expire) {
4452 if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
4453 return;
4454 if (seconds <= 0) {
4455 addReplySds(c,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4456 return;
4457 }
4458 }
4459
37ab76c9 4460 touchWatchedKey(c->db,key);
526d00a5 4461 if (nx) deleteIfVolatile(c->db,key);
09241813 4462 retval = dbAdd(c->db,key,val);
4463 if (retval == REDIS_ERR) {
ed9b544e 4464 if (!nx) {
09241813 4465 dbReplace(c->db,key,val);
526d00a5 4466 incrRefCount(val);
ed9b544e 4467 } else {
c937aa89 4468 addReply(c,shared.czero);
ed9b544e 4469 return;
4470 }
4471 } else {
526d00a5 4472 incrRefCount(val);
ed9b544e 4473 }
4474 server.dirty++;
526d00a5 4475 removeExpire(c->db,key);
4476 if (expire) setExpire(c->db,key,time(NULL)+seconds);
c937aa89 4477 addReply(c, nx ? shared.cone : shared.ok);
ed9b544e 4478}
4479
4480static void setCommand(redisClient *c) {
526d00a5 4481 setGenericCommand(c,0,c->argv[1],c->argv[2],NULL);
ed9b544e 4482}
4483
4484static void setnxCommand(redisClient *c) {
526d00a5 4485 setGenericCommand(c,1,c->argv[1],c->argv[2],NULL);
4486}
4487
4488static void setexCommand(redisClient *c) {
4489 setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
ed9b544e 4490}
4491
322fc7d8 4492static int getGenericCommand(redisClient *c) {
dd88747b 4493 robj *o;
e0a62c7f 4494
dd88747b 4495 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
322fc7d8 4496 return REDIS_OK;
dd88747b 4497
4498 if (o->type != REDIS_STRING) {
4499 addReply(c,shared.wrongtypeerr);
4500 return REDIS_ERR;
ed9b544e 4501 } else {
dd88747b 4502 addReplyBulk(c,o);
4503 return REDIS_OK;
ed9b544e 4504 }
4505}
4506
322fc7d8 4507static void getCommand(redisClient *c) {
4508 getGenericCommand(c);
4509}
4510
f6b141c5 4511static void getsetCommand(redisClient *c) {
322fc7d8 4512 if (getGenericCommand(c) == REDIS_ERR) return;
09241813 4513 dbReplace(c->db,c->argv[1],c->argv[2]);
a431eb74 4514 incrRefCount(c->argv[2]);
4515 server.dirty++;
4516 removeExpire(c->db,c->argv[1]);
4517}
4518
70003d28 4519static void mgetCommand(redisClient *c) {
70003d28 4520 int j;
e0a62c7f 4521
c937aa89 4522 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
70003d28 4523 for (j = 1; j < c->argc; j++) {
3305306f 4524 robj *o = lookupKeyRead(c->db,c->argv[j]);
4525 if (o == NULL) {
c937aa89 4526 addReply(c,shared.nullbulk);
70003d28 4527 } else {
70003d28 4528 if (o->type != REDIS_STRING) {
c937aa89 4529 addReply(c,shared.nullbulk);
70003d28 4530 } else {
dd88747b 4531 addReplyBulk(c,o);
70003d28 4532 }
4533 }
4534 }
4535}
4536
6c446631 4537static void msetGenericCommand(redisClient *c, int nx) {
906573e7 4538 int j, busykeys = 0;
6c446631 4539
4540 if ((c->argc % 2) == 0) {
454d4e43 4541 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
6c446631 4542 return;
4543 }
4544 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4545 * set nothing at all if at least one already key exists. */
4546 if (nx) {
4547 for (j = 1; j < c->argc; j += 2) {
906573e7 4548 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
4549 busykeys++;
6c446631 4550 }
4551 }
4552 }
906573e7 4553 if (busykeys) {
4554 addReply(c, shared.czero);
4555 return;
4556 }
6c446631 4557
4558 for (j = 1; j < c->argc; j += 2) {
05df7621 4559 c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
09241813 4560 dbReplace(c->db,c->argv[j],c->argv[j+1]);
4561 incrRefCount(c->argv[j+1]);
6c446631 4562 removeExpire(c->db,c->argv[j]);
4563 }
4564 server.dirty += (c->argc-1)/2;
4565 addReply(c, nx ? shared.cone : shared.ok);
4566}
4567
4568static void msetCommand(redisClient *c) {
4569 msetGenericCommand(c,0);
4570}
4571
4572static void msetnxCommand(redisClient *c) {
4573 msetGenericCommand(c,1);
4574}
4575
d68ed120 4576static void incrDecrCommand(redisClient *c, long long incr) {
ed9b544e 4577 long long value;
ed9b544e 4578 robj *o;
e0a62c7f 4579
3305306f 4580 o = lookupKeyWrite(c->db,c->argv[1]);
6485f293
PN
4581 if (o != NULL && checkType(c,o,REDIS_STRING)) return;
4582 if (getLongLongFromObjectOrReply(c,o,&value,NULL) != REDIS_OK) return;
ed9b544e 4583
4584 value += incr;
d6f4c262 4585 o = createStringObjectFromLongLong(value);
09241813 4586 dbReplace(c->db,c->argv[1],o);
ed9b544e 4587 server.dirty++;
c937aa89 4588 addReply(c,shared.colon);
ed9b544e 4589 addReply(c,o);
4590 addReply(c,shared.crlf);
4591}
4592
4593static void incrCommand(redisClient *c) {
a4d1ba9a 4594 incrDecrCommand(c,1);
ed9b544e 4595}
4596
4597static void decrCommand(redisClient *c) {
a4d1ba9a 4598 incrDecrCommand(c,-1);
ed9b544e 4599}
4600
4601static void incrbyCommand(redisClient *c) {
bbe025e0
AM
4602 long long incr;
4603
bd79a6bd 4604 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
a4d1ba9a 4605 incrDecrCommand(c,incr);
ed9b544e 4606}
4607
4608static void decrbyCommand(redisClient *c) {
bbe025e0
AM
4609 long long incr;
4610
bd79a6bd 4611 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
a4d1ba9a 4612 incrDecrCommand(c,-incr);
ed9b544e 4613}
4614
4b00bebd 4615static void appendCommand(redisClient *c) {
4616 int retval;
4617 size_t totlen;
4618 robj *o;
4619
4620 o = lookupKeyWrite(c->db,c->argv[1]);
4621 if (o == NULL) {
4622 /* Create the key */
09241813 4623 retval = dbAdd(c->db,c->argv[1],c->argv[2]);
4b00bebd 4624 incrRefCount(c->argv[2]);
4625 totlen = stringObjectLen(c->argv[2]);
4626 } else {
4b00bebd 4627 if (o->type != REDIS_STRING) {
4628 addReply(c,shared.wrongtypeerr);
4629 return;
4630 }
4631 /* If the object is specially encoded or shared we have to make
4632 * a copy */
4633 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
4634 robj *decoded = getDecodedObject(o);
4635
4636 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
4637 decrRefCount(decoded);
09241813 4638 dbReplace(c->db,c->argv[1],o);
4b00bebd 4639 }
4640 /* APPEND! */
4641 if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
4642 o->ptr = sdscatlen(o->ptr,
4643 c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
4644 } else {
4645 o->ptr = sdscatprintf(o->ptr, "%ld",
4646 (unsigned long) c->argv[2]->ptr);
4647 }
4648 totlen = sdslen(o->ptr);
4649 }
4650 server.dirty++;
4651 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
4652}
4653
39191553 4654static void substrCommand(redisClient *c) {
4655 robj *o;
4656 long start = atoi(c->argv[2]->ptr);
4657 long end = atoi(c->argv[3]->ptr);
dd88747b 4658 size_t rangelen, strlen;
4659 sds range;
39191553 4660
dd88747b 4661 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4662 checkType(c,o,REDIS_STRING)) return;
39191553 4663
dd88747b 4664 o = getDecodedObject(o);
4665 strlen = sdslen(o->ptr);
8fe7fad7 4666
dd88747b 4667 /* convert negative indexes */
4668 if (start < 0) start = strlen+start;
4669 if (end < 0) end = strlen+end;
4670 if (start < 0) start = 0;
4671 if (end < 0) end = 0;
39191553 4672
dd88747b 4673 /* indexes sanity checks */
4674 if (start > end || (size_t)start >= strlen) {
4675 /* Out of range start or start > end result in null reply */
4676 addReply(c,shared.nullbulk);
4677 decrRefCount(o);
4678 return;
39191553 4679 }
dd88747b 4680 if ((size_t)end >= strlen) end = strlen-1;
4681 rangelen = (end-start)+1;
4682
4683 /* Return the result */
4684 addReplySds(c,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen));
4685 range = sdsnewlen((char*)o->ptr+start,rangelen);
4686 addReplySds(c,range);
4687 addReply(c,shared.crlf);
4688 decrRefCount(o);
39191553 4689}
4690
ed9b544e 4691/* ========================= Type agnostic commands ========================= */
4692
4693static void delCommand(redisClient *c) {
5109cdff 4694 int deleted = 0, j;
4695
4696 for (j = 1; j < c->argc; j++) {
09241813 4697 if (dbDelete(c->db,c->argv[j])) {
37ab76c9 4698 touchWatchedKey(c->db,c->argv[j]);
5109cdff 4699 server.dirty++;
4700 deleted++;
4701 }
4702 }
482b672d 4703 addReplyLongLong(c,deleted);
ed9b544e 4704}
4705
4706static void existsCommand(redisClient *c) {
f4f06efc 4707 expireIfNeeded(c->db,c->argv[1]);
09241813 4708 if (dbExists(c->db,c->argv[1])) {
f4f06efc
PN
4709 addReply(c, shared.cone);
4710 } else {
4711 addReply(c, shared.czero);
4712 }
ed9b544e 4713}
4714
4715static void selectCommand(redisClient *c) {
4716 int id = atoi(c->argv[1]->ptr);
e0a62c7f 4717
ed9b544e 4718 if (selectDb(c,id) == REDIS_ERR) {
774e3047 4719 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
ed9b544e 4720 } else {
4721 addReply(c,shared.ok);
4722 }
4723}
4724
4725static void randomkeyCommand(redisClient *c) {
dc4be23e 4726 robj *key;
e0a62c7f 4727
09241813 4728 if ((key = dbRandomKey(c->db)) == NULL) {
dc4be23e 4729 addReply(c,shared.nullbulk);
4730 return;
4731 }
4732
09241813 4733 addReplyBulk(c,key);
4734 decrRefCount(key);
ed9b544e 4735}
4736
4737static void keysCommand(redisClient *c) {
4738 dictIterator *di;
4739 dictEntry *de;
4740 sds pattern = c->argv[1]->ptr;
4741 int plen = sdslen(pattern);
a3f9eec2 4742 unsigned long numkeys = 0;
ed9b544e 4743 robj *lenobj = createObject(REDIS_STRING,NULL);
4744
3305306f 4745 di = dictGetIterator(c->db->dict);
ed9b544e 4746 addReply(c,lenobj);
4747 decrRefCount(lenobj);
4748 while((de = dictNext(di)) != NULL) {
09241813 4749 sds key = dictGetEntryKey(de);
4750 robj *keyobj;
3305306f 4751
ed9b544e 4752 if ((pattern[0] == '*' && pattern[1] == '\0') ||
4753 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
09241813 4754 keyobj = createStringObject(key,sdslen(key));
3305306f 4755 if (expireIfNeeded(c->db,keyobj) == 0) {
dd88747b 4756 addReplyBulk(c,keyobj);
3305306f 4757 numkeys++;
3305306f 4758 }
09241813 4759 decrRefCount(keyobj);
ed9b544e 4760 }
4761 }
4762 dictReleaseIterator(di);
a3f9eec2 4763 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
ed9b544e 4764}
4765
4766static void dbsizeCommand(redisClient *c) {
4767 addReplySds(c,
3305306f 4768 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
ed9b544e 4769}
4770
4771static void lastsaveCommand(redisClient *c) {
4772 addReplySds(c,
c937aa89 4773 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
ed9b544e 4774}
4775
4776static void typeCommand(redisClient *c) {
3305306f 4777 robj *o;
ed9b544e 4778 char *type;
3305306f 4779
4780 o = lookupKeyRead(c->db,c->argv[1]);
4781 if (o == NULL) {
c937aa89 4782 type = "+none";
ed9b544e 4783 } else {
ed9b544e 4784 switch(o->type) {
c937aa89 4785 case REDIS_STRING: type = "+string"; break;
4786 case REDIS_LIST: type = "+list"; break;
4787 case REDIS_SET: type = "+set"; break;
412a8bce 4788 case REDIS_ZSET: type = "+zset"; break;
ada386b2 4789 case REDIS_HASH: type = "+hash"; break;
4790 default: type = "+unknown"; break;
ed9b544e 4791 }
4792 }
4793 addReplySds(c,sdsnew(type));
4794 addReply(c,shared.crlf);
4795}
4796
4797static void saveCommand(redisClient *c) {
9d65a1bb 4798 if (server.bgsavechildpid != -1) {
05557f6d 4799 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
4800 return;
4801 }
f78fd11b 4802 if (rdbSave(server.dbfilename) == REDIS_OK) {
ed9b544e 4803 addReply(c,shared.ok);
4804 } else {
4805 addReply(c,shared.err);
4806 }
4807}
4808
4809static void bgsaveCommand(redisClient *c) {
9d65a1bb 4810 if (server.bgsavechildpid != -1) {
ed9b544e 4811 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
4812 return;
4813 }
f78fd11b 4814 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
49b99ab4 4815 char *status = "+Background saving started\r\n";
4816 addReplySds(c,sdsnew(status));
ed9b544e 4817 } else {
4818 addReply(c,shared.err);
4819 }
4820}
4821
4822static void shutdownCommand(redisClient *c) {
fab43727 4823 if (prepareForShutdown() == REDIS_OK)
4824 exit(0);
4825 addReplySds(c, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
ed9b544e 4826}
4827
4828static void renameGenericCommand(redisClient *c, int nx) {
ed9b544e 4829 robj *o;
4830
4831 /* To use the same key as src and dst is probably an error */
4832 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
c937aa89 4833 addReply(c,shared.sameobjecterr);
ed9b544e 4834 return;
4835 }
4836
dd88747b 4837 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
ed9b544e 4838 return;
dd88747b 4839
ed9b544e 4840 incrRefCount(o);
3305306f 4841 deleteIfVolatile(c->db,c->argv[2]);
09241813 4842 if (dbAdd(c->db,c->argv[2],o) == REDIS_ERR) {
ed9b544e 4843 if (nx) {
4844 decrRefCount(o);
c937aa89 4845 addReply(c,shared.czero);
ed9b544e 4846 return;
4847 }
09241813 4848 dbReplace(c->db,c->argv[2],o);
ed9b544e 4849 }
09241813 4850 dbDelete(c->db,c->argv[1]);
b167f877 4851 touchWatchedKey(c->db,c->argv[2]);
ed9b544e 4852 server.dirty++;
c937aa89 4853 addReply(c,nx ? shared.cone : shared.ok);
ed9b544e 4854}
4855
4856static void renameCommand(redisClient *c) {
4857 renameGenericCommand(c,0);
4858}
4859
4860static void renamenxCommand(redisClient *c) {
4861 renameGenericCommand(c,1);
4862}
4863
4864static void moveCommand(redisClient *c) {
3305306f 4865 robj *o;
4866 redisDb *src, *dst;
ed9b544e 4867 int srcid;
4868
4869 /* Obtain source and target DB pointers */
3305306f 4870 src = c->db;
4871 srcid = c->db->id;
ed9b544e 4872 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
c937aa89 4873 addReply(c,shared.outofrangeerr);
ed9b544e 4874 return;
4875 }
3305306f 4876 dst = c->db;
4877 selectDb(c,srcid); /* Back to the source DB */
ed9b544e 4878
4879 /* If the user is moving using as target the same
4880 * DB as the source DB it is probably an error. */
4881 if (src == dst) {
c937aa89 4882 addReply(c,shared.sameobjecterr);
ed9b544e 4883 return;
4884 }
4885
4886 /* Check if the element exists and get a reference */
3305306f 4887 o = lookupKeyWrite(c->db,c->argv[1]);
4888 if (!o) {
c937aa89 4889 addReply(c,shared.czero);
ed9b544e 4890 return;
4891 }
4892
4893 /* Try to add the element to the target DB */
3305306f 4894 deleteIfVolatile(dst,c->argv[1]);
09241813 4895 if (dbAdd(dst,c->argv[1],o) == REDIS_ERR) {
c937aa89 4896 addReply(c,shared.czero);
ed9b544e 4897 return;
4898 }
ed9b544e 4899 incrRefCount(o);
4900
4901 /* OK! key moved, free the entry in the source DB */
09241813 4902 dbDelete(src,c->argv[1]);
ed9b544e 4903 server.dirty++;
c937aa89 4904 addReply(c,shared.cone);
ed9b544e 4905}
4906
4907/* =================================== Lists ================================ */
d0686e07
PN
4908
4909
4910/* Check the argument length to see if it requires us to convert the ziplist
4911 * to a real list. Only check raw-encoded objects because integer encoded
4912 * objects are never too long. */
4913static void listTryConversion(robj *subject, robj *value) {
4914 if (subject->encoding != REDIS_ENCODING_ZIPLIST) return;
4915 if (value->encoding == REDIS_ENCODING_RAW &&
4916 sdslen(value->ptr) > server.list_max_ziplist_value)
4917 convertList(subject,REDIS_ENCODING_LIST);
4918}
4919
c7d9d662 4920static void lPush(robj *subject, robj *value, int where) {
d0686e07
PN
4921 /* Check if we need to convert the ziplist */
4922 listTryConversion(subject,value);
4923 if (subject->encoding == REDIS_ENCODING_ZIPLIST &&
4924 ziplistLen(subject->ptr) > server.list_max_ziplist_entries)
4925 convertList(subject,REDIS_ENCODING_LIST);
4926
c7d9d662
PN
4927 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4928 int pos = (where == REDIS_HEAD) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
4929 value = getDecodedObject(value);
4930 subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),pos);
4931 decrRefCount(value);
4932 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4933 if (where == REDIS_HEAD) {
4934 listAddNodeHead(subject->ptr,value);
4935 } else {
4936 listAddNodeTail(subject->ptr,value);
4937 }
4938 incrRefCount(value);
4939 } else {
4940 redisPanic("Unknown list encoding");
4941 }
4942}
4943
d72562f7
PN
4944static robj *lPop(robj *subject, int where) {
4945 robj *value = NULL;
4946 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4947 unsigned char *p;
b6eb9703 4948 unsigned char *vstr;
d72562f7 4949 unsigned int vlen;
b6eb9703 4950 long long vlong;
d72562f7
PN
4951 int pos = (where == REDIS_HEAD) ? 0 : -1;
4952 p = ziplistIndex(subject->ptr,pos);
b6eb9703
PN
4953 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
4954 if (vstr) {
4955 value = createStringObject((char*)vstr,vlen);
d72562f7 4956 } else {
b6eb9703 4957 value = createStringObjectFromLongLong(vlong);
d72562f7 4958 }
0f62e177
PN
4959 /* We only need to delete an element when it exists */
4960 subject->ptr = ziplistDelete(subject->ptr,&p);
d72562f7 4961 }
d72562f7
PN
4962 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4963 list *list = subject->ptr;
4964 listNode *ln;
4965 if (where == REDIS_HEAD) {
4966 ln = listFirst(list);
4967 } else {
4968 ln = listLast(list);
4969 }
4970 if (ln != NULL) {
4971 value = listNodeValue(ln);
4972 incrRefCount(value);
4973 listDelNode(list,ln);
4974 }
4975 } else {
4976 redisPanic("Unknown list encoding");
4977 }
4978 return value;
4979}
4980
4981static unsigned long lLength(robj *subject) {
4982 if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
4983 return ziplistLen(subject->ptr);
4984 } else if (subject->encoding == REDIS_ENCODING_LIST) {
4985 return listLength((list*)subject->ptr);
4986 } else {
4987 redisPanic("Unknown list encoding");
4988 }
4989}
4990
a6dd455b
PN
4991/* Structure to hold set iteration abstraction. */
4992typedef struct {
4993 robj *subject;
4994 unsigned char encoding;
be02a7c0 4995 unsigned char direction; /* Iteration direction */
a6dd455b
PN
4996 unsigned char *zi;
4997 listNode *ln;
4998} lIterator;
4999
be02a7c0
PN
5000/* Structure for an entry while iterating over a list. */
5001typedef struct {
5002 lIterator *li;
5003 unsigned char *zi; /* Entry in ziplist */
5004 listNode *ln; /* Entry in linked list */
5005} lEntry;
5006
a6dd455b 5007/* Initialize an iterator at the specified index. */
be02a7c0 5008static lIterator *lInitIterator(robj *subject, int index, unsigned char direction) {
a6dd455b
PN
5009 lIterator *li = zmalloc(sizeof(lIterator));
5010 li->subject = subject;
5011 li->encoding = subject->encoding;
be02a7c0 5012 li->direction = direction;
a6dd455b
PN
5013 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
5014 li->zi = ziplistIndex(subject->ptr,index);
5015 } else if (li->encoding == REDIS_ENCODING_LIST) {
5016 li->ln = listIndex(subject->ptr,index);
5017 } else {
5018 redisPanic("Unknown list encoding");
5019 }
5020 return li;
5021}
5022
5023/* Clean up the iterator. */
5024static void lReleaseIterator(lIterator *li) {
5025 zfree(li);
5026}
5027
be02a7c0
PN
5028/* Stores pointer to current the entry in the provided entry structure
5029 * and advances the position of the iterator. Returns 1 when the current
5030 * entry is in fact an entry, 0 otherwise. */
5031static int lNext(lIterator *li, lEntry *entry) {
5032 entry->li = li;
d2ee16ab 5033 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
be02a7c0
PN
5034 entry->zi = li->zi;
5035 if (entry->zi != NULL) {
5036 if (li->direction == REDIS_TAIL)
5037 li->zi = ziplistNext(li->subject->ptr,li->zi);
5038 else
5039 li->zi = ziplistPrev(li->subject->ptr,li->zi);
5040 return 1;
5041 }
d2ee16ab 5042 } else if (li->encoding == REDIS_ENCODING_LIST) {
be02a7c0
PN
5043 entry->ln = li->ln;
5044 if (entry->ln != NULL) {
5045 if (li->direction == REDIS_TAIL)
5046 li->ln = li->ln->next;
5047 else
5048 li->ln = li->ln->prev;
5049 return 1;
5050 }
d2ee16ab
PN
5051 } else {
5052 redisPanic("Unknown list encoding");
5053 }
be02a7c0 5054 return 0;
d2ee16ab
PN
5055}
5056
a6dd455b 5057/* Return entry or NULL at the current position of the iterator. */
be02a7c0
PN
5058static robj *lGet(lEntry *entry) {
5059 lIterator *li = entry->li;
a6dd455b
PN
5060 robj *value = NULL;
5061 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
b6eb9703 5062 unsigned char *vstr;
a6dd455b 5063 unsigned int vlen;
b6eb9703 5064 long long vlong;
be02a7c0 5065 redisAssert(entry->zi != NULL);
b6eb9703
PN
5066 if (ziplistGet(entry->zi,&vstr,&vlen,&vlong)) {
5067 if (vstr) {
5068 value = createStringObject((char*)vstr,vlen);
a6dd455b 5069 } else {
b6eb9703 5070 value = createStringObjectFromLongLong(vlong);
a6dd455b
PN
5071 }
5072 }
5073 } else if (li->encoding == REDIS_ENCODING_LIST) {
be02a7c0
PN
5074 redisAssert(entry->ln != NULL);
5075 value = listNodeValue(entry->ln);
a6dd455b
PN
5076 incrRefCount(value);
5077 } else {
5078 redisPanic("Unknown list encoding");
5079 }
5080 return value;
5081}
5082
d2ee16ab 5083/* Compare the given object with the entry at the current position. */
be02a7c0
PN
5084static int lEqual(lEntry *entry, robj *o) {
5085 lIterator *li = entry->li;
d2ee16ab
PN
5086 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
5087 redisAssert(o->encoding == REDIS_ENCODING_RAW);
be02a7c0 5088 return ziplistCompare(entry->zi,o->ptr,sdslen(o->ptr));
d2ee16ab 5089 } else if (li->encoding == REDIS_ENCODING_LIST) {
be02a7c0 5090 return equalStringObjects(o,listNodeValue(entry->ln));
d2ee16ab
PN
5091 } else {
5092 redisPanic("Unknown list encoding");
5093 }
5094}
5095
be02a7c0
PN
5096/* Delete the element pointed to. */
5097static void lDelete(lEntry *entry) {
5098 lIterator *li = entry->li;
a6dd455b 5099 if (li->encoding == REDIS_ENCODING_ZIPLIST) {
be02a7c0
PN
5100 unsigned char *p = entry->zi;
5101 li->subject->ptr = ziplistDelete(li->subject->ptr,&p);
5102
5103 /* Update position of the iterator depending on the direction */
5104 if (li->direction == REDIS_TAIL)
5105 li->zi = p;
a6dd455b 5106 else
be02a7c0
PN
5107 li->zi = ziplistPrev(li->subject->ptr,p);
5108 } else if (entry->li->encoding == REDIS_ENCODING_LIST) {
5109 listNode *next;
5110 if (li->direction == REDIS_TAIL)
5111 next = entry->ln->next;
a6dd455b 5112 else
be02a7c0
PN
5113 next = entry->ln->prev;
5114 listDelNode(li->subject->ptr,entry->ln);
5115 li->ln = next;
a6dd455b
PN
5116 } else {
5117 redisPanic("Unknown list encoding");
5118 }
5119}
3305306f 5120
d0686e07
PN
5121static void convertList(robj *subject, int enc) {
5122 lIterator *li;
5123 lEntry entry;
5124 redisAssert(subject->type == REDIS_LIST);
5125
5126 if (enc == REDIS_ENCODING_LIST) {
5127 list *l = listCreate();
5128
5129 /* lGet returns a robj with incremented refcount */
5130 li = lInitIterator(subject,0,REDIS_TAIL);
5131 while (lNext(li,&entry)) listAddNodeTail(l,lGet(&entry));
5132 lReleaseIterator(li);
5133
5134 subject->encoding = REDIS_ENCODING_LIST;
5135 zfree(subject->ptr);
5136 subject->ptr = l;
5137 } else {
5138 redisPanic("Unsupported list conversion");
5139 }
5140}
5141
c7d9d662
PN
5142static void pushGenericCommand(redisClient *c, int where) {
5143 robj *lobj = lookupKeyWrite(c->db,c->argv[1]);
3305306f 5144 if (lobj == NULL) {
95242ab5 5145 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
520b5a33 5146 addReply(c,shared.cone);
95242ab5 5147 return;
5148 }
1cd92e7f 5149 lobj = createZiplistObject();
09241813 5150 dbAdd(c->db,c->argv[1],lobj);
ed9b544e 5151 } else {
ed9b544e 5152 if (lobj->type != REDIS_LIST) {
5153 addReply(c,shared.wrongtypeerr);
5154 return;
5155 }
95242ab5 5156 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
520b5a33 5157 addReply(c,shared.cone);
95242ab5 5158 return;
5159 }
ed9b544e 5160 }
c7d9d662
PN
5161 lPush(lobj,c->argv[2],where);
5162 addReplyLongLong(c,lLength(lobj));
ed9b544e 5163 server.dirty++;
ed9b544e 5164}
5165
5166static void lpushCommand(redisClient *c) {
5167 pushGenericCommand(c,REDIS_HEAD);
5168}
5169
5170static void rpushCommand(redisClient *c) {
5171 pushGenericCommand(c,REDIS_TAIL);
5172}
5173
5174static void llenCommand(redisClient *c) {
d72562f7
PN
5175 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.czero);
5176 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
5177 addReplyUlong(c,lLength(o));
ed9b544e 5178}
5179
5180static void lindexCommand(redisClient *c) {
697bd567
PN
5181 robj *o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk);
5182 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
ed9b544e 5183 int index = atoi(c->argv[2]->ptr);
bd8db0ad 5184 robj *value = NULL;
dd88747b 5185
697bd567
PN
5186 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5187 unsigned char *p;
b6eb9703 5188 unsigned char *vstr;
697bd567 5189 unsigned int vlen;
b6eb9703 5190 long long vlong;
697bd567 5191 p = ziplistIndex(o->ptr,index);
b6eb9703
PN
5192 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
5193 if (vstr) {
5194 value = createStringObject((char*)vstr,vlen);
697bd567 5195 } else {
b6eb9703 5196 value = createStringObjectFromLongLong(vlong);
697bd567 5197 }
bd8db0ad
PN
5198 addReplyBulk(c,value);
5199 decrRefCount(value);
697bd567
PN
5200 } else {
5201 addReply(c,shared.nullbulk);
5202 }
5203 } else if (o->encoding == REDIS_ENCODING_LIST) {
5204 listNode *ln = listIndex(o->ptr,index);
5205 if (ln != NULL) {
bd8db0ad
PN
5206 value = listNodeValue(ln);
5207 addReplyBulk(c,value);
697bd567
PN
5208 } else {
5209 addReply(c,shared.nullbulk);
5210 }
ed9b544e 5211 } else {
697bd567 5212 redisPanic("Unknown list encoding");
ed9b544e 5213 }
5214}
5215
5216static void lsetCommand(redisClient *c) {
697bd567
PN
5217 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr);
5218 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
ed9b544e 5219 int index = atoi(c->argv[2]->ptr);
697bd567 5220 robj *value = c->argv[3];
dd88747b 5221
d0686e07 5222 listTryConversion(o,value);
697bd567
PN
5223 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5224 unsigned char *p, *zl = o->ptr;
5225 p = ziplistIndex(zl,index);
5226 if (p == NULL) {
5227 addReply(c,shared.outofrangeerr);
5228 } else {
be02a7c0 5229 o->ptr = ziplistDelete(o->ptr,&p);
697bd567
PN
5230 value = getDecodedObject(value);
5231 o->ptr = ziplistInsert(o->ptr,p,value->ptr,sdslen(value->ptr));
5232 decrRefCount(value);
5233 addReply(c,shared.ok);
5234 server.dirty++;
5235 }
5236 } else if (o->encoding == REDIS_ENCODING_LIST) {
5237 listNode *ln = listIndex(o->ptr,index);
5238 if (ln == NULL) {
5239 addReply(c,shared.outofrangeerr);
5240 } else {
5241 decrRefCount((robj*)listNodeValue(ln));
5242 listNodeValue(ln) = value;
5243 incrRefCount(value);
5244 addReply(c,shared.ok);
5245 server.dirty++;
5246 }
ed9b544e 5247 } else {
697bd567 5248 redisPanic("Unknown list encoding");
ed9b544e 5249 }
5250}
5251
5252static void popGenericCommand(redisClient *c, int where) {
d72562f7
PN
5253 robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk);
5254 if (o == NULL || checkType(c,o,REDIS_LIST)) return;
3305306f 5255
d72562f7
PN
5256 robj *value = lPop(o,where);
5257 if (value == NULL) {
dd88747b 5258 addReply(c,shared.nullbulk);
5259 } else {
d72562f7
PN
5260 addReplyBulk(c,value);
5261 decrRefCount(value);
846d8b3e 5262 if (lLength(o) == 0) dbDelete(c->db,c->argv[1]);
dd88747b 5263 server.dirty++;
ed9b544e 5264 }
5265}
5266
5267static void lpopCommand(redisClient *c) {
5268 popGenericCommand(c,REDIS_HEAD);
5269}
5270
5271static void rpopCommand(redisClient *c) {
5272 popGenericCommand(c,REDIS_TAIL);
5273}
5274
5275static void lrangeCommand(redisClient *c) {
a6dd455b 5276 robj *o, *value;
ed9b544e 5277 int start = atoi(c->argv[2]->ptr);
5278 int end = atoi(c->argv[3]->ptr);
dd88747b 5279 int llen;
5280 int rangelen, j;
be02a7c0 5281 lEntry entry;
dd88747b 5282
4e27f268 5283 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
5284 || checkType(c,o,REDIS_LIST)) return;
a6dd455b 5285 llen = lLength(o);
dd88747b 5286
5287 /* convert negative indexes */
5288 if (start < 0) start = llen+start;
5289 if (end < 0) end = llen+end;
5290 if (start < 0) start = 0;
5291 if (end < 0) end = 0;
5292
5293 /* indexes sanity checks */
5294 if (start > end || start >= llen) {
5295 /* Out of range start or start > end result in empty list */
5296 addReply(c,shared.emptymultibulk);
5297 return;
5298 }
5299 if (end >= llen) end = llen-1;
5300 rangelen = (end-start)+1;
3305306f 5301
dd88747b 5302 /* Return the result in form of a multi-bulk reply */
dd88747b 5303 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
be02a7c0 5304 lIterator *li = lInitIterator(o,start,REDIS_TAIL);
dd88747b 5305 for (j = 0; j < rangelen; j++) {
be02a7c0
PN
5306 redisAssert(lNext(li,&entry));
5307 value = lGet(&entry);
a6dd455b 5308 addReplyBulk(c,value);
be02a7c0 5309 decrRefCount(value);
ed9b544e 5310 }
a6dd455b 5311 lReleaseIterator(li);
ed9b544e 5312}
5313
5314static void ltrimCommand(redisClient *c) {
3305306f 5315 robj *o;
ed9b544e 5316 int start = atoi(c->argv[2]->ptr);
5317 int end = atoi(c->argv[3]->ptr);
dd88747b 5318 int llen;
5319 int j, ltrim, rtrim;
5320 list *list;
5321 listNode *ln;
5322
5323 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
5324 checkType(c,o,REDIS_LIST)) return;
9ae6b0be 5325 llen = lLength(o);
dd88747b 5326
5327 /* convert negative indexes */
5328 if (start < 0) start = llen+start;
5329 if (end < 0) end = llen+end;
5330 if (start < 0) start = 0;
5331 if (end < 0) end = 0;
5332
5333 /* indexes sanity checks */
5334 if (start > end || start >= llen) {
5335 /* Out of range start or start > end result in empty list */
5336 ltrim = llen;
5337 rtrim = 0;
ed9b544e 5338 } else {
dd88747b 5339 if (end >= llen) end = llen-1;
5340 ltrim = start;
5341 rtrim = llen-end-1;
5342 }
ed9b544e 5343
dd88747b 5344 /* Remove list elements to perform the trim */
9ae6b0be
PN
5345 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
5346 o->ptr = ziplistDeleteRange(o->ptr,0,ltrim);
5347 o->ptr = ziplistDeleteRange(o->ptr,-rtrim,rtrim);
5348 } else if (o->encoding == REDIS_ENCODING_LIST) {
5349 list = o->ptr;
5350 for (j = 0; j < ltrim; j++) {
5351 ln = listFirst(list);
5352 listDelNode(list,ln);
5353 }
5354 for (j = 0; j < rtrim; j++) {
5355 ln = listLast(list);
5356 listDelNode(list,ln);
5357 }
5358 } else {
5359 redisPanic("Unknown list encoding");
ed9b544e 5360 }
846d8b3e 5361 if (lLength(o) == 0) dbDelete(c->db,c->argv[1]);
dd88747b 5362 server.dirty++;
5363 addReply(c,shared.ok);
ed9b544e 5364}
5365
5366static void lremCommand(redisClient *c) {
d2ee16ab 5367 robj *subject, *obj = c->argv[3];
dd88747b 5368 int toremove = atoi(c->argv[2]->ptr);
5369 int removed = 0;
be02a7c0 5370 lEntry entry;
a4d1ba9a 5371
d2ee16ab
PN
5372 subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero);
5373 if (subject == NULL || checkType(c,subject,REDIS_LIST)) return;
dd88747b 5374
d2ee16ab
PN
5375 /* Make sure obj is raw when we're dealing with a ziplist */
5376 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
5377 obj = getDecodedObject(obj);
5378
5379 lIterator *li;
dd88747b 5380 if (toremove < 0) {
5381 toremove = -toremove;
be02a7c0 5382 li = lInitIterator(subject,-1,REDIS_HEAD);
d2ee16ab 5383 } else {
be02a7c0 5384 li = lInitIterator(subject,0,REDIS_TAIL);
dd88747b 5385 }
dd88747b 5386
be02a7c0
PN
5387 while (lNext(li,&entry)) {
5388 if (lEqual(&entry,obj)) {
5389 lDelete(&entry);
dd88747b 5390 server.dirty++;
5391 removed++;
3fbf9001 5392 if (toremove && removed == toremove) break;
ed9b544e 5393 }
5394 }
d2ee16ab
PN
5395 lReleaseIterator(li);
5396
5397 /* Clean up raw encoded object */
5398 if (subject->encoding == REDIS_ENCODING_ZIPLIST)
5399 decrRefCount(obj);
5400
846d8b3e 5401 if (lLength(subject) == 0) dbDelete(c->db,c->argv[1]);
dd88747b 5402 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
ed9b544e 5403}
5404
12f9d551 5405/* This is the semantic of this command:
0f5f7e9a 5406 * RPOPLPUSH srclist dstlist:
12f9d551 5407 * IF LLEN(srclist) > 0
5408 * element = RPOP srclist
5409 * LPUSH dstlist element
5410 * RETURN element
5411 * ELSE
5412 * RETURN nil
5413 * END
5414 * END
5415 *
5416 * The idea is to be able to get an element from a list in a reliable way
5417 * since the element is not just returned but pushed against another list
5418 * as well. This command was originally proposed by Ezra Zygmuntowicz.
5419 */
0f5f7e9a 5420static void rpoplpushcommand(redisClient *c) {
0f62e177 5421 robj *sobj, *value;
dd88747b 5422 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5423 checkType(c,sobj,REDIS_LIST)) return;
12f9d551 5424
0f62e177 5425 if (lLength(sobj) == 0) {
12f9d551 5426 addReply(c,shared.nullbulk);
5427 } else {
dd88747b 5428 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
0f62e177
PN
5429 if (dobj && checkType(c,dobj,REDIS_LIST)) return;
5430 value = lPop(sobj,REDIS_TAIL);
12f9d551 5431
dd88747b 5432 /* Add the element to the target list (unless it's directly
5433 * passed to some BLPOP-ing client */
0f62e177
PN
5434 if (!handleClientsWaitingListPush(c,c->argv[2],value)) {
5435 /* Create the list if the key does not exist */
5436 if (!dobj) {
1cd92e7f 5437 dobj = createZiplistObject();
09241813 5438 dbAdd(c->db,c->argv[2],dobj);
12f9d551 5439 }
0f62e177 5440 lPush(dobj,value,REDIS_HEAD);
12f9d551 5441 }
dd88747b 5442
5443 /* Send the element to the client as reply as well */
0f62e177
PN
5444 addReplyBulk(c,value);
5445
5446 /* lPop returns an object with its refcount incremented */
5447 decrRefCount(value);
dd88747b 5448
0f62e177 5449 /* Delete the source list when it is empty */
846d8b3e 5450 if (lLength(sobj) == 0) dbDelete(c->db,c->argv[1]);
dd88747b 5451 server.dirty++;
12f9d551 5452 }
5453}
5454
ed9b544e 5455/* ==================================== Sets ================================ */
5456
5457static void saddCommand(redisClient *c) {
ed9b544e 5458 robj *set;
5459
3305306f 5460 set = lookupKeyWrite(c->db,c->argv[1]);
5461 if (set == NULL) {
ed9b544e 5462 set = createSetObject();
09241813 5463 dbAdd(c->db,c->argv[1],set);
ed9b544e 5464 } else {
ed9b544e 5465 if (set->type != REDIS_SET) {
c937aa89 5466 addReply(c,shared.wrongtypeerr);
ed9b544e 5467 return;
5468 }
5469 }
5470 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
5471 incrRefCount(c->argv[2]);
5472 server.dirty++;
c937aa89 5473 addReply(c,shared.cone);
ed9b544e 5474 } else {
c937aa89 5475 addReply(c,shared.czero);
ed9b544e 5476 }
5477}
5478
5479static void sremCommand(redisClient *c) {
3305306f 5480 robj *set;
ed9b544e 5481
dd88747b 5482 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5483 checkType(c,set,REDIS_SET)) return;
5484
5485 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
5486 server.dirty++;
5487 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
09241813 5488 if (dictSize((dict*)set->ptr) == 0) dbDelete(c->db,c->argv[1]);
dd88747b 5489 addReply(c,shared.cone);
ed9b544e 5490 } else {
dd88747b 5491 addReply(c,shared.czero);
ed9b544e 5492 }
5493}
5494
a4460ef4 5495static void smoveCommand(redisClient *c) {
5496 robj *srcset, *dstset;
5497
5498 srcset = lookupKeyWrite(c->db,c->argv[1]);
5499 dstset = lookupKeyWrite(c->db,c->argv[2]);
5500
5501 /* If the source key does not exist return 0, if it's of the wrong type
5502 * raise an error */
5503 if (srcset == NULL || srcset->type != REDIS_SET) {
5504 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
5505 return;
5506 }
5507 /* Error if the destination key is not a set as well */
5508 if (dstset && dstset->type != REDIS_SET) {
5509 addReply(c,shared.wrongtypeerr);
5510 return;
5511 }
5512 /* Remove the element from the source set */
5513 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
5514 /* Key not found in the src set! return zero */
5515 addReply(c,shared.czero);
5516 return;
5517 }
3ea27d37 5518 if (dictSize((dict*)srcset->ptr) == 0 && srcset != dstset)
09241813 5519 dbDelete(c->db,c->argv[1]);
a4460ef4 5520 server.dirty++;
5521 /* Add the element to the destination set */
5522 if (!dstset) {
5523 dstset = createSetObject();
09241813 5524 dbAdd(c->db,c->argv[2],dstset);
a4460ef4 5525 }
5526 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
5527 incrRefCount(c->argv[3]);
5528 addReply(c,shared.cone);
5529}
5530
ed9b544e 5531static void sismemberCommand(redisClient *c) {
3305306f 5532 robj *set;
ed9b544e 5533
dd88747b 5534 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5535 checkType(c,set,REDIS_SET)) return;
5536
5537 if (dictFind(set->ptr,c->argv[2]))
5538 addReply(c,shared.cone);
5539 else
c937aa89 5540 addReply(c,shared.czero);
ed9b544e 5541}
5542
5543static void scardCommand(redisClient *c) {
3305306f 5544 robj *o;
ed9b544e 5545 dict *s;
dd88747b 5546
5547 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5548 checkType(c,o,REDIS_SET)) return;
e0a62c7f 5549
dd88747b 5550 s = o->ptr;
5551 addReplyUlong(c,dictSize(s));
ed9b544e 5552}
5553
12fea928 5554static void spopCommand(redisClient *c) {
5555 robj *set;
5556 dictEntry *de;
5557
dd88747b 5558 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5559 checkType(c,set,REDIS_SET)) return;
5560
5561 de = dictGetRandomKey(set->ptr);
5562 if (de == NULL) {
12fea928 5563 addReply(c,shared.nullbulk);
5564 } else {
dd88747b 5565 robj *ele = dictGetEntryKey(de);
12fea928 5566
dd88747b 5567 addReplyBulk(c,ele);
5568 dictDelete(set->ptr,ele);
5569 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
09241813 5570 if (dictSize((dict*)set->ptr) == 0) dbDelete(c->db,c->argv[1]);
dd88747b 5571 server.dirty++;
12fea928 5572 }
5573}
5574
2abb95a9 5575static void srandmemberCommand(redisClient *c) {
5576 robj *set;
5577 dictEntry *de;
5578
dd88747b 5579 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5580 checkType(c,set,REDIS_SET)) return;
5581
5582 de = dictGetRandomKey(set->ptr);
5583 if (de == NULL) {
2abb95a9 5584 addReply(c,shared.nullbulk);
5585 } else {
dd88747b 5586 robj *ele = dictGetEntryKey(de);
2abb95a9 5587
dd88747b 5588 addReplyBulk(c,ele);
2abb95a9 5589 }
5590}
5591
ed9b544e 5592static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
5593 dict **d1 = (void*) s1, **d2 = (void*) s2;
5594
3305306f 5595 return dictSize(*d1)-dictSize(*d2);
ed9b544e 5596}
5597
682ac724 5598static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
ed9b544e 5599 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5600 dictIterator *di;
5601 dictEntry *de;
5602 robj *lenobj = NULL, *dstset = NULL;
682ac724 5603 unsigned long j, cardinality = 0;
ed9b544e 5604
ed9b544e 5605 for (j = 0; j < setsnum; j++) {
5606 robj *setobj;
3305306f 5607
5608 setobj = dstkey ?
5609 lookupKeyWrite(c->db,setskeys[j]) :
5610 lookupKeyRead(c->db,setskeys[j]);
5611 if (!setobj) {
ed9b544e 5612 zfree(dv);
5faa6025 5613 if (dstkey) {
09241813 5614 if (dbDelete(c->db,dstkey))
fdcaae84 5615 server.dirty++;
0d36ded0 5616 addReply(c,shared.czero);
5faa6025 5617 } else {
4e27f268 5618 addReply(c,shared.emptymultibulk);
5faa6025 5619 }
ed9b544e 5620 return;
5621 }
ed9b544e 5622 if (setobj->type != REDIS_SET) {
5623 zfree(dv);
c937aa89 5624 addReply(c,shared.wrongtypeerr);
ed9b544e 5625 return;
5626 }
5627 dv[j] = setobj->ptr;
5628 }
5629 /* Sort sets from the smallest to largest, this will improve our
5630 * algorithm's performace */
5631 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
5632
5633 /* The first thing we should output is the total number of elements...
5634 * since this is a multi-bulk write, but at this stage we don't know
5635 * the intersection set size, so we use a trick, append an empty object
5636 * to the output list and save the pointer to later modify it with the
5637 * right length */
5638 if (!dstkey) {
5639 lenobj = createObject(REDIS_STRING,NULL);
5640 addReply(c,lenobj);
5641 decrRefCount(lenobj);
5642 } else {
5643 /* If we have a target key where to store the resulting set
5644 * create this key with an empty set inside */
5645 dstset = createSetObject();
ed9b544e 5646 }
5647
5648 /* Iterate all the elements of the first (smallest) set, and test
5649 * the element against all the other sets, if at least one set does
5650 * not include the element it is discarded */
5651 di = dictGetIterator(dv[0]);
ed9b544e 5652
5653 while((de = dictNext(di)) != NULL) {
5654 robj *ele;
5655
5656 for (j = 1; j < setsnum; j++)
5657 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
5658 if (j != setsnum)
5659 continue; /* at least one set does not contain the member */
5660 ele = dictGetEntryKey(de);
5661 if (!dstkey) {
dd88747b 5662 addReplyBulk(c,ele);
ed9b544e 5663 cardinality++;
5664 } else {
5665 dictAdd(dstset->ptr,ele,NULL);
5666 incrRefCount(ele);
5667 }
5668 }
5669 dictReleaseIterator(di);
5670
83cdfe18 5671 if (dstkey) {
3ea27d37 5672 /* Store the resulting set into the target, if the intersection
5673 * is not an empty set. */
09241813 5674 dbDelete(c->db,dstkey);
3ea27d37 5675 if (dictSize((dict*)dstset->ptr) > 0) {
09241813 5676 dbAdd(c->db,dstkey,dstset);
482b672d 5677 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
3ea27d37 5678 } else {
5679 decrRefCount(dstset);
d36c4e97 5680 addReply(c,shared.czero);
3ea27d37 5681 }
40d224a9 5682 server.dirty++;
d36c4e97 5683 } else {
5684 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
40d224a9 5685 }
ed9b544e 5686 zfree(dv);
5687}
5688
5689static void sinterCommand(redisClient *c) {
5690 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
5691}
5692
5693static void sinterstoreCommand(redisClient *c) {
5694 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
5695}
5696
f4f56e1d 5697#define REDIS_OP_UNION 0
5698#define REDIS_OP_DIFF 1
2830ca53 5699#define REDIS_OP_INTER 2
f4f56e1d 5700
5701static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
40d224a9 5702 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5703 dictIterator *di;
5704 dictEntry *de;
f4f56e1d 5705 robj *dstset = NULL;
40d224a9 5706 int j, cardinality = 0;
5707
40d224a9 5708 for (j = 0; j < setsnum; j++) {
5709 robj *setobj;
5710
5711 setobj = dstkey ?
5712 lookupKeyWrite(c->db,setskeys[j]) :
5713 lookupKeyRead(c->db,setskeys[j]);
5714 if (!setobj) {
5715 dv[j] = NULL;
5716 continue;
5717 }
5718 if (setobj->type != REDIS_SET) {
5719 zfree(dv);
5720 addReply(c,shared.wrongtypeerr);
5721 return;
5722 }
5723 dv[j] = setobj->ptr;
5724 }
5725
5726 /* We need a temp set object to store our union. If the dstkey
5727 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5728 * this set object will be the resulting object to set into the target key*/
5729 dstset = createSetObject();
5730
40d224a9 5731 /* Iterate all the elements of all the sets, add every element a single
5732 * time to the result set */
5733 for (j = 0; j < setsnum; j++) {
51829ed3 5734 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
40d224a9 5735 if (!dv[j]) continue; /* non existing keys are like empty sets */
5736
5737 di = dictGetIterator(dv[j]);
40d224a9 5738
5739 while((de = dictNext(di)) != NULL) {
5740 robj *ele;
5741
5742 /* dictAdd will not add the same element multiple times */
5743 ele = dictGetEntryKey(de);
f4f56e1d 5744 if (op == REDIS_OP_UNION || j == 0) {
5745 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
5746 incrRefCount(ele);
40d224a9 5747 cardinality++;
5748 }
f4f56e1d 5749 } else if (op == REDIS_OP_DIFF) {
5750 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
5751 cardinality--;
5752 }
40d224a9 5753 }
5754 }
5755 dictReleaseIterator(di);
51829ed3 5756
d36c4e97 5757 /* result set is empty? Exit asap. */
5758 if (op == REDIS_OP_DIFF && cardinality == 0) break;
40d224a9 5759 }
5760
f4f56e1d 5761 /* Output the content of the resulting set, if not in STORE mode */
5762 if (!dstkey) {
5763 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
5764 di = dictGetIterator(dstset->ptr);
f4f56e1d 5765 while((de = dictNext(di)) != NULL) {
5766 robj *ele;
5767
5768 ele = dictGetEntryKey(de);
dd88747b 5769 addReplyBulk(c,ele);
f4f56e1d 5770 }
5771 dictReleaseIterator(di);
d36c4e97 5772 decrRefCount(dstset);
83cdfe18
AG
5773 } else {
5774 /* If we have a target key where to store the resulting set
5775 * create this key with the result set inside */
09241813 5776 dbDelete(c->db,dstkey);
3ea27d37 5777 if (dictSize((dict*)dstset->ptr) > 0) {
09241813 5778 dbAdd(c->db,dstkey,dstset);
482b672d 5779 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
3ea27d37 5780 } else {
5781 decrRefCount(dstset);
d36c4e97 5782 addReply(c,shared.czero);
3ea27d37 5783 }
40d224a9 5784 server.dirty++;
5785 }
5786 zfree(dv);
5787}
5788
5789static void sunionCommand(redisClient *c) {
f4f56e1d 5790 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
40d224a9 5791}
5792
5793static void sunionstoreCommand(redisClient *c) {
f4f56e1d 5794 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
5795}
5796
5797static void sdiffCommand(redisClient *c) {
5798 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
5799}
5800
5801static void sdiffstoreCommand(redisClient *c) {
5802 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
40d224a9 5803}
5804
6b47e12e 5805/* ==================================== ZSets =============================== */
5806
5807/* ZSETs are ordered sets using two data structures to hold the same elements
5808 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5809 * data structure.
5810 *
5811 * The elements are added to an hash table mapping Redis objects to scores.
5812 * At the same time the elements are added to a skip list mapping scores
5813 * to Redis objects (so objects are sorted by scores in this "view"). */
5814
5815/* This skiplist implementation is almost a C translation of the original
5816 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5817 * Alternative to Balanced Trees", modified in three ways:
5818 * a) this implementation allows for repeated values.
5819 * b) the comparison is not just by key (our 'score') but by satellite data.
5820 * c) there is a back pointer, so it's a doubly linked list with the back
5821 * pointers being only at "level 1". This allows to traverse the list
5822 * from tail to head, useful for ZREVRANGE. */
5823
5824static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
5825 zskiplistNode *zn = zmalloc(sizeof(*zn));
5826
5827 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
2f4dd7e0 5828 if (level > 1)
2b37892e 5829 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
2f4dd7e0 5830 else
5831 zn->span = NULL;
6b47e12e 5832 zn->score = score;
5833 zn->obj = obj;
5834 return zn;
5835}
5836
5837static zskiplist *zslCreate(void) {
5838 int j;
5839 zskiplist *zsl;
e0a62c7f 5840
6b47e12e 5841 zsl = zmalloc(sizeof(*zsl));
5842 zsl->level = 1;
cc812361 5843 zsl->length = 0;
6b47e12e 5844 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
69d95c3e 5845 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
6b47e12e 5846 zsl->header->forward[j] = NULL;
94e543b5 5847
5848 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5849 if (j < ZSKIPLIST_MAXLEVEL-1)
5850 zsl->header->span[j] = 0;
69d95c3e 5851 }
e3870fab 5852 zsl->header->backward = NULL;
5853 zsl->tail = NULL;
6b47e12e 5854 return zsl;
5855}
5856
fd8ccf44 5857static void zslFreeNode(zskiplistNode *node) {
5858 decrRefCount(node->obj);
ad807e6f 5859 zfree(node->forward);
69d95c3e 5860 zfree(node->span);
fd8ccf44 5861 zfree(node);
5862}
5863
5864static void zslFree(zskiplist *zsl) {
ad807e6f 5865 zskiplistNode *node = zsl->header->forward[0], *next;
fd8ccf44 5866
ad807e6f 5867 zfree(zsl->header->forward);
69d95c3e 5868 zfree(zsl->header->span);
ad807e6f 5869 zfree(zsl->header);
fd8ccf44 5870 while(node) {
599379dd 5871 next = node->forward[0];
fd8ccf44 5872 zslFreeNode(node);
5873 node = next;
5874 }
ad807e6f 5875 zfree(zsl);
fd8ccf44 5876}
5877
6b47e12e 5878static int zslRandomLevel(void) {
5879 int level = 1;
5880 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
5881 level += 1;
10c2baa5 5882 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
6b47e12e 5883}
5884
5885static void zslInsert(zskiplist *zsl, double score, robj *obj) {
5886 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
2b37892e 5887 unsigned int rank[ZSKIPLIST_MAXLEVEL];
6b47e12e 5888 int i, level;
5889
5890 x = zsl->header;
5891 for (i = zsl->level-1; i >= 0; i--) {
2b37892e
PN
5892 /* store rank that is crossed to reach the insert position */
5893 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
69d95c3e 5894
9d60e6e4 5895 while (x->forward[i] &&
5896 (x->forward[i]->score < score ||
5897 (x->forward[i]->score == score &&
69d95c3e 5898 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
a50ea45c 5899 rank[i] += i > 0 ? x->span[i-1] : 1;
6b47e12e 5900 x = x->forward[i];
69d95c3e 5901 }
6b47e12e 5902 update[i] = x;
5903 }
6b47e12e 5904 /* we assume the key is not already inside, since we allow duplicated
5905 * scores, and the re-insertion of score and redis object should never
5906 * happpen since the caller of zslInsert() should test in the hash table
5907 * if the element is already inside or not. */
5908 level = zslRandomLevel();
5909 if (level > zsl->level) {
69d95c3e 5910 for (i = zsl->level; i < level; i++) {
2b37892e 5911 rank[i] = 0;
6b47e12e 5912 update[i] = zsl->header;
2b37892e 5913 update[i]->span[i-1] = zsl->length;
69d95c3e 5914 }
6b47e12e 5915 zsl->level = level;
5916 }
5917 x = zslCreateNode(level,score,obj);
5918 for (i = 0; i < level; i++) {
5919 x->forward[i] = update[i]->forward[i];
5920 update[i]->forward[i] = x;
69d95c3e
PN
5921
5922 /* update span covered by update[i] as x is inserted here */
2b37892e
PN
5923 if (i > 0) {
5924 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
5925 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
5926 }
6b47e12e 5927 }
69d95c3e
PN
5928
5929 /* increment span for untouched levels */
5930 for (i = level; i < zsl->level; i++) {
2b37892e 5931 update[i]->span[i-1]++;
69d95c3e
PN
5932 }
5933
bb975144 5934 x->backward = (update[0] == zsl->header) ? NULL : update[0];
e3870fab 5935 if (x->forward[0])
5936 x->forward[0]->backward = x;
5937 else
5938 zsl->tail = x;
cc812361 5939 zsl->length++;
6b47e12e 5940}
5941
84105336
PN
5942/* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5943void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
5944 int i;
5945 for (i = 0; i < zsl->level; i++) {
5946 if (update[i]->forward[i] == x) {
5947 if (i > 0) {
5948 update[i]->span[i-1] += x->span[i-1] - 1;
5949 }
5950 update[i]->forward[i] = x->forward[i];
5951 } else {
5952 /* invariant: i > 0, because update[0]->forward[0]
5953 * is always equal to x */
5954 update[i]->span[i-1] -= 1;
5955 }
5956 }
5957 if (x->forward[0]) {
5958 x->forward[0]->backward = x->backward;
5959 } else {
5960 zsl->tail = x->backward;
5961 }
5962 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
5963 zsl->level--;
5964 zsl->length--;
5965}
5966
50c55df5 5967/* Delete an element with matching score/object from the skiplist. */
fd8ccf44 5968static int zslDelete(zskiplist *zsl, double score, robj *obj) {
e197b441 5969 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5970 int i;
5971
5972 x = zsl->header;
5973 for (i = zsl->level-1; i >= 0; i--) {
9d60e6e4 5974 while (x->forward[i] &&
5975 (x->forward[i]->score < score ||
5976 (x->forward[i]->score == score &&
5977 compareStringObjects(x->forward[i]->obj,obj) < 0)))
e197b441 5978 x = x->forward[i];
5979 update[i] = x;
5980 }
5981 /* We may have multiple elements with the same score, what we need
5982 * is to find the element with both the right score and object. */
5983 x = x->forward[0];
bf028098 5984 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
84105336 5985 zslDeleteNode(zsl, x, update);
9d60e6e4 5986 zslFreeNode(x);
9d60e6e4 5987 return 1;
5988 } else {
5989 return 0; /* not found */
e197b441 5990 }
5991 return 0; /* not found */
fd8ccf44 5992}
5993
1807985b 5994/* Delete all the elements with score between min and max from the skiplist.
5995 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5996 * Note that this function takes the reference to the hash table view of the
5997 * sorted set, in order to remove the elements from the hash table too. */
f84d3933 5998static unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
1807985b 5999 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
6000 unsigned long removed = 0;
6001 int i;
6002
6003 x = zsl->header;
6004 for (i = zsl->level-1; i >= 0; i--) {
6005 while (x->forward[i] && x->forward[i]->score < min)
6006 x = x->forward[i];
6007 update[i] = x;
6008 }
6009 /* We may have multiple elements with the same score, what we need
6010 * is to find the element with both the right score and object. */
6011 x = x->forward[0];
6012 while (x && x->score <= max) {
84105336
PN
6013 zskiplistNode *next = x->forward[0];
6014 zslDeleteNode(zsl, x, update);
1807985b 6015 dictDelete(dict,x->obj);
6016 zslFreeNode(x);
1807985b 6017 removed++;
6018 x = next;
6019 }
6020 return removed; /* not found */
6021}
1807985b 6022
9212eafd 6023/* Delete all the elements with rank between start and end from the skiplist.
2424490f 6024 * Start and end are inclusive. Note that start and end need to be 1-based */
9212eafd
PN
6025static unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
6026 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
6027 unsigned long traversed = 0, removed = 0;
6028 int i;
6029
9212eafd
PN
6030 x = zsl->header;
6031 for (i = zsl->level-1; i >= 0; i--) {
6032 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
6033 traversed += i > 0 ? x->span[i-1] : 1;
6034 x = x->forward[i];
1807985b 6035 }
9212eafd
PN
6036 update[i] = x;
6037 }
6038
6039 traversed++;
6040 x = x->forward[0];
6041 while (x && traversed <= end) {
84105336
PN
6042 zskiplistNode *next = x->forward[0];
6043 zslDeleteNode(zsl, x, update);
1807985b 6044 dictDelete(dict,x->obj);
6045 zslFreeNode(x);
1807985b 6046 removed++;
9212eafd 6047 traversed++;
1807985b 6048 x = next;
6049 }
9212eafd 6050 return removed;
1807985b 6051}
6052
50c55df5 6053/* Find the first node having a score equal or greater than the specified one.
6054 * Returns NULL if there is no match. */
6055static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
6056 zskiplistNode *x;
6057 int i;
6058
6059 x = zsl->header;
6060 for (i = zsl->level-1; i >= 0; i--) {
6061 while (x->forward[i] && x->forward[i]->score < score)
6062 x = x->forward[i];
6063 }
6064 /* We may have multiple elements with the same score, what we need
6065 * is to find the element with both the right score and object. */
6066 return x->forward[0];
6067}
6068
27b0ccca
PN
6069/* Find the rank for an element by both score and key.
6070 * Returns 0 when the element cannot be found, rank otherwise.
6071 * Note that the rank is 1-based due to the span of zsl->header to the
6072 * first element. */
6073static unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
6074 zskiplistNode *x;
6075 unsigned long rank = 0;
6076 int i;
6077
6078 x = zsl->header;
6079 for (i = zsl->level-1; i >= 0; i--) {
6080 while (x->forward[i] &&
6081 (x->forward[i]->score < score ||
6082 (x->forward[i]->score == score &&
6083 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
a50ea45c 6084 rank += i > 0 ? x->span[i-1] : 1;
27b0ccca
PN
6085 x = x->forward[i];
6086 }
6087
6088 /* x might be equal to zsl->header, so test if obj is non-NULL */
bf028098 6089 if (x->obj && equalStringObjects(x->obj,o)) {
27b0ccca
PN
6090 return rank;
6091 }
6092 }
6093 return 0;
6094}
6095
e74825c2
PN
6096/* Finds an element by its rank. The rank argument needs to be 1-based. */
6097zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
6098 zskiplistNode *x;
6099 unsigned long traversed = 0;
6100 int i;
6101
6102 x = zsl->header;
6103 for (i = zsl->level-1; i >= 0; i--) {
dd88747b 6104 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
6105 {
a50ea45c 6106 traversed += i > 0 ? x->span[i-1] : 1;
e74825c2
PN
6107 x = x->forward[i];
6108 }
e74825c2
PN
6109 if (traversed == rank) {
6110 return x;
6111 }
6112 }
6113 return NULL;
6114}
6115
fd8ccf44 6116/* The actual Z-commands implementations */
6117
7db723ad 6118/* This generic command implements both ZADD and ZINCRBY.
e2665397 6119 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
7db723ad 6120 * the increment if the operation is a ZINCRBY (doincrement == 1). */
e2665397 6121static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
fd8ccf44 6122 robj *zsetobj;
6123 zset *zs;
6124 double *score;
6125
5fc9229c 6126 if (isnan(scoreval)) {
6127 addReplySds(c,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
6128 return;
6129 }
6130
e2665397 6131 zsetobj = lookupKeyWrite(c->db,key);
fd8ccf44 6132 if (zsetobj == NULL) {
6133 zsetobj = createZsetObject();
09241813 6134 dbAdd(c->db,key,zsetobj);
fd8ccf44 6135 } else {
6136 if (zsetobj->type != REDIS_ZSET) {
6137 addReply(c,shared.wrongtypeerr);
6138 return;
6139 }
6140 }
fd8ccf44 6141 zs = zsetobj->ptr;
e2665397 6142
7db723ad 6143 /* Ok now since we implement both ZADD and ZINCRBY here the code
e2665397 6144 * needs to handle the two different conditions. It's all about setting
6145 * '*score', that is, the new score to set, to the right value. */
6146 score = zmalloc(sizeof(double));
6147 if (doincrement) {
6148 dictEntry *de;
6149
6150 /* Read the old score. If the element was not present starts from 0 */
6151 de = dictFind(zs->dict,ele);
6152 if (de) {
6153 double *oldscore = dictGetEntryVal(de);
6154 *score = *oldscore + scoreval;
6155 } else {
6156 *score = scoreval;
6157 }
5fc9229c 6158 if (isnan(*score)) {
6159 addReplySds(c,
6160 sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
6161 zfree(score);
6162 /* Note that we don't need to check if the zset may be empty and
6163 * should be removed here, as we can only obtain Nan as score if
6164 * there was already an element in the sorted set. */
6165 return;
6166 }
e2665397 6167 } else {
6168 *score = scoreval;
6169 }
6170
6171 /* What follows is a simple remove and re-insert operation that is common
7db723ad 6172 * to both ZADD and ZINCRBY... */
e2665397 6173 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
fd8ccf44 6174 /* case 1: New element */
e2665397 6175 incrRefCount(ele); /* added to hash */
6176 zslInsert(zs->zsl,*score,ele);
6177 incrRefCount(ele); /* added to skiplist */
fd8ccf44 6178 server.dirty++;
e2665397 6179 if (doincrement)
e2665397 6180 addReplyDouble(c,*score);
91d71bfc 6181 else
6182 addReply(c,shared.cone);
fd8ccf44 6183 } else {
6184 dictEntry *de;
6185 double *oldscore;
e0a62c7f 6186
fd8ccf44 6187 /* case 2: Score update operation */
e2665397 6188 de = dictFind(zs->dict,ele);
dfc5e96c 6189 redisAssert(de != NULL);
fd8ccf44 6190 oldscore = dictGetEntryVal(de);
6191 if (*score != *oldscore) {
6192 int deleted;
6193
e2665397 6194 /* Remove and insert the element in the skip list with new score */
6195 deleted = zslDelete(zs->zsl,*oldscore,ele);
dfc5e96c 6196 redisAssert(deleted != 0);
e2665397 6197 zslInsert(zs->zsl,*score,ele);
6198 incrRefCount(ele);
6199 /* Update the score in the hash table */
6200 dictReplace(zs->dict,ele,score);
fd8ccf44 6201 server.dirty++;
2161a965 6202 } else {
6203 zfree(score);
fd8ccf44 6204 }
e2665397 6205 if (doincrement)
6206 addReplyDouble(c,*score);
6207 else
6208 addReply(c,shared.czero);
fd8ccf44 6209 }
6210}
6211
e2665397 6212static void zaddCommand(redisClient *c) {
6213 double scoreval;
6214
bd79a6bd 6215 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
e2665397 6216 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
6217}
6218
7db723ad 6219static void zincrbyCommand(redisClient *c) {
e2665397 6220 double scoreval;
6221
bd79a6bd 6222 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
e2665397 6223 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
6224}
6225
1b7106e7 6226static void zremCommand(redisClient *c) {
6227 robj *zsetobj;
6228 zset *zs;
dd88747b 6229 dictEntry *de;
6230 double *oldscore;
6231 int deleted;
1b7106e7 6232
dd88747b 6233 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6234 checkType(c,zsetobj,REDIS_ZSET)) return;
1b7106e7 6235
dd88747b 6236 zs = zsetobj->ptr;
6237 de = dictFind(zs->dict,c->argv[2]);
6238 if (de == NULL) {
6239 addReply(c,shared.czero);
6240 return;
1b7106e7 6241 }
dd88747b 6242 /* Delete from the skiplist */
6243 oldscore = dictGetEntryVal(de);
6244 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
6245 redisAssert(deleted != 0);
6246
6247 /* Delete from the hash table */
6248 dictDelete(zs->dict,c->argv[2]);
6249 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
09241813 6250 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
dd88747b 6251 server.dirty++;
6252 addReply(c,shared.cone);
1b7106e7 6253}
6254
1807985b 6255static void zremrangebyscoreCommand(redisClient *c) {
bbe025e0
AM
6256 double min;
6257 double max;
dd88747b 6258 long deleted;
1807985b 6259 robj *zsetobj;
6260 zset *zs;
6261
bd79a6bd
PN
6262 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
6263 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
bbe025e0 6264
dd88747b 6265 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6266 checkType(c,zsetobj,REDIS_ZSET)) return;
1807985b 6267
dd88747b 6268 zs = zsetobj->ptr;
6269 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
6270 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
09241813 6271 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
dd88747b 6272 server.dirty += deleted;
482b672d 6273 addReplyLongLong(c,deleted);
1807985b 6274}
6275
9212eafd 6276static void zremrangebyrankCommand(redisClient *c) {
bbe025e0
AM
6277 long start;
6278 long end;
dd88747b 6279 int llen;
6280 long deleted;
9212eafd
PN
6281 robj *zsetobj;
6282 zset *zs;
6283
bd79a6bd
PN
6284 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6285 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
bbe025e0 6286
dd88747b 6287 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6288 checkType(c,zsetobj,REDIS_ZSET)) return;
6289 zs = zsetobj->ptr;
6290 llen = zs->zsl->length;
9212eafd 6291
dd88747b 6292 /* convert negative indexes */
6293 if (start < 0) start = llen+start;
6294 if (end < 0) end = llen+end;
6295 if (start < 0) start = 0;
6296 if (end < 0) end = 0;
9212eafd 6297
dd88747b 6298 /* indexes sanity checks */
6299 if (start > end || start >= llen) {
6300 addReply(c,shared.czero);
6301 return;
9212eafd 6302 }
dd88747b 6303 if (end >= llen) end = llen-1;
6304
6305 /* increment start and end because zsl*Rank functions
6306 * use 1-based rank */
6307 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
6308 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
09241813 6309 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
dd88747b 6310 server.dirty += deleted;
482b672d 6311 addReplyLongLong(c, deleted);
9212eafd
PN
6312}
6313
8f92e768
PN
6314typedef struct {
6315 dict *dict;
6316 double weight;
6317} zsetopsrc;
6318
6319static int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
6320 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
6321 unsigned long size1, size2;
6322 size1 = d1->dict ? dictSize(d1->dict) : 0;
6323 size2 = d2->dict ? dictSize(d2->dict) : 0;
6324 return size1 - size2;
6325}
6326
d2764cd6
PN
6327#define REDIS_AGGR_SUM 1
6328#define REDIS_AGGR_MIN 2
6329#define REDIS_AGGR_MAX 3
bc000c1d 6330#define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
d2764cd6
PN
6331
6332inline static void zunionInterAggregate(double *target, double val, int aggregate) {
6333 if (aggregate == REDIS_AGGR_SUM) {
6334 *target = *target + val;
6335 } else if (aggregate == REDIS_AGGR_MIN) {
6336 *target = val < *target ? val : *target;
6337 } else if (aggregate == REDIS_AGGR_MAX) {
6338 *target = val > *target ? val : *target;
6339 } else {
6340 /* safety net */
f83c6cb5 6341 redisPanic("Unknown ZUNION/INTER aggregate type");
d2764cd6
PN
6342 }
6343}
6344
2830ca53 6345static void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
bc000c1d 6346 int i, j, setnum;
d2764cd6 6347 int aggregate = REDIS_AGGR_SUM;
8f92e768 6348 zsetopsrc *src;
2830ca53
PN
6349 robj *dstobj;
6350 zset *dstzset;
b287c9bb
PN
6351 dictIterator *di;
6352 dictEntry *de;
6353
bc000c1d
JC
6354 /* expect setnum input keys to be given */
6355 setnum = atoi(c->argv[2]->ptr);
6356 if (setnum < 1) {
5d373da9 6357 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
2830ca53 6358 return;
b287c9bb 6359 }
2830ca53
PN
6360
6361 /* test if the expected number of keys would overflow */
bc000c1d 6362 if (3+setnum > c->argc) {
b287c9bb
PN
6363 addReply(c,shared.syntaxerr);
6364 return;
6365 }
6366
2830ca53 6367 /* read keys to be used for input */
bc000c1d
JC
6368 src = zmalloc(sizeof(zsetopsrc) * setnum);
6369 for (i = 0, j = 3; i < setnum; i++, j++) {
6370 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
6371 if (!obj) {
8f92e768 6372 src[i].dict = NULL;
b287c9bb 6373 } else {
bc000c1d
JC
6374 if (obj->type == REDIS_ZSET) {
6375 src[i].dict = ((zset*)obj->ptr)->dict;
6376 } else if (obj->type == REDIS_SET) {
6377 src[i].dict = (obj->ptr);
6378 } else {
8f92e768 6379 zfree(src);
b287c9bb
PN
6380 addReply(c,shared.wrongtypeerr);
6381 return;
6382 }
b287c9bb 6383 }
2830ca53
PN
6384
6385 /* default all weights to 1 */
8f92e768 6386 src[i].weight = 1.0;
b287c9bb
PN
6387 }
6388
2830ca53
PN
6389 /* parse optional extra arguments */
6390 if (j < c->argc) {
d2764cd6 6391 int remaining = c->argc - j;
b287c9bb 6392
2830ca53 6393 while (remaining) {
bc000c1d 6394 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
2830ca53 6395 j++; remaining--;
bc000c1d 6396 for (i = 0; i < setnum; i++, j++, remaining--) {
bd79a6bd 6397 if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK)
bbe025e0 6398 return;
2830ca53 6399 }
d2764cd6
PN
6400 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
6401 j++; remaining--;
6402 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
6403 aggregate = REDIS_AGGR_SUM;
6404 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
6405 aggregate = REDIS_AGGR_MIN;
6406 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
6407 aggregate = REDIS_AGGR_MAX;
6408 } else {
6409 zfree(src);
6410 addReply(c,shared.syntaxerr);
6411 return;
6412 }
6413 j++; remaining--;
2830ca53 6414 } else {
8f92e768 6415 zfree(src);
2830ca53
PN
6416 addReply(c,shared.syntaxerr);
6417 return;
6418 }
6419 }
6420 }
b287c9bb 6421
d2764cd6
PN
6422 /* sort sets from the smallest to largest, this will improve our
6423 * algorithm's performance */
bc000c1d 6424 qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);
d2764cd6 6425
2830ca53
PN
6426 dstobj = createZsetObject();
6427 dstzset = dstobj->ptr;
6428
6429 if (op == REDIS_OP_INTER) {
8f92e768
PN
6430 /* skip going over all entries if the smallest zset is NULL or empty */
6431 if (src[0].dict && dictSize(src[0].dict) > 0) {
6432 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6433 * from small to large, all src[i > 0].dict are non-empty too */
6434 di = dictGetIterator(src[0].dict);
2830ca53 6435 while((de = dictNext(di)) != NULL) {
d2764cd6 6436 double *score = zmalloc(sizeof(double)), value;
bc000c1d 6437 *score = src[0].weight * zunionInterDictValue(de);
2830ca53 6438
bc000c1d 6439 for (j = 1; j < setnum; j++) {
d2764cd6 6440 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
2830ca53 6441 if (other) {
bc000c1d 6442 value = src[j].weight * zunionInterDictValue(other);
d2764cd6 6443 zunionInterAggregate(score, value, aggregate);
2830ca53
PN
6444 } else {
6445 break;
6446 }
6447 }
b287c9bb 6448
2830ca53 6449 /* skip entry when not present in every source dict */
bc000c1d 6450 if (j != setnum) {
2830ca53
PN
6451 zfree(score);
6452 } else {
6453 robj *o = dictGetEntryKey(de);
6454 dictAdd(dstzset->dict,o,score);
6455 incrRefCount(o); /* added to dictionary */
6456 zslInsert(dstzset->zsl,*score,o);
6457 incrRefCount(o); /* added to skiplist */
b287c9bb
PN
6458 }
6459 }
2830ca53
PN
6460 dictReleaseIterator(di);
6461 }
6462 } else if (op == REDIS_OP_UNION) {
bc000c1d 6463 for (i = 0; i < setnum; i++) {
8f92e768 6464 if (!src[i].dict) continue;
2830ca53 6465
8f92e768 6466 di = dictGetIterator(src[i].dict);
2830ca53
PN
6467 while((de = dictNext(di)) != NULL) {
6468 /* skip key when already processed */
6469 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
6470
d2764cd6 6471 double *score = zmalloc(sizeof(double)), value;
bc000c1d 6472 *score = src[i].weight * zunionInterDictValue(de);
2830ca53 6473
d2764cd6
PN
6474 /* because the zsets are sorted by size, its only possible
6475 * for sets at larger indices to hold this entry */
bc000c1d 6476 for (j = (i+1); j < setnum; j++) {
d2764cd6 6477 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
2830ca53 6478 if (other) {
bc000c1d 6479 value = src[j].weight * zunionInterDictValue(other);
d2764cd6 6480 zunionInterAggregate(score, value, aggregate);
2830ca53
PN
6481 }
6482 }
b287c9bb 6483
2830ca53
PN
6484 robj *o = dictGetEntryKey(de);
6485 dictAdd(dstzset->dict,o,score);
6486 incrRefCount(o); /* added to dictionary */
6487 zslInsert(dstzset->zsl,*score,o);
6488 incrRefCount(o); /* added to skiplist */
6489 }
6490 dictReleaseIterator(di);
b287c9bb 6491 }
2830ca53
PN
6492 } else {
6493 /* unknown operator */
6494 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
b287c9bb
PN
6495 }
6496
09241813 6497 dbDelete(c->db,dstkey);
3ea27d37 6498 if (dstzset->zsl->length) {
09241813 6499 dbAdd(c->db,dstkey,dstobj);
482b672d 6500 addReplyLongLong(c, dstzset->zsl->length);
3ea27d37 6501 server.dirty++;
6502 } else {
8bca8773 6503 decrRefCount(dstobj);
3ea27d37 6504 addReply(c, shared.czero);
6505 }
8f92e768 6506 zfree(src);
b287c9bb
PN
6507}
6508
5d373da9 6509static void zunionstoreCommand(redisClient *c) {
2830ca53 6510 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
b287c9bb
PN
6511}
6512
5d373da9 6513static void zinterstoreCommand(redisClient *c) {
2830ca53 6514 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
b287c9bb
PN
6515}
6516
e3870fab 6517static void zrangeGenericCommand(redisClient *c, int reverse) {
cc812361 6518 robj *o;
bbe025e0
AM
6519 long start;
6520 long end;
752da584 6521 int withscores = 0;
dd88747b 6522 int llen;
6523 int rangelen, j;
6524 zset *zsetobj;
6525 zskiplist *zsl;
6526 zskiplistNode *ln;
6527 robj *ele;
752da584 6528
bd79a6bd
PN
6529 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6530 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
bbe025e0 6531
752da584 6532 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
6533 withscores = 1;
6534 } else if (c->argc >= 5) {
6535 addReply(c,shared.syntaxerr);
6536 return;
6537 }
cc812361 6538
4e27f268 6539 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6540 || checkType(c,o,REDIS_ZSET)) return;
dd88747b 6541 zsetobj = o->ptr;
6542 zsl = zsetobj->zsl;
6543 llen = zsl->length;
cc812361 6544
dd88747b 6545 /* convert negative indexes */
6546 if (start < 0) start = llen+start;
6547 if (end < 0) end = llen+end;
6548 if (start < 0) start = 0;
6549 if (end < 0) end = 0;
cc812361 6550
dd88747b 6551 /* indexes sanity checks */
6552 if (start > end || start >= llen) {
6553 /* Out of range start or start > end result in empty list */
6554 addReply(c,shared.emptymultibulk);
6555 return;
6556 }
6557 if (end >= llen) end = llen-1;
6558 rangelen = (end-start)+1;
cc812361 6559
dd88747b 6560 /* check if starting point is trivial, before searching
6561 * the element in log(N) time */
6562 if (reverse) {
6563 ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start);
6564 } else {
6565 ln = start == 0 ?
6566 zsl->header->forward[0] : zslGetElementByRank(zsl, start+1);
6567 }
cc812361 6568
dd88747b 6569 /* Return the result in form of a multi-bulk reply */
6570 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
6571 withscores ? (rangelen*2) : rangelen));
6572 for (j = 0; j < rangelen; j++) {
6573 ele = ln->obj;
6574 addReplyBulk(c,ele);
6575 if (withscores)
6576 addReplyDouble(c,ln->score);
6577 ln = reverse ? ln->backward : ln->forward[0];
cc812361 6578 }
6579}
6580
e3870fab 6581static void zrangeCommand(redisClient *c) {
6582 zrangeGenericCommand(c,0);
6583}
6584
6585static void zrevrangeCommand(redisClient *c) {
6586 zrangeGenericCommand(c,1);
6587}
6588
f44dd428 6589/* This command implements both ZRANGEBYSCORE and ZCOUNT.
6590 * If justcount is non-zero, just the count is returned. */
6591static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
50c55df5 6592 robj *o;
f44dd428 6593 double min, max;
6594 int minex = 0, maxex = 0; /* are min or max exclusive? */
80181f78 6595 int offset = 0, limit = -1;
0500ef27
SH
6596 int withscores = 0;
6597 int badsyntax = 0;
6598
f44dd428 6599 /* Parse the min-max interval. If one of the values is prefixed
6600 * by the "(" character, it's considered "open". For instance
6601 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6602 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6603 if (((char*)c->argv[2]->ptr)[0] == '(') {
6604 min = strtod((char*)c->argv[2]->ptr+1,NULL);
6605 minex = 1;
6606 } else {
6607 min = strtod(c->argv[2]->ptr,NULL);
6608 }
6609 if (((char*)c->argv[3]->ptr)[0] == '(') {
6610 max = strtod((char*)c->argv[3]->ptr+1,NULL);
6611 maxex = 1;
6612 } else {
6613 max = strtod(c->argv[3]->ptr,NULL);
6614 }
6615
6616 /* Parse "WITHSCORES": note that if the command was called with
6617 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6618 * enter the following paths to parse WITHSCORES and LIMIT. */
0500ef27 6619 if (c->argc == 5 || c->argc == 8) {
3a3978b1 6620 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
6621 withscores = 1;
6622 else
6623 badsyntax = 1;
0500ef27 6624 }
3a3978b1 6625 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
0500ef27 6626 badsyntax = 1;
0500ef27 6627 if (badsyntax) {
454d4e43 6628 addReplySds(c,
6629 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
80181f78 6630 return;
0500ef27
SH
6631 }
6632
f44dd428 6633 /* Parse "LIMIT" */
0500ef27 6634 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
80181f78 6635 addReply(c,shared.syntaxerr);
6636 return;
0500ef27 6637 } else if (c->argc == (7 + withscores)) {
80181f78 6638 offset = atoi(c->argv[5]->ptr);
6639 limit = atoi(c->argv[6]->ptr);
0b13687c 6640 if (offset < 0) offset = 0;
80181f78 6641 }
50c55df5 6642
f44dd428 6643 /* Ok, lookup the key and get the range */
50c55df5 6644 o = lookupKeyRead(c->db,c->argv[1]);
6645 if (o == NULL) {
4e27f268 6646 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
50c55df5 6647 } else {
6648 if (o->type != REDIS_ZSET) {
6649 addReply(c,shared.wrongtypeerr);
6650 } else {
6651 zset *zsetobj = o->ptr;
6652 zskiplist *zsl = zsetobj->zsl;
6653 zskiplistNode *ln;
f44dd428 6654 robj *ele, *lenobj = NULL;
6655 unsigned long rangelen = 0;
50c55df5 6656
f44dd428 6657 /* Get the first node with the score >= min, or with
6658 * score > min if 'minex' is true. */
50c55df5 6659 ln = zslFirstWithScore(zsl,min);
f44dd428 6660 while (minex && ln && ln->score == min) ln = ln->forward[0];
6661
50c55df5 6662 if (ln == NULL) {
6663 /* No element matching the speciifed interval */
f44dd428 6664 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
50c55df5 6665 return;
6666 }
6667
6668 /* We don't know in advance how many matching elements there
6669 * are in the list, so we push this object that will represent
6670 * the multi-bulk length in the output buffer, and will "fix"
6671 * it later */
f44dd428 6672 if (!justcount) {
6673 lenobj = createObject(REDIS_STRING,NULL);
6674 addReply(c,lenobj);
6675 decrRefCount(lenobj);
6676 }
50c55df5 6677
f44dd428 6678 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
80181f78 6679 if (offset) {
6680 offset--;
6681 ln = ln->forward[0];
6682 continue;
6683 }
6684 if (limit == 0) break;
f44dd428 6685 if (!justcount) {
6686 ele = ln->obj;
dd88747b 6687 addReplyBulk(c,ele);
f44dd428 6688 if (withscores)
6689 addReplyDouble(c,ln->score);
6690 }
50c55df5 6691 ln = ln->forward[0];
6692 rangelen++;
80181f78 6693 if (limit > 0) limit--;
50c55df5 6694 }
f44dd428 6695 if (justcount) {
482b672d 6696 addReplyLongLong(c,(long)rangelen);
f44dd428 6697 } else {
6698 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
6699 withscores ? (rangelen*2) : rangelen);
6700 }
50c55df5 6701 }
6702 }
6703}
6704
f44dd428 6705static void zrangebyscoreCommand(redisClient *c) {
6706 genericZrangebyscoreCommand(c,0);
6707}
6708
6709static void zcountCommand(redisClient *c) {
6710 genericZrangebyscoreCommand(c,1);
6711}
6712
3c41331e 6713static void zcardCommand(redisClient *c) {
e197b441 6714 robj *o;
6715 zset *zs;
dd88747b 6716
6717 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6718 checkType(c,o,REDIS_ZSET)) return;
6719
6720 zs = o->ptr;
6721 addReplyUlong(c,zs->zsl->length);
e197b441 6722}
6723
6e333bbe 6724static void zscoreCommand(redisClient *c) {
6725 robj *o;
6726 zset *zs;
dd88747b 6727 dictEntry *de;
6728
6729 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6730 checkType(c,o,REDIS_ZSET)) return;
6731
6732 zs = o->ptr;
6733 de = dictFind(zs->dict,c->argv[2]);
6734 if (!de) {
96d8b4ee 6735 addReply(c,shared.nullbulk);
6e333bbe 6736 } else {
dd88747b 6737 double *score = dictGetEntryVal(de);
6e333bbe 6738
dd88747b 6739 addReplyDouble(c,*score);
6e333bbe 6740 }
6741}
6742
798d9e55 6743static void zrankGenericCommand(redisClient *c, int reverse) {
69d95c3e 6744 robj *o;
dd88747b 6745 zset *zs;
6746 zskiplist *zsl;
6747 dictEntry *de;
6748 unsigned long rank;
6749 double *score;
6750
6751 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6752 checkType(c,o,REDIS_ZSET)) return;
6753
6754 zs = o->ptr;
6755 zsl = zs->zsl;
6756 de = dictFind(zs->dict,c->argv[2]);
6757 if (!de) {
69d95c3e
PN
6758 addReply(c,shared.nullbulk);
6759 return;
6760 }
69d95c3e 6761
dd88747b 6762 score = dictGetEntryVal(de);
6763 rank = zslGetRank(zsl, *score, c->argv[2]);
6764 if (rank) {
6765 if (reverse) {
482b672d 6766 addReplyLongLong(c, zsl->length - rank);
27b0ccca 6767 } else {
482b672d 6768 addReplyLongLong(c, rank-1);
69d95c3e 6769 }
dd88747b 6770 } else {
6771 addReply(c,shared.nullbulk);
978c2c94 6772 }
6773}
6774
798d9e55
PN
6775static void zrankCommand(redisClient *c) {
6776 zrankGenericCommand(c, 0);
6777}
6778
6779static void zrevrankCommand(redisClient *c) {
6780 zrankGenericCommand(c, 1);
6781}
6782
7fb16bac
PN
6783/* ========================= Hashes utility functions ======================= */
6784#define REDIS_HASH_KEY 1
6785#define REDIS_HASH_VALUE 2
978c2c94 6786
7fb16bac
PN
6787/* Check the length of a number of objects to see if we need to convert a
6788 * zipmap to a real hash. Note that we only check string encoded objects
6789 * as their string length can be queried in constant time. */
6790static void hashTryConversion(robj *subject, robj **argv, int start, int end) {
6791 int i;
6792 if (subject->encoding != REDIS_ENCODING_ZIPMAP) return;
978c2c94 6793
7fb16bac
PN
6794 for (i = start; i <= end; i++) {
6795 if (argv[i]->encoding == REDIS_ENCODING_RAW &&
6796 sdslen(argv[i]->ptr) > server.hash_max_zipmap_value)
6797 {
6798 convertToRealHash(subject);
978c2c94 6799 return;
6800 }
6801 }
7fb16bac 6802}
bae2c7ec 6803
97224de7
PN
6804/* Encode given objects in-place when the hash uses a dict. */
6805static void hashTryObjectEncoding(robj *subject, robj **o1, robj **o2) {
6806 if (subject->encoding == REDIS_ENCODING_HT) {
3f973463
PN
6807 if (o1) *o1 = tryObjectEncoding(*o1);
6808 if (o2) *o2 = tryObjectEncoding(*o2);
97224de7
PN
6809 }
6810}
6811
7fb16bac 6812/* Get the value from a hash identified by key. Returns either a string
a3f3af86
PN
6813 * object or NULL if the value cannot be found. The refcount of the object
6814 * is always increased by 1 when the value was found. */
7fb16bac
PN
6815static robj *hashGet(robj *o, robj *key) {
6816 robj *value = NULL;
978c2c94 6817 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
7fb16bac
PN
6818 unsigned char *v;
6819 unsigned int vlen;
6820 key = getDecodedObject(key);
6821 if (zipmapGet(o->ptr,key->ptr,sdslen(key->ptr),&v,&vlen)) {
6822 value = createStringObject((char*)v,vlen);
6823 }
6824 decrRefCount(key);
6825 } else {
6826 dictEntry *de = dictFind(o->ptr,key);
6827 if (de != NULL) {
6828 value = dictGetEntryVal(de);
a3f3af86 6829 incrRefCount(value);
7fb16bac
PN
6830 }
6831 }
6832 return value;
6833}
978c2c94 6834
7fb16bac
PN
6835/* Test if the key exists in the given hash. Returns 1 if the key
6836 * exists and 0 when it doesn't. */
6837static int hashExists(robj *o, robj *key) {
6838 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6839 key = getDecodedObject(key);
6840 if (zipmapExists(o->ptr,key->ptr,sdslen(key->ptr))) {
6841 decrRefCount(key);
6842 return 1;
6843 }
6844 decrRefCount(key);
6845 } else {
6846 if (dictFind(o->ptr,key) != NULL) {
6847 return 1;
6848 }
6849 }
6850 return 0;
6851}
bae2c7ec 6852
7fb16bac
PN
6853/* Add an element, discard the old if the key already exists.
6854 * Return 0 on insert and 1 on update. */
feb8d7e6 6855static int hashSet(robj *o, robj *key, robj *value) {
7fb16bac
PN
6856 int update = 0;
6857 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6858 key = getDecodedObject(key);
6859 value = getDecodedObject(value);
6860 o->ptr = zipmapSet(o->ptr,
6861 key->ptr,sdslen(key->ptr),
6862 value->ptr,sdslen(value->ptr), &update);
6863 decrRefCount(key);
6864 decrRefCount(value);
6865
6866 /* Check if the zipmap needs to be upgraded to a real hash table */
6867 if (zipmapLen(o->ptr) > server.hash_max_zipmap_entries)
bae2c7ec 6868 convertToRealHash(o);
978c2c94 6869 } else {
7fb16bac
PN
6870 if (dictReplace(o->ptr,key,value)) {
6871 /* Insert */
6872 incrRefCount(key);
978c2c94 6873 } else {
7fb16bac 6874 /* Update */
978c2c94 6875 update = 1;
6876 }
7fb16bac 6877 incrRefCount(value);
978c2c94 6878 }
7fb16bac 6879 return update;
978c2c94 6880}
6881
7fb16bac
PN
6882/* Delete an element from a hash.
6883 * Return 1 on deleted and 0 on not found. */
6884static int hashDelete(robj *o, robj *key) {
6885 int deleted = 0;
6886 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6887 key = getDecodedObject(key);
6888 o->ptr = zipmapDel(o->ptr,key->ptr,sdslen(key->ptr), &deleted);
6889 decrRefCount(key);
6890 } else {
6891 deleted = dictDelete((dict*)o->ptr,key) == DICT_OK;
6892 /* Always check if the dictionary needs a resize after a delete. */
6893 if (deleted && htNeedsResize(o->ptr)) dictResize(o->ptr);
d33278d1 6894 }
7fb16bac
PN
6895 return deleted;
6896}
d33278d1 6897
7fb16bac 6898/* Return the number of elements in a hash. */
c811bb38 6899static unsigned long hashLength(robj *o) {
7fb16bac
PN
6900 return (o->encoding == REDIS_ENCODING_ZIPMAP) ?
6901 zipmapLen((unsigned char*)o->ptr) : dictSize((dict*)o->ptr);
6902}
6903
6904/* Structure to hold hash iteration abstration. Note that iteration over
6905 * hashes involves both fields and values. Because it is possible that
6906 * not both are required, store pointers in the iterator to avoid
6907 * unnecessary memory allocation for fields/values. */
6908typedef struct {
6909 int encoding;
6910 unsigned char *zi;
6911 unsigned char *zk, *zv;
6912 unsigned int zklen, zvlen;
6913
6914 dictIterator *di;
6915 dictEntry *de;
6916} hashIterator;
6917
c44d3b56
PN
6918static hashIterator *hashInitIterator(robj *subject) {
6919 hashIterator *hi = zmalloc(sizeof(hashIterator));
7fb16bac
PN
6920 hi->encoding = subject->encoding;
6921 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6922 hi->zi = zipmapRewind(subject->ptr);
6923 } else if (hi->encoding == REDIS_ENCODING_HT) {
6924 hi->di = dictGetIterator(subject->ptr);
d33278d1 6925 } else {
7fb16bac 6926 redisAssert(NULL);
d33278d1 6927 }
c44d3b56 6928 return hi;
7fb16bac 6929}
d33278d1 6930
7fb16bac
PN
6931static void hashReleaseIterator(hashIterator *hi) {
6932 if (hi->encoding == REDIS_ENCODING_HT) {
6933 dictReleaseIterator(hi->di);
d33278d1 6934 }
c44d3b56 6935 zfree(hi);
7fb16bac 6936}
d33278d1 6937
7fb16bac
PN
6938/* Move to the next entry in the hash. Return REDIS_OK when the next entry
6939 * could be found and REDIS_ERR when the iterator reaches the end. */
c811bb38 6940static int hashNext(hashIterator *hi) {
7fb16bac
PN
6941 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6942 if ((hi->zi = zipmapNext(hi->zi, &hi->zk, &hi->zklen,
6943 &hi->zv, &hi->zvlen)) == NULL) return REDIS_ERR;
6944 } else {
6945 if ((hi->de = dictNext(hi->di)) == NULL) return REDIS_ERR;
6946 }
6947 return REDIS_OK;
6948}
d33278d1 6949
0c390abc 6950/* Get key or value object at current iteration position.
a3f3af86 6951 * This increases the refcount of the field object by 1. */
c811bb38 6952static robj *hashCurrent(hashIterator *hi, int what) {
7fb16bac
PN
6953 robj *o;
6954 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6955 if (what & REDIS_HASH_KEY) {
6956 o = createStringObject((char*)hi->zk,hi->zklen);
6957 } else {
6958 o = createStringObject((char*)hi->zv,hi->zvlen);
d33278d1 6959 }
d33278d1 6960 } else {
7fb16bac
PN
6961 if (what & REDIS_HASH_KEY) {
6962 o = dictGetEntryKey(hi->de);
6963 } else {
6964 o = dictGetEntryVal(hi->de);
d33278d1 6965 }
a3f3af86 6966 incrRefCount(o);
d33278d1 6967 }
7fb16bac 6968 return o;
d33278d1
PN
6969}
6970
7fb16bac
PN
6971static robj *hashLookupWriteOrCreate(redisClient *c, robj *key) {
6972 robj *o = lookupKeyWrite(c->db,key);
01426b05
PN
6973 if (o == NULL) {
6974 o = createHashObject();
09241813 6975 dbAdd(c->db,key,o);
01426b05
PN
6976 } else {
6977 if (o->type != REDIS_HASH) {
6978 addReply(c,shared.wrongtypeerr);
7fb16bac 6979 return NULL;
01426b05
PN
6980 }
6981 }
7fb16bac
PN
6982 return o;
6983}
01426b05 6984
7fb16bac
PN
6985/* ============================= Hash commands ============================== */
6986static void hsetCommand(redisClient *c) {
6e9e463f 6987 int update;
7fb16bac 6988 robj *o;
bbe025e0 6989
7fb16bac
PN
6990 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6991 hashTryConversion(o,c->argv,2,3);
97224de7 6992 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
feb8d7e6 6993 update = hashSet(o,c->argv[2],c->argv[3]);
6e9e463f 6994 addReply(c, update ? shared.czero : shared.cone);
7fb16bac
PN
6995 server.dirty++;
6996}
01426b05 6997
1f1c7695
PN
6998static void hsetnxCommand(redisClient *c) {
6999 robj *o;
7000 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
7001 hashTryConversion(o,c->argv,2,3);
7002
7003 if (hashExists(o, c->argv[2])) {
7004 addReply(c, shared.czero);
01426b05 7005 } else {
97224de7 7006 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
feb8d7e6 7007 hashSet(o,c->argv[2],c->argv[3]);
1f1c7695
PN
7008 addReply(c, shared.cone);
7009 server.dirty++;
7010 }
7011}
01426b05 7012
7fb16bac
PN
7013static void hmsetCommand(redisClient *c) {
7014 int i;
7015 robj *o;
01426b05 7016
7fb16bac
PN
7017 if ((c->argc % 2) == 1) {
7018 addReplySds(c,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
7019 return;
7020 }
01426b05 7021
7fb16bac
PN
7022 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
7023 hashTryConversion(o,c->argv,2,c->argc-1);
7024 for (i = 2; i < c->argc; i += 2) {
97224de7 7025 hashTryObjectEncoding(o,&c->argv[i], &c->argv[i+1]);
feb8d7e6 7026 hashSet(o,c->argv[i],c->argv[i+1]);
7fb16bac
PN
7027 }
7028 addReply(c, shared.ok);
edc2f63a 7029 server.dirty++;
7fb16bac
PN
7030}
7031
7032static void hincrbyCommand(redisClient *c) {
7033 long long value, incr;
7034 robj *o, *current, *new;
7035
bd79a6bd 7036 if (getLongLongFromObjectOrReply(c,c->argv[3],&incr,NULL) != REDIS_OK) return;
7fb16bac
PN
7037 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
7038 if ((current = hashGet(o,c->argv[2])) != NULL) {
946342c1
PN
7039 if (getLongLongFromObjectOrReply(c,current,&value,
7040 "hash value is not an integer") != REDIS_OK) {
7041 decrRefCount(current);
7042 return;
7043 }
a3f3af86 7044 decrRefCount(current);
7fb16bac
PN
7045 } else {
7046 value = 0;
01426b05
PN
7047 }
7048
7fb16bac 7049 value += incr;
3f973463
PN
7050 new = createStringObjectFromLongLong(value);
7051 hashTryObjectEncoding(o,&c->argv[2],NULL);
feb8d7e6 7052 hashSet(o,c->argv[2],new);
7fb16bac
PN
7053 decrRefCount(new);
7054 addReplyLongLong(c,value);
01426b05 7055 server.dirty++;
01426b05
PN
7056}
7057
978c2c94 7058static void hgetCommand(redisClient *c) {
7fb16bac 7059 robj *o, *value;
dd88747b 7060 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
7061 checkType(c,o,REDIS_HASH)) return;
7062
7fb16bac
PN
7063 if ((value = hashGet(o,c->argv[2])) != NULL) {
7064 addReplyBulk(c,value);
a3f3af86 7065 decrRefCount(value);
dd88747b 7066 } else {
7fb16bac 7067 addReply(c,shared.nullbulk);
69d95c3e 7068 }
69d95c3e
PN
7069}
7070
09aeb579
PN
7071static void hmgetCommand(redisClient *c) {
7072 int i;
7fb16bac
PN
7073 robj *o, *value;
7074 o = lookupKeyRead(c->db,c->argv[1]);
7075 if (o != NULL && o->type != REDIS_HASH) {
7076 addReply(c,shared.wrongtypeerr);
09aeb579
PN
7077 }
7078
7fb16bac
PN
7079 /* Note the check for o != NULL happens inside the loop. This is
7080 * done because objects that cannot be found are considered to be
7081 * an empty hash. The reply should then be a series of NULLs. */
09aeb579 7082 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-2));
7fb16bac
PN
7083 for (i = 2; i < c->argc; i++) {
7084 if (o != NULL && (value = hashGet(o,c->argv[i])) != NULL) {
7085 addReplyBulk(c,value);
a3f3af86 7086 decrRefCount(value);
7fb16bac
PN
7087 } else {
7088 addReply(c,shared.nullbulk);
09aeb579
PN
7089 }
7090 }
7091}
7092
07efaf74 7093static void hdelCommand(redisClient *c) {
dd88747b 7094 robj *o;
dd88747b 7095 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
7096 checkType(c,o,REDIS_HASH)) return;
07efaf74 7097
7fb16bac 7098 if (hashDelete(o,c->argv[2])) {
09241813 7099 if (hashLength(o) == 0) dbDelete(c->db,c->argv[1]);
7fb16bac
PN
7100 addReply(c,shared.cone);
7101 server.dirty++;
dd88747b 7102 } else {
7fb16bac 7103 addReply(c,shared.czero);
07efaf74 7104 }
7105}
7106
92b27fe9 7107static void hlenCommand(redisClient *c) {
7108 robj *o;
dd88747b 7109 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
92b27fe9 7110 checkType(c,o,REDIS_HASH)) return;
7111
7fb16bac 7112 addReplyUlong(c,hashLength(o));
92b27fe9 7113}
7114
78409a0f 7115static void genericHgetallCommand(redisClient *c, int flags) {
7fb16bac 7116 robj *o, *lenobj, *obj;
78409a0f 7117 unsigned long count = 0;
c44d3b56 7118 hashIterator *hi;
78409a0f 7119
4e27f268 7120 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
78409a0f 7121 || checkType(c,o,REDIS_HASH)) return;
7122
7123 lenobj = createObject(REDIS_STRING,NULL);
7124 addReply(c,lenobj);
7125 decrRefCount(lenobj);
7126
c44d3b56
PN
7127 hi = hashInitIterator(o);
7128 while (hashNext(hi) != REDIS_ERR) {
7fb16bac 7129 if (flags & REDIS_HASH_KEY) {
c44d3b56 7130 obj = hashCurrent(hi,REDIS_HASH_KEY);
7fb16bac 7131 addReplyBulk(c,obj);
a3f3af86 7132 decrRefCount(obj);
7fb16bac 7133 count++;
78409a0f 7134 }
7fb16bac 7135 if (flags & REDIS_HASH_VALUE) {
c44d3b56 7136 obj = hashCurrent(hi,REDIS_HASH_VALUE);
7fb16bac 7137 addReplyBulk(c,obj);
a3f3af86 7138 decrRefCount(obj);
7fb16bac 7139 count++;
78409a0f 7140 }
78409a0f 7141 }
c44d3b56 7142 hashReleaseIterator(hi);
7fb16bac 7143
78409a0f 7144 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",count);
7145}
7146
7147static void hkeysCommand(redisClient *c) {
7fb16bac 7148 genericHgetallCommand(c,REDIS_HASH_KEY);
78409a0f 7149}
7150
7151static void hvalsCommand(redisClient *c) {
7fb16bac 7152 genericHgetallCommand(c,REDIS_HASH_VALUE);
78409a0f 7153}
7154
7155static void hgetallCommand(redisClient *c) {
7fb16bac 7156 genericHgetallCommand(c,REDIS_HASH_KEY|REDIS_HASH_VALUE);
78409a0f 7157}
7158
a86f14b1 7159static void hexistsCommand(redisClient *c) {
7160 robj *o;
a86f14b1 7161 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
7162 checkType(c,o,REDIS_HASH)) return;
7163
7fb16bac 7164 addReply(c, hashExists(o,c->argv[2]) ? shared.cone : shared.czero);
a86f14b1 7165}
7166
ada386b2 7167static void convertToRealHash(robj *o) {
7168 unsigned char *key, *val, *p, *zm = o->ptr;
7169 unsigned int klen, vlen;
7170 dict *dict = dictCreate(&hashDictType,NULL);
7171
7172 assert(o->type == REDIS_HASH && o->encoding != REDIS_ENCODING_HT);
7173 p = zipmapRewind(zm);
7174 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
7175 robj *keyobj, *valobj;
7176
7177 keyobj = createStringObject((char*)key,klen);
7178 valobj = createStringObject((char*)val,vlen);
05df7621 7179 keyobj = tryObjectEncoding(keyobj);
7180 valobj = tryObjectEncoding(valobj);
ada386b2 7181 dictAdd(dict,keyobj,valobj);
7182 }
7183 o->encoding = REDIS_ENCODING_HT;
7184 o->ptr = dict;
7185 zfree(zm);
7186}
7187
6b47e12e 7188/* ========================= Non type-specific commands ==================== */
7189
ed9b544e 7190static void flushdbCommand(redisClient *c) {
ca37e9cd 7191 server.dirty += dictSize(c->db->dict);
9b30e1a2 7192 touchWatchedKeysOnFlush(c->db->id);
3305306f 7193 dictEmpty(c->db->dict);
7194 dictEmpty(c->db->expires);
ed9b544e 7195 addReply(c,shared.ok);
ed9b544e 7196}
7197
7198static void flushallCommand(redisClient *c) {
9b30e1a2 7199 touchWatchedKeysOnFlush(-1);
ca37e9cd 7200 server.dirty += emptyDb();
ed9b544e 7201 addReply(c,shared.ok);
500ece7c 7202 if (server.bgsavechildpid != -1) {
7203 kill(server.bgsavechildpid,SIGKILL);
7204 rdbRemoveTempFile(server.bgsavechildpid);
7205 }
f78fd11b 7206 rdbSave(server.dbfilename);
ca37e9cd 7207 server.dirty++;
ed9b544e 7208}
7209
56906eef 7210static redisSortOperation *createSortOperation(int type, robj *pattern) {
ed9b544e 7211 redisSortOperation *so = zmalloc(sizeof(*so));
ed9b544e 7212 so->type = type;
7213 so->pattern = pattern;
7214 return so;
7215}
7216
7217/* Return the value associated to the key with a name obtained
55017f9d
PN
7218 * substituting the first occurence of '*' in 'pattern' with 'subst'.
7219 * The returned object will always have its refcount increased by 1
7220 * when it is non-NULL. */
56906eef 7221static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
6d7d1370 7222 char *p, *f;
ed9b544e 7223 sds spat, ssub;
6d7d1370
PN
7224 robj keyobj, fieldobj, *o;
7225 int prefixlen, sublen, postfixlen, fieldlen;
ed9b544e 7226 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
7227 struct {
f1017b3f 7228 long len;
7229 long free;
ed9b544e 7230 char buf[REDIS_SORTKEY_MAX+1];
6d7d1370 7231 } keyname, fieldname;
ed9b544e 7232
28173a49 7233 /* If the pattern is "#" return the substitution object itself in order
7234 * to implement the "SORT ... GET #" feature. */
7235 spat = pattern->ptr;
7236 if (spat[0] == '#' && spat[1] == '\0') {
55017f9d 7237 incrRefCount(subst);
28173a49 7238 return subst;
7239 }
7240
7241 /* The substitution object may be specially encoded. If so we create
9d65a1bb 7242 * a decoded object on the fly. Otherwise getDecodedObject will just
7243 * increment the ref count, that we'll decrement later. */
7244 subst = getDecodedObject(subst);
942a3961 7245
ed9b544e 7246 ssub = subst->ptr;
7247 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
7248 p = strchr(spat,'*');
ed5a857a 7249 if (!p) {
7250 decrRefCount(subst);
7251 return NULL;
7252 }
ed9b544e 7253
6d7d1370
PN
7254 /* Find out if we're dealing with a hash dereference. */
7255 if ((f = strstr(p+1, "->")) != NULL) {
7256 fieldlen = sdslen(spat)-(f-spat);
7257 /* this also copies \0 character */
7258 memcpy(fieldname.buf,f+2,fieldlen-1);
7259 fieldname.len = fieldlen-2;
7260 } else {
7261 fieldlen = 0;
7262 }
7263
ed9b544e 7264 prefixlen = p-spat;
7265 sublen = sdslen(ssub);
6d7d1370 7266 postfixlen = sdslen(spat)-(prefixlen+1)-fieldlen;
ed9b544e 7267 memcpy(keyname.buf,spat,prefixlen);
7268 memcpy(keyname.buf+prefixlen,ssub,sublen);
7269 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
7270 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
7271 keyname.len = prefixlen+sublen+postfixlen;
942a3961 7272 decrRefCount(subst);
7273
6d7d1370
PN
7274 /* Lookup substituted key */
7275 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2));
7276 o = lookupKeyRead(db,&keyobj);
55017f9d
PN
7277 if (o == NULL) return NULL;
7278
7279 if (fieldlen > 0) {
7280 if (o->type != REDIS_HASH || fieldname.len < 1) return NULL;
6d7d1370 7281
705dad38
PN
7282 /* Retrieve value from hash by the field name. This operation
7283 * already increases the refcount of the returned object. */
6d7d1370
PN
7284 initStaticStringObject(fieldobj,((char*)&fieldname)+(sizeof(long)*2));
7285 o = hashGet(o, &fieldobj);
705dad38 7286 } else {
55017f9d 7287 if (o->type != REDIS_STRING) return NULL;
b6f07345 7288
705dad38
PN
7289 /* Every object that this function returns needs to have its refcount
7290 * increased. sortCommand decreases it again. */
7291 incrRefCount(o);
6d7d1370
PN
7292 }
7293
7294 return o;
ed9b544e 7295}
7296
7297/* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
7298 * the additional parameter is not standard but a BSD-specific we have to
7299 * pass sorting parameters via the global 'server' structure */
7300static int sortCompare(const void *s1, const void *s2) {
7301 const redisSortObject *so1 = s1, *so2 = s2;
7302 int cmp;
7303
7304 if (!server.sort_alpha) {
7305 /* Numeric sorting. Here it's trivial as we precomputed scores */
7306 if (so1->u.score > so2->u.score) {
7307 cmp = 1;
7308 } else if (so1->u.score < so2->u.score) {
7309 cmp = -1;
7310 } else {
7311 cmp = 0;
7312 }
7313 } else {
7314 /* Alphanumeric sorting */
7315 if (server.sort_bypattern) {
7316 if (!so1->u.cmpobj || !so2->u.cmpobj) {
7317 /* At least one compare object is NULL */
7318 if (so1->u.cmpobj == so2->u.cmpobj)
7319 cmp = 0;
7320 else if (so1->u.cmpobj == NULL)
7321 cmp = -1;
7322 else
7323 cmp = 1;
7324 } else {
7325 /* We have both the objects, use strcoll */
7326 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
7327 }
7328 } else {
08ee9b57 7329 /* Compare elements directly. */
7330 cmp = compareStringObjects(so1->obj,so2->obj);
ed9b544e 7331 }
7332 }
7333 return server.sort_desc ? -cmp : cmp;
7334}
7335
7336/* The SORT command is the most complex command in Redis. Warning: this code
7337 * is optimized for speed and a bit less for readability */
7338static void sortCommand(redisClient *c) {
ed9b544e 7339 list *operations;
a03611e1 7340 unsigned int outputlen = 0;
ed9b544e 7341 int desc = 0, alpha = 0;
7342 int limit_start = 0, limit_count = -1, start, end;
7343 int j, dontsort = 0, vectorlen;
7344 int getop = 0; /* GET operation counter */
443c6409 7345 robj *sortval, *sortby = NULL, *storekey = NULL;
ed9b544e 7346 redisSortObject *vector; /* Resulting vector to sort */
7347
7348 /* Lookup the key to sort. It must be of the right types */
3305306f 7349 sortval = lookupKeyRead(c->db,c->argv[1]);
7350 if (sortval == NULL) {
4e27f268 7351 addReply(c,shared.emptymultibulk);
ed9b544e 7352 return;
7353 }
a5eb649b 7354 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
7355 sortval->type != REDIS_ZSET)
7356 {
c937aa89 7357 addReply(c,shared.wrongtypeerr);
ed9b544e 7358 return;
7359 }
7360
7361 /* Create a list of operations to perform for every sorted element.
7362 * Operations can be GET/DEL/INCR/DECR */
7363 operations = listCreate();
092dac2a 7364 listSetFreeMethod(operations,zfree);
ed9b544e 7365 j = 2;
7366
7367 /* Now we need to protect sortval incrementing its count, in the future
7368 * SORT may have options able to overwrite/delete keys during the sorting
7369 * and the sorted key itself may get destroied */
7370 incrRefCount(sortval);
7371
7372 /* The SORT command has an SQL-alike syntax, parse it */
7373 while(j < c->argc) {
7374 int leftargs = c->argc-j-1;
7375 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
7376 desc = 0;
7377 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
7378 desc = 1;
7379 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
7380 alpha = 1;
7381 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
7382 limit_start = atoi(c->argv[j+1]->ptr);
7383 limit_count = atoi(c->argv[j+2]->ptr);
7384 j+=2;
443c6409 7385 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
7386 storekey = c->argv[j+1];
7387 j++;
ed9b544e 7388 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
7389 sortby = c->argv[j+1];
7390 /* If the BY pattern does not contain '*', i.e. it is constant,
7391 * we don't need to sort nor to lookup the weight keys. */
7392 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
7393 j++;
7394 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
7395 listAddNodeTail(operations,createSortOperation(
7396 REDIS_SORT_GET,c->argv[j+1]));
7397 getop++;
7398 j++;
ed9b544e 7399 } else {
7400 decrRefCount(sortval);
7401 listRelease(operations);
c937aa89 7402 addReply(c,shared.syntaxerr);
ed9b544e 7403 return;
7404 }
7405 j++;
7406 }
7407
7408 /* Load the sorting vector with all the objects to sort */
a5eb649b 7409 switch(sortval->type) {
a03611e1 7410 case REDIS_LIST: vectorlen = lLength(sortval); break;
a5eb649b 7411 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
7412 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
f83c6cb5 7413 default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
a5eb649b 7414 }
ed9b544e 7415 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
ed9b544e 7416 j = 0;
a5eb649b 7417
ed9b544e 7418 if (sortval->type == REDIS_LIST) {
a03611e1
PN
7419 lIterator *li = lInitIterator(sortval,0,REDIS_TAIL);
7420 lEntry entry;
7421 while(lNext(li,&entry)) {
7422 vector[j].obj = lGet(&entry);
ed9b544e 7423 vector[j].u.score = 0;
7424 vector[j].u.cmpobj = NULL;
ed9b544e 7425 j++;
7426 }
a03611e1 7427 lReleaseIterator(li);
ed9b544e 7428 } else {
a5eb649b 7429 dict *set;
ed9b544e 7430 dictIterator *di;
7431 dictEntry *setele;
7432
a5eb649b 7433 if (sortval->type == REDIS_SET) {
7434 set = sortval->ptr;
7435 } else {
7436 zset *zs = sortval->ptr;
7437 set = zs->dict;
7438 }
7439
ed9b544e 7440 di = dictGetIterator(set);
ed9b544e 7441 while((setele = dictNext(di)) != NULL) {
7442 vector[j].obj = dictGetEntryKey(setele);
7443 vector[j].u.score = 0;
7444 vector[j].u.cmpobj = NULL;
7445 j++;
7446 }
7447 dictReleaseIterator(di);
7448 }
dfc5e96c 7449 redisAssert(j == vectorlen);
ed9b544e 7450
7451 /* Now it's time to load the right scores in the sorting vector */
7452 if (dontsort == 0) {
7453 for (j = 0; j < vectorlen; j++) {
6d7d1370 7454 robj *byval;
ed9b544e 7455 if (sortby) {
6d7d1370 7456 /* lookup value to sort by */
3305306f 7457 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
705dad38 7458 if (!byval) continue;
ed9b544e 7459 } else {
6d7d1370
PN
7460 /* use object itself to sort by */
7461 byval = vector[j].obj;
7462 }
7463
7464 if (alpha) {
08ee9b57 7465 if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
6d7d1370
PN
7466 } else {
7467 if (byval->encoding == REDIS_ENCODING_RAW) {
7468 vector[j].u.score = strtod(byval->ptr,NULL);
16fa22f1 7469 } else if (byval->encoding == REDIS_ENCODING_INT) {
6d7d1370
PN
7470 /* Don't need to decode the object if it's
7471 * integer-encoded (the only encoding supported) so
7472 * far. We can just cast it */
16fa22f1
PN
7473 vector[j].u.score = (long)byval->ptr;
7474 } else {
7475 redisAssert(1 != 1);
942a3961 7476 }
ed9b544e 7477 }
6d7d1370 7478
705dad38
PN
7479 /* when the object was retrieved using lookupKeyByPattern,
7480 * its refcount needs to be decreased. */
7481 if (sortby) {
7482 decrRefCount(byval);
ed9b544e 7483 }
7484 }
7485 }
7486
7487 /* We are ready to sort the vector... perform a bit of sanity check
7488 * on the LIMIT option too. We'll use a partial version of quicksort. */
7489 start = (limit_start < 0) ? 0 : limit_start;
7490 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
7491 if (start >= vectorlen) {
7492 start = vectorlen-1;
7493 end = vectorlen-2;
7494 }
7495 if (end >= vectorlen) end = vectorlen-1;
7496
7497 if (dontsort == 0) {
7498 server.sort_desc = desc;
7499 server.sort_alpha = alpha;
7500 server.sort_bypattern = sortby ? 1 : 0;
5f5b9840 7501 if (sortby && (start != 0 || end != vectorlen-1))
7502 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
7503 else
7504 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
ed9b544e 7505 }
7506
7507 /* Send command output to the output buffer, performing the specified
7508 * GET/DEL/INCR/DECR operations if any. */
7509 outputlen = getop ? getop*(end-start+1) : end-start+1;
443c6409 7510 if (storekey == NULL) {
7511 /* STORE option not specified, sent the sorting result to client */
7512 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
7513 for (j = start; j <= end; j++) {
7514 listNode *ln;
c7df85a4 7515 listIter li;
7516
dd88747b 7517 if (!getop) addReplyBulk(c,vector[j].obj);
c7df85a4 7518 listRewind(operations,&li);
7519 while((ln = listNext(&li))) {
443c6409 7520 redisSortOperation *sop = ln->value;
7521 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7522 vector[j].obj);
7523
7524 if (sop->type == REDIS_SORT_GET) {
55017f9d 7525 if (!val) {
443c6409 7526 addReply(c,shared.nullbulk);
7527 } else {
dd88747b 7528 addReplyBulk(c,val);
55017f9d 7529 decrRefCount(val);
443c6409 7530 }
7531 } else {
dfc5e96c 7532 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
443c6409 7533 }
7534 }
ed9b544e 7535 }
443c6409 7536 } else {
74e0f445 7537 robj *sobj = createZiplistObject();
443c6409 7538
7539 /* STORE option specified, set the sorting result as a List object */
7540 for (j = start; j <= end; j++) {
7541 listNode *ln;
c7df85a4 7542 listIter li;
7543
443c6409 7544 if (!getop) {
a03611e1
PN
7545 lPush(sobj,vector[j].obj,REDIS_TAIL);
7546 } else {
7547 listRewind(operations,&li);
7548 while((ln = listNext(&li))) {
7549 redisSortOperation *sop = ln->value;
7550 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7551 vector[j].obj);
7552
7553 if (sop->type == REDIS_SORT_GET) {
7554 if (!val) val = createStringObject("",0);
7555
7556 /* lPush does an incrRefCount, so we should take care
7557 * care of the incremented refcount caused by either
7558 * lookupKeyByPattern or createStringObject("",0) */
7559 lPush(sobj,val,REDIS_TAIL);
7560 decrRefCount(val);
443c6409 7561 } else {
a03611e1
PN
7562 /* always fails */
7563 redisAssert(sop->type == REDIS_SORT_GET);
443c6409 7564 }
ed9b544e 7565 }
ed9b544e 7566 }
ed9b544e 7567 }
846d8b3e 7568 dbReplace(c->db,storekey,sobj);
443c6409 7569 /* Note: we add 1 because the DB is dirty anyway since even if the
7570 * SORT result is empty a new key is set and maybe the old content
7571 * replaced. */
7572 server.dirty += 1+outputlen;
7573 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
ed9b544e 7574 }
7575
7576 /* Cleanup */
a03611e1
PN
7577 if (sortval->type == REDIS_LIST)
7578 for (j = 0; j < vectorlen; j++)
7579 decrRefCount(vector[j].obj);
ed9b544e 7580 decrRefCount(sortval);
7581 listRelease(operations);
7582 for (j = 0; j < vectorlen; j++) {
16fa22f1 7583 if (alpha && vector[j].u.cmpobj)
ed9b544e 7584 decrRefCount(vector[j].u.cmpobj);
7585 }
7586 zfree(vector);
7587}
7588
ec6c7a1d 7589/* Convert an amount of bytes into a human readable string in the form
7590 * of 100B, 2G, 100M, 4K, and so forth. */
7591static void bytesToHuman(char *s, unsigned long long n) {
7592 double d;
7593
7594 if (n < 1024) {
7595 /* Bytes */
7596 sprintf(s,"%lluB",n);
7597 return;
7598 } else if (n < (1024*1024)) {
7599 d = (double)n/(1024);
7600 sprintf(s,"%.2fK",d);
7601 } else if (n < (1024LL*1024*1024)) {
7602 d = (double)n/(1024*1024);
7603 sprintf(s,"%.2fM",d);
7604 } else if (n < (1024LL*1024*1024*1024)) {
7605 d = (double)n/(1024LL*1024*1024);
b72f6a4b 7606 sprintf(s,"%.2fG",d);
ec6c7a1d 7607 }
7608}
7609
1c85b79f 7610/* Create the string returned by the INFO command. This is decoupled
7611 * by the INFO command itself as we need to report the same information
7612 * on memory corruption problems. */
7613static sds genRedisInfoString(void) {
ed9b544e 7614 sds info;
7615 time_t uptime = time(NULL)-server.stat_starttime;
c3cb078d 7616 int j;
ec6c7a1d 7617 char hmem[64];
55a8298f 7618
b72f6a4b 7619 bytesToHuman(hmem,zmalloc_used_memory());
ed9b544e 7620 info = sdscatprintf(sdsempty(),
7621 "redis_version:%s\r\n"
5436146c
PN
7622 "redis_git_sha1:%s\r\n"
7623 "redis_git_dirty:%d\r\n"
f1017b3f 7624 "arch_bits:%s\r\n"
7a932b74 7625 "multiplexing_api:%s\r\n"
0d7170a4 7626 "process_id:%ld\r\n"
682ac724 7627 "uptime_in_seconds:%ld\r\n"
7628 "uptime_in_days:%ld\r\n"
ed9b544e 7629 "connected_clients:%d\r\n"
7630 "connected_slaves:%d\r\n"
f86a74e9 7631 "blocked_clients:%d\r\n"
5fba9f71 7632 "used_memory:%zu\r\n"
ec6c7a1d 7633 "used_memory_human:%s\r\n"
ed9b544e 7634 "changes_since_last_save:%lld\r\n"
be2bb6b0 7635 "bgsave_in_progress:%d\r\n"
682ac724 7636 "last_save_time:%ld\r\n"
b3fad521 7637 "bgrewriteaof_in_progress:%d\r\n"
ed9b544e 7638 "total_connections_received:%lld\r\n"
7639 "total_commands_processed:%lld\r\n"
2a6a2ed1 7640 "expired_keys:%lld\r\n"
3be2c9d7 7641 "hash_max_zipmap_entries:%zu\r\n"
7642 "hash_max_zipmap_value:%zu\r\n"
ffc6b7f8 7643 "pubsub_channels:%ld\r\n"
7644 "pubsub_patterns:%u\r\n"
7d98e08c 7645 "vm_enabled:%d\r\n"
a0f643ea 7646 "role:%s\r\n"
ed9b544e 7647 ,REDIS_VERSION,
5436146c 7648 REDIS_GIT_SHA1,
274e45e3 7649 strtol(REDIS_GIT_DIRTY,NULL,10) > 0,
f1017b3f 7650 (sizeof(long) == 8) ? "64" : "32",
7a932b74 7651 aeGetApiName(),
0d7170a4 7652 (long) getpid(),
a0f643ea 7653 uptime,
7654 uptime/(3600*24),
ed9b544e 7655 listLength(server.clients)-listLength(server.slaves),
7656 listLength(server.slaves),
d5d55fc3 7657 server.blpop_blocked_clients,
b72f6a4b 7658 zmalloc_used_memory(),
ec6c7a1d 7659 hmem,
ed9b544e 7660 server.dirty,
9d65a1bb 7661 server.bgsavechildpid != -1,
ed9b544e 7662 server.lastsave,
b3fad521 7663 server.bgrewritechildpid != -1,
ed9b544e 7664 server.stat_numconnections,
7665 server.stat_numcommands,
2a6a2ed1 7666 server.stat_expiredkeys,
55a8298f 7667 server.hash_max_zipmap_entries,
7668 server.hash_max_zipmap_value,
ffc6b7f8 7669 dictSize(server.pubsub_channels),
7670 listLength(server.pubsub_patterns),
7d98e08c 7671 server.vm_enabled != 0,
a0f643ea 7672 server.masterhost == NULL ? "master" : "slave"
ed9b544e 7673 );
a0f643ea 7674 if (server.masterhost) {
7675 info = sdscatprintf(info,
7676 "master_host:%s\r\n"
7677 "master_port:%d\r\n"
7678 "master_link_status:%s\r\n"
7679 "master_last_io_seconds_ago:%d\r\n"
7680 ,server.masterhost,
7681 server.masterport,
7682 (server.replstate == REDIS_REPL_CONNECTED) ?
7683 "up" : "down",
f72b934d 7684 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
a0f643ea 7685 );
7686 }
7d98e08c 7687 if (server.vm_enabled) {
1064ef87 7688 lockThreadedIO();
7d98e08c 7689 info = sdscatprintf(info,
7690 "vm_conf_max_memory:%llu\r\n"
7691 "vm_conf_page_size:%llu\r\n"
7692 "vm_conf_pages:%llu\r\n"
7693 "vm_stats_used_pages:%llu\r\n"
7694 "vm_stats_swapped_objects:%llu\r\n"
7695 "vm_stats_swappin_count:%llu\r\n"
7696 "vm_stats_swappout_count:%llu\r\n"
b9bc0eef 7697 "vm_stats_io_newjobs_len:%lu\r\n"
7698 "vm_stats_io_processing_len:%lu\r\n"
7699 "vm_stats_io_processed_len:%lu\r\n"
25fd2cb2 7700 "vm_stats_io_active_threads:%lu\r\n"
d5d55fc3 7701 "vm_stats_blocked_clients:%lu\r\n"
7d98e08c 7702 ,(unsigned long long) server.vm_max_memory,
7703 (unsigned long long) server.vm_page_size,
7704 (unsigned long long) server.vm_pages,
7705 (unsigned long long) server.vm_stats_used_pages,
7706 (unsigned long long) server.vm_stats_swapped_objects,
7707 (unsigned long long) server.vm_stats_swapins,
b9bc0eef 7708 (unsigned long long) server.vm_stats_swapouts,
7709 (unsigned long) listLength(server.io_newjobs),
7710 (unsigned long) listLength(server.io_processing),
7711 (unsigned long) listLength(server.io_processed),
d5d55fc3 7712 (unsigned long) server.io_active_threads,
7713 (unsigned long) server.vm_blocked_clients
7d98e08c 7714 );
1064ef87 7715 unlockThreadedIO();
7d98e08c 7716 }
c3cb078d 7717 for (j = 0; j < server.dbnum; j++) {
7718 long long keys, vkeys;
7719
7720 keys = dictSize(server.db[j].dict);
7721 vkeys = dictSize(server.db[j].expires);
7722 if (keys || vkeys) {
9d65a1bb 7723 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
c3cb078d 7724 j, keys, vkeys);
7725 }
7726 }
1c85b79f 7727 return info;
7728}
7729
7730static void infoCommand(redisClient *c) {
7731 sds info = genRedisInfoString();
83c6a618 7732 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
7733 (unsigned long)sdslen(info)));
ed9b544e 7734 addReplySds(c,info);
70003d28 7735 addReply(c,shared.crlf);
ed9b544e 7736}
7737
3305306f 7738static void monitorCommand(redisClient *c) {
7739 /* ignore MONITOR if aleady slave or in monitor mode */
7740 if (c->flags & REDIS_SLAVE) return;
7741
7742 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
7743 c->slaveseldb = 0;
6b47e12e 7744 listAddNodeTail(server.monitors,c);
3305306f 7745 addReply(c,shared.ok);
7746}
7747
7748/* ================================= Expire ================================= */
7749static int removeExpire(redisDb *db, robj *key) {
09241813 7750 if (dictDelete(db->expires,key->ptr) == DICT_OK) {
3305306f 7751 return 1;
7752 } else {
7753 return 0;
7754 }
7755}
7756
7757static int setExpire(redisDb *db, robj *key, time_t when) {
09241813 7758 sds copy = sdsdup(key->ptr);
7759 if (dictAdd(db->expires,copy,(void*)when) == DICT_ERR) {
7760 sdsfree(copy);
3305306f 7761 return 0;
7762 } else {
3305306f 7763 return 1;
7764 }
7765}
7766
bb32ede5 7767/* Return the expire time of the specified key, or -1 if no expire
7768 * is associated with this key (i.e. the key is non volatile) */
7769static time_t getExpire(redisDb *db, robj *key) {
7770 dictEntry *de;
7771
7772 /* No expire? return ASAP */
7773 if (dictSize(db->expires) == 0 ||
09241813 7774 (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
bb32ede5 7775
7776 return (time_t) dictGetEntryVal(de);
7777}
7778
3305306f 7779static int expireIfNeeded(redisDb *db, robj *key) {
7780 time_t when;
7781 dictEntry *de;
7782
7783 /* No expire? return ASAP */
7784 if (dictSize(db->expires) == 0 ||
09241813 7785 (de = dictFind(db->expires,key->ptr)) == NULL) return 0;
3305306f 7786
7787 /* Lookup the expire */
7788 when = (time_t) dictGetEntryVal(de);
7789 if (time(NULL) <= when) return 0;
7790
7791 /* Delete the key */
09241813 7792 dbDelete(db,key);
2a6a2ed1 7793 server.stat_expiredkeys++;
09241813 7794 return 1;
3305306f 7795}
7796
7797static int deleteIfVolatile(redisDb *db, robj *key) {
7798 dictEntry *de;
7799
7800 /* No expire? return ASAP */
7801 if (dictSize(db->expires) == 0 ||
09241813 7802 (de = dictFind(db->expires,key->ptr)) == NULL) return 0;
3305306f 7803
7804 /* Delete the key */
0c66a471 7805 server.dirty++;
2a6a2ed1 7806 server.stat_expiredkeys++;
09241813 7807 dictDelete(db->expires,key->ptr);
7808 return dictDelete(db->dict,key->ptr) == DICT_OK;
3305306f 7809}
7810
bbe025e0 7811static void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
3305306f 7812 dictEntry *de;
bbe025e0
AM
7813 time_t seconds;
7814
bd79a6bd 7815 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
bbe025e0
AM
7816
7817 seconds -= offset;
3305306f 7818
09241813 7819 de = dictFind(c->db->dict,key->ptr);
3305306f 7820 if (de == NULL) {
7821 addReply(c,shared.czero);
7822 return;
7823 }
d4dd6556 7824 if (seconds <= 0) {
09241813 7825 if (dbDelete(c->db,key)) server.dirty++;
43e5ccdf 7826 addReply(c, shared.cone);
3305306f 7827 return;
7828 } else {
7829 time_t when = time(NULL)+seconds;
802e8373 7830 if (setExpire(c->db,key,when)) {
3305306f 7831 addReply(c,shared.cone);
77423026 7832 server.dirty++;
7833 } else {
3305306f 7834 addReply(c,shared.czero);
77423026 7835 }
3305306f 7836 return;
7837 }
7838}
7839
802e8373 7840static void expireCommand(redisClient *c) {
bbe025e0 7841 expireGenericCommand(c,c->argv[1],c->argv[2],0);
802e8373 7842}
7843
7844static void expireatCommand(redisClient *c) {
bbe025e0 7845 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
802e8373 7846}
7847
fd88489a 7848static void ttlCommand(redisClient *c) {
7849 time_t expire;
7850 int ttl = -1;
7851
7852 expire = getExpire(c->db,c->argv[1]);
7853 if (expire != -1) {
7854 ttl = (int) (expire-time(NULL));
7855 if (ttl < 0) ttl = -1;
7856 }
7857 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
7858}
7859
6e469882 7860/* ================================ MULTI/EXEC ============================== */
7861
7862/* Client state initialization for MULTI/EXEC */
7863static void initClientMultiState(redisClient *c) {
7864 c->mstate.commands = NULL;
7865 c->mstate.count = 0;
7866}
7867
7868/* Release all the resources associated with MULTI/EXEC state */
7869static void freeClientMultiState(redisClient *c) {
7870 int j;
7871
7872 for (j = 0; j < c->mstate.count; j++) {
7873 int i;
7874 multiCmd *mc = c->mstate.commands+j;
7875
7876 for (i = 0; i < mc->argc; i++)
7877 decrRefCount(mc->argv[i]);
7878 zfree(mc->argv);
7879 }
7880 zfree(c->mstate.commands);
7881}
7882
7883/* Add a new command into the MULTI commands queue */
7884static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
7885 multiCmd *mc;
7886 int j;
7887
7888 c->mstate.commands = zrealloc(c->mstate.commands,
7889 sizeof(multiCmd)*(c->mstate.count+1));
7890 mc = c->mstate.commands+c->mstate.count;
7891 mc->cmd = cmd;
7892 mc->argc = c->argc;
7893 mc->argv = zmalloc(sizeof(robj*)*c->argc);
7894 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
7895 for (j = 0; j < c->argc; j++)
7896 incrRefCount(mc->argv[j]);
7897 c->mstate.count++;
7898}
7899
7900static void multiCommand(redisClient *c) {
6531c94d 7901 if (c->flags & REDIS_MULTI) {
7902 addReplySds(c,sdsnew("-ERR MULTI calls can not be nested\r\n"));
7903 return;
7904 }
6e469882 7905 c->flags |= REDIS_MULTI;
36c548f0 7906 addReply(c,shared.ok);
6e469882 7907}
7908
18b6cb76
DJ
7909static void discardCommand(redisClient *c) {
7910 if (!(c->flags & REDIS_MULTI)) {
7911 addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
7912 return;
7913 }
7914
7915 freeClientMultiState(c);
7916 initClientMultiState(c);
7917 c->flags &= (~REDIS_MULTI);
7918 addReply(c,shared.ok);
7919}
7920
66c8853f 7921/* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7922 * implememntation for more information. */
7923static void execCommandReplicateMulti(redisClient *c) {
7924 struct redisCommand *cmd;
7925 robj *multistring = createStringObject("MULTI",5);
7926
7927 cmd = lookupCommand("multi");
7928 if (server.appendonly)
7929 feedAppendOnlyFile(cmd,c->db->id,&multistring,1);
7930 if (listLength(server.slaves))
7931 replicationFeedSlaves(server.slaves,c->db->id,&multistring,1);
7932 decrRefCount(multistring);
7933}
7934
6e469882 7935static void execCommand(redisClient *c) {
7936 int j;
7937 robj **orig_argv;
7938 int orig_argc;
7939
7940 if (!(c->flags & REDIS_MULTI)) {
7941 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
7942 return;
7943 }
7944
37ab76c9 7945 /* Check if we need to abort the EXEC if some WATCHed key was touched.
7946 * A failed EXEC will return a multi bulk nil object. */
7947 if (c->flags & REDIS_DIRTY_CAS) {
7948 freeClientMultiState(c);
7949 initClientMultiState(c);
7950 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
7951 unwatchAllKeys(c);
7952 addReply(c,shared.nullmultibulk);
7953 return;
7954 }
7955
66c8853f 7956 /* Replicate a MULTI request now that we are sure the block is executed.
7957 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7958 * both the AOF and the replication link will have the same consistency
7959 * and atomicity guarantees. */
7960 execCommandReplicateMulti(c);
7961
7962 /* Exec all the queued commands */
1ad4d316 7963 unwatchAllKeys(c); /* Unwatch ASAP otherwise we'll waste CPU cycles */
6e469882 7964 orig_argv = c->argv;
7965 orig_argc = c->argc;
7966 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
7967 for (j = 0; j < c->mstate.count; j++) {
7968 c->argc = c->mstate.commands[j].argc;
7969 c->argv = c->mstate.commands[j].argv;
7970 call(c,c->mstate.commands[j].cmd);
7971 }
7972 c->argv = orig_argv;
7973 c->argc = orig_argc;
7974 freeClientMultiState(c);
7975 initClientMultiState(c);
1ad4d316 7976 c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS);
66c8853f 7977 /* Make sure the EXEC command is always replicated / AOF, since we
7978 * always send the MULTI command (we can't know beforehand if the
7979 * next operations will contain at least a modification to the DB). */
7980 server.dirty++;
6e469882 7981}
7982
4409877e 7983/* =========================== Blocking Operations ========================= */
7984
7985/* Currently Redis blocking operations support is limited to list POP ops,
7986 * so the current implementation is not fully generic, but it is also not
7987 * completely specific so it will not require a rewrite to support new
7988 * kind of blocking operations in the future.
7989 *
7990 * Still it's important to note that list blocking operations can be already
7991 * used as a notification mechanism in order to implement other blocking
7992 * operations at application level, so there must be a very strong evidence
7993 * of usefulness and generality before new blocking operations are implemented.
7994 *
7995 * This is how the current blocking POP works, we use BLPOP as example:
7996 * - If the user calls BLPOP and the key exists and contains a non empty list
7997 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7998 * if there is not to block.
7999 * - If instead BLPOP is called and the key does not exists or the list is
8000 * empty we need to block. In order to do so we remove the notification for
8001 * new data to read in the client socket (so that we'll not serve new
8002 * requests if the blocking request is not served). Also we put the client
37ab76c9 8003 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
4409877e 8004 * blocking for this keys.
8005 * - If a PUSH operation against a key with blocked clients waiting is
8006 * performed, we serve the first in the list: basically instead to push
8007 * the new element inside the list we return it to the (first / oldest)
8008 * blocking client, unblock the client, and remove it form the list.
8009 *
8010 * The above comment and the source code should be enough in order to understand
8011 * the implementation and modify / fix it later.
8012 */
8013
8014/* Set a client in blocking mode for the specified key, with the specified
8015 * timeout */
b177fd30 8016static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
4409877e 8017 dictEntry *de;
8018 list *l;
b177fd30 8019 int j;
4409877e 8020
37ab76c9 8021 c->blocking_keys = zmalloc(sizeof(robj*)*numkeys);
8022 c->blocking_keys_num = numkeys;
4409877e 8023 c->blockingto = timeout;
b177fd30 8024 for (j = 0; j < numkeys; j++) {
8025 /* Add the key in the client structure, to map clients -> keys */
37ab76c9 8026 c->blocking_keys[j] = keys[j];
b177fd30 8027 incrRefCount(keys[j]);
4409877e 8028
b177fd30 8029 /* And in the other "side", to map keys -> clients */
37ab76c9 8030 de = dictFind(c->db->blocking_keys,keys[j]);
b177fd30 8031 if (de == NULL) {
8032 int retval;
8033
8034 /* For every key we take a list of clients blocked for it */
8035 l = listCreate();
37ab76c9 8036 retval = dictAdd(c->db->blocking_keys,keys[j],l);
b177fd30 8037 incrRefCount(keys[j]);
8038 assert(retval == DICT_OK);
8039 } else {
8040 l = dictGetEntryVal(de);
8041 }
8042 listAddNodeTail(l,c);
4409877e 8043 }
b177fd30 8044 /* Mark the client as a blocked client */
4409877e 8045 c->flags |= REDIS_BLOCKED;
d5d55fc3 8046 server.blpop_blocked_clients++;
4409877e 8047}
8048
8049/* Unblock a client that's waiting in a blocking operation such as BLPOP */
b0d8747d 8050static void unblockClientWaitingData(redisClient *c) {
4409877e 8051 dictEntry *de;
8052 list *l;
b177fd30 8053 int j;
4409877e 8054
37ab76c9 8055 assert(c->blocking_keys != NULL);
b177fd30 8056 /* The client may wait for multiple keys, so unblock it for every key. */
37ab76c9 8057 for (j = 0; j < c->blocking_keys_num; j++) {
b177fd30 8058 /* Remove this client from the list of clients waiting for this key. */
37ab76c9 8059 de = dictFind(c->db->blocking_keys,c->blocking_keys[j]);
b177fd30 8060 assert(de != NULL);
8061 l = dictGetEntryVal(de);
8062 listDelNode(l,listSearchKey(l,c));
8063 /* If the list is empty we need to remove it to avoid wasting memory */
8064 if (listLength(l) == 0)
37ab76c9 8065 dictDelete(c->db->blocking_keys,c->blocking_keys[j]);
8066 decrRefCount(c->blocking_keys[j]);
b177fd30 8067 }
8068 /* Cleanup the client structure */
37ab76c9 8069 zfree(c->blocking_keys);
8070 c->blocking_keys = NULL;
4409877e 8071 c->flags &= (~REDIS_BLOCKED);
d5d55fc3 8072 server.blpop_blocked_clients--;
5921aa36 8073 /* We want to process data if there is some command waiting
b0d8747d 8074 * in the input buffer. Note that this is safe even if
8075 * unblockClientWaitingData() gets called from freeClient() because
8076 * freeClient() will be smart enough to call this function
8077 * *after* c->querybuf was set to NULL. */
4409877e 8078 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
8079}
8080
8081/* This should be called from any function PUSHing into lists.
8082 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
8083 * 'ele' is the element pushed.
8084 *
8085 * If the function returns 0 there was no client waiting for a list push
8086 * against this key.
8087 *
8088 * If the function returns 1 there was a client waiting for a list push
8089 * against this key, the element was passed to this client thus it's not
8090 * needed to actually add it to the list and the caller should return asap. */
8091static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
8092 struct dictEntry *de;
8093 redisClient *receiver;
8094 list *l;
8095 listNode *ln;
8096
37ab76c9 8097 de = dictFind(c->db->blocking_keys,key);
4409877e 8098 if (de == NULL) return 0;
8099 l = dictGetEntryVal(de);
8100 ln = listFirst(l);
8101 assert(ln != NULL);
8102 receiver = ln->value;
4409877e 8103
b177fd30 8104 addReplySds(receiver,sdsnew("*2\r\n"));
dd88747b 8105 addReplyBulk(receiver,key);
8106 addReplyBulk(receiver,ele);
b0d8747d 8107 unblockClientWaitingData(receiver);
4409877e 8108 return 1;
8109}
8110
8111/* Blocking RPOP/LPOP */
8112static void blockingPopGenericCommand(redisClient *c, int where) {
8113 robj *o;
8114 time_t timeout;
b177fd30 8115 int j;
4409877e 8116
b177fd30 8117 for (j = 1; j < c->argc-1; j++) {
8118 o = lookupKeyWrite(c->db,c->argv[j]);
8119 if (o != NULL) {
8120 if (o->type != REDIS_LIST) {
8121 addReply(c,shared.wrongtypeerr);
4409877e 8122 return;
b177fd30 8123 } else {
8124 list *list = o->ptr;
8125 if (listLength(list) != 0) {
8126 /* If the list contains elements fall back to the usual
8127 * non-blocking POP operation */
8128 robj *argv[2], **orig_argv;
8129 int orig_argc;
e0a62c7f 8130
b177fd30 8131 /* We need to alter the command arguments before to call
8132 * popGenericCommand() as the command takes a single key. */
8133 orig_argv = c->argv;
8134 orig_argc = c->argc;
8135 argv[1] = c->argv[j];
8136 c->argv = argv;
8137 c->argc = 2;
8138
8139 /* Also the return value is different, we need to output
8140 * the multi bulk reply header and the key name. The
8141 * "real" command will add the last element (the value)
8142 * for us. If this souds like an hack to you it's just
8143 * because it is... */
8144 addReplySds(c,sdsnew("*2\r\n"));
dd88747b 8145 addReplyBulk(c,argv[1]);
b177fd30 8146 popGenericCommand(c,where);
8147
8148 /* Fix the client structure with the original stuff */
8149 c->argv = orig_argv;
8150 c->argc = orig_argc;
8151 return;
8152 }
4409877e 8153 }
8154 }
8155 }
8156 /* If the list is empty or the key does not exists we must block */
b177fd30 8157 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
4409877e 8158 if (timeout > 0) timeout += time(NULL);
b177fd30 8159 blockForKeys(c,c->argv+1,c->argc-2,timeout);
4409877e 8160}
8161
8162static void blpopCommand(redisClient *c) {
8163 blockingPopGenericCommand(c,REDIS_HEAD);
8164}
8165
8166static void brpopCommand(redisClient *c) {
8167 blockingPopGenericCommand(c,REDIS_TAIL);
8168}
8169
ed9b544e 8170/* =============================== Replication ============================= */
8171
a4d1ba9a 8172static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 8173 ssize_t nwritten, ret = size;
8174 time_t start = time(NULL);
8175
8176 timeout++;
8177 while(size) {
8178 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
8179 nwritten = write(fd,ptr,size);
8180 if (nwritten == -1) return -1;
8181 ptr += nwritten;
8182 size -= nwritten;
8183 }
8184 if ((time(NULL)-start) > timeout) {
8185 errno = ETIMEDOUT;
8186 return -1;
8187 }
8188 }
8189 return ret;
8190}
8191
a4d1ba9a 8192static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 8193 ssize_t nread, totread = 0;
8194 time_t start = time(NULL);
8195
8196 timeout++;
8197 while(size) {
8198 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
8199 nread = read(fd,ptr,size);
8200 if (nread == -1) return -1;
8201 ptr += nread;
8202 size -= nread;
8203 totread += nread;
8204 }
8205 if ((time(NULL)-start) > timeout) {
8206 errno = ETIMEDOUT;
8207 return -1;
8208 }
8209 }
8210 return totread;
8211}
8212
8213static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
8214 ssize_t nread = 0;
8215
8216 size--;
8217 while(size) {
8218 char c;
8219
8220 if (syncRead(fd,&c,1,timeout) == -1) return -1;
8221 if (c == '\n') {
8222 *ptr = '\0';
8223 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
8224 return nread;
8225 } else {
8226 *ptr++ = c;
8227 *ptr = '\0';
8228 nread++;
8229 }
8230 }
8231 return nread;
8232}
8233
8234static void syncCommand(redisClient *c) {
40d224a9 8235 /* ignore SYNC if aleady slave or in monitor mode */
8236 if (c->flags & REDIS_SLAVE) return;
8237
8238 /* SYNC can't be issued when the server has pending data to send to
8239 * the client about already issued commands. We need a fresh reply
8240 * buffer registering the differences between the BGSAVE and the current
8241 * dataset, so that we can copy to other slaves if needed. */
8242 if (listLength(c->reply) != 0) {
8243 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
8244 return;
8245 }
8246
8247 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
8248 /* Here we need to check if there is a background saving operation
8249 * in progress, or if it is required to start one */
9d65a1bb 8250 if (server.bgsavechildpid != -1) {
40d224a9 8251 /* Ok a background save is in progress. Let's check if it is a good
8252 * one for replication, i.e. if there is another slave that is
8253 * registering differences since the server forked to save */
8254 redisClient *slave;
8255 listNode *ln;
c7df85a4 8256 listIter li;
40d224a9 8257
c7df85a4 8258 listRewind(server.slaves,&li);
8259 while((ln = listNext(&li))) {
40d224a9 8260 slave = ln->value;
8261 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
40d224a9 8262 }
8263 if (ln) {
8264 /* Perfect, the server is already registering differences for
8265 * another slave. Set the right state, and copy the buffer. */
8266 listRelease(c->reply);
8267 c->reply = listDup(slave->reply);
40d224a9 8268 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8269 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
8270 } else {
8271 /* No way, we need to wait for the next BGSAVE in order to
8272 * register differences */
8273 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
8274 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
8275 }
8276 } else {
8277 /* Ok we don't have a BGSAVE in progress, let's start one */
8278 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
8279 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
8280 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
8281 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
8282 return;
8283 }
8284 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8285 }
6208b3a7 8286 c->repldbfd = -1;
40d224a9 8287 c->flags |= REDIS_SLAVE;
8288 c->slaveseldb = 0;
6b47e12e 8289 listAddNodeTail(server.slaves,c);
40d224a9 8290 return;
8291}
8292
6208b3a7 8293static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
8294 redisClient *slave = privdata;
8295 REDIS_NOTUSED(el);
8296 REDIS_NOTUSED(mask);
8297 char buf[REDIS_IOBUF_LEN];
8298 ssize_t nwritten, buflen;
8299
8300 if (slave->repldboff == 0) {
8301 /* Write the bulk write count before to transfer the DB. In theory here
8302 * we don't know how much room there is in the output buffer of the
8303 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
8304 * operations) will never be smaller than the few bytes we need. */
8305 sds bulkcount;
8306
8307 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
8308 slave->repldbsize);
8309 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
8310 {
8311 sdsfree(bulkcount);
8312 freeClient(slave);
8313 return;
8314 }
8315 sdsfree(bulkcount);
8316 }
8317 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
8318 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
8319 if (buflen <= 0) {
8320 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
8321 (buflen == 0) ? "premature EOF" : strerror(errno));
8322 freeClient(slave);
8323 return;
8324 }
8325 if ((nwritten = write(fd,buf,buflen)) == -1) {
f870935d 8326 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
6208b3a7 8327 strerror(errno));
8328 freeClient(slave);
8329 return;
8330 }
8331 slave->repldboff += nwritten;
8332 if (slave->repldboff == slave->repldbsize) {
8333 close(slave->repldbfd);
8334 slave->repldbfd = -1;
8335 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
8336 slave->replstate = REDIS_REPL_ONLINE;
8337 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
266373b2 8338 sendReplyToClient, slave) == AE_ERR) {
6208b3a7 8339 freeClient(slave);
8340 return;
8341 }
8342 addReplySds(slave,sdsempty());
8343 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
8344 }
8345}
ed9b544e 8346
a3b21203 8347/* This function is called at the end of every backgrond saving.
8348 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
8349 * otherwise REDIS_ERR is passed to the function.
8350 *
8351 * The goal of this function is to handle slaves waiting for a successful
8352 * background saving in order to perform non-blocking synchronization. */
8353static void updateSlavesWaitingBgsave(int bgsaveerr) {
6208b3a7 8354 listNode *ln;
8355 int startbgsave = 0;
c7df85a4 8356 listIter li;
ed9b544e 8357
c7df85a4 8358 listRewind(server.slaves,&li);
8359 while((ln = listNext(&li))) {
6208b3a7 8360 redisClient *slave = ln->value;
ed9b544e 8361
6208b3a7 8362 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
8363 startbgsave = 1;
8364 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
8365 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
dde65f3f 8366 struct redis_stat buf;
e0a62c7f 8367
6208b3a7 8368 if (bgsaveerr != REDIS_OK) {
8369 freeClient(slave);
8370 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
8371 continue;
8372 }
8373 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
dde65f3f 8374 redis_fstat(slave->repldbfd,&buf) == -1) {
6208b3a7 8375 freeClient(slave);
8376 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
8377 continue;
8378 }
8379 slave->repldboff = 0;
8380 slave->repldbsize = buf.st_size;
8381 slave->replstate = REDIS_REPL_SEND_BULK;
8382 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
266373b2 8383 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
6208b3a7 8384 freeClient(slave);
8385 continue;
8386 }
8387 }
ed9b544e 8388 }
6208b3a7 8389 if (startbgsave) {
8390 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
c7df85a4 8391 listIter li;
8392
8393 listRewind(server.slaves,&li);
6208b3a7 8394 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
c7df85a4 8395 while((ln = listNext(&li))) {
6208b3a7 8396 redisClient *slave = ln->value;
ed9b544e 8397
6208b3a7 8398 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
8399 freeClient(slave);
8400 }
8401 }
8402 }
ed9b544e 8403}
8404
8405static int syncWithMaster(void) {
d0ccebcf 8406 char buf[1024], tmpfile[256], authcmd[1024];
18e61fa2 8407 long dumpsize;
ed9b544e 8408 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
8c5abee8 8409 int dfd, maxtries = 5;
ed9b544e 8410
8411 if (fd == -1) {
8412 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
8413 strerror(errno));
8414 return REDIS_ERR;
8415 }
d0ccebcf 8416
8417 /* AUTH with the master if required. */
8418 if(server.masterauth) {
8419 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
8420 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
8421 close(fd);
8422 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
8423 strerror(errno));
8424 return REDIS_ERR;
8425 }
8426 /* Read the AUTH result. */
8427 if (syncReadLine(fd,buf,1024,3600) == -1) {
8428 close(fd);
8429 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
8430 strerror(errno));
8431 return REDIS_ERR;
8432 }
8433 if (buf[0] != '+') {
8434 close(fd);
8435 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
8436 return REDIS_ERR;
8437 }
8438 }
8439
ed9b544e 8440 /* Issue the SYNC command */
8441 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
8442 close(fd);
8443 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
8444 strerror(errno));
8445 return REDIS_ERR;
8446 }
8447 /* Read the bulk write count */
8c4d91fc 8448 if (syncReadLine(fd,buf,1024,3600) == -1) {
ed9b544e 8449 close(fd);
8450 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
8451 strerror(errno));
8452 return REDIS_ERR;
8453 }
4aa701c1 8454 if (buf[0] != '$') {
8455 close(fd);
8456 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8457 return REDIS_ERR;
8458 }
18e61fa2 8459 dumpsize = strtol(buf+1,NULL,10);
8460 redisLog(REDIS_NOTICE,"Receiving %ld bytes data dump from MASTER",dumpsize);
ed9b544e 8461 /* Read the bulk write data on a temp file */
8c5abee8 8462 while(maxtries--) {
8463 snprintf(tmpfile,256,
8464 "temp-%d.%ld.rdb",(int)time(NULL),(long int)getpid());
8465 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
8466 if (dfd != -1) break;
5de9ad7c 8467 sleep(1);
8c5abee8 8468 }
ed9b544e 8469 if (dfd == -1) {
8470 close(fd);
8471 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
8472 return REDIS_ERR;
8473 }
8474 while(dumpsize) {
8475 int nread, nwritten;
8476
8477 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
8478 if (nread == -1) {
8479 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
8480 strerror(errno));
8481 close(fd);
8482 close(dfd);
8483 return REDIS_ERR;
8484 }
8485 nwritten = write(dfd,buf,nread);
8486 if (nwritten == -1) {
8487 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
8488 close(fd);
8489 close(dfd);
8490 return REDIS_ERR;
8491 }
8492 dumpsize -= nread;
8493 }
8494 close(dfd);
8495 if (rename(tmpfile,server.dbfilename) == -1) {
8496 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
8497 unlink(tmpfile);
8498 close(fd);
8499 return REDIS_ERR;
8500 }
8501 emptyDb();
f78fd11b 8502 if (rdbLoad(server.dbfilename) != REDIS_OK) {
ed9b544e 8503 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
8504 close(fd);
8505 return REDIS_ERR;
8506 }
8507 server.master = createClient(fd);
8508 server.master->flags |= REDIS_MASTER;
179b3952 8509 server.master->authenticated = 1;
ed9b544e 8510 server.replstate = REDIS_REPL_CONNECTED;
8511 return REDIS_OK;
8512}
8513
321b0e13 8514static void slaveofCommand(redisClient *c) {
8515 if (!strcasecmp(c->argv[1]->ptr,"no") &&
8516 !strcasecmp(c->argv[2]->ptr,"one")) {
8517 if (server.masterhost) {
8518 sdsfree(server.masterhost);
8519 server.masterhost = NULL;
8520 if (server.master) freeClient(server.master);
8521 server.replstate = REDIS_REPL_NONE;
8522 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
8523 }
8524 } else {
8525 sdsfree(server.masterhost);
8526 server.masterhost = sdsdup(c->argv[1]->ptr);
8527 server.masterport = atoi(c->argv[2]->ptr);
8528 if (server.master) freeClient(server.master);
8529 server.replstate = REDIS_REPL_CONNECT;
8530 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
8531 server.masterhost, server.masterport);
8532 }
8533 addReply(c,shared.ok);
8534}
8535
3fd78bcd 8536/* ============================ Maxmemory directive ======================== */
8537
a5819310 8538/* Try to free one object form the pre-allocated objects free list.
8539 * This is useful under low mem conditions as by default we take 1 million
8540 * free objects allocated. On success REDIS_OK is returned, otherwise
8541 * REDIS_ERR. */
8542static int tryFreeOneObjectFromFreelist(void) {
f870935d 8543 robj *o;
8544
a5819310 8545 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
8546 if (listLength(server.objfreelist)) {
8547 listNode *head = listFirst(server.objfreelist);
8548 o = listNodeValue(head);
8549 listDelNode(server.objfreelist,head);
8550 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8551 zfree(o);
8552 return REDIS_OK;
8553 } else {
8554 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8555 return REDIS_ERR;
8556 }
f870935d 8557}
8558
3fd78bcd 8559/* This function gets called when 'maxmemory' is set on the config file to limit
8560 * the max memory used by the server, and we are out of memory.
8561 * This function will try to, in order:
8562 *
8563 * - Free objects from the free list
8564 * - Try to remove keys with an EXPIRE set
8565 *
8566 * It is not possible to free enough memory to reach used-memory < maxmemory
8567 * the server will start refusing commands that will enlarge even more the
8568 * memory usage.
8569 */
8570static void freeMemoryIfNeeded(void) {
8571 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
a5819310 8572 int j, k, freed = 0;
8573
8574 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
8575 for (j = 0; j < server.dbnum; j++) {
8576 int minttl = -1;
8577 robj *minkey = NULL;
8578 struct dictEntry *de;
8579
8580 if (dictSize(server.db[j].expires)) {
8581 freed = 1;
8582 /* From a sample of three keys drop the one nearest to
8583 * the natural expire */
8584 for (k = 0; k < 3; k++) {
8585 time_t t;
8586
8587 de = dictGetRandomKey(server.db[j].expires);
8588 t = (time_t) dictGetEntryVal(de);
8589 if (minttl == -1 || t < minttl) {
8590 minkey = dictGetEntryKey(de);
8591 minttl = t;
3fd78bcd 8592 }
3fd78bcd 8593 }
09241813 8594 dbDelete(server.db+j,minkey);
3fd78bcd 8595 }
3fd78bcd 8596 }
a5819310 8597 if (!freed) return; /* nothing to free... */
3fd78bcd 8598 }
8599}
8600
f80dff62 8601/* ============================== Append Only file ========================== */
8602
560db612 8603/* Called when the user switches from "appendonly yes" to "appendonly no"
8604 * at runtime using the CONFIG command. */
8605static void stopAppendOnly(void) {
8606 flushAppendOnlyFile();
8607 aof_fsync(server.appendfd);
8608 close(server.appendfd);
8609
8610 server.appendfd = -1;
8611 server.appendseldb = -1;
8612 server.appendonly = 0;
8613 /* rewrite operation in progress? kill it, wait child exit */
8614 if (server.bgsavechildpid != -1) {
8615 int statloc;
8616
8617 if (kill(server.bgsavechildpid,SIGKILL) != -1)
8618 wait3(&statloc,0,NULL);
8619 /* reset the buffer accumulating changes while the child saves */
8620 sdsfree(server.bgrewritebuf);
8621 server.bgrewritebuf = sdsempty();
8622 server.bgsavechildpid = -1;
8623 }
8624}
8625
8626/* Called when the user switches from "appendonly no" to "appendonly yes"
8627 * at runtime using the CONFIG command. */
8628static int startAppendOnly(void) {
8629 server.appendonly = 1;
8630 server.lastfsync = time(NULL);
8631 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
8632 if (server.appendfd == -1) {
8633 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno));
8634 return REDIS_ERR;
8635 }
8636 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
8637 server.appendonly = 0;
8638 close(server.appendfd);
8639 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));
8640 return REDIS_ERR;
8641 }
8642 return REDIS_OK;
8643}
8644
28ed1f33 8645/* Write the append only file buffer on disk.
8646 *
8647 * Since we are required to write the AOF before replying to the client,
8648 * and the only way the client socket can get a write is entering when the
8649 * the event loop, we accumulate all the AOF writes in a memory
8650 * buffer and write it on disk using this function just before entering
8651 * the event loop again. */
8652static void flushAppendOnlyFile(void) {
8653 time_t now;
8654 ssize_t nwritten;
8655
8656 if (sdslen(server.aofbuf) == 0) return;
8657
8658 /* We want to perform a single write. This should be guaranteed atomic
8659 * at least if the filesystem we are writing is a real physical one.
8660 * While this will save us against the server being killed I don't think
8661 * there is much to do about the whole server stopping for power problems
8662 * or alike */
8663 nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf));
8664 if (nwritten != (signed)sdslen(server.aofbuf)) {
8665 /* Ooops, we are in troubles. The best thing to do for now is
8666 * aborting instead of giving the illusion that everything is
8667 * working as expected. */
8668 if (nwritten == -1) {
8669 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
8670 } else {
8671 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
8672 }
8673 exit(1);
8674 }
8675 sdsfree(server.aofbuf);
8676 server.aofbuf = sdsempty();
8677
38db9171 8678 /* Don't Fsync if no-appendfsync-on-rewrite is set to yes and we have
8679 * childs performing heavy I/O on disk. */
8680 if (server.no_appendfsync_on_rewrite &&
8681 (server.bgrewritechildpid != -1 || server.bgsavechildpid != -1))
8682 return;
28ed1f33 8683 /* Fsync if needed */
8684 now = time(NULL);
8685 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
8686 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
8687 now-server.lastfsync > 1))
8688 {
8689 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8690 * flushing metadata. */
8691 aof_fsync(server.appendfd); /* Let's try to get this data on the disk */
8692 server.lastfsync = now;
8693 }
8694}
8695
9376e434
PN
8696static sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) {
8697 int j;
8698 buf = sdscatprintf(buf,"*%d\r\n",argc);
8699 for (j = 0; j < argc; j++) {
8700 robj *o = getDecodedObject(argv[j]);
8701 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
8702 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
8703 buf = sdscatlen(buf,"\r\n",2);
8704 decrRefCount(o);
8705 }
8706 return buf;
8707}
8708
8709static sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) {
8710 int argc = 3;
8711 long when;
8712 robj *argv[3];
8713
8714 /* Make sure we can use strtol */
8715 seconds = getDecodedObject(seconds);
8716 when = time(NULL)+strtol(seconds->ptr,NULL,10);
8717 decrRefCount(seconds);
8718
8719 argv[0] = createStringObject("EXPIREAT",8);
8720 argv[1] = key;
8721 argv[2] = createObject(REDIS_STRING,
8722 sdscatprintf(sdsempty(),"%ld",when));
8723 buf = catAppendOnlyGenericCommand(buf, argc, argv);
8724 decrRefCount(argv[0]);
8725 decrRefCount(argv[2]);
8726 return buf;
8727}
8728
f80dff62 8729static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
8730 sds buf = sdsempty();
f80dff62 8731 robj *tmpargv[3];
8732
8733 /* The DB this command was targetting is not the same as the last command
8734 * we appendend. To issue a SELECT command is needed. */
8735 if (dictid != server.appendseldb) {
8736 char seldb[64];
8737
8738 snprintf(seldb,sizeof(seldb),"%d",dictid);
682ac724 8739 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
83c6a618 8740 (unsigned long)strlen(seldb),seldb);
f80dff62 8741 server.appendseldb = dictid;
8742 }
8743
f80dff62 8744 if (cmd->proc == expireCommand) {
9376e434
PN
8745 /* Translate EXPIRE into EXPIREAT */
8746 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8747 } else if (cmd->proc == setexCommand) {
8748 /* Translate SETEX to SET and EXPIREAT */
8749 tmpargv[0] = createStringObject("SET",3);
f80dff62 8750 tmpargv[1] = argv[1];
9376e434
PN
8751 tmpargv[2] = argv[3];
8752 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
8753 decrRefCount(tmpargv[0]);
8754 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8755 } else {
8756 buf = catAppendOnlyGenericCommand(buf,argc,argv);
f80dff62 8757 }
8758
28ed1f33 8759 /* Append to the AOF buffer. This will be flushed on disk just before
8760 * of re-entering the event loop, so before the client will get a
8761 * positive reply about the operation performed. */
8762 server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf));
8763
85a83172 8764 /* If a background append only file rewriting is in progress we want to
8765 * accumulate the differences between the child DB and the current one
8766 * in a buffer, so that when the child process will do its work we
8767 * can append the differences to the new append only file. */
8768 if (server.bgrewritechildpid != -1)
8769 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
8770
8771 sdsfree(buf);
f80dff62 8772}
8773
8774/* In Redis commands are always executed in the context of a client, so in
8775 * order to load the append only file we need to create a fake client. */
8776static struct redisClient *createFakeClient(void) {
8777 struct redisClient *c = zmalloc(sizeof(*c));
8778
8779 selectDb(c,0);
8780 c->fd = -1;
8781 c->querybuf = sdsempty();
8782 c->argc = 0;
8783 c->argv = NULL;
8784 c->flags = 0;
9387d17d 8785 /* We set the fake client as a slave waiting for the synchronization
8786 * so that Redis will not try to send replies to this client. */
8787 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
f80dff62 8788 c->reply = listCreate();
8789 listSetFreeMethod(c->reply,decrRefCount);
8790 listSetDupMethod(c->reply,dupClientReplyValue);
4132ad8d 8791 initClientMultiState(c);
f80dff62 8792 return c;
8793}
8794
8795static void freeFakeClient(struct redisClient *c) {
8796 sdsfree(c->querybuf);
8797 listRelease(c->reply);
4132ad8d 8798 freeClientMultiState(c);
f80dff62 8799 zfree(c);
8800}
8801
8802/* Replay the append log file. On error REDIS_OK is returned. On non fatal
8803 * error (the append only file is zero-length) REDIS_ERR is returned. On
8804 * fatal error an error message is logged and the program exists. */
8805int loadAppendOnlyFile(char *filename) {
8806 struct redisClient *fakeClient;
8807 FILE *fp = fopen(filename,"r");
8808 struct redis_stat sb;
4132ad8d 8809 int appendonly = server.appendonly;
f80dff62 8810
8811 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
8812 return REDIS_ERR;
8813
8814 if (fp == NULL) {
8815 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
8816 exit(1);
8817 }
8818
4132ad8d
PN
8819 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8820 * to the same file we're about to read. */
8821 server.appendonly = 0;
8822
f80dff62 8823 fakeClient = createFakeClient();
8824 while(1) {
8825 int argc, j;
8826 unsigned long len;
8827 robj **argv;
8828 char buf[128];
8829 sds argsds;
8830 struct redisCommand *cmd;
a89b7013 8831 int force_swapout;
f80dff62 8832
8833 if (fgets(buf,sizeof(buf),fp) == NULL) {
8834 if (feof(fp))
8835 break;
8836 else
8837 goto readerr;
8838 }
8839 if (buf[0] != '*') goto fmterr;
8840 argc = atoi(buf+1);
8841 argv = zmalloc(sizeof(robj*)*argc);
8842 for (j = 0; j < argc; j++) {
8843 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
8844 if (buf[0] != '$') goto fmterr;
8845 len = strtol(buf+1,NULL,10);
8846 argsds = sdsnewlen(NULL,len);
0f151ef1 8847 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
f80dff62 8848 argv[j] = createObject(REDIS_STRING,argsds);
8849 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
8850 }
8851
8852 /* Command lookup */
8853 cmd = lookupCommand(argv[0]->ptr);
8854 if (!cmd) {
8855 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
8856 exit(1);
8857 }
bdcb92f2 8858 /* Try object encoding */
f80dff62 8859 if (cmd->flags & REDIS_CMD_BULK)
05df7621 8860 argv[argc-1] = tryObjectEncoding(argv[argc-1]);
f80dff62 8861 /* Run the command in the context of a fake client */
8862 fakeClient->argc = argc;
8863 fakeClient->argv = argv;
8864 cmd->proc(fakeClient);
8865 /* Discard the reply objects list from the fake client */
8866 while(listLength(fakeClient->reply))
8867 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
8868 /* Clean up, ready for the next command */
8869 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
8870 zfree(argv);
b492cf00 8871 /* Handle swapping while loading big datasets when VM is on */
a89b7013 8872 force_swapout = 0;
8873 if ((zmalloc_used_memory() - server.vm_max_memory) > 1024*1024*32)
8874 force_swapout = 1;
8875
8876 if (server.vm_enabled && force_swapout) {
b492cf00 8877 while (zmalloc_used_memory() > server.vm_max_memory) {
a69a0c9c 8878 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
b492cf00 8879 }
8880 }
f80dff62 8881 }
4132ad8d
PN
8882
8883 /* This point can only be reached when EOF is reached without errors.
8884 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8885 if (fakeClient->flags & REDIS_MULTI) goto readerr;
8886
f80dff62 8887 fclose(fp);
8888 freeFakeClient(fakeClient);
4132ad8d 8889 server.appendonly = appendonly;
f80dff62 8890 return REDIS_OK;
8891
8892readerr:
8893 if (feof(fp)) {
8894 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
8895 } else {
8896 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
8897 }
8898 exit(1);
8899fmterr:
8900 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
8901 exit(1);
8902}
8903
9c8e3cee 8904/* Write binary-safe string into a file in the bulkformat
8905 * $<count>\r\n<payload>\r\n */
8906static int fwriteBulkString(FILE *fp, char *s, unsigned long len) {
9eaef89f
PN
8907 char cbuf[128];
8908 int clen;
8909 cbuf[0] = '$';
8910 clen = 1+ll2string(cbuf+1,sizeof(cbuf)-1,len);
8911 cbuf[clen++] = '\r';
8912 cbuf[clen++] = '\n';
8913 if (fwrite(cbuf,clen,1,fp) == 0) return 0;
8914 if (len > 0 && fwrite(s,len,1,fp) == 0) return 0;
9c8e3cee 8915 if (fwrite("\r\n",2,1,fp) == 0) return 0;
8916 return 1;
8917}
8918
9d65a1bb 8919/* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8920static int fwriteBulkDouble(FILE *fp, double d) {
8921 char buf[128], dbuf[128];
8922
8923 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
8924 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
8925 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8926 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
8927 return 1;
8928}
8929
8930/* Write a long value in bulk format $<count>\r\n<payload>\r\n */
9eaef89f
PN
8931static int fwriteBulkLongLong(FILE *fp, long long l) {
8932 char bbuf[128], lbuf[128];
8933 unsigned int blen, llen;
8934 llen = ll2string(lbuf,32,l);
8935 blen = snprintf(bbuf,sizeof(bbuf),"$%u\r\n%s\r\n",llen,lbuf);
8936 if (fwrite(bbuf,blen,1,fp) == 0) return 0;
9d65a1bb 8937 return 1;
8938}
8939
9eaef89f
PN
8940/* Delegate writing an object to writing a bulk string or bulk long long. */
8941static int fwriteBulkObject(FILE *fp, robj *obj) {
8942 /* Avoid using getDecodedObject to help copy-on-write (we are often
8943 * in a child process when this function is called). */
8944 if (obj->encoding == REDIS_ENCODING_INT) {
8945 return fwriteBulkLongLong(fp,(long)obj->ptr);
8946 } else if (obj->encoding == REDIS_ENCODING_RAW) {
8947 return fwriteBulkString(fp,obj->ptr,sdslen(obj->ptr));
8948 } else {
8949 redisPanic("Unknown string encoding");
8950 }
8951}
8952
9d65a1bb 8953/* Write a sequence of commands able to fully rebuild the dataset into
8954 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8955static int rewriteAppendOnlyFile(char *filename) {
8956 dictIterator *di = NULL;
8957 dictEntry *de;
8958 FILE *fp;
8959 char tmpfile[256];
8960 int j;
8961 time_t now = time(NULL);
8962
8963 /* Note that we have to use a different temp name here compared to the
8964 * one used by rewriteAppendOnlyFileBackground() function. */
8965 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
8966 fp = fopen(tmpfile,"w");
8967 if (!fp) {
8968 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
8969 return REDIS_ERR;
8970 }
8971 for (j = 0; j < server.dbnum; j++) {
8972 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
8973 redisDb *db = server.db+j;
8974 dict *d = db->dict;
8975 if (dictSize(d) == 0) continue;
8976 di = dictGetIterator(d);
8977 if (!di) {
8978 fclose(fp);
8979 return REDIS_ERR;
8980 }
8981
8982 /* SELECT the new DB */
8983 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
9eaef89f 8984 if (fwriteBulkLongLong(fp,j) == 0) goto werr;
9d65a1bb 8985
8986 /* Iterate this DB writing every entry */
8987 while((de = dictNext(di)) != NULL) {
09241813 8988 sds keystr = dictGetEntryKey(de);
8989 robj key, *o;
e7546c63 8990 time_t expiretime;
8991 int swapped;
8992
09241813 8993 keystr = dictGetEntryKey(de);
560db612 8994 o = dictGetEntryVal(de);
09241813 8995 initStaticStringObject(key,keystr);
b9bc0eef 8996 /* If the value for this key is swapped, load a preview in memory.
8997 * We use a "swapped" flag to remember if we need to free the
8998 * value object instead to just increment the ref count anyway
8999 * in order to avoid copy-on-write of pages if we are forked() */
560db612 9000 if (!server.vm_enabled || o->storage == REDIS_VM_MEMORY ||
9001 o->storage == REDIS_VM_SWAPPING) {
e7546c63 9002 swapped = 0;
9003 } else {
560db612 9004 o = vmPreviewObject(o);
e7546c63 9005 swapped = 1;
9006 }
09241813 9007 expiretime = getExpire(db,&key);
9d65a1bb 9008
9009 /* Save the key and associated value */
9d65a1bb 9010 if (o->type == REDIS_STRING) {
9011 /* Emit a SET command */
9012 char cmd[]="*3\r\n$3\r\nSET\r\n";
9013 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9014 /* Key and value */
09241813 9015 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9c8e3cee 9016 if (fwriteBulkObject(fp,o) == 0) goto werr;
9d65a1bb 9017 } else if (o->type == REDIS_LIST) {
9018 /* Emit the RPUSHes needed to rebuild the list */
6ddc908a
PN
9019 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
9020 if (o->encoding == REDIS_ENCODING_ZIPLIST) {
9021 unsigned char *zl = o->ptr;
9022 unsigned char *p = ziplistIndex(zl,0);
9023 unsigned char *vstr;
9024 unsigned int vlen;
9025 long long vlong;
9026
9027 while(ziplistGet(p,&vstr,&vlen,&vlong)) {
9028 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
846d8b3e 9029 if (fwriteBulkObject(fp,&key) == 0) goto werr;
6ddc908a
PN
9030 if (vstr) {
9031 if (fwriteBulkString(fp,(char*)vstr,vlen) == 0)
9032 goto werr;
9033 } else {
9034 if (fwriteBulkLongLong(fp,vlong) == 0)
9035 goto werr;
9036 }
9037 p = ziplistNext(zl,p);
9038 }
9039 } else if (o->encoding == REDIS_ENCODING_LIST) {
9040 list *list = o->ptr;
9041 listNode *ln;
9042 listIter li;
9043
9044 listRewind(list,&li);
9045 while((ln = listNext(&li))) {
9046 robj *eleobj = listNodeValue(ln);
9047
9048 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
846d8b3e 9049 if (fwriteBulkObject(fp,&key) == 0) goto werr;
6ddc908a
PN
9050 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9051 }
9052 } else {
9053 redisPanic("Unknown list encoding");
9d65a1bb 9054 }
9055 } else if (o->type == REDIS_SET) {
9056 /* Emit the SADDs needed to rebuild the set */
9057 dict *set = o->ptr;
9058 dictIterator *di = dictGetIterator(set);
9059 dictEntry *de;
9060
9061 while((de = dictNext(di)) != NULL) {
9062 char cmd[]="*3\r\n$4\r\nSADD\r\n";
9063 robj *eleobj = dictGetEntryKey(de);
9064
9065 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
09241813 9066 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9c8e3cee 9067 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 9068 }
9069 dictReleaseIterator(di);
9070 } else if (o->type == REDIS_ZSET) {
9071 /* Emit the ZADDs needed to rebuild the sorted set */
9072 zset *zs = o->ptr;
9073 dictIterator *di = dictGetIterator(zs->dict);
9074 dictEntry *de;
9075
9076 while((de = dictNext(di)) != NULL) {
9077 char cmd[]="*4\r\n$4\r\nZADD\r\n";
9078 robj *eleobj = dictGetEntryKey(de);
9079 double *score = dictGetEntryVal(de);
9080
9081 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
09241813 9082 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9d65a1bb 9083 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
9c8e3cee 9084 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 9085 }
9086 dictReleaseIterator(di);
9c8e3cee 9087 } else if (o->type == REDIS_HASH) {
9088 char cmd[]="*4\r\n$4\r\nHSET\r\n";
9089
9090 /* Emit the HSETs needed to rebuild the hash */
9091 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9092 unsigned char *p = zipmapRewind(o->ptr);
9093 unsigned char *field, *val;
9094 unsigned int flen, vlen;
9095
9096 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
9097 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
09241813 9098 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9c8e3cee 9099 if (fwriteBulkString(fp,(char*)field,flen) == -1)
9100 return -1;
9101 if (fwriteBulkString(fp,(char*)val,vlen) == -1)
9102 return -1;
9103 }
9104 } else {
9105 dictIterator *di = dictGetIterator(o->ptr);
9106 dictEntry *de;
9107
9108 while((de = dictNext(di)) != NULL) {
9109 robj *field = dictGetEntryKey(de);
9110 robj *val = dictGetEntryVal(de);
9111
9112 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
09241813 9113 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9c8e3cee 9114 if (fwriteBulkObject(fp,field) == -1) return -1;
9115 if (fwriteBulkObject(fp,val) == -1) return -1;
9116 }
9117 dictReleaseIterator(di);
9118 }
9d65a1bb 9119 } else {
f83c6cb5 9120 redisPanic("Unknown object type");
9d65a1bb 9121 }
9122 /* Save the expire time */
9123 if (expiretime != -1) {
e96e4fbf 9124 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
9d65a1bb 9125 /* If this key is already expired skip it */
9126 if (expiretime < now) continue;
9127 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
09241813 9128 if (fwriteBulkObject(fp,&key) == 0) goto werr;
9eaef89f 9129 if (fwriteBulkLongLong(fp,expiretime) == 0) goto werr;
9d65a1bb 9130 }
b9bc0eef 9131 if (swapped) decrRefCount(o);
9d65a1bb 9132 }
9133 dictReleaseIterator(di);
9134 }
9135
9136 /* Make sure data will not remain on the OS's output buffers */
9137 fflush(fp);
b0bd87f6 9138 aof_fsync(fileno(fp));
9d65a1bb 9139 fclose(fp);
e0a62c7f 9140
9d65a1bb 9141 /* Use RENAME to make sure the DB file is changed atomically only
9142 * if the generate DB file is ok. */
9143 if (rename(tmpfile,filename) == -1) {
9144 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
9145 unlink(tmpfile);
9146 return REDIS_ERR;
9147 }
9148 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
9149 return REDIS_OK;
9150
9151werr:
9152 fclose(fp);
9153 unlink(tmpfile);
e96e4fbf 9154 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
9d65a1bb 9155 if (di) dictReleaseIterator(di);
9156 return REDIS_ERR;
9157}
9158
9159/* This is how rewriting of the append only file in background works:
9160 *
9161 * 1) The user calls BGREWRITEAOF
9162 * 2) Redis calls this function, that forks():
9163 * 2a) the child rewrite the append only file in a temp file.
9164 * 2b) the parent accumulates differences in server.bgrewritebuf.
9165 * 3) When the child finished '2a' exists.
9166 * 4) The parent will trap the exit code, if it's OK, will append the
9167 * data accumulated into server.bgrewritebuf into the temp file, and
9168 * finally will rename(2) the temp file in the actual file name.
9169 * The the new file is reopened as the new append only file. Profit!
9170 */
9171static int rewriteAppendOnlyFileBackground(void) {
9172 pid_t childpid;
9173
9174 if (server.bgrewritechildpid != -1) return REDIS_ERR;
054e426d 9175 if (server.vm_enabled) waitEmptyIOJobsQueue();
9d65a1bb 9176 if ((childpid = fork()) == 0) {
9177 /* Child */
9178 char tmpfile[256];
9d65a1bb 9179
054e426d 9180 if (server.vm_enabled) vmReopenSwapFile();
9181 close(server.fd);
9d65a1bb 9182 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
9183 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
478c2c6f 9184 _exit(0);
9d65a1bb 9185 } else {
478c2c6f 9186 _exit(1);
9d65a1bb 9187 }
9188 } else {
9189 /* Parent */
9190 if (childpid == -1) {
9191 redisLog(REDIS_WARNING,
9192 "Can't rewrite append only file in background: fork: %s",
9193 strerror(errno));
9194 return REDIS_ERR;
9195 }
9196 redisLog(REDIS_NOTICE,
9197 "Background append only file rewriting started by pid %d",childpid);
9198 server.bgrewritechildpid = childpid;
884d4b39 9199 updateDictResizePolicy();
85a83172 9200 /* We set appendseldb to -1 in order to force the next call to the
9201 * feedAppendOnlyFile() to issue a SELECT command, so the differences
9202 * accumulated by the parent into server.bgrewritebuf will start
9203 * with a SELECT statement and it will be safe to merge. */
9204 server.appendseldb = -1;
9d65a1bb 9205 return REDIS_OK;
9206 }
9207 return REDIS_OK; /* unreached */
9208}
9209
9210static void bgrewriteaofCommand(redisClient *c) {
9211 if (server.bgrewritechildpid != -1) {
9212 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
9213 return;
9214 }
9215 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
49b99ab4 9216 char *status = "+Background append only file rewriting started\r\n";
9217 addReplySds(c,sdsnew(status));
9d65a1bb 9218 } else {
9219 addReply(c,shared.err);
9220 }
9221}
9222
9223static void aofRemoveTempFile(pid_t childpid) {
9224 char tmpfile[256];
9225
9226 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
9227 unlink(tmpfile);
9228}
9229
996cb5f7 9230/* Virtual Memory is composed mainly of two subsystems:
9231 * - Blocking Virutal Memory
9232 * - Threaded Virtual Memory I/O
9233 * The two parts are not fully decoupled, but functions are split among two
9234 * different sections of the source code (delimited by comments) in order to
9235 * make more clear what functionality is about the blocking VM and what about
9236 * the threaded (not blocking) VM.
9237 *
9238 * Redis VM design:
9239 *
9240 * Redis VM is a blocking VM (one that blocks reading swapped values from
9241 * disk into memory when a value swapped out is needed in memory) that is made
9242 * unblocking by trying to examine the command argument vector in order to
9243 * load in background values that will likely be needed in order to exec
9244 * the command. The command is executed only once all the relevant keys
9245 * are loaded into memory.
9246 *
9247 * This basically is almost as simple of a blocking VM, but almost as parallel
9248 * as a fully non-blocking VM.
9249 */
9250
560db612 9251/* =================== Virtual Memory - Blocking Side ====================== */
2e5eb04e 9252
560db612 9253/* Create a VM pointer object. This kind of objects are used in place of
9254 * values in the key -> value hash table, for swapped out objects. */
9255static vmpointer *createVmPointer(int vtype) {
9256 vmpointer *vp = zmalloc(sizeof(vmpointer));
2e5eb04e 9257
560db612 9258 vp->type = REDIS_VMPOINTER;
9259 vp->storage = REDIS_VM_SWAPPED;
9260 vp->vtype = vtype;
9261 return vp;
2e5eb04e 9262}
9263
75680a3c 9264static void vmInit(void) {
9265 off_t totsize;
996cb5f7 9266 int pipefds[2];
bcaa7a4f 9267 size_t stacksize;
8b5bb414 9268 struct flock fl;
75680a3c 9269
4ad37480 9270 if (server.vm_max_threads != 0)
9271 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
9272
054e426d 9273 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
8b5bb414 9274 /* Try to open the old swap file, otherwise create it */
6fa987e3 9275 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
9276 server.vm_fp = fopen(server.vm_swap_file,"w+b");
9277 }
75680a3c 9278 if (server.vm_fp == NULL) {
6fa987e3 9279 redisLog(REDIS_WARNING,
8b5bb414 9280 "Can't open the swap file: %s. Exiting.",
6fa987e3 9281 strerror(errno));
75680a3c 9282 exit(1);
9283 }
9284 server.vm_fd = fileno(server.vm_fp);
8b5bb414 9285 /* Lock the swap file for writing, this is useful in order to avoid
9286 * another instance to use the same swap file for a config error. */
9287 fl.l_type = F_WRLCK;
9288 fl.l_whence = SEEK_SET;
9289 fl.l_start = fl.l_len = 0;
9290 if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
9291 redisLog(REDIS_WARNING,
9292 "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));
9293 exit(1);
9294 }
9295 /* Initialize */
75680a3c 9296 server.vm_next_page = 0;
9297 server.vm_near_pages = 0;
7d98e08c 9298 server.vm_stats_used_pages = 0;
9299 server.vm_stats_swapped_objects = 0;
9300 server.vm_stats_swapouts = 0;
9301 server.vm_stats_swapins = 0;
75680a3c 9302 totsize = server.vm_pages*server.vm_page_size;
9303 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
9304 if (ftruncate(server.vm_fd,totsize) == -1) {
9305 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
9306 strerror(errno));
9307 exit(1);
9308 } else {
9309 redisLog(REDIS_NOTICE,"Swap file allocated with success");
9310 }
7d30035d 9311 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
f870935d 9312 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
4ef8de8a 9313 (long long) (server.vm_pages+7)/8, server.vm_pages);
7d30035d 9314 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
92f8e882 9315
996cb5f7 9316 /* Initialize threaded I/O (used by Virtual Memory) */
9317 server.io_newjobs = listCreate();
9318 server.io_processing = listCreate();
9319 server.io_processed = listCreate();
d5d55fc3 9320 server.io_ready_clients = listCreate();
92f8e882 9321 pthread_mutex_init(&server.io_mutex,NULL);
a5819310 9322 pthread_mutex_init(&server.obj_freelist_mutex,NULL);
9323 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
92f8e882 9324 server.io_active_threads = 0;
996cb5f7 9325 if (pipe(pipefds) == -1) {
9326 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
9327 ,strerror(errno));
9328 exit(1);
9329 }
9330 server.io_ready_pipe_read = pipefds[0];
9331 server.io_ready_pipe_write = pipefds[1];
9332 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
bcaa7a4f 9333 /* LZF requires a lot of stack */
9334 pthread_attr_init(&server.io_threads_attr);
9335 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
9336 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
9337 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
b9bc0eef 9338 /* Listen for events in the threaded I/O pipe */
9339 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
9340 vmThreadedIOCompletedJob, NULL) == AE_ERR)
9341 oom("creating file event");
75680a3c 9342}
9343
06224fec 9344/* Mark the page as used */
9345static void vmMarkPageUsed(off_t page) {
9346 off_t byte = page/8;
9347 int bit = page&7;
970e10bb 9348 redisAssert(vmFreePage(page) == 1);
06224fec 9349 server.vm_bitmap[byte] |= 1<<bit;
9350}
9351
9352/* Mark N contiguous pages as used, with 'page' being the first. */
9353static void vmMarkPagesUsed(off_t page, off_t count) {
9354 off_t j;
9355
9356 for (j = 0; j < count; j++)
7d30035d 9357 vmMarkPageUsed(page+j);
7d98e08c 9358 server.vm_stats_used_pages += count;
7c775e09 9359 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
9360 (long long)count, (long long)page);
06224fec 9361}
9362
9363/* Mark the page as free */
9364static void vmMarkPageFree(off_t page) {
9365 off_t byte = page/8;
9366 int bit = page&7;
970e10bb 9367 redisAssert(vmFreePage(page) == 0);
06224fec 9368 server.vm_bitmap[byte] &= ~(1<<bit);
9369}
9370
9371/* Mark N contiguous pages as free, with 'page' being the first. */
9372static void vmMarkPagesFree(off_t page, off_t count) {
9373 off_t j;
9374
9375 for (j = 0; j < count; j++)
7d30035d 9376 vmMarkPageFree(page+j);
7d98e08c 9377 server.vm_stats_used_pages -= count;
7c775e09 9378 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
9379 (long long)count, (long long)page);
06224fec 9380}
9381
9382/* Test if the page is free */
9383static int vmFreePage(off_t page) {
9384 off_t byte = page/8;
9385 int bit = page&7;
7d30035d 9386 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
06224fec 9387}
9388
9389/* Find N contiguous free pages storing the first page of the cluster in *first.
e0a62c7f 9390 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
3a66edc7 9391 * REDIS_ERR is returned.
06224fec 9392 *
9393 * This function uses a simple algorithm: we try to allocate
9394 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
9395 * again from the start of the swap file searching for free spaces.
9396 *
9397 * If it looks pretty clear that there are no free pages near our offset
9398 * we try to find less populated places doing a forward jump of
9399 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
9400 * without hurry, and then we jump again and so forth...
e0a62c7f 9401 *
06224fec 9402 * This function can be improved using a free list to avoid to guess
9403 * too much, since we could collect data about freed pages.
9404 *
9405 * note: I implemented this function just after watching an episode of
9406 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
9407 */
c7df85a4 9408static int vmFindContiguousPages(off_t *first, off_t n) {
06224fec 9409 off_t base, offset = 0, since_jump = 0, numfree = 0;
9410
9411 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
9412 server.vm_near_pages = 0;
9413 server.vm_next_page = 0;
9414 }
9415 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
9416 base = server.vm_next_page;
9417
9418 while(offset < server.vm_pages) {
9419 off_t this = base+offset;
9420
9421 /* If we overflow, restart from page zero */
9422 if (this >= server.vm_pages) {
9423 this -= server.vm_pages;
9424 if (this == 0) {
9425 /* Just overflowed, what we found on tail is no longer
9426 * interesting, as it's no longer contiguous. */
9427 numfree = 0;
9428 }
9429 }
9430 if (vmFreePage(this)) {
9431 /* This is a free page */
9432 numfree++;
9433 /* Already got N free pages? Return to the caller, with success */
9434 if (numfree == n) {
7d30035d 9435 *first = this-(n-1);
9436 server.vm_next_page = this+1;
7c775e09 9437 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
3a66edc7 9438 return REDIS_OK;
06224fec 9439 }
9440 } else {
9441 /* The current one is not a free page */
9442 numfree = 0;
9443 }
9444
9445 /* Fast-forward if the current page is not free and we already
9446 * searched enough near this place. */
9447 since_jump++;
9448 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
9449 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
9450 since_jump = 0;
9451 /* Note that even if we rewind after the jump, we are don't need
9452 * to make sure numfree is set to zero as we only jump *if* it
9453 * is set to zero. */
9454 } else {
9455 /* Otherwise just check the next page */
9456 offset++;
9457 }
9458 }
3a66edc7 9459 return REDIS_ERR;
9460}
9461
a5819310 9462/* Write the specified object at the specified page of the swap file */
9463static int vmWriteObjectOnSwap(robj *o, off_t page) {
9464 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9465 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
9466 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9467 redisLog(REDIS_WARNING,
9ebed7cf 9468 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
a5819310 9469 strerror(errno));
9470 return REDIS_ERR;
9471 }
9472 rdbSaveObject(server.vm_fp,o);
ba76a8f9 9473 fflush(server.vm_fp);
a5819310 9474 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9475 return REDIS_OK;
9476}
9477
a4798f73 9478/* Transfers the 'val' object to disk. Store all the information
9479 * a 'vmpointer' object containing all the information needed to load the
9480 * object back later is returned.
9481 *
3a66edc7 9482 * If we can't find enough contiguous empty pages to swap the object on disk
a4798f73 9483 * NULL is returned. */
560db612 9484static vmpointer *vmSwapObjectBlocking(robj *val) {
b9bc0eef 9485 off_t pages = rdbSavedObjectPages(val,NULL);
3a66edc7 9486 off_t page;
560db612 9487 vmpointer *vp;
3a66edc7 9488
560db612 9489 assert(val->storage == REDIS_VM_MEMORY);
9490 assert(val->refcount == 1);
9491 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return NULL;
9492 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return NULL;
9493
9494 vp = createVmPointer(val->type);
9495 vp->page = page;
9496 vp->usedpages = pages;
3a66edc7 9497 decrRefCount(val); /* Deallocate the object from memory. */
9498 vmMarkPagesUsed(page,pages);
560db612 9499 redisLog(REDIS_DEBUG,"VM: object %p swapped out at %lld (%lld pages)",
9500 (void*) val,
7d30035d 9501 (unsigned long long) page, (unsigned long long) pages);
7d98e08c 9502 server.vm_stats_swapped_objects++;
9503 server.vm_stats_swapouts++;
560db612 9504 return vp;
3a66edc7 9505}
9506
a5819310 9507static robj *vmReadObjectFromSwap(off_t page, int type) {
9508 robj *o;
3a66edc7 9509
a5819310 9510 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9511 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
3a66edc7 9512 redisLog(REDIS_WARNING,
d5d55fc3 9513 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
3a66edc7 9514 strerror(errno));
478c2c6f 9515 _exit(1);
3a66edc7 9516 }
a5819310 9517 o = rdbLoadObject(type,server.vm_fp);
9518 if (o == NULL) {
d5d55fc3 9519 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
478c2c6f 9520 _exit(1);
3a66edc7 9521 }
a5819310 9522 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9523 return o;
9524}
9525
560db612 9526/* Load the specified object from swap to memory.
a5819310 9527 * The newly allocated object is returned.
9528 *
9529 * If preview is true the unserialized object is returned to the caller but
560db612 9530 * the pages are not marked as freed, nor the vp object is freed. */
9531static robj *vmGenericLoadObject(vmpointer *vp, int preview) {
a5819310 9532 robj *val;
9533
560db612 9534 redisAssert(vp->type == REDIS_VMPOINTER &&
9535 (vp->storage == REDIS_VM_SWAPPED || vp->storage == REDIS_VM_LOADING));
9536 val = vmReadObjectFromSwap(vp->page,vp->vtype);
7e69548d 9537 if (!preview) {
560db612 9538 redisLog(REDIS_DEBUG, "VM: object %p loaded from disk", (void*)vp);
9539 vmMarkPagesFree(vp->page,vp->usedpages);
9540 zfree(vp);
7d98e08c 9541 server.vm_stats_swapped_objects--;
38aba9a1 9542 } else {
560db612 9543 redisLog(REDIS_DEBUG, "VM: object %p previewed from disk", (void*)vp);
7e69548d 9544 }
7d98e08c 9545 server.vm_stats_swapins++;
3a66edc7 9546 return val;
06224fec 9547}
9548
560db612 9549/* Plain object loading, from swap to memory.
9550 *
9551 * 'o' is actually a redisVmPointer structure that will be freed by the call.
9552 * The return value is the loaded object. */
9553static robj *vmLoadObject(robj *o) {
996cb5f7 9554 /* If we are loading the object in background, stop it, we
9555 * need to load this object synchronously ASAP. */
560db612 9556 if (o->storage == REDIS_VM_LOADING)
9557 vmCancelThreadedIOJob(o);
9558 return vmGenericLoadObject((vmpointer*)o,0);
7e69548d 9559}
9560
9561/* Just load the value on disk, without to modify the key.
9562 * This is useful when we want to perform some operation on the value
9563 * without to really bring it from swap to memory, like while saving the
9564 * dataset or rewriting the append only log. */
560db612 9565static robj *vmPreviewObject(robj *o) {
9566 return vmGenericLoadObject((vmpointer*)o,1);
7e69548d 9567}
9568
4ef8de8a 9569/* How a good candidate is this object for swapping?
9570 * The better candidate it is, the greater the returned value.
9571 *
9572 * Currently we try to perform a fast estimation of the object size in
9573 * memory, and combine it with aging informations.
9574 *
9575 * Basically swappability = idle-time * log(estimated size)
9576 *
9577 * Bigger objects are preferred over smaller objects, but not
9578 * proportionally, this is why we use the logarithm. This algorithm is
9579 * just a first try and will probably be tuned later. */
9580static double computeObjectSwappability(robj *o) {
560db612 9581 /* actual age can be >= minage, but not < minage. As we use wrapping
9582 * 21 bit clocks with minutes resolution for the LRU. */
9583 time_t minage = abs(server.lruclock - o->lru);
4ef8de8a 9584 long asize = 0;
9585 list *l;
9586 dict *d;
9587 struct dictEntry *de;
9588 int z;
9589
560db612 9590 if (minage <= 0) return 0;
4ef8de8a 9591 switch(o->type) {
9592 case REDIS_STRING:
9593 if (o->encoding != REDIS_ENCODING_RAW) {
9594 asize = sizeof(*o);
9595 } else {
9596 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
9597 }
9598 break;
9599 case REDIS_LIST:
9600 l = o->ptr;
9601 listNode *ln = listFirst(l);
9602
9603 asize = sizeof(list);
9604 if (ln) {
9605 robj *ele = ln->value;
9606 long elesize;
9607
9608 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
560db612 9609 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
4ef8de8a 9610 asize += (sizeof(listNode)+elesize)*listLength(l);
9611 }
9612 break;
9613 case REDIS_SET:
9614 case REDIS_ZSET:
9615 z = (o->type == REDIS_ZSET);
9616 d = z ? ((zset*)o->ptr)->dict : o->ptr;
9617
9618 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9619 if (z) asize += sizeof(zset)-sizeof(dict);
9620 if (dictSize(d)) {
9621 long elesize;
9622 robj *ele;
9623
9624 de = dictGetRandomKey(d);
9625 ele = dictGetEntryKey(de);
9626 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
560db612 9627 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
4ef8de8a 9628 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9629 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
9630 }
9631 break;
a97b9060 9632 case REDIS_HASH:
9633 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9634 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
9635 unsigned int len = zipmapLen((unsigned char*)o->ptr);
9636 unsigned int klen, vlen;
9637 unsigned char *key, *val;
9638
9639 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
9640 klen = 0;
9641 vlen = 0;
9642 }
9643 asize = len*(klen+vlen+3);
9644 } else if (o->encoding == REDIS_ENCODING_HT) {
9645 d = o->ptr;
9646 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9647 if (dictSize(d)) {
9648 long elesize;
9649 robj *ele;
9650
9651 de = dictGetRandomKey(d);
9652 ele = dictGetEntryKey(de);
9653 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
560db612 9654 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
a97b9060 9655 ele = dictGetEntryVal(de);
9656 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
560db612 9657 (sizeof(*o)+sdslen(ele->ptr)) : sizeof(*o);
a97b9060 9658 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9659 }
9660 }
9661 break;
4ef8de8a 9662 }
560db612 9663 return (double)minage*log(1+asize);
4ef8de8a 9664}
9665
9666/* Try to swap an object that's a good candidate for swapping.
9667 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
a69a0c9c 9668 * to swap any object at all.
9669 *
9670 * If 'usethreaded' is true, Redis will try to swap the object in background
9671 * using I/O threads. */
9672static int vmSwapOneObject(int usethreads) {
4ef8de8a 9673 int j, i;
9674 struct dictEntry *best = NULL;
9675 double best_swappability = 0;
b9bc0eef 9676 redisDb *best_db = NULL;
44262c58 9677 robj *val;
9678 sds key;
4ef8de8a 9679
9680 for (j = 0; j < server.dbnum; j++) {
9681 redisDb *db = server.db+j;
b72f6a4b 9682 /* Why maxtries is set to 100?
9683 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9684 * are swappable objects */
b0d8747d 9685 int maxtries = 100;
4ef8de8a 9686
9687 if (dictSize(db->dict) == 0) continue;
9688 for (i = 0; i < 5; i++) {
9689 dictEntry *de;
9690 double swappability;
9691
e3cadb8a 9692 if (maxtries) maxtries--;
4ef8de8a 9693 de = dictGetRandomKey(db->dict);
4ef8de8a 9694 val = dictGetEntryVal(de);
1064ef87 9695 /* Only swap objects that are currently in memory.
9696 *
560db612 9697 * Also don't swap shared objects: not a good idea in general and
9698 * we need to ensure that the main thread does not touch the
1064ef87 9699 * object while the I/O thread is using it, but we can't
9700 * control other keys without adding additional mutex. */
560db612 9701 if (val->storage != REDIS_VM_MEMORY || val->refcount != 1) {
e3cadb8a 9702 if (maxtries) i--; /* don't count this try */
9703 continue;
9704 }
4ef8de8a 9705 swappability = computeObjectSwappability(val);
9706 if (!best || swappability > best_swappability) {
9707 best = de;
9708 best_swappability = swappability;
b9bc0eef 9709 best_db = db;
4ef8de8a 9710 }
9711 }
9712 }
7c775e09 9713 if (best == NULL) return REDIS_ERR;
4ef8de8a 9714 key = dictGetEntryKey(best);
9715 val = dictGetEntryVal(best);
9716
e3cadb8a 9717 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
44262c58 9718 key, best_swappability);
4ef8de8a 9719
4ef8de8a 9720 /* Swap it */
a69a0c9c 9721 if (usethreads) {
4c8f2370 9722 robj *keyobj = createStringObject(key,sdslen(key));
9723 vmSwapObjectThreaded(keyobj,val,best_db);
9724 decrRefCount(keyobj);
4ef8de8a 9725 return REDIS_OK;
9726 } else {
560db612 9727 vmpointer *vp;
9728
9729 if ((vp = vmSwapObjectBlocking(val)) != NULL) {
9730 dictGetEntryVal(best) = vp;
a69a0c9c 9731 return REDIS_OK;
9732 } else {
9733 return REDIS_ERR;
9734 }
4ef8de8a 9735 }
9736}
9737
a69a0c9c 9738static int vmSwapOneObjectBlocking() {
9739 return vmSwapOneObject(0);
9740}
9741
9742static int vmSwapOneObjectThreaded() {
9743 return vmSwapOneObject(1);
9744}
9745
7e69548d 9746/* Return true if it's safe to swap out objects in a given moment.
9747 * Basically we don't want to swap objects out while there is a BGSAVE
9748 * or a BGAEOREWRITE running in backgroud. */
9749static int vmCanSwapOut(void) {
9750 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
9751}
9752
996cb5f7 9753/* =================== Virtual Memory - Threaded I/O ======================= */
9754
b9bc0eef 9755static void freeIOJob(iojob *j) {
d5d55fc3 9756 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
9757 j->type == REDIS_IOJOB_DO_SWAP ||
9758 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
560db612 9759 {
e4ed181d 9760 /* we fix the storage type, otherwise decrRefCount() will try to
9761 * kill the I/O thread Job (that does no longer exists). */
9762 if (j->val->storage == REDIS_VM_SWAPPING)
560db612 9763 j->val->storage = REDIS_VM_MEMORY;
b9bc0eef 9764 decrRefCount(j->val);
560db612 9765 }
9766 decrRefCount(j->key);
b9bc0eef 9767 zfree(j);
9768}
9769
996cb5f7 9770/* Every time a thread finished a Job, it writes a byte into the write side
9771 * of an unix pipe in order to "awake" the main thread, and this function
9772 * is called. */
9773static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
9774 int mask)
9775{
9776 char buf[1];
b0d8747d 9777 int retval, processed = 0, toprocess = -1, trytoswap = 1;
996cb5f7 9778 REDIS_NOTUSED(el);
9779 REDIS_NOTUSED(mask);
9780 REDIS_NOTUSED(privdata);
9781
9782 /* For every byte we read in the read side of the pipe, there is one
9783 * I/O job completed to process. */
9784 while((retval = read(fd,buf,1)) == 1) {
b9bc0eef 9785 iojob *j;
9786 listNode *ln;
b9bc0eef 9787 struct dictEntry *de;
9788
996cb5f7 9789 redisLog(REDIS_DEBUG,"Processing I/O completed job");
b9bc0eef 9790
9791 /* Get the processed element (the oldest one) */
9792 lockThreadedIO();
1064ef87 9793 assert(listLength(server.io_processed) != 0);
f6c0bba8 9794 if (toprocess == -1) {
9795 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
9796 if (toprocess <= 0) toprocess = 1;
9797 }
b9bc0eef 9798 ln = listFirst(server.io_processed);
9799 j = ln->value;
9800 listDelNode(server.io_processed,ln);
9801 unlockThreadedIO();
9802 /* If this job is marked as canceled, just ignore it */
9803 if (j->canceled) {
9804 freeIOJob(j);
9805 continue;
9806 }
9807 /* Post process it in the main thread, as there are things we
9808 * can do just here to avoid race conditions and/or invasive locks */
560db612 9809 redisLog(REDIS_DEBUG,"COMPLETED Job type: %d, ID %p, key: %s", j->type, (void*)j->id, (unsigned char*)j->key->ptr);
44262c58 9810 de = dictFind(j->db->dict,j->key->ptr);
e4ed181d 9811 redisAssert(de != NULL);
b9bc0eef 9812 if (j->type == REDIS_IOJOB_LOAD) {
d5d55fc3 9813 redisDb *db;
560db612 9814 vmpointer *vp = dictGetEntryVal(de);
d5d55fc3 9815
b9bc0eef 9816 /* Key loaded, bring it at home */
560db612 9817 vmMarkPagesFree(vp->page,vp->usedpages);
b9bc0eef 9818 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
560db612 9819 (unsigned char*) j->key->ptr);
b9bc0eef 9820 server.vm_stats_swapped_objects--;
9821 server.vm_stats_swapins++;
d5d55fc3 9822 dictGetEntryVal(de) = j->val;
9823 incrRefCount(j->val);
9824 db = j->db;
d5d55fc3 9825 /* Handle clients waiting for this key to be loaded. */
560db612 9826 handleClientsBlockedOnSwappedKey(db,j->key);
9827 freeIOJob(j);
9828 zfree(vp);
b9bc0eef 9829 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9830 /* Now we know the amount of pages required to swap this object.
9831 * Let's find some space for it, and queue this task again
9832 * rebranded as REDIS_IOJOB_DO_SWAP. */
054e426d 9833 if (!vmCanSwapOut() ||
9834 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
9835 {
9836 /* Ooops... no space or we can't swap as there is
9837 * a fork()ed Redis trying to save stuff on disk. */
560db612 9838 j->val->storage = REDIS_VM_MEMORY; /* undo operation */
b9bc0eef 9839 freeIOJob(j);
9840 } else {
c7df85a4 9841 /* Note that we need to mark this pages as used now,
9842 * if the job will be canceled, we'll mark them as freed
9843 * again. */
9844 vmMarkPagesUsed(j->page,j->pages);
b9bc0eef 9845 j->type = REDIS_IOJOB_DO_SWAP;
9846 lockThreadedIO();
9847 queueIOJob(j);
9848 unlockThreadedIO();
9849 }
9850 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
560db612 9851 vmpointer *vp;
b9bc0eef 9852
9853 /* Key swapped. We can finally free some memory. */
560db612 9854 if (j->val->storage != REDIS_VM_SWAPPING) {
9855 vmpointer *vp = (vmpointer*) j->id;
9856 printf("storage: %d\n",vp->storage);
9857 printf("key->name: %s\n",(char*)j->key->ptr);
6c96ba7d 9858 printf("val: %p\n",(void*)j->val);
9859 printf("val->type: %d\n",j->val->type);
9860 printf("val->ptr: %s\n",(char*)j->val->ptr);
9861 }
560db612 9862 redisAssert(j->val->storage == REDIS_VM_SWAPPING);
9863 vp = createVmPointer(j->val->type);
9864 vp->page = j->page;
9865 vp->usedpages = j->pages;
9866 dictGetEntryVal(de) = vp;
e4ed181d 9867 /* Fix the storage otherwise decrRefCount will attempt to
9868 * remove the associated I/O job */
9869 j->val->storage = REDIS_VM_MEMORY;
560db612 9870 decrRefCount(j->val);
b9bc0eef 9871 redisLog(REDIS_DEBUG,
9872 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
560db612 9873 (unsigned char*) j->key->ptr,
b9bc0eef 9874 (unsigned long long) j->page, (unsigned long long) j->pages);
9875 server.vm_stats_swapped_objects++;
9876 server.vm_stats_swapouts++;
9877 freeIOJob(j);
f11b8647 9878 /* Put a few more swap requests in queue if we are still
9879 * out of memory */
b0d8747d 9880 if (trytoswap && vmCanSwapOut() &&
9881 zmalloc_used_memory() > server.vm_max_memory)
9882 {
f11b8647 9883 int more = 1;
9884 while(more) {
9885 lockThreadedIO();
9886 more = listLength(server.io_newjobs) <
9887 (unsigned) server.vm_max_threads;
9888 unlockThreadedIO();
9889 /* Don't waste CPU time if swappable objects are rare. */
b0d8747d 9890 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
9891 trytoswap = 0;
9892 break;
9893 }
f11b8647 9894 }
9895 }
b9bc0eef 9896 }
c953f24b 9897 processed++;
f6c0bba8 9898 if (processed == toprocess) return;
996cb5f7 9899 }
9900 if (retval < 0 && errno != EAGAIN) {
9901 redisLog(REDIS_WARNING,
9902 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9903 strerror(errno));
9904 }
9905}
9906
9907static void lockThreadedIO(void) {
9908 pthread_mutex_lock(&server.io_mutex);
9909}
9910
9911static void unlockThreadedIO(void) {
9912 pthread_mutex_unlock(&server.io_mutex);
9913}
9914
9915/* Remove the specified object from the threaded I/O queue if still not
9916 * processed, otherwise make sure to flag it as canceled. */
9917static void vmCancelThreadedIOJob(robj *o) {
9918 list *lists[3] = {
6c96ba7d 9919 server.io_newjobs, /* 0 */
9920 server.io_processing, /* 1 */
9921 server.io_processed /* 2 */
996cb5f7 9922 };
9923 int i;
9924
9925 assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
2e111efe 9926again:
996cb5f7 9927 lockThreadedIO();
560db612 9928 /* Search for a matching object in one of the queues */
996cb5f7 9929 for (i = 0; i < 3; i++) {
9930 listNode *ln;
c7df85a4 9931 listIter li;
996cb5f7 9932
c7df85a4 9933 listRewind(lists[i],&li);
9934 while ((ln = listNext(&li)) != NULL) {
996cb5f7 9935 iojob *job = ln->value;
9936
6c96ba7d 9937 if (job->canceled) continue; /* Skip this, already canceled. */
560db612 9938 if (job->id == o) {
dbc289ae 9939 redisLog(REDIS_DEBUG,"*** CANCELED %p (key %s) (type %d) (LIST ID %d)\n",
9940 (void*)job, (char*)job->key->ptr, job->type, i);
427a2153 9941 /* Mark the pages as free since the swap didn't happened
9942 * or happened but is now discarded. */
970e10bb 9943 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
427a2153 9944 vmMarkPagesFree(job->page,job->pages);
9945 /* Cancel the job. It depends on the list the job is
9946 * living in. */
996cb5f7 9947 switch(i) {
9948 case 0: /* io_newjobs */
6c96ba7d 9949 /* If the job was yet not processed the best thing to do
996cb5f7 9950 * is to remove it from the queue at all */
6c96ba7d 9951 freeIOJob(job);
996cb5f7 9952 listDelNode(lists[i],ln);
9953 break;
9954 case 1: /* io_processing */
d5d55fc3 9955 /* Oh Shi- the thread is messing with the Job:
9956 *
9957 * Probably it's accessing the object if this is a
9958 * PREPARE_SWAP or DO_SWAP job.
9959 * If it's a LOAD job it may be reading from disk and
9960 * if we don't wait for the job to terminate before to
9961 * cancel it, maybe in a few microseconds data can be
9962 * corrupted in this pages. So the short story is:
9963 *
9964 * Better to wait for the job to move into the
9965 * next queue (processed)... */
9966
9967 /* We try again and again until the job is completed. */
9968 unlockThreadedIO();
9969 /* But let's wait some time for the I/O thread
9970 * to finish with this job. After all this condition
9971 * should be very rare. */
9972 usleep(1);
9973 goto again;
996cb5f7 9974 case 2: /* io_processed */
2e111efe 9975 /* The job was already processed, that's easy...
9976 * just mark it as canceled so that we'll ignore it
9977 * when processing completed jobs. */
996cb5f7 9978 job->canceled = 1;
9979 break;
9980 }
c7df85a4 9981 /* Finally we have to adjust the storage type of the object
9982 * in order to "UNDO" the operaiton. */
996cb5f7 9983 if (o->storage == REDIS_VM_LOADING)
9984 o->storage = REDIS_VM_SWAPPED;
9985 else if (o->storage == REDIS_VM_SWAPPING)
9986 o->storage = REDIS_VM_MEMORY;
9987 unlockThreadedIO();
e4ed181d 9988 redisLog(REDIS_DEBUG,"*** DONE");
996cb5f7 9989 return;
9990 }
9991 }
9992 }
9993 unlockThreadedIO();
560db612 9994 printf("Not found: %p\n", (void*)o);
9995 redisAssert(1 != 1); /* We should never reach this */
996cb5f7 9996}
9997
b9bc0eef 9998static void *IOThreadEntryPoint(void *arg) {
9999 iojob *j;
10000 listNode *ln;
10001 REDIS_NOTUSED(arg);
10002
10003 pthread_detach(pthread_self());
10004 while(1) {
10005 /* Get a new job to process */
10006 lockThreadedIO();
10007 if (listLength(server.io_newjobs) == 0) {
10008 /* No new jobs in queue, exit. */
9ebed7cf 10009 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
10010 (long) pthread_self());
b9bc0eef 10011 server.io_active_threads--;
10012 unlockThreadedIO();
10013 return NULL;
10014 }
10015 ln = listFirst(server.io_newjobs);
10016 j = ln->value;
10017 listDelNode(server.io_newjobs,ln);
10018 /* Add the job in the processing queue */
10019 j->thread = pthread_self();
10020 listAddNodeTail(server.io_processing,j);
10021 ln = listLast(server.io_processing); /* We use ln later to remove it */
10022 unlockThreadedIO();
9ebed7cf 10023 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
10024 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
b9bc0eef 10025
10026 /* Process the Job */
10027 if (j->type == REDIS_IOJOB_LOAD) {
560db612 10028 vmpointer *vp = (vmpointer*)j->id;
10029 j->val = vmReadObjectFromSwap(j->page,vp->vtype);
b9bc0eef 10030 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
10031 FILE *fp = fopen("/dev/null","w+");
10032 j->pages = rdbSavedObjectPages(j->val,fp);
10033 fclose(fp);
10034 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
a5819310 10035 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
10036 j->canceled = 1;
b9bc0eef 10037 }
10038
10039 /* Done: insert the job into the processed queue */
9ebed7cf 10040 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
10041 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
b9bc0eef 10042 lockThreadedIO();
10043 listDelNode(server.io_processing,ln);
10044 listAddNodeTail(server.io_processed,j);
10045 unlockThreadedIO();
e0a62c7f 10046
b9bc0eef 10047 /* Signal the main thread there is new stuff to process */
10048 assert(write(server.io_ready_pipe_write,"x",1) == 1);
10049 }
10050 return NULL; /* never reached */
10051}
10052
10053static void spawnIOThread(void) {
10054 pthread_t thread;
478c2c6f 10055 sigset_t mask, omask;
a97b9060 10056 int err;
b9bc0eef 10057
478c2c6f 10058 sigemptyset(&mask);
10059 sigaddset(&mask,SIGCHLD);
10060 sigaddset(&mask,SIGHUP);
10061 sigaddset(&mask,SIGPIPE);
10062 pthread_sigmask(SIG_SETMASK, &mask, &omask);
a97b9060 10063 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
10064 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
10065 strerror(err));
10066 usleep(1000000);
10067 }
478c2c6f 10068 pthread_sigmask(SIG_SETMASK, &omask, NULL);
b9bc0eef 10069 server.io_active_threads++;
10070}
10071
4ee9488d 10072/* We need to wait for the last thread to exit before we are able to
10073 * fork() in order to BGSAVE or BGREWRITEAOF. */
054e426d 10074static void waitEmptyIOJobsQueue(void) {
4ee9488d 10075 while(1) {
76b7233a 10076 int io_processed_len;
10077
4ee9488d 10078 lockThreadedIO();
054e426d 10079 if (listLength(server.io_newjobs) == 0 &&
10080 listLength(server.io_processing) == 0 &&
10081 server.io_active_threads == 0)
10082 {
4ee9488d 10083 unlockThreadedIO();
10084 return;
10085 }
76b7233a 10086 /* While waiting for empty jobs queue condition we post-process some
10087 * finshed job, as I/O threads may be hanging trying to write against
10088 * the io_ready_pipe_write FD but there are so much pending jobs that
10089 * it's blocking. */
10090 io_processed_len = listLength(server.io_processed);
4ee9488d 10091 unlockThreadedIO();
76b7233a 10092 if (io_processed_len) {
10093 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
10094 usleep(1000); /* 1 millisecond */
10095 } else {
10096 usleep(10000); /* 10 milliseconds */
10097 }
4ee9488d 10098 }
10099}
10100
054e426d 10101static void vmReopenSwapFile(void) {
478c2c6f 10102 /* Note: we don't close the old one as we are in the child process
10103 * and don't want to mess at all with the original file object. */
054e426d 10104 server.vm_fp = fopen(server.vm_swap_file,"r+b");
10105 if (server.vm_fp == NULL) {
10106 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
10107 server.vm_swap_file);
478c2c6f 10108 _exit(1);
054e426d 10109 }
10110 server.vm_fd = fileno(server.vm_fp);
10111}
10112
b9bc0eef 10113/* This function must be called while with threaded IO locked */
10114static void queueIOJob(iojob *j) {
6c96ba7d 10115 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
10116 (void*)j, j->type, (char*)j->key->ptr);
b9bc0eef 10117 listAddNodeTail(server.io_newjobs,j);
10118 if (server.io_active_threads < server.vm_max_threads)
10119 spawnIOThread();
10120}
10121
10122static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
10123 iojob *j;
e0a62c7f 10124
b9bc0eef 10125 j = zmalloc(sizeof(*j));
10126 j->type = REDIS_IOJOB_PREPARE_SWAP;
10127 j->db = db;
78ebe4c8 10128 j->key = key;
7dd8e7cf 10129 incrRefCount(key);
560db612 10130 j->id = j->val = val;
b9bc0eef 10131 incrRefCount(val);
10132 j->canceled = 0;
10133 j->thread = (pthread_t) -1;
560db612 10134 val->storage = REDIS_VM_SWAPPING;
b9bc0eef 10135
10136 lockThreadedIO();
10137 queueIOJob(j);
10138 unlockThreadedIO();
10139 return REDIS_OK;
10140}
10141
b0d8747d 10142/* ============ Virtual Memory - Blocking clients on missing keys =========== */
10143
d5d55fc3 10144/* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
10145 * If there is not already a job loading the key, it is craeted.
10146 * The key is added to the io_keys list in the client structure, and also
10147 * in the hash table mapping swapped keys to waiting clients, that is,
10148 * server.io_waited_keys. */
10149static int waitForSwappedKey(redisClient *c, robj *key) {
10150 struct dictEntry *de;
10151 robj *o;
10152 list *l;
10153
10154 /* If the key does not exist or is already in RAM we don't need to
10155 * block the client at all. */
09241813 10156 de = dictFind(c->db->dict,key->ptr);
d5d55fc3 10157 if (de == NULL) return 0;
560db612 10158 o = dictGetEntryVal(de);
d5d55fc3 10159 if (o->storage == REDIS_VM_MEMORY) {
10160 return 0;
10161 } else if (o->storage == REDIS_VM_SWAPPING) {
10162 /* We were swapping the key, undo it! */
10163 vmCancelThreadedIOJob(o);
10164 return 0;
10165 }
e0a62c7f 10166
d5d55fc3 10167 /* OK: the key is either swapped, or being loaded just now. */
10168
10169 /* Add the key to the list of keys this client is waiting for.
10170 * This maps clients to keys they are waiting for. */
10171 listAddNodeTail(c->io_keys,key);
10172 incrRefCount(key);
10173
10174 /* Add the client to the swapped keys => clients waiting map. */
10175 de = dictFind(c->db->io_keys,key);
10176 if (de == NULL) {
10177 int retval;
10178
10179 /* For every key we take a list of clients blocked for it */
10180 l = listCreate();
10181 retval = dictAdd(c->db->io_keys,key,l);
10182 incrRefCount(key);
10183 assert(retval == DICT_OK);
10184 } else {
10185 l = dictGetEntryVal(de);
10186 }
10187 listAddNodeTail(l,c);
10188
10189 /* Are we already loading the key from disk? If not create a job */
10190 if (o->storage == REDIS_VM_SWAPPED) {
10191 iojob *j;
560db612 10192 vmpointer *vp = (vmpointer*)o;
d5d55fc3 10193
10194 o->storage = REDIS_VM_LOADING;
10195 j = zmalloc(sizeof(*j));
10196 j->type = REDIS_IOJOB_LOAD;
10197 j->db = c->db;
560db612 10198 j->id = (robj*)vp;
10199 j->key = key;
10200 incrRefCount(key);
10201 j->page = vp->page;
d5d55fc3 10202 j->val = NULL;
10203 j->canceled = 0;
10204 j->thread = (pthread_t) -1;
10205 lockThreadedIO();
10206 queueIOJob(j);
10207 unlockThreadedIO();
10208 }
10209 return 1;
10210}
10211
6f078746
PN
10212/* Preload keys for any command with first, last and step values for
10213 * the command keys prototype, as defined in the command table. */
10214static void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10215 int j, last;
10216 if (cmd->vm_firstkey == 0) return;
10217 last = cmd->vm_lastkey;
10218 if (last < 0) last = argc+last;
10219 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
10220 redisAssert(j < argc);
10221 waitForSwappedKey(c,argv[j]);
10222 }
10223}
10224
5d373da9 10225/* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
739ba0d2
PN
10226 * Note that the number of keys to preload is user-defined, so we need to
10227 * apply a sanity check against argc. */
ca1788b5 10228static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
76583ea4 10229 int i, num;
ca1788b5 10230 REDIS_NOTUSED(cmd);
ca1788b5
PN
10231
10232 num = atoi(argv[2]->ptr);
739ba0d2 10233 if (num > (argc-3)) return;
76583ea4 10234 for (i = 0; i < num; i++) {
ca1788b5 10235 waitForSwappedKey(c,argv[3+i]);
76583ea4
PN
10236 }
10237}
10238
3805e04f
PN
10239/* Preload keys needed to execute the entire MULTI/EXEC block.
10240 *
10241 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
10242 * and will block the client when any command requires a swapped out value. */
10243static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
10244 int i, margc;
10245 struct redisCommand *mcmd;
10246 robj **margv;
10247 REDIS_NOTUSED(cmd);
10248 REDIS_NOTUSED(argc);
10249 REDIS_NOTUSED(argv);
10250
10251 if (!(c->flags & REDIS_MULTI)) return;
10252 for (i = 0; i < c->mstate.count; i++) {
10253 mcmd = c->mstate.commands[i].cmd;
10254 margc = c->mstate.commands[i].argc;
10255 margv = c->mstate.commands[i].argv;
10256
10257 if (mcmd->vm_preload_proc != NULL) {
10258 mcmd->vm_preload_proc(c,mcmd,margc,margv);
10259 } else {
10260 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
10261 }
76583ea4
PN
10262 }
10263}
10264
b0d8747d 10265/* Is this client attempting to run a command against swapped keys?
d5d55fc3 10266 * If so, block it ASAP, load the keys in background, then resume it.
b0d8747d 10267 *
d5d55fc3 10268 * The important idea about this function is that it can fail! If keys will
10269 * still be swapped when the client is resumed, this key lookups will
10270 * just block loading keys from disk. In practical terms this should only
10271 * happen with SORT BY command or if there is a bug in this function.
10272 *
10273 * Return 1 if the client is marked as blocked, 0 if the client can
10274 * continue as the keys it is going to access appear to be in memory. */
0a6f3f0f 10275static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
76583ea4 10276 if (cmd->vm_preload_proc != NULL) {
ca1788b5 10277 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
76583ea4 10278 } else {
6f078746 10279 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
76583ea4
PN
10280 }
10281
d5d55fc3 10282 /* If the client was blocked for at least one key, mark it as blocked. */
10283 if (listLength(c->io_keys)) {
10284 c->flags |= REDIS_IO_WAIT;
10285 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
10286 server.vm_blocked_clients++;
10287 return 1;
10288 } else {
10289 return 0;
10290 }
10291}
10292
10293/* Remove the 'key' from the list of blocked keys for a given client.
10294 *
10295 * The function returns 1 when there are no longer blocking keys after
10296 * the current one was removed (and the client can be unblocked). */
10297static int dontWaitForSwappedKey(redisClient *c, robj *key) {
10298 list *l;
10299 listNode *ln;
10300 listIter li;
10301 struct dictEntry *de;
10302
10303 /* Remove the key from the list of keys this client is waiting for. */
10304 listRewind(c->io_keys,&li);
10305 while ((ln = listNext(&li)) != NULL) {
bf028098 10306 if (equalStringObjects(ln->value,key)) {
d5d55fc3 10307 listDelNode(c->io_keys,ln);
10308 break;
10309 }
10310 }
10311 assert(ln != NULL);
10312
10313 /* Remove the client form the key => waiting clients map. */
10314 de = dictFind(c->db->io_keys,key);
10315 assert(de != NULL);
10316 l = dictGetEntryVal(de);
10317 ln = listSearchKey(l,c);
10318 assert(ln != NULL);
10319 listDelNode(l,ln);
10320 if (listLength(l) == 0)
10321 dictDelete(c->db->io_keys,key);
10322
10323 return listLength(c->io_keys) == 0;
10324}
10325
560db612 10326/* Every time we now a key was loaded back in memory, we handle clients
10327 * waiting for this key if any. */
d5d55fc3 10328static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
10329 struct dictEntry *de;
10330 list *l;
10331 listNode *ln;
10332 int len;
10333
10334 de = dictFind(db->io_keys,key);
10335 if (!de) return;
10336
10337 l = dictGetEntryVal(de);
10338 len = listLength(l);
10339 /* Note: we can't use something like while(listLength(l)) as the list
10340 * can be freed by the calling function when we remove the last element. */
10341 while (len--) {
10342 ln = listFirst(l);
10343 redisClient *c = ln->value;
10344
10345 if (dontWaitForSwappedKey(c,key)) {
10346 /* Put the client in the list of clients ready to go as we
10347 * loaded all the keys about it. */
10348 listAddNodeTail(server.io_ready_clients,c);
10349 }
10350 }
b0d8747d 10351}
b0d8747d 10352
500ece7c 10353/* =========================== Remote Configuration ========================= */
10354
10355static void configSetCommand(redisClient *c) {
10356 robj *o = getDecodedObject(c->argv[3]);
2e5eb04e 10357 long long ll;
10358
500ece7c 10359 if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
10360 zfree(server.dbfilename);
10361 server.dbfilename = zstrdup(o->ptr);
10362 } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
10363 zfree(server.requirepass);
10364 server.requirepass = zstrdup(o->ptr);
10365 } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
10366 zfree(server.masterauth);
10367 server.masterauth = zstrdup(o->ptr);
10368 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
2e5eb04e 10369 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10370 ll < 0) goto badfmt;
10371 server.maxmemory = ll;
10372 } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
10373 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
10374 ll < 0 || ll > LONG_MAX) goto badfmt;
10375 server.maxidletime = ll;
1b677732 10376 } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
10377 if (!strcasecmp(o->ptr,"no")) {
10378 server.appendfsync = APPENDFSYNC_NO;
10379 } else if (!strcasecmp(o->ptr,"everysec")) {
10380 server.appendfsync = APPENDFSYNC_EVERYSEC;
10381 } else if (!strcasecmp(o->ptr,"always")) {
10382 server.appendfsync = APPENDFSYNC_ALWAYS;
10383 } else {
10384 goto badfmt;
10385 }
38db9171 10386 } else if (!strcasecmp(c->argv[2]->ptr,"no-appendfsync-on-rewrite")) {
10387 int yn = yesnotoi(o->ptr);
10388
10389 if (yn == -1) goto badfmt;
10390 server.no_appendfsync_on_rewrite = yn;
2e5eb04e 10391 } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
10392 int old = server.appendonly;
10393 int new = yesnotoi(o->ptr);
10394
10395 if (new == -1) goto badfmt;
10396 if (old != new) {
10397 if (new == 0) {
10398 stopAppendOnly();
10399 } else {
10400 if (startAppendOnly() == REDIS_ERR) {
10401 addReplySds(c,sdscatprintf(sdsempty(),
10402 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
10403 decrRefCount(o);
10404 return;
10405 }
10406 }
10407 }
a34e0a25 10408 } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
10409 int vlen, j;
10410 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
10411
10412 /* Perform sanity check before setting the new config:
10413 * - Even number of args
10414 * - Seconds >= 1, changes >= 0 */
10415 if (vlen & 1) {
10416 sdsfreesplitres(v,vlen);
10417 goto badfmt;
10418 }
10419 for (j = 0; j < vlen; j++) {
10420 char *eptr;
10421 long val;
10422
10423 val = strtoll(v[j], &eptr, 10);
10424 if (eptr[0] != '\0' ||
10425 ((j & 1) == 0 && val < 1) ||
10426 ((j & 1) == 1 && val < 0)) {
10427 sdsfreesplitres(v,vlen);
10428 goto badfmt;
10429 }
10430 }
10431 /* Finally set the new config */
10432 resetServerSaveParams();
10433 for (j = 0; j < vlen; j += 2) {
10434 time_t seconds;
10435 int changes;
10436
10437 seconds = strtoll(v[j],NULL,10);
10438 changes = strtoll(v[j+1],NULL,10);
10439 appendServerSaveParams(seconds, changes);
10440 }
10441 sdsfreesplitres(v,vlen);
500ece7c 10442 } else {
10443 addReplySds(c,sdscatprintf(sdsempty(),
10444 "-ERR not supported CONFIG parameter %s\r\n",
10445 (char*)c->argv[2]->ptr));
10446 decrRefCount(o);
10447 return;
10448 }
10449 decrRefCount(o);
10450 addReply(c,shared.ok);
a34e0a25 10451 return;
10452
10453badfmt: /* Bad format errors */
10454 addReplySds(c,sdscatprintf(sdsempty(),
10455 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
10456 (char*)o->ptr,
10457 (char*)c->argv[2]->ptr));
10458 decrRefCount(o);
500ece7c 10459}
10460
10461static void configGetCommand(redisClient *c) {
10462 robj *o = getDecodedObject(c->argv[2]);
10463 robj *lenobj = createObject(REDIS_STRING,NULL);
10464 char *pattern = o->ptr;
10465 int matches = 0;
10466
10467 addReply(c,lenobj);
10468 decrRefCount(lenobj);
10469
10470 if (stringmatch(pattern,"dbfilename",0)) {
10471 addReplyBulkCString(c,"dbfilename");
10472 addReplyBulkCString(c,server.dbfilename);
10473 matches++;
10474 }
10475 if (stringmatch(pattern,"requirepass",0)) {
10476 addReplyBulkCString(c,"requirepass");
10477 addReplyBulkCString(c,server.requirepass);
10478 matches++;
10479 }
10480 if (stringmatch(pattern,"masterauth",0)) {
10481 addReplyBulkCString(c,"masterauth");
10482 addReplyBulkCString(c,server.masterauth);
10483 matches++;
10484 }
10485 if (stringmatch(pattern,"maxmemory",0)) {
10486 char buf[128];
10487
2e5eb04e 10488 ll2string(buf,128,server.maxmemory);
500ece7c 10489 addReplyBulkCString(c,"maxmemory");
10490 addReplyBulkCString(c,buf);
10491 matches++;
10492 }
2e5eb04e 10493 if (stringmatch(pattern,"timeout",0)) {
10494 char buf[128];
10495
10496 ll2string(buf,128,server.maxidletime);
10497 addReplyBulkCString(c,"timeout");
10498 addReplyBulkCString(c,buf);
10499 matches++;
10500 }
10501 if (stringmatch(pattern,"appendonly",0)) {
10502 addReplyBulkCString(c,"appendonly");
10503 addReplyBulkCString(c,server.appendonly ? "yes" : "no");
10504 matches++;
10505 }
38db9171 10506 if (stringmatch(pattern,"no-appendfsync-on-rewrite",0)) {
10507 addReplyBulkCString(c,"no-appendfsync-on-rewrite");
10508 addReplyBulkCString(c,server.no_appendfsync_on_rewrite ? "yes" : "no");
10509 matches++;
10510 }
1b677732 10511 if (stringmatch(pattern,"appendfsync",0)) {
10512 char *policy;
10513
10514 switch(server.appendfsync) {
10515 case APPENDFSYNC_NO: policy = "no"; break;
10516 case APPENDFSYNC_EVERYSEC: policy = "everysec"; break;
10517 case APPENDFSYNC_ALWAYS: policy = "always"; break;
10518 default: policy = "unknown"; break; /* too harmless to panic */
10519 }
10520 addReplyBulkCString(c,"appendfsync");
10521 addReplyBulkCString(c,policy);
10522 matches++;
10523 }
a34e0a25 10524 if (stringmatch(pattern,"save",0)) {
10525 sds buf = sdsempty();
10526 int j;
10527
10528 for (j = 0; j < server.saveparamslen; j++) {
10529 buf = sdscatprintf(buf,"%ld %d",
10530 server.saveparams[j].seconds,
10531 server.saveparams[j].changes);
10532 if (j != server.saveparamslen-1)
10533 buf = sdscatlen(buf," ",1);
10534 }
10535 addReplyBulkCString(c,"save");
10536 addReplyBulkCString(c,buf);
10537 sdsfree(buf);
10538 matches++;
10539 }
500ece7c 10540 decrRefCount(o);
10541 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",matches*2);
10542}
10543
10544static void configCommand(redisClient *c) {
10545 if (!strcasecmp(c->argv[1]->ptr,"set")) {
10546 if (c->argc != 4) goto badarity;
10547 configSetCommand(c);
10548 } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
10549 if (c->argc != 3) goto badarity;
10550 configGetCommand(c);
10551 } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
10552 if (c->argc != 2) goto badarity;
10553 server.stat_numcommands = 0;
10554 server.stat_numconnections = 0;
10555 server.stat_expiredkeys = 0;
10556 server.stat_starttime = time(NULL);
10557 addReply(c,shared.ok);
10558 } else {
10559 addReplySds(c,sdscatprintf(sdsempty(),
10560 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10561 }
10562 return;
10563
10564badarity:
10565 addReplySds(c,sdscatprintf(sdsempty(),
10566 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10567 (char*) c->argv[1]->ptr));
10568}
10569
befec3cd 10570/* =========================== Pubsub implementation ======================== */
10571
ffc6b7f8 10572static void freePubsubPattern(void *p) {
10573 pubsubPattern *pat = p;
10574
10575 decrRefCount(pat->pattern);
10576 zfree(pat);
10577}
10578
10579static int listMatchPubsubPattern(void *a, void *b) {
10580 pubsubPattern *pa = a, *pb = b;
10581
10582 return (pa->client == pb->client) &&
bf028098 10583 (equalStringObjects(pa->pattern,pb->pattern));
ffc6b7f8 10584}
10585
10586/* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10587 * 0 if the client was already subscribed to that channel. */
10588static int pubsubSubscribeChannel(redisClient *c, robj *channel) {
befec3cd 10589 struct dictEntry *de;
10590 list *clients = NULL;
10591 int retval = 0;
10592
ffc6b7f8 10593 /* Add the channel to the client -> channels hash table */
10594 if (dictAdd(c->pubsub_channels,channel,NULL) == DICT_OK) {
befec3cd 10595 retval = 1;
ffc6b7f8 10596 incrRefCount(channel);
10597 /* Add the client to the channel -> list of clients hash table */
10598 de = dictFind(server.pubsub_channels,channel);
befec3cd 10599 if (de == NULL) {
10600 clients = listCreate();
ffc6b7f8 10601 dictAdd(server.pubsub_channels,channel,clients);
10602 incrRefCount(channel);
befec3cd 10603 } else {
10604 clients = dictGetEntryVal(de);
10605 }
10606 listAddNodeTail(clients,c);
10607 }
10608 /* Notify the client */
10609 addReply(c,shared.mbulk3);
10610 addReply(c,shared.subscribebulk);
ffc6b7f8 10611 addReplyBulk(c,channel);
482b672d 10612 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
befec3cd 10613 return retval;
10614}
10615
ffc6b7f8 10616/* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10617 * 0 if the client was not subscribed to the specified channel. */
10618static int pubsubUnsubscribeChannel(redisClient *c, robj *channel, int notify) {
befec3cd 10619 struct dictEntry *de;
10620 list *clients;
10621 listNode *ln;
10622 int retval = 0;
10623
ffc6b7f8 10624 /* Remove the channel from the client -> channels hash table */
10625 incrRefCount(channel); /* channel may be just a pointer to the same object
201037f5 10626 we have in the hash tables. Protect it... */
ffc6b7f8 10627 if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
befec3cd 10628 retval = 1;
ffc6b7f8 10629 /* Remove the client from the channel -> clients list hash table */
10630 de = dictFind(server.pubsub_channels,channel);
befec3cd 10631 assert(de != NULL);
10632 clients = dictGetEntryVal(de);
10633 ln = listSearchKey(clients,c);
10634 assert(ln != NULL);
10635 listDelNode(clients,ln);
ff767a75 10636 if (listLength(clients) == 0) {
10637 /* Free the list and associated hash entry at all if this was
10638 * the latest client, so that it will be possible to abuse
ffc6b7f8 10639 * Redis PUBSUB creating millions of channels. */
10640 dictDelete(server.pubsub_channels,channel);
ff767a75 10641 }
befec3cd 10642 }
10643 /* Notify the client */
10644 if (notify) {
10645 addReply(c,shared.mbulk3);
10646 addReply(c,shared.unsubscribebulk);
ffc6b7f8 10647 addReplyBulk(c,channel);
482b672d 10648 addReplyLongLong(c,dictSize(c->pubsub_channels)+
ffc6b7f8 10649 listLength(c->pubsub_patterns));
10650
10651 }
10652 decrRefCount(channel); /* it is finally safe to release it */
10653 return retval;
10654}
10655
10656/* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10657static int pubsubSubscribePattern(redisClient *c, robj *pattern) {
10658 int retval = 0;
10659
10660 if (listSearchKey(c->pubsub_patterns,pattern) == NULL) {
10661 retval = 1;
10662 pubsubPattern *pat;
10663 listAddNodeTail(c->pubsub_patterns,pattern);
10664 incrRefCount(pattern);
10665 pat = zmalloc(sizeof(*pat));
10666 pat->pattern = getDecodedObject(pattern);
10667 pat->client = c;
10668 listAddNodeTail(server.pubsub_patterns,pat);
10669 }
10670 /* Notify the client */
10671 addReply(c,shared.mbulk3);
10672 addReply(c,shared.psubscribebulk);
10673 addReplyBulk(c,pattern);
482b672d 10674 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
ffc6b7f8 10675 return retval;
10676}
10677
10678/* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10679 * 0 if the client was not subscribed to the specified channel. */
10680static int pubsubUnsubscribePattern(redisClient *c, robj *pattern, int notify) {
10681 listNode *ln;
10682 pubsubPattern pat;
10683 int retval = 0;
10684
10685 incrRefCount(pattern); /* Protect the object. May be the same we remove */
10686 if ((ln = listSearchKey(c->pubsub_patterns,pattern)) != NULL) {
10687 retval = 1;
10688 listDelNode(c->pubsub_patterns,ln);
10689 pat.client = c;
10690 pat.pattern = pattern;
10691 ln = listSearchKey(server.pubsub_patterns,&pat);
10692 listDelNode(server.pubsub_patterns,ln);
10693 }
10694 /* Notify the client */
10695 if (notify) {
10696 addReply(c,shared.mbulk3);
10697 addReply(c,shared.punsubscribebulk);
10698 addReplyBulk(c,pattern);
482b672d 10699 addReplyLongLong(c,dictSize(c->pubsub_channels)+
ffc6b7f8 10700 listLength(c->pubsub_patterns));
befec3cd 10701 }
ffc6b7f8 10702 decrRefCount(pattern);
befec3cd 10703 return retval;
10704}
10705
ffc6b7f8 10706/* Unsubscribe from all the channels. Return the number of channels the
10707 * client was subscribed from. */
10708static int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
10709 dictIterator *di = dictGetIterator(c->pubsub_channels);
befec3cd 10710 dictEntry *de;
10711 int count = 0;
10712
10713 while((de = dictNext(di)) != NULL) {
ffc6b7f8 10714 robj *channel = dictGetEntryKey(de);
befec3cd 10715
ffc6b7f8 10716 count += pubsubUnsubscribeChannel(c,channel,notify);
befec3cd 10717 }
10718 dictReleaseIterator(di);
10719 return count;
10720}
10721
ffc6b7f8 10722/* Unsubscribe from all the patterns. Return the number of patterns the
10723 * client was subscribed from. */
10724static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify) {
10725 listNode *ln;
10726 listIter li;
10727 int count = 0;
10728
10729 listRewind(c->pubsub_patterns,&li);
10730 while ((ln = listNext(&li)) != NULL) {
10731 robj *pattern = ln->value;
10732
10733 count += pubsubUnsubscribePattern(c,pattern,notify);
10734 }
10735 return count;
10736}
10737
befec3cd 10738/* Publish a message */
ffc6b7f8 10739static int pubsubPublishMessage(robj *channel, robj *message) {
befec3cd 10740 int receivers = 0;
10741 struct dictEntry *de;
ffc6b7f8 10742 listNode *ln;
10743 listIter li;
befec3cd 10744
ffc6b7f8 10745 /* Send to clients listening for that channel */
10746 de = dictFind(server.pubsub_channels,channel);
befec3cd 10747 if (de) {
10748 list *list = dictGetEntryVal(de);
10749 listNode *ln;
10750 listIter li;
10751
10752 listRewind(list,&li);
10753 while ((ln = listNext(&li)) != NULL) {
10754 redisClient *c = ln->value;
10755
10756 addReply(c,shared.mbulk3);
10757 addReply(c,shared.messagebulk);
ffc6b7f8 10758 addReplyBulk(c,channel);
befec3cd 10759 addReplyBulk(c,message);
10760 receivers++;
10761 }
10762 }
ffc6b7f8 10763 /* Send to clients listening to matching channels */
10764 if (listLength(server.pubsub_patterns)) {
10765 listRewind(server.pubsub_patterns,&li);
10766 channel = getDecodedObject(channel);
10767 while ((ln = listNext(&li)) != NULL) {
10768 pubsubPattern *pat = ln->value;
10769
10770 if (stringmatchlen((char*)pat->pattern->ptr,
10771 sdslen(pat->pattern->ptr),
10772 (char*)channel->ptr,
10773 sdslen(channel->ptr),0)) {
c8d0ea0e 10774 addReply(pat->client,shared.mbulk4);
10775 addReply(pat->client,shared.pmessagebulk);
10776 addReplyBulk(pat->client,pat->pattern);
ffc6b7f8 10777 addReplyBulk(pat->client,channel);
10778 addReplyBulk(pat->client,message);
10779 receivers++;
10780 }
10781 }
10782 decrRefCount(channel);
10783 }
befec3cd 10784 return receivers;
10785}
10786
10787static void subscribeCommand(redisClient *c) {
10788 int j;
10789
10790 for (j = 1; j < c->argc; j++)
ffc6b7f8 10791 pubsubSubscribeChannel(c,c->argv[j]);
befec3cd 10792}
10793
10794static void unsubscribeCommand(redisClient *c) {
10795 if (c->argc == 1) {
ffc6b7f8 10796 pubsubUnsubscribeAllChannels(c,1);
10797 return;
10798 } else {
10799 int j;
10800
10801 for (j = 1; j < c->argc; j++)
10802 pubsubUnsubscribeChannel(c,c->argv[j],1);
10803 }
10804}
10805
10806static void psubscribeCommand(redisClient *c) {
10807 int j;
10808
10809 for (j = 1; j < c->argc; j++)
10810 pubsubSubscribePattern(c,c->argv[j]);
10811}
10812
10813static void punsubscribeCommand(redisClient *c) {
10814 if (c->argc == 1) {
10815 pubsubUnsubscribeAllPatterns(c,1);
befec3cd 10816 return;
10817 } else {
10818 int j;
10819
10820 for (j = 1; j < c->argc; j++)
ffc6b7f8 10821 pubsubUnsubscribePattern(c,c->argv[j],1);
befec3cd 10822 }
10823}
10824
10825static void publishCommand(redisClient *c) {
10826 int receivers = pubsubPublishMessage(c->argv[1],c->argv[2]);
482b672d 10827 addReplyLongLong(c,receivers);
befec3cd 10828}
10829
37ab76c9 10830/* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
10831 *
10832 * The implementation uses a per-DB hash table mapping keys to list of clients
10833 * WATCHing those keys, so that given a key that is going to be modified
10834 * we can mark all the associated clients as dirty.
10835 *
10836 * Also every client contains a list of WATCHed keys so that's possible to
10837 * un-watch such keys when the client is freed or when UNWATCH is called. */
10838
10839/* In the client->watched_keys list we need to use watchedKey structures
10840 * as in order to identify a key in Redis we need both the key name and the
10841 * DB */
10842typedef struct watchedKey {
10843 robj *key;
10844 redisDb *db;
10845} watchedKey;
10846
10847/* Watch for the specified key */
10848static void watchForKey(redisClient *c, robj *key) {
10849 list *clients = NULL;
10850 listIter li;
10851 listNode *ln;
10852 watchedKey *wk;
10853
10854 /* Check if we are already watching for this key */
10855 listRewind(c->watched_keys,&li);
10856 while((ln = listNext(&li))) {
10857 wk = listNodeValue(ln);
10858 if (wk->db == c->db && equalStringObjects(key,wk->key))
10859 return; /* Key already watched */
10860 }
10861 /* This key is not already watched in this DB. Let's add it */
10862 clients = dictFetchValue(c->db->watched_keys,key);
10863 if (!clients) {
10864 clients = listCreate();
10865 dictAdd(c->db->watched_keys,key,clients);
10866 incrRefCount(key);
10867 }
10868 listAddNodeTail(clients,c);
10869 /* Add the new key to the lits of keys watched by this client */
10870 wk = zmalloc(sizeof(*wk));
10871 wk->key = key;
10872 wk->db = c->db;
10873 incrRefCount(key);
10874 listAddNodeTail(c->watched_keys,wk);
10875}
10876
10877/* Unwatch all the keys watched by this client. To clean the EXEC dirty
10878 * flag is up to the caller. */
10879static void unwatchAllKeys(redisClient *c) {
10880 listIter li;
10881 listNode *ln;
10882
10883 if (listLength(c->watched_keys) == 0) return;
10884 listRewind(c->watched_keys,&li);
10885 while((ln = listNext(&li))) {
10886 list *clients;
10887 watchedKey *wk;
10888
10889 /* Lookup the watched key -> clients list and remove the client
10890 * from the list */
10891 wk = listNodeValue(ln);
10892 clients = dictFetchValue(wk->db->watched_keys, wk->key);
10893 assert(clients != NULL);
10894 listDelNode(clients,listSearchKey(clients,c));
10895 /* Kill the entry at all if this was the only client */
10896 if (listLength(clients) == 0)
10897 dictDelete(wk->db->watched_keys, wk->key);
10898 /* Remove this watched key from the client->watched list */
10899 listDelNode(c->watched_keys,ln);
10900 decrRefCount(wk->key);
10901 zfree(wk);
10902 }
10903}
10904
ca3f830b 10905/* "Touch" a key, so that if this key is being WATCHed by some client the
37ab76c9 10906 * next EXEC will fail. */
10907static void touchWatchedKey(redisDb *db, robj *key) {
10908 list *clients;
10909 listIter li;
10910 listNode *ln;
10911
10912 if (dictSize(db->watched_keys) == 0) return;
10913 clients = dictFetchValue(db->watched_keys, key);
10914 if (!clients) return;
10915
10916 /* Mark all the clients watching this key as REDIS_DIRTY_CAS */
10917 /* Check if we are already watching for this key */
10918 listRewind(clients,&li);
10919 while((ln = listNext(&li))) {
10920 redisClient *c = listNodeValue(ln);
10921
10922 c->flags |= REDIS_DIRTY_CAS;
10923 }
10924}
10925
9b30e1a2 10926/* On FLUSHDB or FLUSHALL all the watched keys that are present before the
10927 * flush but will be deleted as effect of the flushing operation should
10928 * be touched. "dbid" is the DB that's getting the flush. -1 if it is
10929 * a FLUSHALL operation (all the DBs flushed). */
10930static void touchWatchedKeysOnFlush(int dbid) {
10931 listIter li1, li2;
10932 listNode *ln;
10933
10934 /* For every client, check all the waited keys */
10935 listRewind(server.clients,&li1);
10936 while((ln = listNext(&li1))) {
10937 redisClient *c = listNodeValue(ln);
10938 listRewind(c->watched_keys,&li2);
10939 while((ln = listNext(&li2))) {
10940 watchedKey *wk = listNodeValue(ln);
10941
10942 /* For every watched key matching the specified DB, if the
10943 * key exists, mark the client as dirty, as the key will be
10944 * removed. */
10945 if (dbid == -1 || wk->db->id == dbid) {
09241813 10946 if (dictFind(wk->db->dict, wk->key->ptr) != NULL)
9b30e1a2 10947 c->flags |= REDIS_DIRTY_CAS;
10948 }
10949 }
10950 }
10951}
10952
37ab76c9 10953static void watchCommand(redisClient *c) {
10954 int j;
10955
6531c94d 10956 if (c->flags & REDIS_MULTI) {
10957 addReplySds(c,sdsnew("-ERR WATCH inside MULTI is not allowed\r\n"));
10958 return;
10959 }
37ab76c9 10960 for (j = 1; j < c->argc; j++)
10961 watchForKey(c,c->argv[j]);
10962 addReply(c,shared.ok);
10963}
10964
10965static void unwatchCommand(redisClient *c) {
10966 unwatchAllKeys(c);
10967 c->flags &= (~REDIS_DIRTY_CAS);
10968 addReply(c,shared.ok);
10969}
10970
7f957c92 10971/* ================================= Debugging ============================== */
10972
ba798261 10973/* Compute the sha1 of string at 's' with 'len' bytes long.
10974 * The SHA1 is then xored againt the string pointed by digest.
10975 * Since xor is commutative, this operation is used in order to
10976 * "add" digests relative to unordered elements.
10977 *
10978 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10979static void xorDigest(unsigned char *digest, void *ptr, size_t len) {
10980 SHA1_CTX ctx;
10981 unsigned char hash[20], *s = ptr;
10982 int j;
10983
10984 SHA1Init(&ctx);
10985 SHA1Update(&ctx,s,len);
10986 SHA1Final(hash,&ctx);
10987
10988 for (j = 0; j < 20; j++)
10989 digest[j] ^= hash[j];
10990}
10991
10992static void xorObjectDigest(unsigned char *digest, robj *o) {
10993 o = getDecodedObject(o);
10994 xorDigest(digest,o->ptr,sdslen(o->ptr));
10995 decrRefCount(o);
10996}
10997
10998/* This function instead of just computing the SHA1 and xoring it
10999 * against diget, also perform the digest of "digest" itself and
11000 * replace the old value with the new one.
11001 *
11002 * So the final digest will be:
11003 *
11004 * digest = SHA1(digest xor SHA1(data))
11005 *
11006 * This function is used every time we want to preserve the order so
11007 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
11008 *
11009 * Also note that mixdigest("foo") followed by mixdigest("bar")
11010 * will lead to a different digest compared to "fo", "obar".
11011 */
11012static void mixDigest(unsigned char *digest, void *ptr, size_t len) {
11013 SHA1_CTX ctx;
11014 char *s = ptr;
11015
11016 xorDigest(digest,s,len);
11017 SHA1Init(&ctx);
11018 SHA1Update(&ctx,digest,20);
11019 SHA1Final(digest,&ctx);
11020}
11021
11022static void mixObjectDigest(unsigned char *digest, robj *o) {
11023 o = getDecodedObject(o);
11024 mixDigest(digest,o->ptr,sdslen(o->ptr));
11025 decrRefCount(o);
11026}
11027
11028/* Compute the dataset digest. Since keys, sets elements, hashes elements
11029 * are not ordered, we use a trick: every aggregate digest is the xor
11030 * of the digests of their elements. This way the order will not change
11031 * the result. For list instead we use a feedback entering the output digest
11032 * as input in order to ensure that a different ordered list will result in
11033 * a different digest. */
11034static void computeDatasetDigest(unsigned char *final) {
11035 unsigned char digest[20];
11036 char buf[128];
11037 dictIterator *di = NULL;
11038 dictEntry *de;
11039 int j;
11040 uint32_t aux;
11041
11042 memset(final,0,20); /* Start with a clean result */
11043
11044 for (j = 0; j < server.dbnum; j++) {
11045 redisDb *db = server.db+j;
11046
11047 if (dictSize(db->dict) == 0) continue;
11048 di = dictGetIterator(db->dict);
11049
11050 /* hash the DB id, so the same dataset moved in a different
11051 * DB will lead to a different digest */
11052 aux = htonl(j);
11053 mixDigest(final,&aux,sizeof(aux));
11054
11055 /* Iterate this DB writing every entry */
11056 while((de = dictNext(di)) != NULL) {
09241813 11057 sds key;
11058 robj *keyobj, *o;
ba798261 11059 time_t expiretime;
11060
11061 memset(digest,0,20); /* This key-val digest */
11062 key = dictGetEntryKey(de);
09241813 11063 keyobj = createStringObject(key,sdslen(key));
11064
11065 mixDigest(digest,key,sdslen(key));
11066
11067 /* Make sure the key is loaded if VM is active */
11068 o = lookupKeyRead(db,keyobj);
cbae1d34 11069
ba798261 11070 aux = htonl(o->type);
11071 mixDigest(digest,&aux,sizeof(aux));
09241813 11072 expiretime = getExpire(db,keyobj);
ba798261 11073
11074 /* Save the key and associated value */
11075 if (o->type == REDIS_STRING) {
11076 mixObjectDigest(digest,o);
11077 } else if (o->type == REDIS_LIST) {
dc845730
PN
11078 lIterator *li = lInitIterator(o,0,REDIS_TAIL);
11079 lEntry entry;
11080 while(lNext(li,&entry)) {
11081 robj *eleobj = lGet(&entry);
ba798261 11082 mixObjectDigest(digest,eleobj);
dc845730 11083 decrRefCount(eleobj);
ba798261 11084 }
dc845730 11085 lReleaseIterator(li);
ba798261 11086 } else if (o->type == REDIS_SET) {
11087 dict *set = o->ptr;
11088 dictIterator *di = dictGetIterator(set);
11089 dictEntry *de;
11090
11091 while((de = dictNext(di)) != NULL) {
11092 robj *eleobj = dictGetEntryKey(de);
11093
11094 xorObjectDigest(digest,eleobj);
11095 }
11096 dictReleaseIterator(di);
11097 } else if (o->type == REDIS_ZSET) {
11098 zset *zs = o->ptr;
11099 dictIterator *di = dictGetIterator(zs->dict);
11100 dictEntry *de;
11101
11102 while((de = dictNext(di)) != NULL) {
11103 robj *eleobj = dictGetEntryKey(de);
11104 double *score = dictGetEntryVal(de);
11105 unsigned char eledigest[20];
11106
11107 snprintf(buf,sizeof(buf),"%.17g",*score);
11108 memset(eledigest,0,20);
11109 mixObjectDigest(eledigest,eleobj);
11110 mixDigest(eledigest,buf,strlen(buf));
11111 xorDigest(digest,eledigest,20);
11112 }
11113 dictReleaseIterator(di);
11114 } else if (o->type == REDIS_HASH) {
11115 hashIterator *hi;
11116 robj *obj;
11117
11118 hi = hashInitIterator(o);
11119 while (hashNext(hi) != REDIS_ERR) {
11120 unsigned char eledigest[20];
11121
11122 memset(eledigest,0,20);
11123 obj = hashCurrent(hi,REDIS_HASH_KEY);
11124 mixObjectDigest(eledigest,obj);
11125 decrRefCount(obj);
11126 obj = hashCurrent(hi,REDIS_HASH_VALUE);
11127 mixObjectDigest(eledigest,obj);
11128 decrRefCount(obj);
11129 xorDigest(digest,eledigest,20);
11130 }
11131 hashReleaseIterator(hi);
11132 } else {
11133 redisPanic("Unknown object type");
11134 }
ba798261 11135 /* If the key has an expire, add it to the mix */
11136 if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
11137 /* We can finally xor the key-val digest to the final digest */
11138 xorDigest(final,digest,20);
09241813 11139 decrRefCount(keyobj);
ba798261 11140 }
11141 dictReleaseIterator(di);
11142 }
11143}
11144
7f957c92 11145static void debugCommand(redisClient *c) {
11146 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
11147 *((char*)-1) = 'x';
210e29f7 11148 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
11149 if (rdbSave(server.dbfilename) != REDIS_OK) {
11150 addReply(c,shared.err);
11151 return;
11152 }
11153 emptyDb();
11154 if (rdbLoad(server.dbfilename) != REDIS_OK) {
11155 addReply(c,shared.err);
11156 return;
11157 }
11158 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
11159 addReply(c,shared.ok);
71c2b467 11160 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
11161 emptyDb();
11162 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
11163 addReply(c,shared.err);
11164 return;
11165 }
11166 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
11167 addReply(c,shared.ok);
333298da 11168 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
09241813 11169 dictEntry *de = dictFind(c->db->dict,c->argv[2]->ptr);
11170 robj *val;
333298da 11171
11172 if (!de) {
11173 addReply(c,shared.nokeyerr);
11174 return;
11175 }
333298da 11176 val = dictGetEntryVal(de);
560db612 11177 if (!server.vm_enabled || (val->storage == REDIS_VM_MEMORY ||
11178 val->storage == REDIS_VM_SWAPPING)) {
07efaf74 11179 char *strenc;
11180 char buf[128];
11181
11182 if (val->encoding < (sizeof(strencoding)/sizeof(char*))) {
11183 strenc = strencoding[val->encoding];
11184 } else {
11185 snprintf(buf,64,"unknown encoding %d\n", val->encoding);
11186 strenc = buf;
11187 }
ace06542 11188 addReplySds(c,sdscatprintf(sdsempty(),
09241813 11189 "+Value at:%p refcount:%d "
07efaf74 11190 "encoding:%s serializedlength:%lld\r\n",
09241813 11191 (void*)val, val->refcount,
07efaf74 11192 strenc, (long long) rdbSavedObjectLen(val,NULL)));
ace06542 11193 } else {
560db612 11194 vmpointer *vp = (vmpointer*) val;
ace06542 11195 addReplySds(c,sdscatprintf(sdsempty(),
09241813 11196 "+Value swapped at: page %llu "
ace06542 11197 "using %llu pages\r\n",
09241813 11198 (unsigned long long) vp->page,
560db612 11199 (unsigned long long) vp->usedpages));
ace06542 11200 }
78ebe4c8 11201 } else if (!strcasecmp(c->argv[1]->ptr,"swapin") && c->argc == 3) {
11202 lookupKeyRead(c->db,c->argv[2]);
11203 addReply(c,shared.ok);
7d30035d 11204 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
09241813 11205 dictEntry *de = dictFind(c->db->dict,c->argv[2]->ptr);
11206 robj *val;
560db612 11207 vmpointer *vp;
7d30035d 11208
11209 if (!server.vm_enabled) {
11210 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
11211 return;
11212 }
11213 if (!de) {
11214 addReply(c,shared.nokeyerr);
11215 return;
11216 }
7d30035d 11217 val = dictGetEntryVal(de);
4ef8de8a 11218 /* Swap it */
560db612 11219 if (val->storage != REDIS_VM_MEMORY) {
7d30035d 11220 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
560db612 11221 } else if (val->refcount != 1) {
11222 addReplySds(c,sdsnew("-ERR Object is shared\r\n"));
11223 } else if ((vp = vmSwapObjectBlocking(val)) != NULL) {
11224 dictGetEntryVal(de) = vp;
7d30035d 11225 addReply(c,shared.ok);
11226 } else {
11227 addReply(c,shared.err);
11228 }
59305dc7 11229 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
11230 long keys, j;
11231 robj *key, *val;
11232 char buf[128];
11233
11234 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
11235 return;
11236 for (j = 0; j < keys; j++) {
11237 snprintf(buf,sizeof(buf),"key:%lu",j);
11238 key = createStringObject(buf,strlen(buf));
11239 if (lookupKeyRead(c->db,key) != NULL) {
11240 decrRefCount(key);
11241 continue;
11242 }
11243 snprintf(buf,sizeof(buf),"value:%lu",j);
11244 val = createStringObject(buf,strlen(buf));
09241813 11245 dbAdd(c->db,key,val);
11246 decrRefCount(key);
59305dc7 11247 }
11248 addReply(c,shared.ok);
ba798261 11249 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
11250 unsigned char digest[20];
11251 sds d = sdsnew("+");
11252 int j;
11253
11254 computeDatasetDigest(digest);
11255 for (j = 0; j < 20; j++)
11256 d = sdscatprintf(d, "%02x",digest[j]);
11257
11258 d = sdscatlen(d,"\r\n",2);
11259 addReplySds(c,d);
7f957c92 11260 } else {
333298da 11261 addReplySds(c,sdsnew(
bdcb92f2 11262 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
7f957c92 11263 }
11264}
56906eef 11265
6c96ba7d 11266static void _redisAssert(char *estr, char *file, int line) {
dfc5e96c 11267 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
fdfb02e7 11268 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
dfc5e96c 11269#ifdef HAVE_BACKTRACE
11270 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
11271 *((char*)-1) = 'x';
11272#endif
11273}
11274
c651fd9e 11275static void _redisPanic(char *msg, char *file, int line) {
11276 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
17772754 11277 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
c651fd9e 11278#ifdef HAVE_BACKTRACE
11279 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
11280 *((char*)-1) = 'x';
11281#endif
11282}
11283
bcfc686d 11284/* =================================== Main! ================================ */
56906eef 11285
bcfc686d 11286#ifdef __linux__
11287int linuxOvercommitMemoryValue(void) {
11288 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
11289 char buf[64];
56906eef 11290
bcfc686d 11291 if (!fp) return -1;
11292 if (fgets(buf,64,fp) == NULL) {
11293 fclose(fp);
11294 return -1;
11295 }
11296 fclose(fp);
56906eef 11297
bcfc686d 11298 return atoi(buf);
11299}
11300
11301void linuxOvercommitMemoryWarning(void) {
11302 if (linuxOvercommitMemoryValue() == 0) {
7ccd2d0a 11303 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 11304 }
11305}
11306#endif /* __linux__ */
11307
11308static void daemonize(void) {
11309 int fd;
11310 FILE *fp;
11311
11312 if (fork() != 0) exit(0); /* parent exits */
11313 setsid(); /* create a new session */
11314
11315 /* Every output goes to /dev/null. If Redis is daemonized but
11316 * the 'logfile' is set to 'stdout' in the configuration file
11317 * it will not log at all. */
11318 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
11319 dup2(fd, STDIN_FILENO);
11320 dup2(fd, STDOUT_FILENO);
11321 dup2(fd, STDERR_FILENO);
11322 if (fd > STDERR_FILENO) close(fd);
11323 }
11324 /* Try to write the pid file */
11325 fp = fopen(server.pidfile,"w");
11326 if (fp) {
11327 fprintf(fp,"%d\n",getpid());
11328 fclose(fp);
56906eef 11329 }
56906eef 11330}
11331
42ab0172 11332static void version() {
8a3b0d2d 11333 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
11334 REDIS_GIT_SHA1, atoi(REDIS_GIT_DIRTY) > 0);
42ab0172
AO
11335 exit(0);
11336}
11337
723fb69b
AO
11338static void usage() {
11339 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
e9409273 11340 fprintf(stderr," ./redis-server - (read config from stdin)\n");
723fb69b
AO
11341 exit(1);
11342}
11343
bcfc686d 11344int main(int argc, char **argv) {
9651a787 11345 time_t start;
11346
bcfc686d 11347 initServerConfig();
1a132bbc 11348 sortCommandTable();
bcfc686d 11349 if (argc == 2) {
44efe66e 11350 if (strcmp(argv[1], "-v") == 0 ||
11351 strcmp(argv[1], "--version") == 0) version();
11352 if (strcmp(argv[1], "--help") == 0) usage();
bcfc686d 11353 resetServerSaveParams();
11354 loadServerConfig(argv[1]);
723fb69b
AO
11355 } else if ((argc > 2)) {
11356 usage();
bcfc686d 11357 } else {
11358 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'");
11359 }
bcfc686d 11360 if (server.daemonize) daemonize();
71c54b21 11361 initServer();
bcfc686d 11362 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
11363#ifdef __linux__
11364 linuxOvercommitMemoryWarning();
11365#endif
9651a787 11366 start = time(NULL);
bcfc686d 11367 if (server.appendonly) {
11368 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
9651a787 11369 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
bcfc686d 11370 } else {
11371 if (rdbLoad(server.dbfilename) == REDIS_OK)
9651a787 11372 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
bcfc686d 11373 }
bcfc686d 11374 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
d5d55fc3 11375 aeSetBeforeSleepProc(server.el,beforeSleep);
bcfc686d 11376 aeMain(server.el);
11377 aeDeleteEventLoop(server.el);
11378 return 0;
11379}
11380
11381/* ============================= Backtrace support ========================= */
11382
11383#ifdef HAVE_BACKTRACE
11384static char *findFuncName(void *pointer, unsigned long *offset);
11385
56906eef 11386static void *getMcontextEip(ucontext_t *uc) {
11387#if defined(__FreeBSD__)
11388 return (void*) uc->uc_mcontext.mc_eip;
11389#elif defined(__dietlibc__)
11390 return (void*) uc->uc_mcontext.eip;
06db1f50 11391#elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
da0a1620 11392 #if __x86_64__
11393 return (void*) uc->uc_mcontext->__ss.__rip;
11394 #else
56906eef 11395 return (void*) uc->uc_mcontext->__ss.__eip;
da0a1620 11396 #endif
06db1f50 11397#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
cb7e07cc 11398 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
06db1f50 11399 return (void*) uc->uc_mcontext->__ss.__rip;
cbc59b38 11400 #else
11401 return (void*) uc->uc_mcontext->__ss.__eip;
e0a62c7f 11402 #endif
54bac49d 11403#elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
c04c9ac9 11404 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
b91cf5ef 11405#elif defined(__ia64__) /* Linux IA64 */
11406 return (void*) uc->uc_mcontext.sc_ip;
11407#else
11408 return NULL;
56906eef 11409#endif
11410}
11411
11412static void segvHandler(int sig, siginfo_t *info, void *secret) {
11413 void *trace[100];
11414 char **messages = NULL;
11415 int i, trace_size = 0;
11416 unsigned long offset=0;
56906eef 11417 ucontext_t *uc = (ucontext_t*) secret;
1c85b79f 11418 sds infostring;
56906eef 11419 REDIS_NOTUSED(info);
11420
11421 redisLog(REDIS_WARNING,
11422 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
1c85b79f 11423 infostring = genRedisInfoString();
11424 redisLog(REDIS_WARNING, "%s",infostring);
11425 /* It's not safe to sdsfree() the returned string under memory
11426 * corruption conditions. Let it leak as we are going to abort */
e0a62c7f 11427
56906eef 11428 trace_size = backtrace(trace, 100);
de96dbfe 11429 /* overwrite sigaction with caller's address */
b91cf5ef 11430 if (getMcontextEip(uc) != NULL) {
11431 trace[1] = getMcontextEip(uc);
11432 }
56906eef 11433 messages = backtrace_symbols(trace, trace_size);
fe3bbfbe 11434
d76412d1 11435 for (i=1; i<trace_size; ++i) {
56906eef 11436 char *fn = findFuncName(trace[i], &offset), *p;
11437
11438 p = strchr(messages[i],'+');
11439 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
11440 redisLog(REDIS_WARNING,"%s", messages[i]);
11441 } else {
11442 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
11443 }
11444 }
b177fd30 11445 /* free(messages); Don't call free() with possibly corrupted memory. */
478c2c6f 11446 _exit(0);
fe3bbfbe 11447}
56906eef 11448
fab43727 11449static void sigtermHandler(int sig) {
11450 REDIS_NOTUSED(sig);
b58ba105 11451
fab43727 11452 redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
11453 server.shutdown_asap = 1;
b58ba105
AM
11454}
11455
56906eef 11456static void setupSigSegvAction(void) {
11457 struct sigaction act;
11458
11459 sigemptyset (&act.sa_mask);
11460 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
11461 * is used. Otherwise, sa_handler is used */
11462 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
11463 act.sa_sigaction = segvHandler;
11464 sigaction (SIGSEGV, &act, NULL);
11465 sigaction (SIGBUS, &act, NULL);
12fea928 11466 sigaction (SIGFPE, &act, NULL);
11467 sigaction (SIGILL, &act, NULL);
11468 sigaction (SIGBUS, &act, NULL);
b58ba105
AM
11469
11470 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
fab43727 11471 act.sa_handler = sigtermHandler;
b58ba105 11472 sigaction (SIGTERM, &act, NULL);
e65fdc78 11473 return;
56906eef 11474}
e65fdc78 11475
bcfc686d 11476#include "staticsymbols.h"
11477/* This function try to convert a pointer into a function name. It's used in
11478 * oreder to provide a backtrace under segmentation fault that's able to
11479 * display functions declared as static (otherwise the backtrace is useless). */
11480static char *findFuncName(void *pointer, unsigned long *offset){
11481 int i, ret = -1;
11482 unsigned long off, minoff = 0;
ed9b544e 11483
bcfc686d 11484 /* Try to match against the Symbol with the smallest offset */
11485 for (i=0; symsTable[i].pointer; i++) {
11486 unsigned long lp = (unsigned long) pointer;
0bc03378 11487
bcfc686d 11488 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
11489 off=lp-symsTable[i].pointer;
11490 if (ret < 0 || off < minoff) {
11491 minoff=off;
11492 ret=i;
11493 }
11494 }
0bc03378 11495 }
bcfc686d 11496 if (ret == -1) return NULL;
11497 *offset = minoff;
11498 return symsTable[ret].name;
0bc03378 11499}
bcfc686d 11500#else /* HAVE_BACKTRACE */
11501static void setupSigSegvAction(void) {
0bc03378 11502}
bcfc686d 11503#endif /* HAVE_BACKTRACE */
0bc03378 11504
ed9b544e 11505
ed9b544e 11506
bcfc686d 11507/* The End */
11508
11509
ed9b544e 11510