]> git.saurik.com Git - redis.git/blame - redis.c
gitignore updated
[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
fda32cb6 30#define REDIS_VERSION "2.1.0"
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 */
78#include "sha1.h" /* SHA1 is used for DEBUG DIGEST */
5436146c 79#include "release.h" /* Release and/or git repository information */
ed9b544e 80
81/* Error codes */
82#define REDIS_OK 0
83#define REDIS_ERR -1
84
85/* Static server configuration */
86#define REDIS_SERVERPORT 6379 /* TCP port */
87#define REDIS_MAXIDLETIME (60*5) /* default client timeout */
6208b3a7 88#define REDIS_IOBUF_LEN 1024
ed9b544e 89#define REDIS_LOADBUF_LEN 1024
248ea310 90#define REDIS_STATIC_ARGS 8
ed9b544e 91#define REDIS_DEFAULT_DBNUM 16
92#define REDIS_CONFIGLINE_MAX 1024
93#define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
94#define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
8ca3e9d1 95#define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
6f376729 96#define REDIS_MAX_WRITE_PER_EVENT (1024*64)
2895e862 97#define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
98
99/* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
100#define REDIS_WRITEV_THRESHOLD 3
101/* Max number of iovecs used for each writev call */
102#define REDIS_WRITEV_IOVEC_COUNT 256
ed9b544e 103
104/* Hash table parameters */
105#define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
ed9b544e 106
107/* Command flags */
3fd78bcd 108#define REDIS_CMD_BULK 1 /* Bulk write command */
109#define REDIS_CMD_INLINE 2 /* Inline command */
110/* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
111 this flags will return an error when the 'maxmemory' option is set in the
112 config file and the server is using more than maxmemory bytes of memory.
113 In short this commands are denied on low memory conditions. */
114#define REDIS_CMD_DENYOOM 4
4005fef1 115#define REDIS_CMD_FORCE_REPLICATION 8 /* Force replication even if dirty is 0 */
ed9b544e 116
117/* Object types */
118#define REDIS_STRING 0
119#define REDIS_LIST 1
120#define REDIS_SET 2
1812e024 121#define REDIS_ZSET 3
122#define REDIS_HASH 4
f78fd11b 123
5234952b 124/* Objects encoding. Some kind of objects like Strings and Hashes can be
125 * internally represented in multiple ways. The 'encoding' field of the object
126 * is set to one of this fields for this object. */
942a3961 127#define REDIS_ENCODING_RAW 0 /* Raw representation */
128#define REDIS_ENCODING_INT 1 /* Encoded as integer */
5234952b 129#define REDIS_ENCODING_ZIPMAP 2 /* Encoded as zipmap */
130#define REDIS_ENCODING_HT 3 /* Encoded as an hash table */
942a3961 131
07efaf74 132static char* strencoding[] = {
133 "raw", "int", "zipmap", "hashtable"
134};
135
f78fd11b 136/* Object types only used for dumping to disk */
bb32ede5 137#define REDIS_EXPIRETIME 253
ed9b544e 138#define REDIS_SELECTDB 254
139#define REDIS_EOF 255
140
f78fd11b 141/* Defines related to the dump file format. To store 32 bits lengths for short
142 * keys requires a lot of space, so we check the most significant 2 bits of
143 * the first byte to interpreter the length:
144 *
145 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
146 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
147 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
a4d1ba9a 148 * 11|000000 this means: specially encoded object will follow. The six bits
149 * number specify the kind of object that follows.
150 * See the REDIS_RDB_ENC_* defines.
f78fd11b 151 *
10c43610 152 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
153 * values, will fit inside. */
f78fd11b 154#define REDIS_RDB_6BITLEN 0
155#define REDIS_RDB_14BITLEN 1
156#define REDIS_RDB_32BITLEN 2
17be1a4a 157#define REDIS_RDB_ENCVAL 3
f78fd11b 158#define REDIS_RDB_LENERR UINT_MAX
159
a4d1ba9a 160/* When a length of a string object stored on disk has the first two bits
161 * set, the remaining two bits specify a special encoding for the object
162 * accordingly to the following defines: */
163#define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
164#define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
165#define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
774e3047 166#define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
a4d1ba9a 167
75680a3c 168/* Virtual memory object->where field. */
169#define REDIS_VM_MEMORY 0 /* The object is on memory */
170#define REDIS_VM_SWAPPED 1 /* The object is on disk */
171#define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
172#define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
173
06224fec 174/* Virtual memory static configuration stuff.
175 * Check vmFindContiguousPages() to know more about this magic numbers. */
176#define REDIS_VM_MAX_NEAR_PAGES 65536
177#define REDIS_VM_MAX_RANDOM_JUMP 4096
92f8e882 178#define REDIS_VM_MAX_THREADS 32
bcaa7a4f 179#define REDIS_THREAD_STACK_SIZE (1024*1024*4)
f6c0bba8 180/* The following is the *percentage* of completed I/O jobs to process when the
181 * handelr is called. While Virtual Memory I/O operations are performed by
182 * threads, this operations must be processed by the main thread when completed
183 * in order to take effect. */
c953f24b 184#define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
06224fec 185
ed9b544e 186/* Client flags */
d5d55fc3 187#define REDIS_SLAVE 1 /* This client is a slave server */
188#define REDIS_MASTER 2 /* This client is a master server */
189#define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
190#define REDIS_MULTI 8 /* This client is in a MULTI context */
191#define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
192#define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
ed9b544e 193
40d224a9 194/* Slave replication state - slave side */
ed9b544e 195#define REDIS_REPL_NONE 0 /* No active replication */
196#define REDIS_REPL_CONNECT 1 /* Must connect to master */
197#define REDIS_REPL_CONNECTED 2 /* Connected to master */
198
40d224a9 199/* Slave replication state - from the point of view of master
200 * Note that in SEND_BULK and ONLINE state the slave receives new updates
201 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
202 * to start the next background saving in order to send updates to it. */
203#define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
204#define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
205#define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
206#define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
207
ed9b544e 208/* List related stuff */
209#define REDIS_HEAD 0
210#define REDIS_TAIL 1
211
212/* Sort operations */
213#define REDIS_SORT_GET 0
443c6409 214#define REDIS_SORT_ASC 1
215#define REDIS_SORT_DESC 2
ed9b544e 216#define REDIS_SORTKEY_MAX 1024
217
218/* Log levels */
219#define REDIS_DEBUG 0
f870935d 220#define REDIS_VERBOSE 1
221#define REDIS_NOTICE 2
222#define REDIS_WARNING 3
ed9b544e 223
224/* Anti-warning macro... */
225#define REDIS_NOTUSED(V) ((void) V)
226
6b47e12e 227#define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
228#define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
ed9b544e 229
48f0308a 230/* Append only defines */
231#define APPENDFSYNC_NO 0
232#define APPENDFSYNC_ALWAYS 1
233#define APPENDFSYNC_EVERYSEC 2
234
cbba7dd7 235/* Hashes related defaults */
236#define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
237#define REDIS_HASH_MAX_ZIPMAP_VALUE 512
238
dfc5e96c 239/* We can print the stacktrace, so our assert is defined this way: */
478c2c6f 240#define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
c651fd9e 241#define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
6c96ba7d 242static void _redisAssert(char *estr, char *file, int line);
c651fd9e 243static void _redisPanic(char *msg, char *file, int line);
dfc5e96c 244
ed9b544e 245/*================================= Data types ============================== */
246
247/* A redis object, that is a type able to hold a string / list / set */
75680a3c 248
249/* The VM object structure */
250struct redisObjectVM {
3a66edc7 251 off_t page; /* the page at witch the object is stored on disk */
252 off_t usedpages; /* number of pages used on disk */
253 time_t atime; /* Last access time */
75680a3c 254} vm;
255
256/* The actual Redis Object */
ed9b544e 257typedef struct redisObject {
ed9b544e 258 void *ptr;
942a3961 259 unsigned char type;
260 unsigned char encoding;
d894161b 261 unsigned char storage; /* If this object is a key, where is the value?
262 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
263 unsigned char vtype; /* If this object is a key, and value is swapped out,
264 * this is the type of the swapped out object. */
ed9b544e 265 int refcount;
75680a3c 266 /* VM fields, this are only allocated if VM is active, otherwise the
267 * object allocation function will just allocate
268 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
269 * Redis without VM active will not have any overhead. */
270 struct redisObjectVM vm;
ed9b544e 271} robj;
272
dfc5e96c 273/* Macro used to initalize a Redis object allocated on the stack.
274 * Note that this macro is taken near the structure definition to make sure
275 * we'll update it when the structure is changed, to avoid bugs like
276 * bug #85 introduced exactly in this way. */
277#define initStaticStringObject(_var,_ptr) do { \
278 _var.refcount = 1; \
279 _var.type = REDIS_STRING; \
280 _var.encoding = REDIS_ENCODING_RAW; \
281 _var.ptr = _ptr; \
3a66edc7 282 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
dfc5e96c 283} while(0);
284
3305306f 285typedef struct redisDb {
4409877e 286 dict *dict; /* The keyspace for this DB */
287 dict *expires; /* Timeout of keys with a timeout set */
288 dict *blockingkeys; /* Keys with clients waiting for data (BLPOP) */
d5d55fc3 289 dict *io_keys; /* Keys with clients waiting for VM I/O */
3305306f 290 int id;
291} redisDb;
292
6e469882 293/* Client MULTI/EXEC state */
294typedef struct multiCmd {
295 robj **argv;
296 int argc;
297 struct redisCommand *cmd;
298} multiCmd;
299
300typedef struct multiState {
301 multiCmd *commands; /* Array of MULTI commands */
302 int count; /* Total number of MULTI commands */
303} multiState;
304
ed9b544e 305/* With multiplexing we need to take per-clinet state.
306 * Clients are taken in a liked list. */
307typedef struct redisClient {
308 int fd;
3305306f 309 redisDb *db;
ed9b544e 310 int dictid;
311 sds querybuf;
e8a74421 312 robj **argv, **mbargv;
313 int argc, mbargc;
40d224a9 314 int bulklen; /* bulk read len. -1 if not in bulk read mode */
e8a74421 315 int multibulk; /* multi bulk command format active */
ed9b544e 316 list *reply;
317 int sentlen;
318 time_t lastinteraction; /* time of the last interaction, used for timeout */
d5d55fc3 319 int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
40d224a9 320 int slaveseldb; /* slave selected db, if this client is a slave */
321 int authenticated; /* when requirepass is non-NULL */
322 int replstate; /* replication state if this is a slave */
323 int repldbfd; /* replication DB file descriptor */
6e469882 324 long repldboff; /* replication DB file offset */
40d224a9 325 off_t repldbsize; /* replication DB file size */
6e469882 326 multiState mstate; /* MULTI/EXEC state */
d5d55fc3 327 robj **blockingkeys; /* The key we are waiting to terminate a blocking
4409877e 328 * operation such as BLPOP. Otherwise NULL. */
b177fd30 329 int blockingkeysnum; /* Number of blocking keys */
4409877e 330 time_t blockingto; /* Blocking operation timeout. If UNIX current time
331 * is >= blockingto then the operation timed out. */
92f8e882 332 list *io_keys; /* Keys this client is waiting to be loaded from the
333 * swap file in order to continue. */
ffc6b7f8 334 dict *pubsub_channels; /* channels a client is interested in (SUBSCRIBE) */
335 list *pubsub_patterns; /* patterns a client is interested in (SUBSCRIBE) */
ed9b544e 336} redisClient;
337
338struct saveparam {
339 time_t seconds;
340 int changes;
341};
342
343/* Global server state structure */
344struct redisServer {
345 int port;
346 int fd;
3305306f 347 redisDb *db;
ed9b544e 348 long long dirty; /* changes to DB from the last save */
349 list *clients;
87eca727 350 list *slaves, *monitors;
ed9b544e 351 char neterr[ANET_ERR_LEN];
352 aeEventLoop *el;
353 int cronloops; /* number of times the cron function run */
354 list *objfreelist; /* A list of freed objects to avoid malloc() */
355 time_t lastsave; /* Unix time of last save succeeede */
ed9b544e 356 /* Fields used only for stats */
357 time_t stat_starttime; /* server start time */
358 long long stat_numcommands; /* number of processed commands */
359 long long stat_numconnections; /* number of connections received */
2a6a2ed1 360 long long stat_expiredkeys; /* number of expired keys */
ed9b544e 361 /* Configuration */
362 int verbosity;
363 int glueoutputbuf;
364 int maxidletime;
365 int dbnum;
366 int daemonize;
44b38ef4 367 int appendonly;
48f0308a 368 int appendfsync;
fab43727 369 int shutdown_asap;
48f0308a 370 time_t lastfsync;
44b38ef4 371 int appendfd;
372 int appendseldb;
ed329fcf 373 char *pidfile;
9f3c422c 374 pid_t bgsavechildpid;
9d65a1bb 375 pid_t bgrewritechildpid;
376 sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
28ed1f33 377 sds aofbuf; /* AOF buffer, written before entering the event loop */
ed9b544e 378 struct saveparam *saveparams;
379 int saveparamslen;
380 char *logfile;
381 char *bindaddr;
382 char *dbfilename;
44b38ef4 383 char *appendfilename;
abcb223e 384 char *requirepass;
121f70cf 385 int rdbcompression;
8ca3e9d1 386 int activerehashing;
ed9b544e 387 /* Replication related */
388 int isslave;
d0ccebcf 389 char *masterauth;
ed9b544e 390 char *masterhost;
391 int masterport;
40d224a9 392 redisClient *master; /* client that is master for this slave */
ed9b544e 393 int replstate;
285add55 394 unsigned int maxclients;
4ef8de8a 395 unsigned long long maxmemory;
d5d55fc3 396 unsigned int blpop_blocked_clients;
397 unsigned int vm_blocked_clients;
ed9b544e 398 /* Sort parameters - qsort_r() is only available under BSD so we
399 * have to take this state global, in order to pass it to sortCompare() */
400 int sort_desc;
401 int sort_alpha;
402 int sort_bypattern;
75680a3c 403 /* Virtual memory configuration */
404 int vm_enabled;
054e426d 405 char *vm_swap_file;
75680a3c 406 off_t vm_page_size;
407 off_t vm_pages;
4ef8de8a 408 unsigned long long vm_max_memory;
cbba7dd7 409 /* Hashes config */
410 size_t hash_max_zipmap_entries;
411 size_t hash_max_zipmap_value;
75680a3c 412 /* Virtual memory state */
413 FILE *vm_fp;
414 int vm_fd;
415 off_t vm_next_page; /* Next probably empty page */
416 off_t vm_near_pages; /* Number of pages allocated sequentially */
06224fec 417 unsigned char *vm_bitmap; /* Bitmap of free/used pages */
3a66edc7 418 time_t unixtime; /* Unix time sampled every second. */
92f8e882 419 /* Virtual memory I/O threads stuff */
92f8e882 420 /* An I/O thread process an element taken from the io_jobs queue and
996cb5f7 421 * put the result of the operation in the io_done list. While the
422 * job is being processed, it's put on io_processing queue. */
423 list *io_newjobs; /* List of VM I/O jobs yet to be processed */
424 list *io_processing; /* List of VM I/O jobs being processed */
425 list *io_processed; /* List of VM I/O jobs already processed */
d5d55fc3 426 list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
996cb5f7 427 pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
a5819310 428 pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
429 pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
bcaa7a4f 430 pthread_attr_t io_threads_attr; /* attributes for threads creation */
92f8e882 431 int io_active_threads; /* Number of running I/O threads */
432 int vm_max_threads; /* Max number of I/O threads running at the same time */
996cb5f7 433 /* Our main thread is blocked on the event loop, locking for sockets ready
434 * to be read or written, so when a threaded I/O operation is ready to be
435 * processed by the main thread, the I/O thread will use a unix pipe to
436 * awake the main thread. The followings are the two pipe FDs. */
437 int io_ready_pipe_read;
438 int io_ready_pipe_write;
7d98e08c 439 /* Virtual memory stats */
440 unsigned long long vm_stats_used_pages;
441 unsigned long long vm_stats_swapped_objects;
442 unsigned long long vm_stats_swapouts;
443 unsigned long long vm_stats_swapins;
befec3cd 444 /* Pubsub */
ffc6b7f8 445 dict *pubsub_channels; /* Map channels to list of subscribed clients */
446 list *pubsub_patterns; /* A list of pubsub_patterns */
befec3cd 447 /* Misc */
b9bc0eef 448 FILE *devnull;
ed9b544e 449};
450
ffc6b7f8 451typedef struct pubsubPattern {
452 redisClient *client;
453 robj *pattern;
454} pubsubPattern;
455
ed9b544e 456typedef void redisCommandProc(redisClient *c);
ca1788b5 457typedef void redisVmPreloadProc(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
ed9b544e 458struct redisCommand {
459 char *name;
460 redisCommandProc *proc;
461 int arity;
462 int flags;
76583ea4
PN
463 /* Use a function to determine which keys need to be loaded
464 * in the background prior to executing this command. Takes precedence
465 * over vm_firstkey and others, ignored when NULL */
ca1788b5 466 redisVmPreloadProc *vm_preload_proc;
7c775e09 467 /* What keys should be loaded in background when calling this command? */
468 int vm_firstkey; /* The first argument that's a key (0 = no keys) */
469 int vm_lastkey; /* THe last argument that's a key */
470 int vm_keystep; /* The step between first and last key */
ed9b544e 471};
472
de96dbfe 473struct redisFunctionSym {
474 char *name;
56906eef 475 unsigned long pointer;
de96dbfe 476};
477
ed9b544e 478typedef struct _redisSortObject {
479 robj *obj;
480 union {
481 double score;
482 robj *cmpobj;
483 } u;
484} redisSortObject;
485
486typedef struct _redisSortOperation {
487 int type;
488 robj *pattern;
489} redisSortOperation;
490
6b47e12e 491/* ZSETs use a specialized version of Skiplists */
492
493typedef struct zskiplistNode {
494 struct zskiplistNode **forward;
e3870fab 495 struct zskiplistNode *backward;
912b9165 496 unsigned int *span;
6b47e12e 497 double score;
498 robj *obj;
499} zskiplistNode;
500
501typedef struct zskiplist {
e3870fab 502 struct zskiplistNode *header, *tail;
d13f767c 503 unsigned long length;
6b47e12e 504 int level;
505} zskiplist;
506
1812e024 507typedef struct zset {
508 dict *dict;
6b47e12e 509 zskiplist *zsl;
1812e024 510} zset;
511
6b47e12e 512/* Our shared "common" objects */
513
05df7621 514#define REDIS_SHARED_INTEGERS 10000
ed9b544e 515struct sharedObjectsStruct {
c937aa89 516 robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
6e469882 517 *colon, *nullbulk, *nullmultibulk, *queued,
c937aa89 518 *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
519 *outofrangeerr, *plus,
ed9b544e 520 *select0, *select1, *select2, *select3, *select4,
befec3cd 521 *select5, *select6, *select7, *select8, *select9,
c8d0ea0e 522 *messagebulk, *pmessagebulk, *subscribebulk, *unsubscribebulk, *mbulk3,
523 *mbulk4, *psubscribebulk, *punsubscribebulk,
524 *integers[REDIS_SHARED_INTEGERS];
ed9b544e 525} shared;
526
a7866db6 527/* Global vars that are actally used as constants. The following double
528 * values are used for double on-disk serialization, and are initialized
529 * at runtime to avoid strange compiler optimizations. */
530
531static double R_Zero, R_PosInf, R_NegInf, R_Nan;
532
92f8e882 533/* VM threaded I/O request message */
b9bc0eef 534#define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
535#define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
536#define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
d5d55fc3 537typedef struct iojob {
996cb5f7 538 int type; /* Request type, REDIS_IOJOB_* */
b9bc0eef 539 redisDb *db;/* Redis database */
92f8e882 540 robj *key; /* This I/O request is about swapping this key */
b9bc0eef 541 robj *val; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
92f8e882 542 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
543 off_t page; /* Swap page where to read/write the object */
248ea310 544 off_t pages; /* Swap pages needed to save object. PREPARE_SWAP return val */
996cb5f7 545 int canceled; /* True if this command was canceled by blocking side of VM */
546 pthread_t thread; /* ID of the thread processing this entry */
547} iojob;
92f8e882 548
ed9b544e 549/*================================ Prototypes =============================== */
550
551static void freeStringObject(robj *o);
552static void freeListObject(robj *o);
553static void freeSetObject(robj *o);
554static void decrRefCount(void *o);
555static robj *createObject(int type, void *ptr);
556static void freeClient(redisClient *c);
f78fd11b 557static int rdbLoad(char *filename);
ed9b544e 558static void addReply(redisClient *c, robj *obj);
559static void addReplySds(redisClient *c, sds s);
560static void incrRefCount(robj *o);
f78fd11b 561static int rdbSaveBackground(char *filename);
ed9b544e 562static robj *createStringObject(char *ptr, size_t len);
4ef8de8a 563static robj *dupStringObject(robj *o);
248ea310 564static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
dd142b9c 565static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc);
28ed1f33 566static void flushAppendOnlyFile(void);
44b38ef4 567static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
ed9b544e 568static int syncWithMaster(void);
05df7621 569static robj *tryObjectEncoding(robj *o);
9d65a1bb 570static robj *getDecodedObject(robj *o);
3305306f 571static int removeExpire(redisDb *db, robj *key);
572static int expireIfNeeded(redisDb *db, robj *key);
573static int deleteIfVolatile(redisDb *db, robj *key);
1b03836c 574static int deleteIfSwapped(redisDb *db, robj *key);
94754ccc 575static int deleteKey(redisDb *db, robj *key);
bb32ede5 576static time_t getExpire(redisDb *db, robj *key);
577static int setExpire(redisDb *db, robj *key, time_t when);
a3b21203 578static void updateSlavesWaitingBgsave(int bgsaveerr);
3fd78bcd 579static void freeMemoryIfNeeded(void);
de96dbfe 580static int processCommand(redisClient *c);
56906eef 581static void setupSigSegvAction(void);
a3b21203 582static void rdbRemoveTempFile(pid_t childpid);
9d65a1bb 583static void aofRemoveTempFile(pid_t childpid);
0ea663ea 584static size_t stringObjectLen(robj *o);
638e42ac 585static void processInputBuffer(redisClient *c);
6b47e12e 586static zskiplist *zslCreate(void);
fd8ccf44 587static void zslFree(zskiplist *zsl);
2b59cfdf 588static void zslInsert(zskiplist *zsl, double score, robj *obj);
2895e862 589static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
6e469882 590static void initClientMultiState(redisClient *c);
591static void freeClientMultiState(redisClient *c);
592static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
b0d8747d 593static void unblockClientWaitingData(redisClient *c);
4409877e 594static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
75680a3c 595static void vmInit(void);
a35ddf12 596static void vmMarkPagesFree(off_t page, off_t count);
55cf8433 597static robj *vmLoadObject(robj *key);
7e69548d 598static robj *vmPreviewObject(robj *key);
a69a0c9c 599static int vmSwapOneObjectBlocking(void);
600static int vmSwapOneObjectThreaded(void);
7e69548d 601static int vmCanSwapOut(void);
a5819310 602static int tryFreeOneObjectFromFreelist(void);
996cb5f7 603static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
604static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
605static void vmCancelThreadedIOJob(robj *o);
b9bc0eef 606static void lockThreadedIO(void);
607static void unlockThreadedIO(void);
608static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
609static void freeIOJob(iojob *j);
610static void queueIOJob(iojob *j);
a5819310 611static int vmWriteObjectOnSwap(robj *o, off_t page);
612static robj *vmReadObjectFromSwap(off_t page, int type);
054e426d 613static void waitEmptyIOJobsQueue(void);
614static void vmReopenSwapFile(void);
970e10bb 615static int vmFreePage(off_t page);
ca1788b5 616static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
3805e04f 617static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv);
0a6f3f0f 618static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd);
d5d55fc3 619static int dontWaitForSwappedKey(redisClient *c, robj *key);
620static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
621static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
622static struct redisCommand *lookupCommand(char *name);
623static void call(redisClient *c, struct redisCommand *cmd);
624static void resetClient(redisClient *c);
ada386b2 625static void convertToRealHash(robj *o);
ffc6b7f8 626static int pubsubUnsubscribeAllChannels(redisClient *c, int notify);
627static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
628static void freePubsubPattern(void *p);
629static int listMatchPubsubPattern(void *a, void *b);
630static int compareStringObjects(robj *a, robj *b);
bf028098 631static int equalStringObjects(robj *a, robj *b);
befec3cd 632static void usage();
8f63ddca 633static int rewriteAppendOnlyFileBackground(void);
242a64f3 634static int vmSwapObjectBlocking(robj *key, robj *val);
fab43727 635static int prepareForShutdown();
ed9b544e 636
abcb223e 637static void authCommand(redisClient *c);
ed9b544e 638static void pingCommand(redisClient *c);
639static void echoCommand(redisClient *c);
640static void setCommand(redisClient *c);
641static void setnxCommand(redisClient *c);
526d00a5 642static void setexCommand(redisClient *c);
ed9b544e 643static void getCommand(redisClient *c);
644static void delCommand(redisClient *c);
645static void existsCommand(redisClient *c);
646static void incrCommand(redisClient *c);
647static void decrCommand(redisClient *c);
648static void incrbyCommand(redisClient *c);
649static void decrbyCommand(redisClient *c);
650static void selectCommand(redisClient *c);
651static void randomkeyCommand(redisClient *c);
652static void keysCommand(redisClient *c);
653static void dbsizeCommand(redisClient *c);
654static void lastsaveCommand(redisClient *c);
655static void saveCommand(redisClient *c);
656static void bgsaveCommand(redisClient *c);
9d65a1bb 657static void bgrewriteaofCommand(redisClient *c);
ed9b544e 658static void shutdownCommand(redisClient *c);
659static void moveCommand(redisClient *c);
660static void renameCommand(redisClient *c);
661static void renamenxCommand(redisClient *c);
662static void lpushCommand(redisClient *c);
663static void rpushCommand(redisClient *c);
664static void lpopCommand(redisClient *c);
665static void rpopCommand(redisClient *c);
666static void llenCommand(redisClient *c);
667static void lindexCommand(redisClient *c);
668static void lrangeCommand(redisClient *c);
669static void ltrimCommand(redisClient *c);
670static void typeCommand(redisClient *c);
671static void lsetCommand(redisClient *c);
672static void saddCommand(redisClient *c);
673static void sremCommand(redisClient *c);
a4460ef4 674static void smoveCommand(redisClient *c);
ed9b544e 675static void sismemberCommand(redisClient *c);
676static void scardCommand(redisClient *c);
12fea928 677static void spopCommand(redisClient *c);
2abb95a9 678static void srandmemberCommand(redisClient *c);
ed9b544e 679static void sinterCommand(redisClient *c);
680static void sinterstoreCommand(redisClient *c);
40d224a9 681static void sunionCommand(redisClient *c);
682static void sunionstoreCommand(redisClient *c);
f4f56e1d 683static void sdiffCommand(redisClient *c);
684static void sdiffstoreCommand(redisClient *c);
ed9b544e 685static void syncCommand(redisClient *c);
686static void flushdbCommand(redisClient *c);
687static void flushallCommand(redisClient *c);
688static void sortCommand(redisClient *c);
689static void lremCommand(redisClient *c);
0f5f7e9a 690static void rpoplpushcommand(redisClient *c);
ed9b544e 691static void infoCommand(redisClient *c);
70003d28 692static void mgetCommand(redisClient *c);
87eca727 693static void monitorCommand(redisClient *c);
3305306f 694static void expireCommand(redisClient *c);
802e8373 695static void expireatCommand(redisClient *c);
f6b141c5 696static void getsetCommand(redisClient *c);
fd88489a 697static void ttlCommand(redisClient *c);
321b0e13 698static void slaveofCommand(redisClient *c);
7f957c92 699static void debugCommand(redisClient *c);
f6b141c5 700static void msetCommand(redisClient *c);
701static void msetnxCommand(redisClient *c);
fd8ccf44 702static void zaddCommand(redisClient *c);
7db723ad 703static void zincrbyCommand(redisClient *c);
cc812361 704static void zrangeCommand(redisClient *c);
50c55df5 705static void zrangebyscoreCommand(redisClient *c);
f44dd428 706static void zcountCommand(redisClient *c);
e3870fab 707static void zrevrangeCommand(redisClient *c);
3c41331e 708static void zcardCommand(redisClient *c);
1b7106e7 709static void zremCommand(redisClient *c);
6e333bbe 710static void zscoreCommand(redisClient *c);
1807985b 711static void zremrangebyscoreCommand(redisClient *c);
6e469882 712static void multiCommand(redisClient *c);
713static void execCommand(redisClient *c);
18b6cb76 714static void discardCommand(redisClient *c);
4409877e 715static void blpopCommand(redisClient *c);
716static void brpopCommand(redisClient *c);
4b00bebd 717static void appendCommand(redisClient *c);
39191553 718static void substrCommand(redisClient *c);
69d95c3e 719static void zrankCommand(redisClient *c);
798d9e55 720static void zrevrankCommand(redisClient *c);
978c2c94 721static void hsetCommand(redisClient *c);
1f1c7695 722static void hsetnxCommand(redisClient *c);
978c2c94 723static void hgetCommand(redisClient *c);
09aeb579
PN
724static void hmsetCommand(redisClient *c);
725static void hmgetCommand(redisClient *c);
07efaf74 726static void hdelCommand(redisClient *c);
92b27fe9 727static void hlenCommand(redisClient *c);
9212eafd 728static void zremrangebyrankCommand(redisClient *c);
5d373da9 729static void zunionstoreCommand(redisClient *c);
730static void zinterstoreCommand(redisClient *c);
78409a0f 731static void hkeysCommand(redisClient *c);
732static void hvalsCommand(redisClient *c);
733static void hgetallCommand(redisClient *c);
a86f14b1 734static void hexistsCommand(redisClient *c);
500ece7c 735static void configCommand(redisClient *c);
01426b05 736static void hincrbyCommand(redisClient *c);
befec3cd 737static void subscribeCommand(redisClient *c);
738static void unsubscribeCommand(redisClient *c);
ffc6b7f8 739static void psubscribeCommand(redisClient *c);
740static void punsubscribeCommand(redisClient *c);
befec3cd 741static void publishCommand(redisClient *c);
f6b141c5 742
ed9b544e 743/*================================= Globals ================================= */
744
745/* Global vars */
746static struct redisServer server; /* server global state */
747static struct redisCommand cmdTable[] = {
76583ea4
PN
748 {"get",getCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
749 {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
750 {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
526d00a5 751 {"setex",setexCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,0,0,0},
76583ea4
PN
752 {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
753 {"substr",substrCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
754 {"del",delCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
755 {"exists",existsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
756 {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
757 {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
758 {"mget",mgetCommand,-2,REDIS_CMD_INLINE,NULL,1,-1,1},
759 {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
760 {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
761 {"rpop",rpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
762 {"lpop",lpopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
763 {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
764 {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,NULL,1,1,1},
765 {"llen",llenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
766 {"lindex",lindexCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
767 {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
768 {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
769 {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
770 {"lrem",lremCommand,4,REDIS_CMD_BULK,NULL,1,1,1},
771 {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,2,1},
772 {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
773 {"srem",sremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
774 {"smove",smoveCommand,4,REDIS_CMD_BULK,NULL,1,2,1},
775 {"sismember",sismemberCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
776 {"scard",scardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
777 {"spop",spopCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
778 {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
779 {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
780 {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
781 {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
782 {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
783 {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,-1,1},
784 {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,2,-1,1},
785 {"smembers",sinterCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
786 {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
787 {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
788 {"zrem",zremCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
789 {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
790 {"zremrangebyrank",zremrangebyrankCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
5d373da9 791 {"zunionstore",zunionstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
792 {"zinterstore",zinterstoreCommand,-4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
76583ea4
PN
793 {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
794 {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
795 {"zcount",zcountCommand,4,REDIS_CMD_INLINE,NULL,1,1,1},
796 {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,NULL,1,1,1},
797 {"zcard",zcardCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
798 {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
799 {"zrank",zrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
800 {"zrevrank",zrevrankCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
801 {"hset",hsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
1f1c7695 802 {"hsetnx",hsetnxCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
09aeb579 803 {"hget",hgetCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
d33278d1 804 {"hmset",hmsetCommand,-4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
09aeb579 805 {"hmget",hmgetCommand,-3,REDIS_CMD_BULK,NULL,1,1,1},
01426b05 806 {"hincrby",hincrbyCommand,4,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
76583ea4
PN
807 {"hdel",hdelCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
808 {"hlen",hlenCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
809 {"hkeys",hkeysCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
810 {"hvals",hvalsCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
811 {"hgetall",hgetallCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
4583c4f0 812 {"hexists",hexistsCommand,3,REDIS_CMD_BULK,NULL,1,1,1},
76583ea4
PN
813 {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
814 {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
815 {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,1,1},
816 {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
817 {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,NULL,1,-1,2},
818 {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
819 {"select",selectCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
820 {"move",moveCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
821 {"rename",renameCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
822 {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,NULL,1,1,1},
823 {"expire",expireCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
824 {"expireat",expireatCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
825 {"keys",keysCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
826 {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
827 {"auth",authCommand,2,REDIS_CMD_INLINE,NULL,0,0,0},
828 {"ping",pingCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
829 {"echo",echoCommand,2,REDIS_CMD_BULK,NULL,0,0,0},
830 {"save",saveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
831 {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
832 {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
833 {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
834 {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
835 {"type",typeCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
836 {"multi",multiCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
3805e04f 837 {"exec",execCommand,1,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0},
76583ea4
PN
838 {"discard",discardCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
839 {"sync",syncCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
840 {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
841 {"flushall",flushallCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
842 {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,NULL,1,1,1},
843 {"info",infoCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
844 {"monitor",monitorCommand,1,REDIS_CMD_INLINE,NULL,0,0,0},
845 {"ttl",ttlCommand,2,REDIS_CMD_INLINE,NULL,1,1,1},
846 {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,NULL,0,0,0},
847 {"debug",debugCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
500ece7c 848 {"config",configCommand,-2,REDIS_CMD_BULK,NULL,0,0,0},
befec3cd 849 {"subscribe",subscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
850 {"unsubscribe",unsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
ffc6b7f8 851 {"psubscribe",psubscribeCommand,-2,REDIS_CMD_INLINE,NULL,0,0,0},
852 {"punsubscribe",punsubscribeCommand,-1,REDIS_CMD_INLINE,NULL,0,0,0},
4005fef1 853 {"publish",publishCommand,3,REDIS_CMD_BULK|REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0},
76583ea4 854 {NULL,NULL,0,0,NULL,0,0,0}
ed9b544e 855};
bcfc686d 856
ed9b544e 857/*============================ Utility functions ============================ */
858
859/* Glob-style pattern matching. */
500ece7c 860static int stringmatchlen(const char *pattern, int patternLen,
ed9b544e 861 const char *string, int stringLen, int nocase)
862{
863 while(patternLen) {
864 switch(pattern[0]) {
865 case '*':
866 while (pattern[1] == '*') {
867 pattern++;
868 patternLen--;
869 }
870 if (patternLen == 1)
871 return 1; /* match */
872 while(stringLen) {
873 if (stringmatchlen(pattern+1, patternLen-1,
874 string, stringLen, nocase))
875 return 1; /* match */
876 string++;
877 stringLen--;
878 }
879 return 0; /* no match */
880 break;
881 case '?':
882 if (stringLen == 0)
883 return 0; /* no match */
884 string++;
885 stringLen--;
886 break;
887 case '[':
888 {
889 int not, match;
890
891 pattern++;
892 patternLen--;
893 not = pattern[0] == '^';
894 if (not) {
895 pattern++;
896 patternLen--;
897 }
898 match = 0;
899 while(1) {
900 if (pattern[0] == '\\') {
901 pattern++;
902 patternLen--;
903 if (pattern[0] == string[0])
904 match = 1;
905 } else if (pattern[0] == ']') {
906 break;
907 } else if (patternLen == 0) {
908 pattern--;
909 patternLen++;
910 break;
911 } else if (pattern[1] == '-' && patternLen >= 3) {
912 int start = pattern[0];
913 int end = pattern[2];
914 int c = string[0];
915 if (start > end) {
916 int t = start;
917 start = end;
918 end = t;
919 }
920 if (nocase) {
921 start = tolower(start);
922 end = tolower(end);
923 c = tolower(c);
924 }
925 pattern += 2;
926 patternLen -= 2;
927 if (c >= start && c <= end)
928 match = 1;
929 } else {
930 if (!nocase) {
931 if (pattern[0] == string[0])
932 match = 1;
933 } else {
934 if (tolower((int)pattern[0]) == tolower((int)string[0]))
935 match = 1;
936 }
937 }
938 pattern++;
939 patternLen--;
940 }
941 if (not)
942 match = !match;
943 if (!match)
944 return 0; /* no match */
945 string++;
946 stringLen--;
947 break;
948 }
949 case '\\':
950 if (patternLen >= 2) {
951 pattern++;
952 patternLen--;
953 }
954 /* fall through */
955 default:
956 if (!nocase) {
957 if (pattern[0] != string[0])
958 return 0; /* no match */
959 } else {
960 if (tolower((int)pattern[0]) != tolower((int)string[0]))
961 return 0; /* no match */
962 }
963 string++;
964 stringLen--;
965 break;
966 }
967 pattern++;
968 patternLen--;
969 if (stringLen == 0) {
970 while(*pattern == '*') {
971 pattern++;
972 patternLen--;
973 }
974 break;
975 }
976 }
977 if (patternLen == 0 && stringLen == 0)
978 return 1;
979 return 0;
980}
981
500ece7c 982static int stringmatch(const char *pattern, const char *string, int nocase) {
983 return stringmatchlen(pattern,strlen(pattern),string,strlen(string),nocase);
984}
985
2b619329 986/* Convert a string representing an amount of memory into the number of
987 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
988 * (1024*1024*1024).
989 *
990 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
991 * set to 0 */
992static long long memtoll(const char *p, int *err) {
993 const char *u;
994 char buf[128];
995 long mul; /* unit multiplier */
996 long long val;
997 unsigned int digits;
998
999 if (err) *err = 0;
1000 /* Search the first non digit character. */
1001 u = p;
1002 if (*u == '-') u++;
1003 while(*u && isdigit(*u)) u++;
1004 if (*u == '\0' || !strcasecmp(u,"b")) {
1005 mul = 1;
72324005 1006 } else if (!strcasecmp(u,"k")) {
2b619329 1007 mul = 1000;
72324005 1008 } else if (!strcasecmp(u,"kb")) {
2b619329 1009 mul = 1024;
72324005 1010 } else if (!strcasecmp(u,"m")) {
2b619329 1011 mul = 1000*1000;
72324005 1012 } else if (!strcasecmp(u,"mb")) {
2b619329 1013 mul = 1024*1024;
72324005 1014 } else if (!strcasecmp(u,"g")) {
2b619329 1015 mul = 1000L*1000*1000;
72324005 1016 } else if (!strcasecmp(u,"gb")) {
2b619329 1017 mul = 1024L*1024*1024;
1018 } else {
1019 if (err) *err = 1;
1020 mul = 1;
1021 }
1022 digits = u-p;
1023 if (digits >= sizeof(buf)) {
1024 if (err) *err = 1;
1025 return LLONG_MAX;
1026 }
1027 memcpy(buf,p,digits);
1028 buf[digits] = '\0';
1029 val = strtoll(buf,NULL,10);
1030 return val*mul;
1031}
1032
ee14da56 1033/* Convert a long long into a string. Returns the number of
1034 * characters needed to represent the number, that can be shorter if passed
1035 * buffer length is not enough to store the whole number. */
1036static int ll2string(char *s, size_t len, long long value) {
1037 char buf[32], *p;
1038 unsigned long long v;
1039 size_t l;
1040
1041 if (len == 0) return 0;
1042 v = (value < 0) ? -value : value;
1043 p = buf+31; /* point to the last character */
1044 do {
1045 *p-- = '0'+(v%10);
1046 v /= 10;
1047 } while(v);
1048 if (value < 0) *p-- = '-';
1049 p++;
1050 l = 32-(p-buf);
1051 if (l+1 > len) l = len-1; /* Make sure it fits, including the nul term */
1052 memcpy(s,p,l);
1053 s[l] = '\0';
1054 return l;
1055}
1056
56906eef 1057static void redisLog(int level, const char *fmt, ...) {
ed9b544e 1058 va_list ap;
1059 FILE *fp;
1060
1061 fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
1062 if (!fp) return;
1063
1064 va_start(ap, fmt);
1065 if (level >= server.verbosity) {
6766f45e 1066 char *c = ".-*#";
1904ecc1 1067 char buf[64];
1068 time_t now;
1069
1070 now = time(NULL);
6c9385e0 1071 strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
054e426d 1072 fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
ed9b544e 1073 vfprintf(fp, fmt, ap);
1074 fprintf(fp,"\n");
1075 fflush(fp);
1076 }
1077 va_end(ap);
1078
1079 if (server.logfile) fclose(fp);
1080}
1081
1082/*====================== Hash table type implementation ==================== */
1083
1084/* This is an hash table type that uses the SDS dynamic strings libary as
1085 * keys and radis objects as values (objects can hold SDS strings,
1086 * lists, sets). */
1087
1812e024 1088static void dictVanillaFree(void *privdata, void *val)
1089{
1090 DICT_NOTUSED(privdata);
1091 zfree(val);
1092}
1093
4409877e 1094static void dictListDestructor(void *privdata, void *val)
1095{
1096 DICT_NOTUSED(privdata);
1097 listRelease((list*)val);
1098}
1099
ed9b544e 1100static int sdsDictKeyCompare(void *privdata, const void *key1,
1101 const void *key2)
1102{
1103 int l1,l2;
1104 DICT_NOTUSED(privdata);
1105
1106 l1 = sdslen((sds)key1);
1107 l2 = sdslen((sds)key2);
1108 if (l1 != l2) return 0;
1109 return memcmp(key1, key2, l1) == 0;
1110}
1111
1112static void dictRedisObjectDestructor(void *privdata, void *val)
1113{
1114 DICT_NOTUSED(privdata);
1115
a35ddf12 1116 if (val == NULL) return; /* Values of swapped out keys as set to NULL */
ed9b544e 1117 decrRefCount(val);
1118}
1119
942a3961 1120static int dictObjKeyCompare(void *privdata, const void *key1,
ed9b544e 1121 const void *key2)
1122{
1123 const robj *o1 = key1, *o2 = key2;
1124 return sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1125}
1126
942a3961 1127static unsigned int dictObjHash(const void *key) {
ed9b544e 1128 const robj *o = key;
1129 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1130}
1131
942a3961 1132static int dictEncObjKeyCompare(void *privdata, const void *key1,
1133 const void *key2)
1134{
9d65a1bb 1135 robj *o1 = (robj*) key1, *o2 = (robj*) key2;
1136 int cmp;
942a3961 1137
2a1198b4 1138 if (o1->encoding == REDIS_ENCODING_INT &&
dc05abde 1139 o2->encoding == REDIS_ENCODING_INT)
1140 return o1->ptr == o2->ptr;
2a1198b4 1141
9d65a1bb 1142 o1 = getDecodedObject(o1);
1143 o2 = getDecodedObject(o2);
1144 cmp = sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
1145 decrRefCount(o1);
1146 decrRefCount(o2);
1147 return cmp;
942a3961 1148}
1149
1150static unsigned int dictEncObjHash(const void *key) {
9d65a1bb 1151 robj *o = (robj*) key;
942a3961 1152
ed9e4966 1153 if (o->encoding == REDIS_ENCODING_RAW) {
1154 return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1155 } else {
1156 if (o->encoding == REDIS_ENCODING_INT) {
1157 char buf[32];
1158 int len;
1159
ee14da56 1160 len = ll2string(buf,32,(long)o->ptr);
ed9e4966 1161 return dictGenHashFunction((unsigned char*)buf, len);
1162 } else {
1163 unsigned int hash;
1164
1165 o = getDecodedObject(o);
1166 hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
1167 decrRefCount(o);
1168 return hash;
1169 }
1170 }
942a3961 1171}
1172
f2d9f50f 1173/* Sets type and expires */
ed9b544e 1174static dictType setDictType = {
942a3961 1175 dictEncObjHash, /* hash function */
ed9b544e 1176 NULL, /* key dup */
1177 NULL, /* val dup */
942a3961 1178 dictEncObjKeyCompare, /* key compare */
ed9b544e 1179 dictRedisObjectDestructor, /* key destructor */
1180 NULL /* val destructor */
1181};
1182
f2d9f50f 1183/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1812e024 1184static dictType zsetDictType = {
1185 dictEncObjHash, /* hash function */
1186 NULL, /* key dup */
1187 NULL, /* val dup */
1188 dictEncObjKeyCompare, /* key compare */
1189 dictRedisObjectDestructor, /* key destructor */
da0a1620 1190 dictVanillaFree /* val destructor of malloc(sizeof(double)) */
1812e024 1191};
1192
f2d9f50f 1193/* Db->dict */
5234952b 1194static dictType dbDictType = {
942a3961 1195 dictObjHash, /* hash function */
ed9b544e 1196 NULL, /* key dup */
1197 NULL, /* val dup */
942a3961 1198 dictObjKeyCompare, /* key compare */
ed9b544e 1199 dictRedisObjectDestructor, /* key destructor */
1200 dictRedisObjectDestructor /* val destructor */
1201};
1202
f2d9f50f 1203/* Db->expires */
1204static dictType keyptrDictType = {
1205 dictObjHash, /* hash function */
1206 NULL, /* key dup */
1207 NULL, /* val dup */
1208 dictObjKeyCompare, /* key compare */
1209 dictRedisObjectDestructor, /* key destructor */
1210 NULL /* val destructor */
1211};
1212
5234952b 1213/* Hash type hash table (note that small hashes are represented with zimpaps) */
1214static dictType hashDictType = {
1215 dictEncObjHash, /* hash function */
1216 NULL, /* key dup */
1217 NULL, /* val dup */
1218 dictEncObjKeyCompare, /* key compare */
1219 dictRedisObjectDestructor, /* key destructor */
1220 dictRedisObjectDestructor /* val destructor */
1221};
1222
4409877e 1223/* Keylist hash table type has unencoded redis objects as keys and
d5d55fc3 1224 * lists as values. It's used for blocking operations (BLPOP) and to
1225 * map swapped keys to a list of clients waiting for this keys to be loaded. */
4409877e 1226static dictType keylistDictType = {
1227 dictObjHash, /* hash function */
1228 NULL, /* key dup */
1229 NULL, /* val dup */
1230 dictObjKeyCompare, /* key compare */
1231 dictRedisObjectDestructor, /* key destructor */
1232 dictListDestructor /* val destructor */
1233};
1234
42ab0172
AO
1235static void version();
1236
ed9b544e 1237/* ========================= Random utility functions ======================= */
1238
1239/* Redis generally does not try to recover from out of memory conditions
1240 * when allocating objects or strings, it is not clear if it will be possible
1241 * to report this condition to the client since the networking layer itself
1242 * is based on heap allocation for send buffers, so we simply abort.
1243 * At least the code will be simpler to read... */
1244static void oom(const char *msg) {
71c54b21 1245 redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
ed9b544e 1246 sleep(1);
1247 abort();
1248}
1249
1250/* ====================== Redis server networking stuff ===================== */
56906eef 1251static void closeTimedoutClients(void) {
ed9b544e 1252 redisClient *c;
ed9b544e 1253 listNode *ln;
1254 time_t now = time(NULL);
c7df85a4 1255 listIter li;
ed9b544e 1256
c7df85a4 1257 listRewind(server.clients,&li);
1258 while ((ln = listNext(&li)) != NULL) {
ed9b544e 1259 c = listNodeValue(ln);
f86a74e9 1260 if (server.maxidletime &&
1261 !(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
c7cf2ec9 1262 !(c->flags & REDIS_MASTER) && /* no timeout for masters */
ffc6b7f8 1263 dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
1264 listLength(c->pubsub_patterns) == 0 &&
d6cc8867 1265 (now - c->lastinteraction > server.maxidletime))
f86a74e9 1266 {
f870935d 1267 redisLog(REDIS_VERBOSE,"Closing idle client");
ed9b544e 1268 freeClient(c);
f86a74e9 1269 } else if (c->flags & REDIS_BLOCKED) {
58d976b8 1270 if (c->blockingto != 0 && c->blockingto < now) {
b177fd30 1271 addReply(c,shared.nullmultibulk);
b0d8747d 1272 unblockClientWaitingData(c);
f86a74e9 1273 }
ed9b544e 1274 }
1275 }
ed9b544e 1276}
1277
12fea928 1278static int htNeedsResize(dict *dict) {
1279 long long size, used;
1280
1281 size = dictSlots(dict);
1282 used = dictSize(dict);
1283 return (size && used && size > DICT_HT_INITIAL_SIZE &&
1284 (used*100/size < REDIS_HT_MINFILL));
1285}
1286
0bc03378 1287/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1288 * we resize the hash table to save memory */
56906eef 1289static void tryResizeHashTables(void) {
0bc03378 1290 int j;
1291
1292 for (j = 0; j < server.dbnum; j++) {
5413c40d 1293 if (htNeedsResize(server.db[j].dict))
0bc03378 1294 dictResize(server.db[j].dict);
12fea928 1295 if (htNeedsResize(server.db[j].expires))
1296 dictResize(server.db[j].expires);
0bc03378 1297 }
1298}
1299
8ca3e9d1 1300/* Our hash table implementation performs rehashing incrementally while
1301 * we write/read from the hash table. Still if the server is idle, the hash
1302 * table will use two tables for a long time. So we try to use 1 millisecond
1303 * of CPU time at every serverCron() loop in order to rehash some key. */
1304static void incrementallyRehash(void) {
1305 int j;
1306
1307 for (j = 0; j < server.dbnum; j++) {
1308 if (dictIsRehashing(server.db[j].dict)) {
1309 dictRehashMilliseconds(server.db[j].dict,1);
1310 break; /* already used our millisecond for this loop... */
1311 }
1312 }
1313}
1314
9d65a1bb 1315/* A background saving child (BGSAVE) terminated its work. Handle this. */
1316void backgroundSaveDoneHandler(int statloc) {
1317 int exitcode = WEXITSTATUS(statloc);
1318 int bysignal = WIFSIGNALED(statloc);
1319
1320 if (!bysignal && exitcode == 0) {
1321 redisLog(REDIS_NOTICE,
1322 "Background saving terminated with success");
1323 server.dirty = 0;
1324 server.lastsave = time(NULL);
1325 } else if (!bysignal && exitcode != 0) {
1326 redisLog(REDIS_WARNING, "Background saving error");
1327 } else {
1328 redisLog(REDIS_WARNING,
454eea7c 1329 "Background saving terminated by signal %d", WTERMSIG(statloc));
9d65a1bb 1330 rdbRemoveTempFile(server.bgsavechildpid);
1331 }
1332 server.bgsavechildpid = -1;
1333 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1334 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1335 updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
1336}
1337
1338/* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1339 * Handle this. */
1340void backgroundRewriteDoneHandler(int statloc) {
1341 int exitcode = WEXITSTATUS(statloc);
1342 int bysignal = WIFSIGNALED(statloc);
1343
1344 if (!bysignal && exitcode == 0) {
1345 int fd;
1346 char tmpfile[256];
1347
1348 redisLog(REDIS_NOTICE,
1349 "Background append only file rewriting terminated with success");
1350 /* Now it's time to flush the differences accumulated by the parent */
1351 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
1352 fd = open(tmpfile,O_WRONLY|O_APPEND);
1353 if (fd == -1) {
1354 redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
1355 goto cleanup;
1356 }
1357 /* Flush our data... */
1358 if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
1359 (signed) sdslen(server.bgrewritebuf)) {
1360 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));
1361 close(fd);
1362 goto cleanup;
1363 }
b32627cd 1364 redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
9d65a1bb 1365 /* Now our work is to rename the temp file into the stable file. And
1366 * switch the file descriptor used by the server for append only. */
1367 if (rename(tmpfile,server.appendfilename) == -1) {
1368 redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
1369 close(fd);
1370 goto cleanup;
1371 }
1372 /* Mission completed... almost */
1373 redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
1374 if (server.appendfd != -1) {
1375 /* If append only is actually enabled... */
1376 close(server.appendfd);
1377 server.appendfd = fd;
1378 fsync(fd);
85a83172 1379 server.appendseldb = -1; /* Make sure it will issue SELECT */
9d65a1bb 1380 redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
1381 } else {
1382 /* If append only is disabled we just generate a dump in this
1383 * format. Why not? */
1384 close(fd);
1385 }
1386 } else if (!bysignal && exitcode != 0) {
1387 redisLog(REDIS_WARNING, "Background append only file rewriting error");
1388 } else {
1389 redisLog(REDIS_WARNING,
454eea7c 1390 "Background append only file rewriting terminated by signal %d",
1391 WTERMSIG(statloc));
9d65a1bb 1392 }
1393cleanup:
1394 sdsfree(server.bgrewritebuf);
1395 server.bgrewritebuf = sdsempty();
1396 aofRemoveTempFile(server.bgrewritechildpid);
1397 server.bgrewritechildpid = -1;
1398}
1399
884d4b39 1400/* This function is called once a background process of some kind terminates,
1401 * as we want to avoid resizing the hash tables when there is a child in order
1402 * to play well with copy-on-write (otherwise when a resize happens lots of
1403 * memory pages are copied). The goal of this function is to update the ability
1404 * for dict.c to resize the hash tables accordingly to the fact we have o not
1405 * running childs. */
1406static void updateDictResizePolicy(void) {
1407 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
1408 dictEnableResize();
1409 else
1410 dictDisableResize();
1411}
1412
56906eef 1413static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
94754ccc 1414 int j, loops = server.cronloops++;
ed9b544e 1415 REDIS_NOTUSED(eventLoop);
1416 REDIS_NOTUSED(id);
1417 REDIS_NOTUSED(clientData);
1418
3a66edc7 1419 /* We take a cached value of the unix time in the global state because
1420 * with virtual memory and aging there is to store the current time
1421 * in objects at every object access, and accuracy is not needed.
1422 * To access a global var is faster than calling time(NULL) */
1423 server.unixtime = time(NULL);
1424
fab43727 1425 /* We received a SIGTERM, shutting down here in a safe way, as it is
1426 * not ok doing so inside the signal handler. */
1427 if (server.shutdown_asap) {
1428 if (prepareForShutdown() == REDIS_OK) exit(0);
1429 redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
1430 }
1431
0bc03378 1432 /* Show some info about non-empty databases */
ed9b544e 1433 for (j = 0; j < server.dbnum; j++) {
dec423d9 1434 long long size, used, vkeys;
94754ccc 1435
3305306f 1436 size = dictSlots(server.db[j].dict);
1437 used = dictSize(server.db[j].dict);
94754ccc 1438 vkeys = dictSize(server.db[j].expires);
1763929f 1439 if (!(loops % 50) && (used || vkeys)) {
f870935d 1440 redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
a4d1ba9a 1441 /* dictPrintStats(server.dict); */
ed9b544e 1442 }
ed9b544e 1443 }
1444
0bc03378 1445 /* We don't want to resize the hash tables while a bacground saving
1446 * is in progress: the saving child is created using fork() that is
1447 * implemented with a copy-on-write semantic in most modern systems, so
1448 * if we resize the HT while there is the saving child at work actually
1449 * a lot of memory movements in the parent will cause a lot of pages
1450 * copied. */
8ca3e9d1 1451 if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
1452 if (!(loops % 10)) tryResizeHashTables();
1453 if (server.activerehashing) incrementallyRehash();
884d4b39 1454 }
0bc03378 1455
ed9b544e 1456 /* Show information about connected clients */
1763929f 1457 if (!(loops % 50)) {
bdcb92f2 1458 redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
ed9b544e 1459 listLength(server.clients)-listLength(server.slaves),
1460 listLength(server.slaves),
bdcb92f2 1461 zmalloc_used_memory());
ed9b544e 1462 }
1463
1464 /* Close connections of timedout clients */
1763929f 1465 if ((server.maxidletime && !(loops % 100)) || server.blpop_blocked_clients)
ed9b544e 1466 closeTimedoutClients();
1467
9d65a1bb 1468 /* Check if a background saving or AOF rewrite in progress terminated */
1469 if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
ed9b544e 1470 int statloc;
9d65a1bb 1471 pid_t pid;
1472
1473 if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
1474 if (pid == server.bgsavechildpid) {
1475 backgroundSaveDoneHandler(statloc);
ed9b544e 1476 } else {
9d65a1bb 1477 backgroundRewriteDoneHandler(statloc);
ed9b544e 1478 }
884d4b39 1479 updateDictResizePolicy();
ed9b544e 1480 }
1481 } else {
1482 /* If there is not a background saving in progress check if
1483 * we have to save now */
1484 time_t now = time(NULL);
1485 for (j = 0; j < server.saveparamslen; j++) {
1486 struct saveparam *sp = server.saveparams+j;
1487
1488 if (server.dirty >= sp->changes &&
1489 now-server.lastsave > sp->seconds) {
1490 redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
1491 sp->changes, sp->seconds);
f78fd11b 1492 rdbSaveBackground(server.dbfilename);
ed9b544e 1493 break;
1494 }
1495 }
1496 }
94754ccc 1497
f2324293 1498 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1499 * will use few CPU cycles if there are few expiring keys, otherwise
1500 * it will get more aggressive to avoid that too much memory is used by
1501 * keys that can be removed from the keyspace. */
94754ccc 1502 for (j = 0; j < server.dbnum; j++) {
f2324293 1503 int expired;
94754ccc 1504 redisDb *db = server.db+j;
94754ccc 1505
f2324293 1506 /* Continue to expire if at the end of the cycle more than 25%
1507 * of the keys were expired. */
1508 do {
4ef8de8a 1509 long num = dictSize(db->expires);
94754ccc 1510 time_t now = time(NULL);
1511
f2324293 1512 expired = 0;
94754ccc 1513 if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
1514 num = REDIS_EXPIRELOOKUPS_PER_CRON;
1515 while (num--) {
1516 dictEntry *de;
1517 time_t t;
1518
1519 if ((de = dictGetRandomKey(db->expires)) == NULL) break;
1520 t = (time_t) dictGetEntryVal(de);
1521 if (now > t) {
1522 deleteKey(db,dictGetEntryKey(de));
f2324293 1523 expired++;
2a6a2ed1 1524 server.stat_expiredkeys++;
94754ccc 1525 }
1526 }
f2324293 1527 } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
94754ccc 1528 }
1529
4ef8de8a 1530 /* Swap a few keys on disk if we are over the memory limit and VM
f870935d 1531 * is enbled. Try to free objects from the free list first. */
7e69548d 1532 if (vmCanSwapOut()) {
1533 while (server.vm_enabled && zmalloc_used_memory() >
f870935d 1534 server.vm_max_memory)
1535 {
72e9fd40 1536 int retval;
1537
a5819310 1538 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
72e9fd40 1539 retval = (server.vm_max_threads == 0) ?
1540 vmSwapOneObjectBlocking() :
1541 vmSwapOneObjectThreaded();
1763929f 1542 if (retval == REDIS_ERR && !(loops % 300) &&
72e9fd40 1543 zmalloc_used_memory() >
1544 (server.vm_max_memory+server.vm_max_memory/10))
1545 {
1546 redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
7e69548d 1547 }
72e9fd40 1548 /* Note that when using threade I/O we free just one object,
1549 * because anyway when the I/O thread in charge to swap this
1550 * object out will finish, the handler of completed jobs
1551 * will try to swap more objects if we are still out of memory. */
1552 if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
4ef8de8a 1553 }
1554 }
1555
ed9b544e 1556 /* Check if we should connect to a MASTER */
1763929f 1557 if (server.replstate == REDIS_REPL_CONNECT && !(loops % 10)) {
ed9b544e 1558 redisLog(REDIS_NOTICE,"Connecting to MASTER...");
1559 if (syncWithMaster() == REDIS_OK) {
1560 redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
8f63ddca 1561 if (server.appendonly) rewriteAppendOnlyFileBackground();
ed9b544e 1562 }
1563 }
1763929f 1564 return 100;
ed9b544e 1565}
1566
d5d55fc3 1567/* This function gets called every time Redis is entering the
1568 * main loop of the event driven library, that is, before to sleep
1569 * for ready file descriptors. */
1570static void beforeSleep(struct aeEventLoop *eventLoop) {
1571 REDIS_NOTUSED(eventLoop);
1572
28ed1f33 1573 /* Awake clients that got all the swapped keys they requested */
d5d55fc3 1574 if (server.vm_enabled && listLength(server.io_ready_clients)) {
1575 listIter li;
1576 listNode *ln;
1577
1578 listRewind(server.io_ready_clients,&li);
1579 while((ln = listNext(&li))) {
1580 redisClient *c = ln->value;
1581 struct redisCommand *cmd;
1582
1583 /* Resume the client. */
1584 listDelNode(server.io_ready_clients,ln);
1585 c->flags &= (~REDIS_IO_WAIT);
1586 server.vm_blocked_clients--;
1587 aeCreateFileEvent(server.el, c->fd, AE_READABLE,
1588 readQueryFromClient, c);
1589 cmd = lookupCommand(c->argv[0]->ptr);
1590 assert(cmd != NULL);
1591 call(c,cmd);
1592 resetClient(c);
1593 /* There may be more data to process in the input buffer. */
1594 if (c->querybuf && sdslen(c->querybuf) > 0)
1595 processInputBuffer(c);
1596 }
1597 }
28ed1f33 1598 /* Write the AOF buffer on disk */
1599 flushAppendOnlyFile();
d5d55fc3 1600}
1601
ed9b544e 1602static void createSharedObjects(void) {
05df7621 1603 int j;
1604
ed9b544e 1605 shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
1606 shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
1607 shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
c937aa89 1608 shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
1609 shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
1610 shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
1611 shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
1612 shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
1613 shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
ed9b544e 1614 shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
6e469882 1615 shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
ed9b544e 1616 shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
1617 "-ERR Operation against a key holding the wrong kind of value\r\n"));
ed9b544e 1618 shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
1619 "-ERR no such key\r\n"));
ed9b544e 1620 shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
1621 "-ERR syntax error\r\n"));
c937aa89 1622 shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
1623 "-ERR source and destination objects are the same\r\n"));
1624 shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
1625 "-ERR index out of range\r\n"));
ed9b544e 1626 shared.space = createObject(REDIS_STRING,sdsnew(" "));
c937aa89 1627 shared.colon = createObject(REDIS_STRING,sdsnew(":"));
1628 shared.plus = createObject(REDIS_STRING,sdsnew("+"));
ed9b544e 1629 shared.select0 = createStringObject("select 0\r\n",10);
1630 shared.select1 = createStringObject("select 1\r\n",10);
1631 shared.select2 = createStringObject("select 2\r\n",10);
1632 shared.select3 = createStringObject("select 3\r\n",10);
1633 shared.select4 = createStringObject("select 4\r\n",10);
1634 shared.select5 = createStringObject("select 5\r\n",10);
1635 shared.select6 = createStringObject("select 6\r\n",10);
1636 shared.select7 = createStringObject("select 7\r\n",10);
1637 shared.select8 = createStringObject("select 8\r\n",10);
1638 shared.select9 = createStringObject("select 9\r\n",10);
befec3cd 1639 shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
c8d0ea0e 1640 shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
befec3cd 1641 shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
fc46bb71 1642 shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
ffc6b7f8 1643 shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
1644 shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
befec3cd 1645 shared.mbulk3 = createStringObject("*3\r\n",4);
c8d0ea0e 1646 shared.mbulk4 = createStringObject("*4\r\n",4);
05df7621 1647 for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
1648 shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
1649 shared.integers[j]->encoding = REDIS_ENCODING_INT;
1650 }
ed9b544e 1651}
1652
1653static void appendServerSaveParams(time_t seconds, int changes) {
1654 server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
ed9b544e 1655 server.saveparams[server.saveparamslen].seconds = seconds;
1656 server.saveparams[server.saveparamslen].changes = changes;
1657 server.saveparamslen++;
1658}
1659
bcfc686d 1660static void resetServerSaveParams() {
ed9b544e 1661 zfree(server.saveparams);
1662 server.saveparams = NULL;
1663 server.saveparamslen = 0;
1664}
1665
1666static void initServerConfig() {
1667 server.dbnum = REDIS_DEFAULT_DBNUM;
1668 server.port = REDIS_SERVERPORT;
f870935d 1669 server.verbosity = REDIS_VERBOSE;
ed9b544e 1670 server.maxidletime = REDIS_MAXIDLETIME;
1671 server.saveparams = NULL;
1672 server.logfile = NULL; /* NULL = log on standard output */
1673 server.bindaddr = NULL;
1674 server.glueoutputbuf = 1;
1675 server.daemonize = 0;
44b38ef4 1676 server.appendonly = 0;
1b677732 1677 server.appendfsync = APPENDFSYNC_EVERYSEC;
48f0308a 1678 server.lastfsync = time(NULL);
44b38ef4 1679 server.appendfd = -1;
1680 server.appendseldb = -1; /* Make sure the first time will not match */
500ece7c 1681 server.pidfile = zstrdup("/var/run/redis.pid");
1682 server.dbfilename = zstrdup("dump.rdb");
1683 server.appendfilename = zstrdup("appendonly.aof");
abcb223e 1684 server.requirepass = NULL;
b0553789 1685 server.rdbcompression = 1;
8ca3e9d1 1686 server.activerehashing = 1;
285add55 1687 server.maxclients = 0;
d5d55fc3 1688 server.blpop_blocked_clients = 0;
3fd78bcd 1689 server.maxmemory = 0;
75680a3c 1690 server.vm_enabled = 0;
054e426d 1691 server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
75680a3c 1692 server.vm_page_size = 256; /* 256 bytes per page */
1693 server.vm_pages = 1024*1024*100; /* 104 millions of pages */
1694 server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
92f8e882 1695 server.vm_max_threads = 4;
d5d55fc3 1696 server.vm_blocked_clients = 0;
cbba7dd7 1697 server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
1698 server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
fab43727 1699 server.shutdown_asap = 0;
75680a3c 1700
bcfc686d 1701 resetServerSaveParams();
ed9b544e 1702
1703 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1704 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1705 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1706 /* Replication related */
1707 server.isslave = 0;
d0ccebcf 1708 server.masterauth = NULL;
ed9b544e 1709 server.masterhost = NULL;
1710 server.masterport = 6379;
1711 server.master = NULL;
1712 server.replstate = REDIS_REPL_NONE;
a7866db6 1713
1714 /* Double constants initialization */
1715 R_Zero = 0.0;
1716 R_PosInf = 1.0/R_Zero;
1717 R_NegInf = -1.0/R_Zero;
1718 R_Nan = R_Zero/R_Zero;
ed9b544e 1719}
1720
1721static void initServer() {
1722 int j;
1723
1724 signal(SIGHUP, SIG_IGN);
1725 signal(SIGPIPE, SIG_IGN);
fe3bbfbe 1726 setupSigSegvAction();
ed9b544e 1727
b9bc0eef 1728 server.devnull = fopen("/dev/null","w");
1729 if (server.devnull == NULL) {
1730 redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr);
1731 exit(1);
1732 }
ed9b544e 1733 server.clients = listCreate();
1734 server.slaves = listCreate();
87eca727 1735 server.monitors = listCreate();
ed9b544e 1736 server.objfreelist = listCreate();
1737 createSharedObjects();
1738 server.el = aeCreateEventLoop();
3305306f 1739 server.db = zmalloc(sizeof(redisDb)*server.dbnum);
ed9b544e 1740 server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
1741 if (server.fd == -1) {
1742 redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
1743 exit(1);
1744 }
3305306f 1745 for (j = 0; j < server.dbnum; j++) {
5234952b 1746 server.db[j].dict = dictCreate(&dbDictType,NULL);
f2d9f50f 1747 server.db[j].expires = dictCreate(&keyptrDictType,NULL);
4409877e 1748 server.db[j].blockingkeys = dictCreate(&keylistDictType,NULL);
d5d55fc3 1749 if (server.vm_enabled)
1750 server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
3305306f 1751 server.db[j].id = j;
1752 }
ffc6b7f8 1753 server.pubsub_channels = dictCreate(&keylistDictType,NULL);
1754 server.pubsub_patterns = listCreate();
1755 listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
1756 listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
ed9b544e 1757 server.cronloops = 0;
9f3c422c 1758 server.bgsavechildpid = -1;
9d65a1bb 1759 server.bgrewritechildpid = -1;
1760 server.bgrewritebuf = sdsempty();
28ed1f33 1761 server.aofbuf = sdsempty();
ed9b544e 1762 server.lastsave = time(NULL);
1763 server.dirty = 0;
ed9b544e 1764 server.stat_numcommands = 0;
1765 server.stat_numconnections = 0;
2a6a2ed1 1766 server.stat_expiredkeys = 0;
ed9b544e 1767 server.stat_starttime = time(NULL);
3a66edc7 1768 server.unixtime = time(NULL);
d8f8b666 1769 aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
996cb5f7 1770 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
1771 acceptHandler, NULL) == AE_ERR) oom("creating file event");
44b38ef4 1772
1773 if (server.appendonly) {
3bb225d6 1774 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
44b38ef4 1775 if (server.appendfd == -1) {
1776 redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
1777 strerror(errno));
1778 exit(1);
1779 }
1780 }
75680a3c 1781
1782 if (server.vm_enabled) vmInit();
ed9b544e 1783}
1784
1785/* Empty the whole database */
ca37e9cd 1786static long long emptyDb() {
ed9b544e 1787 int j;
ca37e9cd 1788 long long removed = 0;
ed9b544e 1789
3305306f 1790 for (j = 0; j < server.dbnum; j++) {
ca37e9cd 1791 removed += dictSize(server.db[j].dict);
3305306f 1792 dictEmpty(server.db[j].dict);
1793 dictEmpty(server.db[j].expires);
1794 }
ca37e9cd 1795 return removed;
ed9b544e 1796}
1797
85dd2f3a 1798static int yesnotoi(char *s) {
1799 if (!strcasecmp(s,"yes")) return 1;
1800 else if (!strcasecmp(s,"no")) return 0;
1801 else return -1;
1802}
1803
ed9b544e 1804/* I agree, this is a very rudimental way to load a configuration...
1805 will improve later if the config gets more complex */
1806static void loadServerConfig(char *filename) {
c9a111ac 1807 FILE *fp;
ed9b544e 1808 char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
1809 int linenum = 0;
1810 sds line = NULL;
c9a111ac 1811
1812 if (filename[0] == '-' && filename[1] == '\0')
1813 fp = stdin;
1814 else {
1815 if ((fp = fopen(filename,"r")) == NULL) {
9a22de82 1816 redisLog(REDIS_WARNING, "Fatal error, can't open config file '%s'", filename);
c9a111ac 1817 exit(1);
1818 }
ed9b544e 1819 }
c9a111ac 1820
ed9b544e 1821 while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
1822 sds *argv;
1823 int argc, j;
1824
1825 linenum++;
1826 line = sdsnew(buf);
1827 line = sdstrim(line," \t\r\n");
1828
1829 /* Skip comments and blank lines*/
1830 if (line[0] == '#' || line[0] == '\0') {
1831 sdsfree(line);
1832 continue;
1833 }
1834
1835 /* Split into arguments */
1836 argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
1837 sdstolower(argv[0]);
1838
1839 /* Execute config directives */
bb0b03a3 1840 if (!strcasecmp(argv[0],"timeout") && argc == 2) {
ed9b544e 1841 server.maxidletime = atoi(argv[1]);
0150db36 1842 if (server.maxidletime < 0) {
ed9b544e 1843 err = "Invalid timeout value"; goto loaderr;
1844 }
bb0b03a3 1845 } else if (!strcasecmp(argv[0],"port") && argc == 2) {
ed9b544e 1846 server.port = atoi(argv[1]);
1847 if (server.port < 1 || server.port > 65535) {
1848 err = "Invalid port"; goto loaderr;
1849 }
bb0b03a3 1850 } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
ed9b544e 1851 server.bindaddr = zstrdup(argv[1]);
bb0b03a3 1852 } else if (!strcasecmp(argv[0],"save") && argc == 3) {
ed9b544e 1853 int seconds = atoi(argv[1]);
1854 int changes = atoi(argv[2]);
1855 if (seconds < 1 || changes < 0) {
1856 err = "Invalid save parameters"; goto loaderr;
1857 }
1858 appendServerSaveParams(seconds,changes);
bb0b03a3 1859 } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
ed9b544e 1860 if (chdir(argv[1]) == -1) {
1861 redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
1862 argv[1], strerror(errno));
1863 exit(1);
1864 }
bb0b03a3 1865 } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
1866 if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
f870935d 1867 else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
bb0b03a3 1868 else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
1869 else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
ed9b544e 1870 else {
1871 err = "Invalid log level. Must be one of debug, notice, warning";
1872 goto loaderr;
1873 }
bb0b03a3 1874 } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
c9a111ac 1875 FILE *logfp;
ed9b544e 1876
1877 server.logfile = zstrdup(argv[1]);
bb0b03a3 1878 if (!strcasecmp(server.logfile,"stdout")) {
ed9b544e 1879 zfree(server.logfile);
1880 server.logfile = NULL;
1881 }
1882 if (server.logfile) {
1883 /* Test if we are able to open the file. The server will not
1884 * be able to abort just for this problem later... */
c9a111ac 1885 logfp = fopen(server.logfile,"a");
1886 if (logfp == NULL) {
ed9b544e 1887 err = sdscatprintf(sdsempty(),
1888 "Can't open the log file: %s", strerror(errno));
1889 goto loaderr;
1890 }
c9a111ac 1891 fclose(logfp);
ed9b544e 1892 }
bb0b03a3 1893 } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
ed9b544e 1894 server.dbnum = atoi(argv[1]);
1895 if (server.dbnum < 1) {
1896 err = "Invalid number of databases"; goto loaderr;
1897 }
b3f83f12
JZ
1898 } else if (!strcasecmp(argv[0],"include") && argc == 2) {
1899 loadServerConfig(argv[1]);
285add55 1900 } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
1901 server.maxclients = atoi(argv[1]);
3fd78bcd 1902 } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
2b619329 1903 server.maxmemory = memtoll(argv[1],NULL);
bb0b03a3 1904 } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
ed9b544e 1905 server.masterhost = sdsnew(argv[1]);
1906 server.masterport = atoi(argv[2]);
1907 server.replstate = REDIS_REPL_CONNECT;
d0ccebcf 1908 } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
1909 server.masterauth = zstrdup(argv[1]);
bb0b03a3 1910 } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
85dd2f3a 1911 if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
ed9b544e 1912 err = "argument must be 'yes' or 'no'"; goto loaderr;
1913 }
121f70cf 1914 } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
1915 if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
8ca3e9d1 1916 err = "argument must be 'yes' or 'no'"; goto loaderr;
1917 }
1918 } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
1919 if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
121f70cf 1920 err = "argument must be 'yes' or 'no'"; goto loaderr;
1921 }
bb0b03a3 1922 } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
85dd2f3a 1923 if ((server.daemonize = yesnotoi(argv[1])) == -1) {
ed9b544e 1924 err = "argument must be 'yes' or 'no'"; goto loaderr;
1925 }
44b38ef4 1926 } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
1927 if ((server.appendonly = yesnotoi(argv[1])) == -1) {
1928 err = "argument must be 'yes' or 'no'"; goto loaderr;
1929 }
f3b52411
PN
1930 } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
1931 zfree(server.appendfilename);
1932 server.appendfilename = zstrdup(argv[1]);
48f0308a 1933 } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
1766c6da 1934 if (!strcasecmp(argv[1],"no")) {
48f0308a 1935 server.appendfsync = APPENDFSYNC_NO;
1766c6da 1936 } else if (!strcasecmp(argv[1],"always")) {
48f0308a 1937 server.appendfsync = APPENDFSYNC_ALWAYS;
1766c6da 1938 } else if (!strcasecmp(argv[1],"everysec")) {
48f0308a 1939 server.appendfsync = APPENDFSYNC_EVERYSEC;
1940 } else {
1941 err = "argument must be 'no', 'always' or 'everysec'";
1942 goto loaderr;
1943 }
bb0b03a3 1944 } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
054e426d 1945 server.requirepass = zstrdup(argv[1]);
bb0b03a3 1946 } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
500ece7c 1947 zfree(server.pidfile);
054e426d 1948 server.pidfile = zstrdup(argv[1]);
bb0b03a3 1949 } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
500ece7c 1950 zfree(server.dbfilename);
054e426d 1951 server.dbfilename = zstrdup(argv[1]);
75680a3c 1952 } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
1953 if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
1954 err = "argument must be 'yes' or 'no'"; goto loaderr;
1955 }
054e426d 1956 } else if (!strcasecmp(argv[0],"vm-swap-file") && argc == 2) {
fefed597 1957 zfree(server.vm_swap_file);
054e426d 1958 server.vm_swap_file = zstrdup(argv[1]);
4ef8de8a 1959 } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
2b619329 1960 server.vm_max_memory = memtoll(argv[1],NULL);
4ef8de8a 1961 } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
2b619329 1962 server.vm_page_size = memtoll(argv[1], NULL);
4ef8de8a 1963 } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
2b619329 1964 server.vm_pages = memtoll(argv[1], NULL);
92f8e882 1965 } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
1966 server.vm_max_threads = strtoll(argv[1], NULL, 10);
cbba7dd7 1967 } else if (!strcasecmp(argv[0],"hash-max-zipmap-entries") && argc == 2){
2b619329 1968 server.hash_max_zipmap_entries = memtoll(argv[1], NULL);
cbba7dd7 1969 } else if (!strcasecmp(argv[0],"hash-max-zipmap-value") && argc == 2){
2b619329 1970 server.hash_max_zipmap_value = memtoll(argv[1], NULL);
ed9b544e 1971 } else {
1972 err = "Bad directive or wrong number of arguments"; goto loaderr;
1973 }
1974 for (j = 0; j < argc; j++)
1975 sdsfree(argv[j]);
1976 zfree(argv);
1977 sdsfree(line);
1978 }
c9a111ac 1979 if (fp != stdin) fclose(fp);
ed9b544e 1980 return;
1981
1982loaderr:
1983 fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
1984 fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
1985 fprintf(stderr, ">>> '%s'\n", line);
1986 fprintf(stderr, "%s\n", err);
1987 exit(1);
1988}
1989
1990static void freeClientArgv(redisClient *c) {
1991 int j;
1992
1993 for (j = 0; j < c->argc; j++)
1994 decrRefCount(c->argv[j]);
e8a74421 1995 for (j = 0; j < c->mbargc; j++)
1996 decrRefCount(c->mbargv[j]);
ed9b544e 1997 c->argc = 0;
e8a74421 1998 c->mbargc = 0;
ed9b544e 1999}
2000
2001static void freeClient(redisClient *c) {
2002 listNode *ln;
2003
4409877e 2004 /* Note that if the client we are freeing is blocked into a blocking
b0d8747d 2005 * call, we have to set querybuf to NULL *before* to call
2006 * unblockClientWaitingData() to avoid processInputBuffer() will get
2007 * called. Also it is important to remove the file events after
2008 * this, because this call adds the READABLE event. */
4409877e 2009 sdsfree(c->querybuf);
2010 c->querybuf = NULL;
2011 if (c->flags & REDIS_BLOCKED)
b0d8747d 2012 unblockClientWaitingData(c);
4409877e 2013
ffc6b7f8 2014 /* Unsubscribe from all the pubsub channels */
2015 pubsubUnsubscribeAllChannels(c,0);
2016 pubsubUnsubscribeAllPatterns(c,0);
2017 dictRelease(c->pubsub_channels);
2018 listRelease(c->pubsub_patterns);
befec3cd 2019 /* Obvious cleanup */
ed9b544e 2020 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
2021 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
ed9b544e 2022 listRelease(c->reply);
2023 freeClientArgv(c);
2024 close(c->fd);
92f8e882 2025 /* Remove from the list of clients */
ed9b544e 2026 ln = listSearchKey(server.clients,c);
dfc5e96c 2027 redisAssert(ln != NULL);
ed9b544e 2028 listDelNode(server.clients,ln);
d5d55fc3 2029 /* Remove from the list of clients waiting for swapped keys */
2030 if (c->flags & REDIS_IO_WAIT && listLength(c->io_keys) == 0) {
2031 ln = listSearchKey(server.io_ready_clients,c);
2032 if (ln) {
2033 listDelNode(server.io_ready_clients,ln);
2034 server.vm_blocked_clients--;
2035 }
2036 }
2037 while (server.vm_enabled && listLength(c->io_keys)) {
2038 ln = listFirst(c->io_keys);
2039 dontWaitForSwappedKey(c,ln->value);
92f8e882 2040 }
b3e3d0d7 2041 listRelease(c->io_keys);
befec3cd 2042 /* Master/slave cleanup */
ed9b544e 2043 if (c->flags & REDIS_SLAVE) {
6208b3a7 2044 if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
2045 close(c->repldbfd);
87eca727 2046 list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
2047 ln = listSearchKey(l,c);
dfc5e96c 2048 redisAssert(ln != NULL);
87eca727 2049 listDelNode(l,ln);
ed9b544e 2050 }
2051 if (c->flags & REDIS_MASTER) {
2052 server.master = NULL;
2053 server.replstate = REDIS_REPL_CONNECT;
2054 }
befec3cd 2055 /* Release memory */
93ea3759 2056 zfree(c->argv);
e8a74421 2057 zfree(c->mbargv);
6e469882 2058 freeClientMultiState(c);
ed9b544e 2059 zfree(c);
2060}
2061
cc30e368 2062#define GLUEREPLY_UP_TO (1024)
ed9b544e 2063static void glueReplyBuffersIfNeeded(redisClient *c) {
c28b42ac 2064 int copylen = 0;
2065 char buf[GLUEREPLY_UP_TO];
6208b3a7 2066 listNode *ln;
c7df85a4 2067 listIter li;
ed9b544e 2068 robj *o;
2069
c7df85a4 2070 listRewind(c->reply,&li);
2071 while((ln = listNext(&li))) {
c28b42ac 2072 int objlen;
2073
ed9b544e 2074 o = ln->value;
c28b42ac 2075 objlen = sdslen(o->ptr);
2076 if (copylen + objlen <= GLUEREPLY_UP_TO) {
2077 memcpy(buf+copylen,o->ptr,objlen);
2078 copylen += objlen;
ed9b544e 2079 listDelNode(c->reply,ln);
c28b42ac 2080 } else {
2081 if (copylen == 0) return;
2082 break;
ed9b544e 2083 }
ed9b544e 2084 }
c28b42ac 2085 /* Now the output buffer is empty, add the new single element */
2086 o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
2087 listAddNodeHead(c->reply,o);
ed9b544e 2088}
2089
2090static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2091 redisClient *c = privdata;
2092 int nwritten = 0, totwritten = 0, objlen;
2093 robj *o;
2094 REDIS_NOTUSED(el);
2095 REDIS_NOTUSED(mask);
2096
2895e862 2097 /* Use writev() if we have enough buffers to send */
7ea870c0 2098 if (!server.glueoutputbuf &&
e0a62c7f 2099 listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
7ea870c0 2100 !(c->flags & REDIS_MASTER))
2895e862 2101 {
2102 sendReplyToClientWritev(el, fd, privdata, mask);
2103 return;
2104 }
2895e862 2105
ed9b544e 2106 while(listLength(c->reply)) {
c28b42ac 2107 if (server.glueoutputbuf && listLength(c->reply) > 1)
2108 glueReplyBuffersIfNeeded(c);
2109
ed9b544e 2110 o = listNodeValue(listFirst(c->reply));
2111 objlen = sdslen(o->ptr);
2112
2113 if (objlen == 0) {
2114 listDelNode(c->reply,listFirst(c->reply));
2115 continue;
2116 }
2117
2118 if (c->flags & REDIS_MASTER) {
6f376729 2119 /* Don't reply to a master */
ed9b544e 2120 nwritten = objlen - c->sentlen;
2121 } else {
a4d1ba9a 2122 nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
ed9b544e 2123 if (nwritten <= 0) break;
2124 }
2125 c->sentlen += nwritten;
2126 totwritten += nwritten;
2127 /* If we fully sent the object on head go to the next one */
2128 if (c->sentlen == objlen) {
2129 listDelNode(c->reply,listFirst(c->reply));
2130 c->sentlen = 0;
2131 }
6f376729 2132 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
12f9d551 2133 * bytes, in a single threaded server it's a good idea to serve
6f376729 2134 * other clients as well, even if a very large request comes from
2135 * super fast link that is always able to accept data (in real world
12f9d551 2136 * scenario think about 'KEYS *' against the loopback interfae) */
6f376729 2137 if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
ed9b544e 2138 }
2139 if (nwritten == -1) {
2140 if (errno == EAGAIN) {
2141 nwritten = 0;
2142 } else {
f870935d 2143 redisLog(REDIS_VERBOSE,
ed9b544e 2144 "Error writing to client: %s", strerror(errno));
2145 freeClient(c);
2146 return;
2147 }
2148 }
2149 if (totwritten > 0) c->lastinteraction = time(NULL);
2150 if (listLength(c->reply) == 0) {
2151 c->sentlen = 0;
2152 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2153 }
2154}
2155
2895e862 2156static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
2157{
2158 redisClient *c = privdata;
2159 int nwritten = 0, totwritten = 0, objlen, willwrite;
2160 robj *o;
2161 struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
2162 int offset, ion = 0;
2163 REDIS_NOTUSED(el);
2164 REDIS_NOTUSED(mask);
2165
2166 listNode *node;
2167 while (listLength(c->reply)) {
2168 offset = c->sentlen;
2169 ion = 0;
2170 willwrite = 0;
2171
2172 /* fill-in the iov[] array */
2173 for(node = listFirst(c->reply); node; node = listNextNode(node)) {
2174 o = listNodeValue(node);
2175 objlen = sdslen(o->ptr);
2176
e0a62c7f 2177 if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
2895e862 2178 break;
2179
2180 if(ion == REDIS_WRITEV_IOVEC_COUNT)
2181 break; /* no more iovecs */
2182
2183 iov[ion].iov_base = ((char*)o->ptr) + offset;
2184 iov[ion].iov_len = objlen - offset;
2185 willwrite += objlen - offset;
2186 offset = 0; /* just for the first item */
2187 ion++;
2188 }
2189
2190 if(willwrite == 0)
2191 break;
2192
2193 /* write all collected blocks at once */
2194 if((nwritten = writev(fd, iov, ion)) < 0) {
2195 if (errno != EAGAIN) {
f870935d 2196 redisLog(REDIS_VERBOSE,
2895e862 2197 "Error writing to client: %s", strerror(errno));
2198 freeClient(c);
2199 return;
2200 }
2201 break;
2202 }
2203
2204 totwritten += nwritten;
2205 offset = c->sentlen;
2206
2207 /* remove written robjs from c->reply */
2208 while (nwritten && listLength(c->reply)) {
2209 o = listNodeValue(listFirst(c->reply));
2210 objlen = sdslen(o->ptr);
2211
2212 if(nwritten >= objlen - offset) {
2213 listDelNode(c->reply, listFirst(c->reply));
2214 nwritten -= objlen - offset;
2215 c->sentlen = 0;
2216 } else {
2217 /* partial write */
2218 c->sentlen += nwritten;
2219 break;
2220 }
2221 offset = 0;
2222 }
2223 }
2224
e0a62c7f 2225 if (totwritten > 0)
2895e862 2226 c->lastinteraction = time(NULL);
2227
2228 if (listLength(c->reply) == 0) {
2229 c->sentlen = 0;
2230 aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
2231 }
2232}
2233
ed9b544e 2234static struct redisCommand *lookupCommand(char *name) {
2235 int j = 0;
2236 while(cmdTable[j].name != NULL) {
bb0b03a3 2237 if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];
ed9b544e 2238 j++;
2239 }
2240 return NULL;
2241}
2242
2243/* resetClient prepare the client to process the next command */
2244static void resetClient(redisClient *c) {
2245 freeClientArgv(c);
2246 c->bulklen = -1;
e8a74421 2247 c->multibulk = 0;
ed9b544e 2248}
2249
6e469882 2250/* Call() is the core of Redis execution of a command */
2251static void call(redisClient *c, struct redisCommand *cmd) {
2252 long long dirty;
2253
2254 dirty = server.dirty;
2255 cmd->proc(c);
4005fef1 2256 dirty = server.dirty-dirty;
2257
2258 if (server.appendonly && dirty)
6e469882 2259 feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
4005fef1 2260 if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
2261 listLength(server.slaves))
248ea310 2262 replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
6e469882 2263 if (listLength(server.monitors))
dd142b9c 2264 replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
6e469882 2265 server.stat_numcommands++;
2266}
2267
ed9b544e 2268/* If this function gets called we already read a whole
2269 * command, argments are in the client argv/argc fields.
2270 * processCommand() execute the command or prepare the
2271 * server for a bulk read from the client.
2272 *
2273 * If 1 is returned the client is still alive and valid and
2274 * and other operations can be performed by the caller. Otherwise
2275 * if 0 is returned the client was destroied (i.e. after QUIT). */
2276static int processCommand(redisClient *c) {
2277 struct redisCommand *cmd;
ed9b544e 2278
3fd78bcd 2279 /* Free some memory if needed (maxmemory setting) */
2280 if (server.maxmemory) freeMemoryIfNeeded();
2281
e8a74421 2282 /* Handle the multi bulk command type. This is an alternative protocol
2283 * supported by Redis in order to receive commands that are composed of
2284 * multiple binary-safe "bulk" arguments. The latency of processing is
2285 * a bit higher but this allows things like multi-sets, so if this
2286 * protocol is used only for MSET and similar commands this is a big win. */
2287 if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
2288 c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
2289 if (c->multibulk <= 0) {
2290 resetClient(c);
2291 return 1;
2292 } else {
2293 decrRefCount(c->argv[c->argc-1]);
2294 c->argc--;
2295 return 1;
2296 }
2297 } else if (c->multibulk) {
2298 if (c->bulklen == -1) {
2299 if (((char*)c->argv[0]->ptr)[0] != '$') {
2300 addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
2301 resetClient(c);
2302 return 1;
2303 } else {
2304 int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
2305 decrRefCount(c->argv[0]);
2306 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2307 c->argc--;
2308 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2309 resetClient(c);
2310 return 1;
2311 }
2312 c->argc--;
2313 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2314 return 1;
2315 }
2316 } else {
2317 c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
2318 c->mbargv[c->mbargc] = c->argv[0];
2319 c->mbargc++;
2320 c->argc--;
2321 c->multibulk--;
2322 if (c->multibulk == 0) {
2323 robj **auxargv;
2324 int auxargc;
2325
2326 /* Here we need to swap the multi-bulk argc/argv with the
2327 * normal argc/argv of the client structure. */
2328 auxargv = c->argv;
2329 c->argv = c->mbargv;
2330 c->mbargv = auxargv;
2331
2332 auxargc = c->argc;
2333 c->argc = c->mbargc;
2334 c->mbargc = auxargc;
2335
2336 /* We need to set bulklen to something different than -1
2337 * in order for the code below to process the command without
2338 * to try to read the last argument of a bulk command as
2339 * a special argument. */
2340 c->bulklen = 0;
2341 /* continue below and process the command */
2342 } else {
2343 c->bulklen = -1;
2344 return 1;
2345 }
2346 }
2347 }
2348 /* -- end of multi bulk commands processing -- */
2349
ed9b544e 2350 /* The QUIT command is handled as a special case. Normal command
2351 * procs are unable to close the client connection safely */
bb0b03a3 2352 if (!strcasecmp(c->argv[0]->ptr,"quit")) {
ed9b544e 2353 freeClient(c);
2354 return 0;
2355 }
d5d55fc3 2356
2357 /* Now lookup the command and check ASAP about trivial error conditions
2358 * such wrong arity, bad command name and so forth. */
ed9b544e 2359 cmd = lookupCommand(c->argv[0]->ptr);
2360 if (!cmd) {
2c14807b 2361 addReplySds(c,
2362 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2363 (char*)c->argv[0]->ptr));
ed9b544e 2364 resetClient(c);
2365 return 1;
2366 } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
2367 (c->argc < -cmd->arity)) {
454d4e43 2368 addReplySds(c,
2369 sdscatprintf(sdsempty(),
2370 "-ERR wrong number of arguments for '%s' command\r\n",
2371 cmd->name));
ed9b544e 2372 resetClient(c);
2373 return 1;
2374 } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
d5d55fc3 2375 /* This is a bulk command, we have to read the last argument yet. */
ed9b544e 2376 int bulklen = atoi(c->argv[c->argc-1]->ptr);
2377
2378 decrRefCount(c->argv[c->argc-1]);
2379 if (bulklen < 0 || bulklen > 1024*1024*1024) {
2380 c->argc--;
2381 addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
2382 resetClient(c);
2383 return 1;
2384 }
2385 c->argc--;
2386 c->bulklen = bulklen+2; /* add two bytes for CR+LF */
2387 /* It is possible that the bulk read is already in the
8d0490e7 2388 * buffer. Check this condition and handle it accordingly.
2389 * This is just a fast path, alternative to call processInputBuffer().
2390 * It's a good idea since the code is small and this condition
2391 * happens most of the times. */
ed9b544e 2392 if ((signed)sdslen(c->querybuf) >= c->bulklen) {
2393 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2394 c->argc++;
2395 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
2396 } else {
d5d55fc3 2397 /* Otherwise return... there is to read the last argument
2398 * from the socket. */
ed9b544e 2399 return 1;
2400 }
2401 }
942a3961 2402 /* Let's try to encode the bulk object to save space. */
2403 if (cmd->flags & REDIS_CMD_BULK)
05df7621 2404 c->argv[c->argc-1] = tryObjectEncoding(c->argv[c->argc-1]);
942a3961 2405
e63943a4 2406 /* Check if the user is authenticated */
2407 if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
2408 addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
2409 resetClient(c);
2410 return 1;
2411 }
2412
b61a28fe 2413 /* Handle the maxmemory directive */
2414 if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
2415 zmalloc_used_memory() > server.maxmemory)
2416 {
2417 addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2418 resetClient(c);
2419 return 1;
2420 }
2421
d6cc8867 2422 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
e6cca5db 2423 if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
2424 &&
ffc6b7f8 2425 cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
2426 cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
2427 addReplySds(c,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
d6cc8867 2428 resetClient(c);
2429 return 1;
2430 }
2431
ed9b544e 2432 /* Exec the command */
18b6cb76 2433 if (c->flags & REDIS_MULTI && cmd->proc != execCommand && cmd->proc != discardCommand) {
6e469882 2434 queueMultiCommand(c,cmd);
2435 addReply(c,shared.queued);
2436 } else {
d5d55fc3 2437 if (server.vm_enabled && server.vm_max_threads > 0 &&
0a6f3f0f 2438 blockClientOnSwappedKeys(c,cmd)) return 1;
6e469882 2439 call(c,cmd);
2440 }
ed9b544e 2441
2442 /* Prepare the client for the next command */
ed9b544e 2443 resetClient(c);
2444 return 1;
2445}
2446
248ea310 2447static void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc) {
6208b3a7 2448 listNode *ln;
c7df85a4 2449 listIter li;
ed9b544e 2450 int outc = 0, j;
93ea3759 2451 robj **outv;
248ea310 2452 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2453 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2454 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2455 robj *static_outv[REDIS_STATIC_ARGS*3+1];
2456 robj *lenobj;
93ea3759 2457
2458 if (argc <= REDIS_STATIC_ARGS) {
2459 outv = static_outv;
2460 } else {
248ea310 2461 outv = zmalloc(sizeof(robj*)*(argc*3+1));
93ea3759 2462 }
248ea310 2463
2464 lenobj = createObject(REDIS_STRING,
2465 sdscatprintf(sdsempty(), "*%d\r\n", argc));
2466 lenobj->refcount = 0;
2467 outv[outc++] = lenobj;
ed9b544e 2468 for (j = 0; j < argc; j++) {
248ea310 2469 lenobj = createObject(REDIS_STRING,
2470 sdscatprintf(sdsempty(),"$%lu\r\n",
2471 (unsigned long) stringObjectLen(argv[j])));
2472 lenobj->refcount = 0;
2473 outv[outc++] = lenobj;
ed9b544e 2474 outv[outc++] = argv[j];
248ea310 2475 outv[outc++] = shared.crlf;
ed9b544e 2476 }
ed9b544e 2477
40d224a9 2478 /* Increment all the refcounts at start and decrement at end in order to
2479 * be sure to free objects if there is no slave in a replication state
2480 * able to be feed with commands */
2481 for (j = 0; j < outc; j++) incrRefCount(outv[j]);
c7df85a4 2482 listRewind(slaves,&li);
2483 while((ln = listNext(&li))) {
ed9b544e 2484 redisClient *slave = ln->value;
40d224a9 2485
2486 /* Don't feed slaves that are still waiting for BGSAVE to start */
6208b3a7 2487 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
40d224a9 2488
2489 /* Feed all the other slaves, MONITORs and so on */
ed9b544e 2490 if (slave->slaveseldb != dictid) {
2491 robj *selectcmd;
2492
2493 switch(dictid) {
2494 case 0: selectcmd = shared.select0; break;
2495 case 1: selectcmd = shared.select1; break;
2496 case 2: selectcmd = shared.select2; break;
2497 case 3: selectcmd = shared.select3; break;
2498 case 4: selectcmd = shared.select4; break;
2499 case 5: selectcmd = shared.select5; break;
2500 case 6: selectcmd = shared.select6; break;
2501 case 7: selectcmd = shared.select7; break;
2502 case 8: selectcmd = shared.select8; break;
2503 case 9: selectcmd = shared.select9; break;
2504 default:
2505 selectcmd = createObject(REDIS_STRING,
2506 sdscatprintf(sdsempty(),"select %d\r\n",dictid));
2507 selectcmd->refcount = 0;
2508 break;
2509 }
2510 addReply(slave,selectcmd);
2511 slave->slaveseldb = dictid;
2512 }
2513 for (j = 0; j < outc; j++) addReply(slave,outv[j]);
ed9b544e 2514 }
40d224a9 2515 for (j = 0; j < outc; j++) decrRefCount(outv[j]);
93ea3759 2516 if (outv != static_outv) zfree(outv);
ed9b544e 2517}
2518
dd142b9c 2519static sds sdscatrepr(sds s, char *p, size_t len) {
2520 s = sdscatlen(s,"\"",1);
2521 while(len--) {
2522 switch(*p) {
2523 case '\\':
2524 case '"':
2525 s = sdscatprintf(s,"\\%c",*p);
2526 break;
2527 case '\n': s = sdscatlen(s,"\\n",1); break;
2528 case '\r': s = sdscatlen(s,"\\r",1); break;
2529 case '\t': s = sdscatlen(s,"\\t",1); break;
2530 case '\a': s = sdscatlen(s,"\\a",1); break;
2531 case '\b': s = sdscatlen(s,"\\b",1); break;
2532 default:
2533 if (isprint(*p))
2534 s = sdscatprintf(s,"%c",*p);
2535 else
2536 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
2537 break;
2538 }
2539 p++;
2540 }
2541 return sdscatlen(s,"\"",1);
2542}
2543
2544static void replicationFeedMonitors(list *monitors, int dictid, robj **argv, int argc) {
2545 listNode *ln;
2546 listIter li;
2547 int j;
2548 sds cmdrepr = sdsnew("+");
2549 robj *cmdobj;
2550 struct timeval tv;
2551
2552 gettimeofday(&tv,NULL);
2553 cmdrepr = sdscatprintf(cmdrepr,"%ld.%ld ",(long)tv.tv_sec,(long)tv.tv_usec);
2554 if (dictid != 0) cmdrepr = sdscatprintf(cmdrepr,"(db %d) ", dictid);
2555
2556 for (j = 0; j < argc; j++) {
2557 if (argv[j]->encoding == REDIS_ENCODING_INT) {
2558 cmdrepr = sdscatprintf(cmdrepr, "%ld", (long)argv[j]->ptr);
2559 } else {
2560 cmdrepr = sdscatrepr(cmdrepr,(char*)argv[j]->ptr,
2561 sdslen(argv[j]->ptr));
2562 }
2563 if (j != argc-1)
2564 cmdrepr = sdscatlen(cmdrepr," ",1);
2565 }
2566 cmdrepr = sdscatlen(cmdrepr,"\r\n",2);
2567 cmdobj = createObject(REDIS_STRING,cmdrepr);
2568
2569 listRewind(monitors,&li);
2570 while((ln = listNext(&li))) {
2571 redisClient *monitor = ln->value;
2572 addReply(monitor,cmdobj);
2573 }
2574 decrRefCount(cmdobj);
2575}
2576
638e42ac 2577static void processInputBuffer(redisClient *c) {
ed9b544e 2578again:
4409877e 2579 /* Before to process the input buffer, make sure the client is not
2580 * waitig for a blocking operation such as BLPOP. Note that the first
2581 * iteration the client is never blocked, otherwise the processInputBuffer
2582 * would not be called at all, but after the execution of the first commands
2583 * in the input buffer the client may be blocked, and the "goto again"
2584 * will try to reiterate. The following line will make it return asap. */
92f8e882 2585 if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
ed9b544e 2586 if (c->bulklen == -1) {
2587 /* Read the first line of the query */
2588 char *p = strchr(c->querybuf,'\n');
2589 size_t querylen;
644fafa3 2590
ed9b544e 2591 if (p) {
2592 sds query, *argv;
2593 int argc, j;
e0a62c7f 2594
ed9b544e 2595 query = c->querybuf;
2596 c->querybuf = sdsempty();
2597 querylen = 1+(p-(query));
2598 if (sdslen(query) > querylen) {
2599 /* leave data after the first line of the query in the buffer */
2600 c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
2601 }
2602 *p = '\0'; /* remove "\n" */
2603 if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
2604 sdsupdatelen(query);
2605
2606 /* Now we can split the query in arguments */
ed9b544e 2607 argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
93ea3759 2608 sdsfree(query);
2609
2610 if (c->argv) zfree(c->argv);
2611 c->argv = zmalloc(sizeof(robj*)*argc);
93ea3759 2612
2613 for (j = 0; j < argc; j++) {
ed9b544e 2614 if (sdslen(argv[j])) {
2615 c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
2616 c->argc++;
2617 } else {
2618 sdsfree(argv[j]);
2619 }
2620 }
2621 zfree(argv);
7c49733c 2622 if (c->argc) {
2623 /* Execute the command. If the client is still valid
2624 * after processCommand() return and there is something
2625 * on the query buffer try to process the next command. */
2626 if (processCommand(c) && sdslen(c->querybuf)) goto again;
2627 } else {
2628 /* Nothing to process, argc == 0. Just process the query
2629 * buffer if it's not empty or return to the caller */
2630 if (sdslen(c->querybuf)) goto again;
2631 }
ed9b544e 2632 return;
644fafa3 2633 } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
f870935d 2634 redisLog(REDIS_VERBOSE, "Client protocol error");
ed9b544e 2635 freeClient(c);
2636 return;
2637 }
2638 } else {
2639 /* Bulk read handling. Note that if we are at this point
2640 the client already sent a command terminated with a newline,
2641 we are reading the bulk data that is actually the last
2642 argument of the command. */
2643 int qbl = sdslen(c->querybuf);
2644
2645 if (c->bulklen <= qbl) {
2646 /* Copy everything but the final CRLF as final argument */
2647 c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
2648 c->argc++;
2649 c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
638e42ac 2650 /* Process the command. If the client is still valid after
2651 * the processing and there is more data in the buffer
2652 * try to parse it. */
2653 if (processCommand(c) && sdslen(c->querybuf)) goto again;
ed9b544e 2654 return;
2655 }
2656 }
2657}
2658
638e42ac 2659static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
2660 redisClient *c = (redisClient*) privdata;
2661 char buf[REDIS_IOBUF_LEN];
2662 int nread;
2663 REDIS_NOTUSED(el);
2664 REDIS_NOTUSED(mask);
2665
2666 nread = read(fd, buf, REDIS_IOBUF_LEN);
2667 if (nread == -1) {
2668 if (errno == EAGAIN) {
2669 nread = 0;
2670 } else {
f870935d 2671 redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
638e42ac 2672 freeClient(c);
2673 return;
2674 }
2675 } else if (nread == 0) {
f870935d 2676 redisLog(REDIS_VERBOSE, "Client closed connection");
638e42ac 2677 freeClient(c);
2678 return;
2679 }
2680 if (nread) {
2681 c->querybuf = sdscatlen(c->querybuf, buf, nread);
2682 c->lastinteraction = time(NULL);
2683 } else {
2684 return;
2685 }
168ac5c6 2686 processInputBuffer(c);
638e42ac 2687}
2688
ed9b544e 2689static int selectDb(redisClient *c, int id) {
2690 if (id < 0 || id >= server.dbnum)
2691 return REDIS_ERR;
3305306f 2692 c->db = &server.db[id];
ed9b544e 2693 return REDIS_OK;
2694}
2695
40d224a9 2696static void *dupClientReplyValue(void *o) {
2697 incrRefCount((robj*)o);
12d090d2 2698 return o;
40d224a9 2699}
2700
ffc6b7f8 2701static int listMatchObjects(void *a, void *b) {
bf028098 2702 return equalStringObjects(a,b);
ffc6b7f8 2703}
2704
ed9b544e 2705static redisClient *createClient(int fd) {
2706 redisClient *c = zmalloc(sizeof(*c));
2707
2708 anetNonBlock(NULL,fd);
2709 anetTcpNoDelay(NULL,fd);
2710 if (!c) return NULL;
2711 selectDb(c,0);
2712 c->fd = fd;
2713 c->querybuf = sdsempty();
2714 c->argc = 0;
93ea3759 2715 c->argv = NULL;
ed9b544e 2716 c->bulklen = -1;
e8a74421 2717 c->multibulk = 0;
2718 c->mbargc = 0;
2719 c->mbargv = NULL;
ed9b544e 2720 c->sentlen = 0;
2721 c->flags = 0;
2722 c->lastinteraction = time(NULL);
abcb223e 2723 c->authenticated = 0;
40d224a9 2724 c->replstate = REDIS_REPL_NONE;
6b47e12e 2725 c->reply = listCreate();
ed9b544e 2726 listSetFreeMethod(c->reply,decrRefCount);
40d224a9 2727 listSetDupMethod(c->reply,dupClientReplyValue);
92f8e882 2728 c->blockingkeys = NULL;
2729 c->blockingkeysnum = 0;
2730 c->io_keys = listCreate();
2731 listSetFreeMethod(c->io_keys,decrRefCount);
ffc6b7f8 2732 c->pubsub_channels = dictCreate(&setDictType,NULL);
2733 c->pubsub_patterns = listCreate();
2734 listSetFreeMethod(c->pubsub_patterns,decrRefCount);
2735 listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
ed9b544e 2736 if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
266373b2 2737 readQueryFromClient, c) == AE_ERR) {
ed9b544e 2738 freeClient(c);
2739 return NULL;
2740 }
6b47e12e 2741 listAddNodeTail(server.clients,c);
6e469882 2742 initClientMultiState(c);
ed9b544e 2743 return c;
2744}
2745
2746static void addReply(redisClient *c, robj *obj) {
2747 if (listLength(c->reply) == 0 &&
6208b3a7 2748 (c->replstate == REDIS_REPL_NONE ||
2749 c->replstate == REDIS_REPL_ONLINE) &&
ed9b544e 2750 aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
266373b2 2751 sendReplyToClient, c) == AE_ERR) return;
e3cadb8a 2752
2753 if (server.vm_enabled && obj->storage != REDIS_VM_MEMORY) {
2754 obj = dupStringObject(obj);
2755 obj->refcount = 0; /* getDecodedObject() will increment the refcount */
2756 }
9d65a1bb 2757 listAddNodeTail(c->reply,getDecodedObject(obj));
ed9b544e 2758}
2759
2760static void addReplySds(redisClient *c, sds s) {
2761 robj *o = createObject(REDIS_STRING,s);
2762 addReply(c,o);
2763 decrRefCount(o);
2764}
2765
e2665397 2766static void addReplyDouble(redisClient *c, double d) {
2767 char buf[128];
2768
2769 snprintf(buf,sizeof(buf),"%.17g",d);
682ac724 2770 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
83c6a618 2771 (unsigned long) strlen(buf),buf));
e2665397 2772}
2773
aa7c2934
PN
2774static void addReplyLongLong(redisClient *c, long long ll) {
2775 char buf[128];
2776 size_t len;
2777
2778 if (ll == 0) {
2779 addReply(c,shared.czero);
2780 return;
2781 } else if (ll == 1) {
2782 addReply(c,shared.cone);
2783 return;
2784 }
482b672d 2785 buf[0] = ':';
2786 len = ll2string(buf+1,sizeof(buf)-1,ll);
2787 buf[len+1] = '\r';
2788 buf[len+2] = '\n';
2789 addReplySds(c,sdsnewlen(buf,len+3));
aa7c2934
PN
2790}
2791
92b27fe9 2792static void addReplyUlong(redisClient *c, unsigned long ul) {
2793 char buf[128];
2794 size_t len;
2795
dd88747b 2796 if (ul == 0) {
2797 addReply(c,shared.czero);
2798 return;
2799 } else if (ul == 1) {
2800 addReply(c,shared.cone);
2801 return;
2802 }
92b27fe9 2803 len = snprintf(buf,sizeof(buf),":%lu\r\n",ul);
2804 addReplySds(c,sdsnewlen(buf,len));
2805}
2806
942a3961 2807static void addReplyBulkLen(redisClient *c, robj *obj) {
482b672d 2808 size_t len, intlen;
2809 char buf[128];
942a3961 2810
2811 if (obj->encoding == REDIS_ENCODING_RAW) {
2812 len = sdslen(obj->ptr);
2813 } else {
2814 long n = (long)obj->ptr;
2815
e054afda 2816 /* Compute how many bytes will take this integer as a radix 10 string */
942a3961 2817 len = 1;
2818 if (n < 0) {
2819 len++;
2820 n = -n;
2821 }
2822 while((n = n/10) != 0) {
2823 len++;
2824 }
2825 }
482b672d 2826 buf[0] = '$';
2827 intlen = ll2string(buf+1,sizeof(buf)-1,(long long)len);
2828 buf[intlen+1] = '\r';
2829 buf[intlen+2] = '\n';
2830 addReplySds(c,sdsnewlen(buf,intlen+3));
942a3961 2831}
2832
dd88747b 2833static void addReplyBulk(redisClient *c, robj *obj) {
2834 addReplyBulkLen(c,obj);
2835 addReply(c,obj);
2836 addReply(c,shared.crlf);
2837}
2838
500ece7c 2839/* In the CONFIG command we need to add vanilla C string as bulk replies */
2840static void addReplyBulkCString(redisClient *c, char *s) {
2841 if (s == NULL) {
2842 addReply(c,shared.nullbulk);
2843 } else {
2844 robj *o = createStringObject(s,strlen(s));
2845 addReplyBulk(c,o);
2846 decrRefCount(o);
2847 }
2848}
2849
ed9b544e 2850static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2851 int cport, cfd;
2852 char cip[128];
285add55 2853 redisClient *c;
ed9b544e 2854 REDIS_NOTUSED(el);
2855 REDIS_NOTUSED(mask);
2856 REDIS_NOTUSED(privdata);
2857
2858 cfd = anetAccept(server.neterr, fd, cip, &cport);
2859 if (cfd == AE_ERR) {
f870935d 2860 redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
ed9b544e 2861 return;
2862 }
f870935d 2863 redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
285add55 2864 if ((c = createClient(cfd)) == NULL) {
ed9b544e 2865 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2866 close(cfd); /* May be already closed, just ingore errors */
2867 return;
2868 }
285add55 2869 /* If maxclient directive is set and this is one client more... close the
2870 * connection. Note that we create the client instead to check before
2871 * for this condition, since now the socket is already set in nonblocking
2872 * mode and we can send an error for free using the Kernel I/O */
2873 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2874 char *err = "-ERR max number of clients reached\r\n";
2875
2876 /* That's a best effort error message, don't check write errors */
fee803ba 2877 if (write(c->fd,err,strlen(err)) == -1) {
2878 /* Nothing to do, Just to avoid the warning... */
2879 }
285add55 2880 freeClient(c);
2881 return;
2882 }
ed9b544e 2883 server.stat_numconnections++;
2884}
2885
2886/* ======================= Redis objects implementation ===================== */
2887
2888static robj *createObject(int type, void *ptr) {
2889 robj *o;
2890
a5819310 2891 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
ed9b544e 2892 if (listLength(server.objfreelist)) {
2893 listNode *head = listFirst(server.objfreelist);
2894 o = listNodeValue(head);
2895 listDelNode(server.objfreelist,head);
a5819310 2896 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
ed9b544e 2897 } else {
75680a3c 2898 if (server.vm_enabled) {
a5819310 2899 pthread_mutex_unlock(&server.obj_freelist_mutex);
75680a3c 2900 o = zmalloc(sizeof(*o));
2901 } else {
2902 o = zmalloc(sizeof(*o)-sizeof(struct redisObjectVM));
2903 }
ed9b544e 2904 }
ed9b544e 2905 o->type = type;
942a3961 2906 o->encoding = REDIS_ENCODING_RAW;
ed9b544e 2907 o->ptr = ptr;
2908 o->refcount = 1;
3a66edc7 2909 if (server.vm_enabled) {
1064ef87 2910 /* Note that this code may run in the context of an I/O thread
2911 * and accessing to server.unixtime in theory is an error
2912 * (no locks). But in practice this is safe, and even if we read
2913 * garbage Redis will not fail, as it's just a statistical info */
3a66edc7 2914 o->vm.atime = server.unixtime;
2915 o->storage = REDIS_VM_MEMORY;
2916 }
ed9b544e 2917 return o;
2918}
2919
2920static robj *createStringObject(char *ptr, size_t len) {
2921 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
2922}
2923
3f973463
PN
2924static robj *createStringObjectFromLongLong(long long value) {
2925 robj *o;
2926 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
2927 incrRefCount(shared.integers[value]);
2928 o = shared.integers[value];
2929 } else {
3f973463 2930 if (value >= LONG_MIN && value <= LONG_MAX) {
10dea8dc 2931 o = createObject(REDIS_STRING, NULL);
3f973463
PN
2932 o->encoding = REDIS_ENCODING_INT;
2933 o->ptr = (void*)((long)value);
2934 } else {
ee14da56 2935 o = createObject(REDIS_STRING,sdsfromlonglong(value));
3f973463
PN
2936 }
2937 }
2938 return o;
2939}
2940
4ef8de8a 2941static robj *dupStringObject(robj *o) {
b9bc0eef 2942 assert(o->encoding == REDIS_ENCODING_RAW);
4ef8de8a 2943 return createStringObject(o->ptr,sdslen(o->ptr));
2944}
2945
ed9b544e 2946static robj *createListObject(void) {
2947 list *l = listCreate();
2948
ed9b544e 2949 listSetFreeMethod(l,decrRefCount);
2950 return createObject(REDIS_LIST,l);
2951}
2952
2953static robj *createSetObject(void) {
2954 dict *d = dictCreate(&setDictType,NULL);
ed9b544e 2955 return createObject(REDIS_SET,d);
2956}
2957
5234952b 2958static robj *createHashObject(void) {
2959 /* All the Hashes start as zipmaps. Will be automatically converted
2960 * into hash tables if there are enough elements or big elements
2961 * inside. */
2962 unsigned char *zm = zipmapNew();
2963 robj *o = createObject(REDIS_HASH,zm);
2964 o->encoding = REDIS_ENCODING_ZIPMAP;
2965 return o;
2966}
2967
1812e024 2968static robj *createZsetObject(void) {
6b47e12e 2969 zset *zs = zmalloc(sizeof(*zs));
2970
2971 zs->dict = dictCreate(&zsetDictType,NULL);
2972 zs->zsl = zslCreate();
2973 return createObject(REDIS_ZSET,zs);
1812e024 2974}
2975
ed9b544e 2976static void freeStringObject(robj *o) {
942a3961 2977 if (o->encoding == REDIS_ENCODING_RAW) {
2978 sdsfree(o->ptr);
2979 }
ed9b544e 2980}
2981
2982static void freeListObject(robj *o) {
2983 listRelease((list*) o->ptr);
2984}
2985
2986static void freeSetObject(robj *o) {
2987 dictRelease((dict*) o->ptr);
2988}
2989
fd8ccf44 2990static void freeZsetObject(robj *o) {
2991 zset *zs = o->ptr;
2992
2993 dictRelease(zs->dict);
2994 zslFree(zs->zsl);
2995 zfree(zs);
2996}
2997
ed9b544e 2998static void freeHashObject(robj *o) {
cbba7dd7 2999 switch (o->encoding) {
3000 case REDIS_ENCODING_HT:
3001 dictRelease((dict*) o->ptr);
3002 break;
3003 case REDIS_ENCODING_ZIPMAP:
3004 zfree(o->ptr);
3005 break;
3006 default:
f83c6cb5 3007 redisPanic("Unknown hash encoding type");
cbba7dd7 3008 break;
3009 }
ed9b544e 3010}
3011
3012static void incrRefCount(robj *o) {
3013 o->refcount++;
3014}
3015
3016static void decrRefCount(void *obj) {
3017 robj *o = obj;
94754ccc 3018
c651fd9e 3019 if (o->refcount <= 0) redisPanic("decrRefCount against refcount <= 0");
970e10bb 3020 /* Object is a key of a swapped out value, or in the process of being
3021 * loaded. */
996cb5f7 3022 if (server.vm_enabled &&
3023 (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
3024 {
996cb5f7 3025 if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(obj);
f2b8ab34 3026 redisAssert(o->type == REDIS_STRING);
a35ddf12 3027 freeStringObject(o);
3028 vmMarkPagesFree(o->vm.page,o->vm.usedpages);
a5819310 3029 pthread_mutex_lock(&server.obj_freelist_mutex);
a35ddf12 3030 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3031 !listAddNodeHead(server.objfreelist,o))
3032 zfree(o);
a5819310 3033 pthread_mutex_unlock(&server.obj_freelist_mutex);
7d98e08c 3034 server.vm_stats_swapped_objects--;
a35ddf12 3035 return;
3036 }
996cb5f7 3037 /* Object is in memory, or in the process of being swapped out. */
ed9b544e 3038 if (--(o->refcount) == 0) {
996cb5f7 3039 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
3040 vmCancelThreadedIOJob(obj);
ed9b544e 3041 switch(o->type) {
3042 case REDIS_STRING: freeStringObject(o); break;
3043 case REDIS_LIST: freeListObject(o); break;
3044 case REDIS_SET: freeSetObject(o); break;
fd8ccf44 3045 case REDIS_ZSET: freeZsetObject(o); break;
ed9b544e 3046 case REDIS_HASH: freeHashObject(o); break;
f83c6cb5 3047 default: redisPanic("Unknown object type"); break;
ed9b544e 3048 }
a5819310 3049 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
ed9b544e 3050 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
3051 !listAddNodeHead(server.objfreelist,o))
3052 zfree(o);
a5819310 3053 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
ed9b544e 3054 }
3055}
3056
942a3961 3057static robj *lookupKey(redisDb *db, robj *key) {
3058 dictEntry *de = dictFind(db->dict,key);
3a66edc7 3059 if (de) {
55cf8433 3060 robj *key = dictGetEntryKey(de);
3061 robj *val = dictGetEntryVal(de);
3a66edc7 3062
55cf8433 3063 if (server.vm_enabled) {
996cb5f7 3064 if (key->storage == REDIS_VM_MEMORY ||
3065 key->storage == REDIS_VM_SWAPPING)
3066 {
3067 /* If we were swapping the object out, stop it, this key
3068 * was requested. */
3069 if (key->storage == REDIS_VM_SWAPPING)
3070 vmCancelThreadedIOJob(key);
55cf8433 3071 /* Update the access time of the key for the aging algorithm. */
3072 key->vm.atime = server.unixtime;
3073 } else {
d5d55fc3 3074 int notify = (key->storage == REDIS_VM_LOADING);
3075
55cf8433 3076 /* Our value was swapped on disk. Bring it at home. */
f2b8ab34 3077 redisAssert(val == NULL);
55cf8433 3078 val = vmLoadObject(key);
3079 dictGetEntryVal(de) = val;
d5d55fc3 3080
3081 /* Clients blocked by the VM subsystem may be waiting for
3082 * this key... */
3083 if (notify) handleClientsBlockedOnSwappedKey(db,key);
55cf8433 3084 }
3085 }
3086 return val;
3a66edc7 3087 } else {
3088 return NULL;
3089 }
942a3961 3090}
3091
3092static robj *lookupKeyRead(redisDb *db, robj *key) {
3093 expireIfNeeded(db,key);
3094 return lookupKey(db,key);
3095}
3096
3097static robj *lookupKeyWrite(redisDb *db, robj *key) {
3098 deleteIfVolatile(db,key);
3099 return lookupKey(db,key);
3100}
3101
92b27fe9 3102static robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
3103 robj *o = lookupKeyRead(c->db, key);
3104 if (!o) addReply(c,reply);
3105 return o;
3106}
3107
3108static robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
3109 robj *o = lookupKeyWrite(c->db, key);
3110 if (!o) addReply(c,reply);
3111 return o;
3112}
3113
3114static int checkType(redisClient *c, robj *o, int type) {
3115 if (o->type != type) {
3116 addReply(c,shared.wrongtypeerr);
3117 return 1;
3118 }
3119 return 0;
3120}
3121
942a3961 3122static int deleteKey(redisDb *db, robj *key) {
3123 int retval;
3124
3125 /* We need to protect key from destruction: after the first dictDelete()
3126 * it may happen that 'key' is no longer valid if we don't increment
3127 * it's count. This may happen when we get the object reference directly
3128 * from the hash table with dictRandomKey() or dict iterators */
3129 incrRefCount(key);
3130 if (dictSize(db->expires)) dictDelete(db->expires,key);
3131 retval = dictDelete(db->dict,key);
3132 decrRefCount(key);
3133
3134 return retval == DICT_OK;
3135}
3136
724a51b1 3137/* Check if the nul-terminated string 's' can be represented by a long
3138 * (that is, is a number that fits into long without any other space or
3139 * character before or after the digits).
3140 *
3141 * If so, the function returns REDIS_OK and *longval is set to the value
3142 * of the number. Otherwise REDIS_ERR is returned */
f69f2cba 3143static int isStringRepresentableAsLong(sds s, long *longval) {
724a51b1 3144 char buf[32], *endptr;
3145 long value;
3146 int slen;
e0a62c7f 3147
724a51b1 3148 value = strtol(s, &endptr, 10);
3149 if (endptr[0] != '\0') return REDIS_ERR;
ee14da56 3150 slen = ll2string(buf,32,value);
724a51b1 3151
3152 /* If the number converted back into a string is not identical
3153 * then it's not possible to encode the string as integer */
f69f2cba 3154 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
724a51b1 3155 if (longval) *longval = value;
3156 return REDIS_OK;
3157}
3158
942a3961 3159/* Try to encode a string object in order to save space */
05df7621 3160static robj *tryObjectEncoding(robj *o) {
942a3961 3161 long value;
942a3961 3162 sds s = o->ptr;
3305306f 3163
942a3961 3164 if (o->encoding != REDIS_ENCODING_RAW)
05df7621 3165 return o; /* Already encoded */
3305306f 3166
05df7621 3167 /* It's not safe to encode shared objects: shared objects can be shared
942a3961 3168 * everywhere in the "object space" of Redis. Encoded objects can only
3169 * appear as "values" (and not, for instance, as keys) */
05df7621 3170 if (o->refcount > 1) return o;
3305306f 3171
942a3961 3172 /* Currently we try to encode only strings */
dfc5e96c 3173 redisAssert(o->type == REDIS_STRING);
94754ccc 3174
724a51b1 3175 /* Check if we can represent this string as a long integer */
05df7621 3176 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return o;
942a3961 3177
3178 /* Ok, this object can be encoded */
05df7621 3179 if (value >= 0 && value < REDIS_SHARED_INTEGERS) {
3180 decrRefCount(o);
3181 incrRefCount(shared.integers[value]);
3182 return shared.integers[value];
3183 } else {
3184 o->encoding = REDIS_ENCODING_INT;
3185 sdsfree(o->ptr);
3186 o->ptr = (void*) value;
3187 return o;
3188 }
942a3961 3189}
3190
9d65a1bb 3191/* Get a decoded version of an encoded object (returned as a new object).
3192 * If the object is already raw-encoded just increment the ref count. */
3193static robj *getDecodedObject(robj *o) {
942a3961 3194 robj *dec;
e0a62c7f 3195
9d65a1bb 3196 if (o->encoding == REDIS_ENCODING_RAW) {
3197 incrRefCount(o);
3198 return o;
3199 }
942a3961 3200 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
3201 char buf[32];
3202
ee14da56 3203 ll2string(buf,32,(long)o->ptr);
942a3961 3204 dec = createStringObject(buf,strlen(buf));
3205 return dec;
3206 } else {
08ee9b57 3207 redisPanic("Unknown encoding type");
942a3961 3208 }
3305306f 3209}
3210
d7f43c08 3211/* Compare two string objects via strcmp() or alike.
3212 * Note that the objects may be integer-encoded. In such a case we
ee14da56 3213 * use ll2string() to get a string representation of the numbers on the stack
1fd9bc8a 3214 * and compare the strings, it's much faster than calling getDecodedObject().
3215 *
3216 * Important note: if objects are not integer encoded, but binary-safe strings,
3217 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3218 * binary safe. */
724a51b1 3219static int compareStringObjects(robj *a, robj *b) {
dfc5e96c 3220 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
d7f43c08 3221 char bufa[128], bufb[128], *astr, *bstr;
3222 int bothsds = 1;
724a51b1 3223
e197b441 3224 if (a == b) return 0;
d7f43c08 3225 if (a->encoding != REDIS_ENCODING_RAW) {
ee14da56 3226 ll2string(bufa,sizeof(bufa),(long) a->ptr);
d7f43c08 3227 astr = bufa;
3228 bothsds = 0;
724a51b1 3229 } else {
d7f43c08 3230 astr = a->ptr;
724a51b1 3231 }
d7f43c08 3232 if (b->encoding != REDIS_ENCODING_RAW) {
ee14da56 3233 ll2string(bufb,sizeof(bufb),(long) b->ptr);
d7f43c08 3234 bstr = bufb;
3235 bothsds = 0;
3236 } else {
3237 bstr = b->ptr;
3238 }
3239 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
724a51b1 3240}
3241
bf028098 3242/* Equal string objects return 1 if the two objects are the same from the
3243 * point of view of a string comparison, otherwise 0 is returned. Note that
3244 * this function is faster then checking for (compareStringObject(a,b) == 0)
3245 * because it can perform some more optimization. */
3246static int equalStringObjects(robj *a, robj *b) {
3247 if (a->encoding != REDIS_ENCODING_RAW && b->encoding != REDIS_ENCODING_RAW){
3248 return a->ptr == b->ptr;
3249 } else {
3250 return compareStringObjects(a,b) == 0;
3251 }
3252}
3253
0ea663ea 3254static size_t stringObjectLen(robj *o) {
dfc5e96c 3255 redisAssert(o->type == REDIS_STRING);
0ea663ea 3256 if (o->encoding == REDIS_ENCODING_RAW) {
3257 return sdslen(o->ptr);
3258 } else {
3259 char buf[32];
3260
ee14da56 3261 return ll2string(buf,32,(long)o->ptr);
0ea663ea 3262 }
3263}
3264
bd79a6bd
PN
3265static int getDoubleFromObject(robj *o, double *target) {
3266 double value;
682c73e8 3267 char *eptr;
bbe025e0 3268
bd79a6bd
PN
3269 if (o == NULL) {
3270 value = 0;
3271 } else {
3272 redisAssert(o->type == REDIS_STRING);
3273 if (o->encoding == REDIS_ENCODING_RAW) {
3274 value = strtod(o->ptr, &eptr);
682c73e8 3275 if (eptr[0] != '\0') return REDIS_ERR;
bd79a6bd
PN
3276 } else if (o->encoding == REDIS_ENCODING_INT) {
3277 value = (long)o->ptr;
3278 } else {
946342c1 3279 redisPanic("Unknown string encoding");
bd79a6bd
PN
3280 }
3281 }
3282
bd79a6bd
PN
3283 *target = value;
3284 return REDIS_OK;
3285}
bbe025e0 3286
bd79a6bd
PN
3287static int getDoubleFromObjectOrReply(redisClient *c, robj *o, double *target, const char *msg) {
3288 double value;
3289 if (getDoubleFromObject(o, &value) != REDIS_OK) {
3290 if (msg != NULL) {
3291 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3292 } else {
3293 addReplySds(c, sdsnew("-ERR value is not a double\r\n"));
3294 }
bbe025e0
AM
3295 return REDIS_ERR;
3296 }
3297
bd79a6bd 3298 *target = value;
bbe025e0
AM
3299 return REDIS_OK;
3300}
3301
bd79a6bd
PN
3302static int getLongLongFromObject(robj *o, long long *target) {
3303 long long value;
682c73e8 3304 char *eptr;
bbe025e0 3305
bd79a6bd
PN
3306 if (o == NULL) {
3307 value = 0;
3308 } else {
3309 redisAssert(o->type == REDIS_STRING);
3310 if (o->encoding == REDIS_ENCODING_RAW) {
3311 value = strtoll(o->ptr, &eptr, 10);
682c73e8 3312 if (eptr[0] != '\0') return REDIS_ERR;
bd79a6bd
PN
3313 } else if (o->encoding == REDIS_ENCODING_INT) {
3314 value = (long)o->ptr;
3315 } else {
946342c1 3316 redisPanic("Unknown string encoding");
bd79a6bd
PN
3317 }
3318 }
3319
bd79a6bd
PN
3320 *target = value;
3321 return REDIS_OK;
3322}
bbe025e0 3323
bd79a6bd
PN
3324static int getLongLongFromObjectOrReply(redisClient *c, robj *o, long long *target, const char *msg) {
3325 long long value;
3326 if (getLongLongFromObject(o, &value) != REDIS_OK) {
3327 if (msg != NULL) {
3328 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3329 } else {
3330 addReplySds(c, sdsnew("-ERR value is not an integer\r\n"));
3331 }
bbe025e0
AM
3332 return REDIS_ERR;
3333 }
3334
bd79a6bd 3335 *target = value;
bbe025e0
AM
3336 return REDIS_OK;
3337}
3338
bd79a6bd
PN
3339static int getLongFromObjectOrReply(redisClient *c, robj *o, long *target, const char *msg) {
3340 long long value;
bbe025e0 3341
bd79a6bd
PN
3342 if (getLongLongFromObjectOrReply(c, o, &value, msg) != REDIS_OK) return REDIS_ERR;
3343 if (value < LONG_MIN || value > LONG_MAX) {
3344 if (msg != NULL) {
3345 addReplySds(c, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg));
3346 } else {
3347 addReplySds(c, sdsnew("-ERR value is out of range\r\n"));
3348 }
bbe025e0
AM
3349 return REDIS_ERR;
3350 }
3351
bd79a6bd 3352 *target = value;
bbe025e0
AM
3353 return REDIS_OK;
3354}
3355
06233c45 3356/*============================ RDB saving/loading =========================== */
ed9b544e 3357
f78fd11b 3358static int rdbSaveType(FILE *fp, unsigned char type) {
3359 if (fwrite(&type,1,1,fp) == 0) return -1;
3360 return 0;
3361}
3362
bb32ede5 3363static int rdbSaveTime(FILE *fp, time_t t) {
3364 int32_t t32 = (int32_t) t;
3365 if (fwrite(&t32,4,1,fp) == 0) return -1;
3366 return 0;
3367}
3368
e3566d4b 3369/* check rdbLoadLen() comments for more info */
f78fd11b 3370static int rdbSaveLen(FILE *fp, uint32_t len) {
3371 unsigned char buf[2];
3372
3373 if (len < (1<<6)) {
3374 /* Save a 6 bit len */
10c43610 3375 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
f78fd11b 3376 if (fwrite(buf,1,1,fp) == 0) return -1;
3377 } else if (len < (1<<14)) {
3378 /* Save a 14 bit len */
10c43610 3379 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
f78fd11b 3380 buf[1] = len&0xFF;
17be1a4a 3381 if (fwrite(buf,2,1,fp) == 0) return -1;
f78fd11b 3382 } else {
3383 /* Save a 32 bit len */
10c43610 3384 buf[0] = (REDIS_RDB_32BITLEN<<6);
f78fd11b 3385 if (fwrite(buf,1,1,fp) == 0) return -1;
3386 len = htonl(len);
3387 if (fwrite(&len,4,1,fp) == 0) return -1;
3388 }
3389 return 0;
3390}
3391
32a66513 3392/* Encode 'value' as an integer if possible (if integer will fit the
3393 * supported range). If the function sucessful encoded the integer
3394 * then the (up to 5 bytes) encoded representation is written in the
3395 * string pointed by 'enc' and the length is returned. Otherwise
3396 * 0 is returned. */
3397static int rdbEncodeInteger(long long value, unsigned char *enc) {
e3566d4b 3398 /* Finally check if it fits in our ranges */
3399 if (value >= -(1<<7) && value <= (1<<7)-1) {
3400 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
3401 enc[1] = value&0xFF;
3402 return 2;
3403 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
3404 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
3405 enc[1] = value&0xFF;
3406 enc[2] = (value>>8)&0xFF;
3407 return 3;
3408 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
3409 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
3410 enc[1] = value&0xFF;
3411 enc[2] = (value>>8)&0xFF;
3412 enc[3] = (value>>16)&0xFF;
3413 enc[4] = (value>>24)&0xFF;
3414 return 5;
3415 } else {
3416 return 0;
3417 }
3418}
3419
32a66513 3420/* String objects in the form "2391" "-100" without any space and with a
3421 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3422 * encoded as integers to save space */
3423static int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
3424 long long value;
3425 char *endptr, buf[32];
3426
3427 /* Check if it's possible to encode this value as a number */
3428 value = strtoll(s, &endptr, 10);
3429 if (endptr[0] != '\0') return 0;
3430 ll2string(buf,32,value);
3431
3432 /* If the number converted back into a string is not identical
3433 * then it's not possible to encode the string as integer */
3434 if (strlen(buf) != len || memcmp(buf,s,len)) return 0;
3435
3436 return rdbEncodeInteger(value,enc);
3437}
3438
b1befe6a 3439static int rdbSaveLzfStringObject(FILE *fp, unsigned char *s, size_t len) {
3440 size_t comprlen, outlen;
774e3047 3441 unsigned char byte;
3442 void *out;
3443
3444 /* We require at least four bytes compression for this to be worth it */
b1befe6a 3445 if (len <= 4) return 0;
3446 outlen = len-4;
3a2694c4 3447 if ((out = zmalloc(outlen+1)) == NULL) return 0;
b1befe6a 3448 comprlen = lzf_compress(s, len, out, outlen);
774e3047 3449 if (comprlen == 0) {
88e85998 3450 zfree(out);
774e3047 3451 return 0;
3452 }
3453 /* Data compressed! Let's save it on disk */
3454 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
3455 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
3456 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
b1befe6a 3457 if (rdbSaveLen(fp,len) == -1) goto writeerr;
774e3047 3458 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
88e85998 3459 zfree(out);
774e3047 3460 return comprlen;
3461
3462writeerr:
88e85998 3463 zfree(out);
774e3047 3464 return -1;
3465}
3466
e3566d4b 3467/* Save a string objet as [len][data] on disk. If the object is a string
3468 * representation of an integer value we try to safe it in a special form */
b1befe6a 3469static int rdbSaveRawString(FILE *fp, unsigned char *s, size_t len) {
e3566d4b 3470 int enclen;
10c43610 3471
774e3047 3472 /* Try integer encoding */
e3566d4b 3473 if (len <= 11) {
3474 unsigned char buf[5];
b1befe6a 3475 if ((enclen = rdbTryIntegerEncoding((char*)s,len,buf)) > 0) {
e3566d4b 3476 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3477 return 0;
3478 }
3479 }
774e3047 3480
3481 /* Try LZF compression - under 20 bytes it's unable to compress even
88e85998 3482 * aaaaaaaaaaaaaaaaaa so skip it */
121f70cf 3483 if (server.rdbcompression && len > 20) {
774e3047 3484 int retval;
3485
b1befe6a 3486 retval = rdbSaveLzfStringObject(fp,s,len);
774e3047 3487 if (retval == -1) return -1;
3488 if (retval > 0) return 0;
3489 /* retval == 0 means data can't be compressed, save the old way */
3490 }
3491
3492 /* Store verbatim */
10c43610 3493 if (rdbSaveLen(fp,len) == -1) return -1;
b1befe6a 3494 if (len && fwrite(s,len,1,fp) == 0) return -1;
10c43610 3495 return 0;
3496}
3497
942a3961 3498/* Like rdbSaveStringObjectRaw() but handle encoded objects */
3499static int rdbSaveStringObject(FILE *fp, robj *obj) {
3500 int retval;
942a3961 3501
32a66513 3502 /* Avoid to decode the object, then encode it again, if the
3503 * object is alrady integer encoded. */
3504 if (obj->encoding == REDIS_ENCODING_INT) {
3505 long val = (long) obj->ptr;
3506 unsigned char buf[5];
3507 int enclen;
3508
3509 if ((enclen = rdbEncodeInteger(val,buf)) > 0) {
3510 if (fwrite(buf,enclen,1,fp) == 0) return -1;
3511 return 0;
3512 }
3513 /* otherwise... fall throught and continue with the usual
3514 * code path. */
3515 }
3516
f2d9f50f 3517 /* Avoid incr/decr ref count business when possible.
3518 * This plays well with copy-on-write given that we are probably
3519 * in a child process (BGSAVE). Also this makes sure key objects
3520 * of swapped objects are not incRefCount-ed (an assert does not allow
3521 * this in order to avoid bugs) */
3522 if (obj->encoding != REDIS_ENCODING_RAW) {
996cb5f7 3523 obj = getDecodedObject(obj);
b1befe6a 3524 retval = rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
996cb5f7 3525 decrRefCount(obj);
3526 } else {
b1befe6a 3527 retval = rdbSaveRawString(fp,obj->ptr,sdslen(obj->ptr));
996cb5f7 3528 }
9d65a1bb 3529 return retval;
942a3961 3530}
3531
a7866db6 3532/* Save a double value. Doubles are saved as strings prefixed by an unsigned
3533 * 8 bit integer specifing the length of the representation.
3534 * This 8 bit integer has special values in order to specify the following
3535 * conditions:
3536 * 253: not a number
3537 * 254: + inf
3538 * 255: - inf
3539 */
3540static int rdbSaveDoubleValue(FILE *fp, double val) {
3541 unsigned char buf[128];
3542 int len;
3543
3544 if (isnan(val)) {
3545 buf[0] = 253;
3546 len = 1;
3547 } else if (!isfinite(val)) {
3548 len = 1;
3549 buf[0] = (val < 0) ? 255 : 254;
3550 } else {
88e8d89f 3551#if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
fe244589 3552 /* Check if the float is in a safe range to be casted into a
3553 * long long. We are assuming that long long is 64 bit here.
3554 * Also we are assuming that there are no implementations around where
3555 * double has precision < 52 bit.
3556 *
3557 * Under this assumptions we test if a double is inside an interval
3558 * where casting to long long is safe. Then using two castings we
3559 * make sure the decimal part is zero. If all this is true we use
3560 * integer printing function that is much faster. */
fb82e75c 3561 double min = -4503599627370495; /* (2^52)-1 */
3562 double max = 4503599627370496; /* -(2^52) */
fe244589 3563 if (val > min && val < max && val == ((double)((long long)val)))
8c096b16 3564 ll2string((char*)buf+1,sizeof(buf),(long long)val);
3565 else
88e8d89f 3566#endif
8c096b16 3567 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
6c446631 3568 buf[0] = strlen((char*)buf+1);
a7866db6 3569 len = buf[0]+1;
3570 }
3571 if (fwrite(buf,len,1,fp) == 0) return -1;
3572 return 0;
3573}
3574
06233c45 3575/* Save a Redis object. */
3576static int rdbSaveObject(FILE *fp, robj *o) {
3577 if (o->type == REDIS_STRING) {
3578 /* Save a string value */
3579 if (rdbSaveStringObject(fp,o) == -1) return -1;
3580 } else if (o->type == REDIS_LIST) {
3581 /* Save a list value */
3582 list *list = o->ptr;
c7df85a4 3583 listIter li;
06233c45 3584 listNode *ln;
3585
06233c45 3586 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
c7df85a4 3587 listRewind(list,&li);
3588 while((ln = listNext(&li))) {
06233c45 3589 robj *eleobj = listNodeValue(ln);
3590
3591 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3592 }
3593 } else if (o->type == REDIS_SET) {
3594 /* Save a set value */
3595 dict *set = o->ptr;
3596 dictIterator *di = dictGetIterator(set);
3597 dictEntry *de;
3598
3599 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
3600 while((de = dictNext(di)) != NULL) {
3601 robj *eleobj = dictGetEntryKey(de);
3602
3603 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3604 }
3605 dictReleaseIterator(di);
3606 } else if (o->type == REDIS_ZSET) {
3607 /* Save a set value */
3608 zset *zs = o->ptr;
3609 dictIterator *di = dictGetIterator(zs->dict);
3610 dictEntry *de;
3611
3612 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
3613 while((de = dictNext(di)) != NULL) {
3614 robj *eleobj = dictGetEntryKey(de);
3615 double *score = dictGetEntryVal(de);
3616
3617 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
3618 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
3619 }
3620 dictReleaseIterator(di);
b1befe6a 3621 } else if (o->type == REDIS_HASH) {
3622 /* Save a hash value */
3623 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
3624 unsigned char *p = zipmapRewind(o->ptr);
3625 unsigned int count = zipmapLen(o->ptr);
3626 unsigned char *key, *val;
3627 unsigned int klen, vlen;
3628
3629 if (rdbSaveLen(fp,count) == -1) return -1;
3630 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
3631 if (rdbSaveRawString(fp,key,klen) == -1) return -1;
3632 if (rdbSaveRawString(fp,val,vlen) == -1) return -1;
3633 }
3634 } else {
3635 dictIterator *di = dictGetIterator(o->ptr);
3636 dictEntry *de;
3637
3638 if (rdbSaveLen(fp,dictSize((dict*)o->ptr)) == -1) return -1;
3639 while((de = dictNext(di)) != NULL) {
3640 robj *key = dictGetEntryKey(de);
3641 robj *val = dictGetEntryVal(de);
3642
3643 if (rdbSaveStringObject(fp,key) == -1) return -1;
3644 if (rdbSaveStringObject(fp,val) == -1) return -1;
3645 }
3646 dictReleaseIterator(di);
3647 }
06233c45 3648 } else {
f83c6cb5 3649 redisPanic("Unknown object type");
06233c45 3650 }
3651 return 0;
3652}
3653
3654/* Return the length the object will have on disk if saved with
3655 * the rdbSaveObject() function. Currently we use a trick to get
3656 * this length with very little changes to the code. In the future
3657 * we could switch to a faster solution. */
b9bc0eef 3658static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
3659 if (fp == NULL) fp = server.devnull;
06233c45 3660 rewind(fp);
3661 assert(rdbSaveObject(fp,o) != 1);
3662 return ftello(fp);
3663}
3664
06224fec 3665/* Return the number of pages required to save this object in the swap file */
b9bc0eef 3666static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
3667 off_t bytes = rdbSavedObjectLen(o,fp);
e0a62c7f 3668
06224fec 3669 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
3670}
3671
ed9b544e 3672/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
f78fd11b 3673static int rdbSave(char *filename) {
ed9b544e 3674 dictIterator *di = NULL;
3675 dictEntry *de;
ed9b544e 3676 FILE *fp;
3677 char tmpfile[256];
3678 int j;
bb32ede5 3679 time_t now = time(NULL);
ed9b544e 3680
2316bb3b 3681 /* Wait for I/O therads to terminate, just in case this is a
3682 * foreground-saving, to avoid seeking the swap file descriptor at the
3683 * same time. */
3684 if (server.vm_enabled)
3685 waitEmptyIOJobsQueue();
3686
a3b21203 3687 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
ed9b544e 3688 fp = fopen(tmpfile,"w");
3689 if (!fp) {
3690 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
3691 return REDIS_ERR;
3692 }
f78fd11b 3693 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
ed9b544e 3694 for (j = 0; j < server.dbnum; j++) {
bb32ede5 3695 redisDb *db = server.db+j;
3696 dict *d = db->dict;
3305306f 3697 if (dictSize(d) == 0) continue;
ed9b544e 3698 di = dictGetIterator(d);
3699 if (!di) {
3700 fclose(fp);
3701 return REDIS_ERR;
3702 }
3703
3704 /* Write the SELECT DB opcode */
f78fd11b 3705 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
3706 if (rdbSaveLen(fp,j) == -1) goto werr;
ed9b544e 3707
3708 /* Iterate this DB writing every entry */
3709 while((de = dictNext(di)) != NULL) {
3710 robj *key = dictGetEntryKey(de);
3711 robj *o = dictGetEntryVal(de);
bb32ede5 3712 time_t expiretime = getExpire(db,key);
3713
3714 /* Save the expire time */
3715 if (expiretime != -1) {
3716 /* If this key is already expired skip it */
3717 if (expiretime < now) continue;
3718 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
3719 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
3720 }
7e69548d 3721 /* Save the key and associated value. This requires special
3722 * handling if the value is swapped out. */
996cb5f7 3723 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
3724 key->storage == REDIS_VM_SWAPPING) {
7e69548d 3725 /* Save type, key, value */
3726 if (rdbSaveType(fp,o->type) == -1) goto werr;
3727 if (rdbSaveStringObject(fp,key) == -1) goto werr;
3728 if (rdbSaveObject(fp,o) == -1) goto werr;
3729 } else {
996cb5f7 3730 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
b9bc0eef 3731 robj *po;
7e69548d 3732 /* Get a preview of the object in memory */
3733 po = vmPreviewObject(key);
7e69548d 3734 /* Save type, key, value */
3735 if (rdbSaveType(fp,key->vtype) == -1) goto werr;
b9bc0eef 3736 if (rdbSaveStringObject(fp,key) == -1) goto werr;
7e69548d 3737 if (rdbSaveObject(fp,po) == -1) goto werr;
3738 /* Remove the loaded object from memory */
3739 decrRefCount(po);
7e69548d 3740 }
ed9b544e 3741 }
3742 dictReleaseIterator(di);
3743 }
3744 /* EOF opcode */
f78fd11b 3745 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
3746
3747 /* Make sure data will not remain on the OS's output buffers */
ed9b544e 3748 fflush(fp);
3749 fsync(fileno(fp));
3750 fclose(fp);
e0a62c7f 3751
ed9b544e 3752 /* Use RENAME to make sure the DB file is changed atomically only
3753 * if the generate DB file is ok. */
3754 if (rename(tmpfile,filename) == -1) {
325d1eb4 3755 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
ed9b544e 3756 unlink(tmpfile);
3757 return REDIS_ERR;
3758 }
3759 redisLog(REDIS_NOTICE,"DB saved on disk");
3760 server.dirty = 0;
3761 server.lastsave = time(NULL);
3762 return REDIS_OK;
3763
3764werr:
3765 fclose(fp);
3766 unlink(tmpfile);
3767 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
3768 if (di) dictReleaseIterator(di);
3769 return REDIS_ERR;
3770}
3771
f78fd11b 3772static int rdbSaveBackground(char *filename) {
ed9b544e 3773 pid_t childpid;
3774
9d65a1bb 3775 if (server.bgsavechildpid != -1) return REDIS_ERR;
054e426d 3776 if (server.vm_enabled) waitEmptyIOJobsQueue();
ed9b544e 3777 if ((childpid = fork()) == 0) {
3778 /* Child */
054e426d 3779 if (server.vm_enabled) vmReopenSwapFile();
ed9b544e 3780 close(server.fd);
f78fd11b 3781 if (rdbSave(filename) == REDIS_OK) {
478c2c6f 3782 _exit(0);
ed9b544e 3783 } else {
478c2c6f 3784 _exit(1);
ed9b544e 3785 }
3786 } else {
3787 /* Parent */
5a7c647e 3788 if (childpid == -1) {
3789 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
3790 strerror(errno));
3791 return REDIS_ERR;
3792 }
ed9b544e 3793 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
9f3c422c 3794 server.bgsavechildpid = childpid;
884d4b39 3795 updateDictResizePolicy();
ed9b544e 3796 return REDIS_OK;
3797 }
3798 return REDIS_OK; /* unreached */
3799}
3800
a3b21203 3801static void rdbRemoveTempFile(pid_t childpid) {
3802 char tmpfile[256];
3803
3804 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
3805 unlink(tmpfile);
3806}
3807
f78fd11b 3808static int rdbLoadType(FILE *fp) {
3809 unsigned char type;
7b45bfb2 3810 if (fread(&type,1,1,fp) == 0) return -1;
3811 return type;
3812}
3813
bb32ede5 3814static time_t rdbLoadTime(FILE *fp) {
3815 int32_t t32;
3816 if (fread(&t32,4,1,fp) == 0) return -1;
3817 return (time_t) t32;
3818}
3819
e3566d4b 3820/* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3821 * of this file for a description of how this are stored on disk.
3822 *
3823 * isencoded is set to 1 if the readed length is not actually a length but
3824 * an "encoding type", check the above comments for more info */
c78a8ccc 3825static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
f78fd11b 3826 unsigned char buf[2];
3827 uint32_t len;
c78a8ccc 3828 int type;
f78fd11b 3829
e3566d4b 3830 if (isencoded) *isencoded = 0;
c78a8ccc 3831 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
3832 type = (buf[0]&0xC0)>>6;
3833 if (type == REDIS_RDB_6BITLEN) {
3834 /* Read a 6 bit len */
3835 return buf[0]&0x3F;
3836 } else if (type == REDIS_RDB_ENCVAL) {
3837 /* Read a 6 bit len encoding type */
3838 if (isencoded) *isencoded = 1;
3839 return buf[0]&0x3F;
3840 } else if (type == REDIS_RDB_14BITLEN) {
3841 /* Read a 14 bit len */
3842 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
3843 return ((buf[0]&0x3F)<<8)|buf[1];
3844 } else {
3845 /* Read a 32 bit len */
f78fd11b 3846 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
3847 return ntohl(len);
f78fd11b 3848 }
f78fd11b 3849}
3850
ad30aa60 3851/* Load an integer-encoded object from file 'fp', with the specified
3852 * encoding type 'enctype'. If encode is true the function may return
3853 * an integer-encoded object as reply, otherwise the returned object
3854 * will always be encoded as a raw string. */
3855static robj *rdbLoadIntegerObject(FILE *fp, int enctype, int encode) {
e3566d4b 3856 unsigned char enc[4];
3857 long long val;
3858
3859 if (enctype == REDIS_RDB_ENC_INT8) {
3860 if (fread(enc,1,1,fp) == 0) return NULL;
3861 val = (signed char)enc[0];
3862 } else if (enctype == REDIS_RDB_ENC_INT16) {
3863 uint16_t v;
3864 if (fread(enc,2,1,fp) == 0) return NULL;
3865 v = enc[0]|(enc[1]<<8);
3866 val = (int16_t)v;
3867 } else if (enctype == REDIS_RDB_ENC_INT32) {
3868 uint32_t v;
3869 if (fread(enc,4,1,fp) == 0) return NULL;
3870 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
3871 val = (int32_t)v;
3872 } else {
3873 val = 0; /* anti-warning */
f83c6cb5 3874 redisPanic("Unknown RDB integer encoding type");
e3566d4b 3875 }
ad30aa60 3876 if (encode)
3877 return createStringObjectFromLongLong(val);
3878 else
3879 return createObject(REDIS_STRING,sdsfromlonglong(val));
e3566d4b 3880}
3881
c78a8ccc 3882static robj *rdbLoadLzfStringObject(FILE*fp) {
88e85998 3883 unsigned int len, clen;
3884 unsigned char *c = NULL;
3885 sds val = NULL;
3886
c78a8ccc 3887 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3888 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
88e85998 3889 if ((c = zmalloc(clen)) == NULL) goto err;
3890 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
3891 if (fread(c,clen,1,fp) == 0) goto err;
3892 if (lzf_decompress(c,clen,val,len) == 0) goto err;
5109cdff 3893 zfree(c);
88e85998 3894 return createObject(REDIS_STRING,val);
3895err:
3896 zfree(c);
3897 sdsfree(val);
3898 return NULL;
3899}
3900
ad30aa60 3901static robj *rdbGenericLoadStringObject(FILE*fp, int encode) {
e3566d4b 3902 int isencoded;
3903 uint32_t len;
f78fd11b 3904 sds val;
3905
c78a8ccc 3906 len = rdbLoadLen(fp,&isencoded);
e3566d4b 3907 if (isencoded) {
3908 switch(len) {
3909 case REDIS_RDB_ENC_INT8:
3910 case REDIS_RDB_ENC_INT16:
3911 case REDIS_RDB_ENC_INT32:
ad30aa60 3912 return rdbLoadIntegerObject(fp,len,encode);
88e85998 3913 case REDIS_RDB_ENC_LZF:
bdcb92f2 3914 return rdbLoadLzfStringObject(fp);
e3566d4b 3915 default:
f83c6cb5 3916 redisPanic("Unknown RDB encoding type");
e3566d4b 3917 }
3918 }
3919
f78fd11b 3920 if (len == REDIS_RDB_LENERR) return NULL;
3921 val = sdsnewlen(NULL,len);
3922 if (len && fread(val,len,1,fp) == 0) {
3923 sdsfree(val);
3924 return NULL;
3925 }
bdcb92f2 3926 return createObject(REDIS_STRING,val);
f78fd11b 3927}
3928
ad30aa60 3929static robj *rdbLoadStringObject(FILE *fp) {
3930 return rdbGenericLoadStringObject(fp,0);
3931}
3932
3933static robj *rdbLoadEncodedStringObject(FILE *fp) {
3934 return rdbGenericLoadStringObject(fp,1);
3935}
3936
a7866db6 3937/* For information about double serialization check rdbSaveDoubleValue() */
3938static int rdbLoadDoubleValue(FILE *fp, double *val) {
3939 char buf[128];
3940 unsigned char len;
3941
3942 if (fread(&len,1,1,fp) == 0) return -1;
3943 switch(len) {
3944 case 255: *val = R_NegInf; return 0;
3945 case 254: *val = R_PosInf; return 0;
3946 case 253: *val = R_Nan; return 0;
3947 default:
3948 if (fread(buf,len,1,fp) == 0) return -1;
231d758e 3949 buf[len] = '\0';
a7866db6 3950 sscanf(buf, "%lg", val);
3951 return 0;
3952 }
3953}
3954
c78a8ccc 3955/* Load a Redis object of the specified type from the specified file.
3956 * On success a newly allocated object is returned, otherwise NULL. */
3957static robj *rdbLoadObject(int type, FILE *fp) {
3958 robj *o;
3959
bcd11906 3960 redisLog(REDIS_DEBUG,"LOADING OBJECT %d (at %d)\n",type,ftell(fp));
c78a8ccc 3961 if (type == REDIS_STRING) {
3962 /* Read string value */
ad30aa60 3963 if ((o = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 3964 o = tryObjectEncoding(o);
c78a8ccc 3965 } else if (type == REDIS_LIST || type == REDIS_SET) {
3966 /* Read list/set value */
3967 uint32_t listlen;
3968
3969 if ((listlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3970 o = (type == REDIS_LIST) ? createListObject() : createSetObject();
3c68de9b 3971 /* It's faster to expand the dict to the right size asap in order
3972 * to avoid rehashing */
3973 if (type == REDIS_SET && listlen > DICT_HT_INITIAL_SIZE)
3974 dictExpand(o->ptr,listlen);
c78a8ccc 3975 /* Load every single element of the list/set */
3976 while(listlen--) {
3977 robj *ele;
3978
ad30aa60 3979 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 3980 ele = tryObjectEncoding(ele);
c78a8ccc 3981 if (type == REDIS_LIST) {
3982 listAddNodeTail((list*)o->ptr,ele);
3983 } else {
3984 dictAdd((dict*)o->ptr,ele,NULL);
3985 }
3986 }
3987 } else if (type == REDIS_ZSET) {
3988 /* Read list/set value */
ada386b2 3989 size_t zsetlen;
c78a8ccc 3990 zset *zs;
3991
3992 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3993 o = createZsetObject();
3994 zs = o->ptr;
3995 /* Load every single element of the list/set */
3996 while(zsetlen--) {
3997 robj *ele;
3998 double *score = zmalloc(sizeof(double));
3999
ad30aa60 4000 if ((ele = rdbLoadEncodedStringObject(fp)) == NULL) return NULL;
05df7621 4001 ele = tryObjectEncoding(ele);
c78a8ccc 4002 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
4003 dictAdd(zs->dict,ele,score);
4004 zslInsert(zs->zsl,*score,ele);
4005 incrRefCount(ele); /* added to skiplist */
4006 }
ada386b2 4007 } else if (type == REDIS_HASH) {
4008 size_t hashlen;
4009
4010 if ((hashlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
4011 o = createHashObject();
4012 /* Too many entries? Use an hash table. */
4013 if (hashlen > server.hash_max_zipmap_entries)
4014 convertToRealHash(o);
4015 /* Load every key/value, then set it into the zipmap or hash
4016 * table, as needed. */
4017 while(hashlen--) {
4018 robj *key, *val;
4019
4020 if ((key = rdbLoadStringObject(fp)) == NULL) return NULL;
4021 if ((val = rdbLoadStringObject(fp)) == NULL) return NULL;
4022 /* If we are using a zipmap and there are too big values
4023 * the object is converted to real hash table encoding. */
4024 if (o->encoding != REDIS_ENCODING_HT &&
4025 (sdslen(key->ptr) > server.hash_max_zipmap_value ||
4026 sdslen(val->ptr) > server.hash_max_zipmap_value))
4027 {
4028 convertToRealHash(o);
4029 }
4030
4031 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
4032 unsigned char *zm = o->ptr;
4033
4034 zm = zipmapSet(zm,key->ptr,sdslen(key->ptr),
4035 val->ptr,sdslen(val->ptr),NULL);
4036 o->ptr = zm;
4037 decrRefCount(key);
4038 decrRefCount(val);
4039 } else {
05df7621 4040 key = tryObjectEncoding(key);
4041 val = tryObjectEncoding(val);
ada386b2 4042 dictAdd((dict*)o->ptr,key,val);
ada386b2 4043 }
4044 }
c78a8ccc 4045 } else {
f83c6cb5 4046 redisPanic("Unknown object type");
c78a8ccc 4047 }
4048 return o;
4049}
4050
f78fd11b 4051static int rdbLoad(char *filename) {
ed9b544e 4052 FILE *fp;
f78fd11b 4053 uint32_t dbid;
bb32ede5 4054 int type, retval, rdbver;
585af7e2 4055 int swap_all_values = 0;
3305306f 4056 dict *d = server.db[0].dict;
bb32ede5 4057 redisDb *db = server.db+0;
f78fd11b 4058 char buf[1024];
242a64f3 4059 time_t expiretime, now = time(NULL);
b492cf00 4060 long long loadedkeys = 0;
bb32ede5 4061
ed9b544e 4062 fp = fopen(filename,"r");
4063 if (!fp) return REDIS_ERR;
4064 if (fread(buf,9,1,fp) == 0) goto eoferr;
f78fd11b 4065 buf[9] = '\0';
4066 if (memcmp(buf,"REDIS",5) != 0) {
ed9b544e 4067 fclose(fp);
4068 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
4069 return REDIS_ERR;
4070 }
f78fd11b 4071 rdbver = atoi(buf+5);
c78a8ccc 4072 if (rdbver != 1) {
f78fd11b 4073 fclose(fp);
4074 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
4075 return REDIS_ERR;
4076 }
ed9b544e 4077 while(1) {
585af7e2 4078 robj *key, *val;
ed9b544e 4079
585af7e2 4080 expiretime = -1;
ed9b544e 4081 /* Read type. */
f78fd11b 4082 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
bb32ede5 4083 if (type == REDIS_EXPIRETIME) {
4084 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
4085 /* We read the time so we need to read the object type again */
4086 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
4087 }
ed9b544e 4088 if (type == REDIS_EOF) break;
4089 /* Handle SELECT DB opcode as a special case */
4090 if (type == REDIS_SELECTDB) {
c78a8ccc 4091 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
e3566d4b 4092 goto eoferr;
ed9b544e 4093 if (dbid >= (unsigned)server.dbnum) {
f78fd11b 4094 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
ed9b544e 4095 exit(1);
4096 }
bb32ede5 4097 db = server.db+dbid;
4098 d = db->dict;
ed9b544e 4099 continue;
4100 }
4101 /* Read key */
585af7e2 4102 if ((key = rdbLoadStringObject(fp)) == NULL) goto eoferr;
c78a8ccc 4103 /* Read value */
585af7e2 4104 if ((val = rdbLoadObject(type,fp)) == NULL) goto eoferr;
89e689c5 4105 /* Check if the key already expired */
4106 if (expiretime != -1 && expiretime < now) {
4107 decrRefCount(key);
4108 decrRefCount(val);
4109 continue;
4110 }
ed9b544e 4111 /* Add the new object in the hash table */
585af7e2 4112 retval = dictAdd(d,key,val);
ed9b544e 4113 if (retval == DICT_ERR) {
585af7e2 4114 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key->ptr);
ed9b544e 4115 exit(1);
4116 }
242a64f3 4117 loadedkeys++;
bb32ede5 4118 /* Set the expire time if needed */
89e689c5 4119 if (expiretime != -1) setExpire(db,key,expiretime);
242a64f3 4120
b492cf00 4121 /* Handle swapping while loading big datasets when VM is on */
242a64f3 4122
4123 /* If we detecter we are hopeless about fitting something in memory
4124 * we just swap every new key on disk. Directly...
4125 * Note that's important to check for this condition before resorting
4126 * to random sampling, otherwise we may try to swap already
4127 * swapped keys. */
585af7e2 4128 if (swap_all_values) {
4129 dictEntry *de = dictFind(d,key);
242a64f3 4130
4131 /* de may be NULL since the key already expired */
4132 if (de) {
585af7e2 4133 key = dictGetEntryKey(de);
4134 val = dictGetEntryVal(de);
242a64f3 4135
585af7e2 4136 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
242a64f3 4137 dictGetEntryVal(de) = NULL;
4138 }
4139 }
4140 continue;
4141 }
4142
4143 /* If we have still some hope of having some value fitting memory
4144 * then we try random sampling. */
585af7e2 4145 if (!swap_all_values && server.vm_enabled && (loadedkeys % 5000) == 0) {
b492cf00 4146 while (zmalloc_used_memory() > server.vm_max_memory) {
a69a0c9c 4147 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
b492cf00 4148 }
242a64f3 4149 if (zmalloc_used_memory() > server.vm_max_memory)
585af7e2 4150 swap_all_values = 1; /* We are already using too much mem */
b492cf00 4151 }
ed9b544e 4152 }
4153 fclose(fp);
4154 return REDIS_OK;
4155
4156eoferr: /* unexpected end of file is handled here with a fatal exit */
f80dff62 4157 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
ed9b544e 4158 exit(1);
4159 return REDIS_ERR; /* Just to avoid warning */
4160}
4161
b58ba105 4162/*================================== Shutdown =============================== */
fab43727 4163static int prepareForShutdown() {
b58ba105
AM
4164 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
4165 /* Kill the saving child if there is a background saving in progress.
4166 We want to avoid race conditions, for instance our saving child may
4167 overwrite the synchronous saving did by SHUTDOWN. */
4168 if (server.bgsavechildpid != -1) {
4169 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
4170 kill(server.bgsavechildpid,SIGKILL);
4171 rdbRemoveTempFile(server.bgsavechildpid);
4172 }
4173 if (server.appendonly) {
4174 /* Append only file: fsync() the AOF and exit */
4175 fsync(server.appendfd);
4176 if (server.vm_enabled) unlink(server.vm_swap_file);
b58ba105
AM
4177 } else {
4178 /* Snapshotting. Perform a SYNC SAVE and exit */
4179 if (rdbSave(server.dbfilename) == REDIS_OK) {
4180 if (server.daemonize)
4181 unlink(server.pidfile);
4182 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
b58ba105
AM
4183 } else {
4184 /* Ooops.. error saving! The best we can do is to continue
4185 * operating. Note that if there was a background saving process,
4186 * in the next cron() Redis will be notified that the background
4187 * saving aborted, handling special stuff like slaves pending for
4188 * synchronization... */
4189 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
fab43727 4190 return REDIS_ERR;
b58ba105
AM
4191 }
4192 }
8513a757 4193 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
fab43727 4194 return REDIS_OK;
b58ba105
AM
4195}
4196
ed9b544e 4197/*================================== Commands =============================== */
4198
abcb223e 4199static void authCommand(redisClient *c) {
2e77c2ee 4200 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
abcb223e
BH
4201 c->authenticated = 1;
4202 addReply(c,shared.ok);
4203 } else {
4204 c->authenticated = 0;
fa4c0aba 4205 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
abcb223e
BH
4206 }
4207}
4208
ed9b544e 4209static void pingCommand(redisClient *c) {
4210 addReply(c,shared.pong);
4211}
4212
4213static void echoCommand(redisClient *c) {
dd88747b 4214 addReplyBulk(c,c->argv[1]);
ed9b544e 4215}
4216
4217/*=================================== Strings =============================== */
4218
526d00a5 4219static void setGenericCommand(redisClient *c, int nx, robj *key, robj *val, robj *expire) {
ed9b544e 4220 int retval;
10ce1276 4221 long seconds = 0; /* initialized to avoid an harmness warning */
ed9b544e 4222
526d00a5 4223 if (expire) {
4224 if (getLongFromObjectOrReply(c, expire, &seconds, NULL) != REDIS_OK)
4225 return;
4226 if (seconds <= 0) {
4227 addReplySds(c,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4228 return;
4229 }
4230 }
4231
4232 if (nx) deleteIfVolatile(c->db,key);
4233 retval = dictAdd(c->db->dict,key,val);
ed9b544e 4234 if (retval == DICT_ERR) {
4235 if (!nx) {
1b03836c 4236 /* If the key is about a swapped value, we want a new key object
4237 * to overwrite the old. So we delete the old key in the database.
4238 * This will also make sure that swap pages about the old object
4239 * will be marked as free. */
526d00a5 4240 if (server.vm_enabled && deleteIfSwapped(c->db,key))
4241 incrRefCount(key);
4242 dictReplace(c->db->dict,key,val);
4243 incrRefCount(val);
ed9b544e 4244 } else {
c937aa89 4245 addReply(c,shared.czero);
ed9b544e 4246 return;
4247 }
4248 } else {
526d00a5 4249 incrRefCount(key);
4250 incrRefCount(val);
ed9b544e 4251 }
4252 server.dirty++;
526d00a5 4253 removeExpire(c->db,key);
4254 if (expire) setExpire(c->db,key,time(NULL)+seconds);
c937aa89 4255 addReply(c, nx ? shared.cone : shared.ok);
ed9b544e 4256}
4257
4258static void setCommand(redisClient *c) {
526d00a5 4259 setGenericCommand(c,0,c->argv[1],c->argv[2],NULL);
ed9b544e 4260}
4261
4262static void setnxCommand(redisClient *c) {
526d00a5 4263 setGenericCommand(c,1,c->argv[1],c->argv[2],NULL);
4264}
4265
4266static void setexCommand(redisClient *c) {
4267 setGenericCommand(c,0,c->argv[1],c->argv[3],c->argv[2]);
ed9b544e 4268}
4269
322fc7d8 4270static int getGenericCommand(redisClient *c) {
dd88747b 4271 robj *o;
e0a62c7f 4272
dd88747b 4273 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL)
322fc7d8 4274 return REDIS_OK;
dd88747b 4275
4276 if (o->type != REDIS_STRING) {
4277 addReply(c,shared.wrongtypeerr);
4278 return REDIS_ERR;
ed9b544e 4279 } else {
dd88747b 4280 addReplyBulk(c,o);
4281 return REDIS_OK;
ed9b544e 4282 }
4283}
4284
322fc7d8 4285static void getCommand(redisClient *c) {
4286 getGenericCommand(c);
4287}
4288
f6b141c5 4289static void getsetCommand(redisClient *c) {
322fc7d8 4290 if (getGenericCommand(c) == REDIS_ERR) return;
a431eb74 4291 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
4292 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
4293 } else {
4294 incrRefCount(c->argv[1]);
4295 }
4296 incrRefCount(c->argv[2]);
4297 server.dirty++;
4298 removeExpire(c->db,c->argv[1]);
4299}
4300
70003d28 4301static void mgetCommand(redisClient *c) {
70003d28 4302 int j;
e0a62c7f 4303
c937aa89 4304 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
70003d28 4305 for (j = 1; j < c->argc; j++) {
3305306f 4306 robj *o = lookupKeyRead(c->db,c->argv[j]);
4307 if (o == NULL) {
c937aa89 4308 addReply(c,shared.nullbulk);
70003d28 4309 } else {
70003d28 4310 if (o->type != REDIS_STRING) {
c937aa89 4311 addReply(c,shared.nullbulk);
70003d28 4312 } else {
dd88747b 4313 addReplyBulk(c,o);
70003d28 4314 }
4315 }
4316 }
4317}
4318
6c446631 4319static void msetGenericCommand(redisClient *c, int nx) {
906573e7 4320 int j, busykeys = 0;
6c446631 4321
4322 if ((c->argc % 2) == 0) {
454d4e43 4323 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
6c446631 4324 return;
4325 }
4326 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4327 * set nothing at all if at least one already key exists. */
4328 if (nx) {
4329 for (j = 1; j < c->argc; j += 2) {
906573e7 4330 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
4331 busykeys++;
6c446631 4332 }
4333 }
4334 }
906573e7 4335 if (busykeys) {
4336 addReply(c, shared.czero);
4337 return;
4338 }
6c446631 4339
4340 for (j = 1; j < c->argc; j += 2) {
4341 int retval;
4342
05df7621 4343 c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
6c446631 4344 retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
4345 if (retval == DICT_ERR) {
4346 dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
4347 incrRefCount(c->argv[j+1]);
4348 } else {
4349 incrRefCount(c->argv[j]);
4350 incrRefCount(c->argv[j+1]);
4351 }
4352 removeExpire(c->db,c->argv[j]);
4353 }
4354 server.dirty += (c->argc-1)/2;
4355 addReply(c, nx ? shared.cone : shared.ok);
4356}
4357
4358static void msetCommand(redisClient *c) {
4359 msetGenericCommand(c,0);
4360}
4361
4362static void msetnxCommand(redisClient *c) {
4363 msetGenericCommand(c,1);
4364}
4365
d68ed120 4366static void incrDecrCommand(redisClient *c, long long incr) {
ed9b544e 4367 long long value;
4368 int retval;
4369 robj *o;
e0a62c7f 4370
3305306f 4371 o = lookupKeyWrite(c->db,c->argv[1]);
6485f293
PN
4372 if (o != NULL && checkType(c,o,REDIS_STRING)) return;
4373 if (getLongLongFromObjectOrReply(c,o,&value,NULL) != REDIS_OK) return;
ed9b544e 4374
4375 value += incr;
d6f4c262 4376 o = createStringObjectFromLongLong(value);
3305306f 4377 retval = dictAdd(c->db->dict,c->argv[1],o);
ed9b544e 4378 if (retval == DICT_ERR) {
3305306f 4379 dictReplace(c->db->dict,c->argv[1],o);
4380 removeExpire(c->db,c->argv[1]);
ed9b544e 4381 } else {
4382 incrRefCount(c->argv[1]);
4383 }
4384 server.dirty++;
c937aa89 4385 addReply(c,shared.colon);
ed9b544e 4386 addReply(c,o);
4387 addReply(c,shared.crlf);
4388}
4389
4390static void incrCommand(redisClient *c) {
a4d1ba9a 4391 incrDecrCommand(c,1);
ed9b544e 4392}
4393
4394static void decrCommand(redisClient *c) {
a4d1ba9a 4395 incrDecrCommand(c,-1);
ed9b544e 4396}
4397
4398static void incrbyCommand(redisClient *c) {
bbe025e0
AM
4399 long long incr;
4400
bd79a6bd 4401 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
a4d1ba9a 4402 incrDecrCommand(c,incr);
ed9b544e 4403}
4404
4405static void decrbyCommand(redisClient *c) {
bbe025e0
AM
4406 long long incr;
4407
bd79a6bd 4408 if (getLongLongFromObjectOrReply(c, c->argv[2], &incr, NULL) != REDIS_OK) return;
a4d1ba9a 4409 incrDecrCommand(c,-incr);
ed9b544e 4410}
4411
4b00bebd 4412static void appendCommand(redisClient *c) {
4413 int retval;
4414 size_t totlen;
4415 robj *o;
4416
4417 o = lookupKeyWrite(c->db,c->argv[1]);
4418 if (o == NULL) {
4419 /* Create the key */
4420 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
4421 incrRefCount(c->argv[1]);
4422 incrRefCount(c->argv[2]);
4423 totlen = stringObjectLen(c->argv[2]);
4424 } else {
4425 dictEntry *de;
e0a62c7f 4426
4b00bebd 4427 de = dictFind(c->db->dict,c->argv[1]);
4428 assert(de != NULL);
4429
4430 o = dictGetEntryVal(de);
4431 if (o->type != REDIS_STRING) {
4432 addReply(c,shared.wrongtypeerr);
4433 return;
4434 }
4435 /* If the object is specially encoded or shared we have to make
4436 * a copy */
4437 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
4438 robj *decoded = getDecodedObject(o);
4439
4440 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
4441 decrRefCount(decoded);
4442 dictReplace(c->db->dict,c->argv[1],o);
4443 }
4444 /* APPEND! */
4445 if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
4446 o->ptr = sdscatlen(o->ptr,
4447 c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
4448 } else {
4449 o->ptr = sdscatprintf(o->ptr, "%ld",
4450 (unsigned long) c->argv[2]->ptr);
4451 }
4452 totlen = sdslen(o->ptr);
4453 }
4454 server.dirty++;
4455 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
4456}
4457
39191553 4458static void substrCommand(redisClient *c) {
4459 robj *o;
4460 long start = atoi(c->argv[2]->ptr);
4461 long end = atoi(c->argv[3]->ptr);
dd88747b 4462 size_t rangelen, strlen;
4463 sds range;
39191553 4464
dd88747b 4465 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4466 checkType(c,o,REDIS_STRING)) return;
39191553 4467
dd88747b 4468 o = getDecodedObject(o);
4469 strlen = sdslen(o->ptr);
8fe7fad7 4470
dd88747b 4471 /* convert negative indexes */
4472 if (start < 0) start = strlen+start;
4473 if (end < 0) end = strlen+end;
4474 if (start < 0) start = 0;
4475 if (end < 0) end = 0;
39191553 4476
dd88747b 4477 /* indexes sanity checks */
4478 if (start > end || (size_t)start >= strlen) {
4479 /* Out of range start or start > end result in null reply */
4480 addReply(c,shared.nullbulk);
4481 decrRefCount(o);
4482 return;
39191553 4483 }
dd88747b 4484 if ((size_t)end >= strlen) end = strlen-1;
4485 rangelen = (end-start)+1;
4486
4487 /* Return the result */
4488 addReplySds(c,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen));
4489 range = sdsnewlen((char*)o->ptr+start,rangelen);
4490 addReplySds(c,range);
4491 addReply(c,shared.crlf);
4492 decrRefCount(o);
39191553 4493}
4494
ed9b544e 4495/* ========================= Type agnostic commands ========================= */
4496
4497static void delCommand(redisClient *c) {
5109cdff 4498 int deleted = 0, j;
4499
4500 for (j = 1; j < c->argc; j++) {
4501 if (deleteKey(c->db,c->argv[j])) {
4502 server.dirty++;
4503 deleted++;
4504 }
4505 }
482b672d 4506 addReplyLongLong(c,deleted);
ed9b544e 4507}
4508
4509static void existsCommand(redisClient *c) {
f4f06efc
PN
4510 expireIfNeeded(c->db,c->argv[1]);
4511 if (dictFind(c->db->dict,c->argv[1])) {
4512 addReply(c, shared.cone);
4513 } else {
4514 addReply(c, shared.czero);
4515 }
ed9b544e 4516}
4517
4518static void selectCommand(redisClient *c) {
4519 int id = atoi(c->argv[1]->ptr);
e0a62c7f 4520
ed9b544e 4521 if (selectDb(c,id) == REDIS_ERR) {
774e3047 4522 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
ed9b544e 4523 } else {
4524 addReply(c,shared.ok);
4525 }
4526}
4527
4528static void randomkeyCommand(redisClient *c) {
4529 dictEntry *de;
dc4be23e 4530 robj *key;
e0a62c7f 4531
3305306f 4532 while(1) {
4533 de = dictGetRandomKey(c->db->dict);
ce7bef07 4534 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
3305306f 4535 }
2b619329 4536
ed9b544e 4537 if (de == NULL) {
dc4be23e 4538 addReply(c,shared.nullbulk);
4539 return;
4540 }
4541
4542 key = dictGetEntryKey(de);
4543 if (server.vm_enabled) {
4544 key = dupStringObject(key);
4545 addReplyBulk(c,key);
4546 decrRefCount(key);
ed9b544e 4547 } else {
dc4be23e 4548 addReplyBulk(c,key);
ed9b544e 4549 }
4550}
4551
4552static void keysCommand(redisClient *c) {
4553 dictIterator *di;
4554 dictEntry *de;
4555 sds pattern = c->argv[1]->ptr;
4556 int plen = sdslen(pattern);
a3f9eec2 4557 unsigned long numkeys = 0;
ed9b544e 4558 robj *lenobj = createObject(REDIS_STRING,NULL);
4559
3305306f 4560 di = dictGetIterator(c->db->dict);
ed9b544e 4561 addReply(c,lenobj);
4562 decrRefCount(lenobj);
4563 while((de = dictNext(di)) != NULL) {
4564 robj *keyobj = dictGetEntryKey(de);
3305306f 4565
ed9b544e 4566 sds key = keyobj->ptr;
4567 if ((pattern[0] == '*' && pattern[1] == '\0') ||
4568 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
3305306f 4569 if (expireIfNeeded(c->db,keyobj) == 0) {
dd88747b 4570 addReplyBulk(c,keyobj);
3305306f 4571 numkeys++;
3305306f 4572 }
ed9b544e 4573 }
4574 }
4575 dictReleaseIterator(di);
a3f9eec2 4576 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
ed9b544e 4577}
4578
4579static void dbsizeCommand(redisClient *c) {
4580 addReplySds(c,
3305306f 4581 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
ed9b544e 4582}
4583
4584static void lastsaveCommand(redisClient *c) {
4585 addReplySds(c,
c937aa89 4586 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
ed9b544e 4587}
4588
4589static void typeCommand(redisClient *c) {
3305306f 4590 robj *o;
ed9b544e 4591 char *type;
3305306f 4592
4593 o = lookupKeyRead(c->db,c->argv[1]);
4594 if (o == NULL) {
c937aa89 4595 type = "+none";
ed9b544e 4596 } else {
ed9b544e 4597 switch(o->type) {
c937aa89 4598 case REDIS_STRING: type = "+string"; break;
4599 case REDIS_LIST: type = "+list"; break;
4600 case REDIS_SET: type = "+set"; break;
412a8bce 4601 case REDIS_ZSET: type = "+zset"; break;
ada386b2 4602 case REDIS_HASH: type = "+hash"; break;
4603 default: type = "+unknown"; break;
ed9b544e 4604 }
4605 }
4606 addReplySds(c,sdsnew(type));
4607 addReply(c,shared.crlf);
4608}
4609
4610static void saveCommand(redisClient *c) {
9d65a1bb 4611 if (server.bgsavechildpid != -1) {
05557f6d 4612 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
4613 return;
4614 }
f78fd11b 4615 if (rdbSave(server.dbfilename) == REDIS_OK) {
ed9b544e 4616 addReply(c,shared.ok);
4617 } else {
4618 addReply(c,shared.err);
4619 }
4620}
4621
4622static void bgsaveCommand(redisClient *c) {
9d65a1bb 4623 if (server.bgsavechildpid != -1) {
ed9b544e 4624 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
4625 return;
4626 }
f78fd11b 4627 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
49b99ab4 4628 char *status = "+Background saving started\r\n";
4629 addReplySds(c,sdsnew(status));
ed9b544e 4630 } else {
4631 addReply(c,shared.err);
4632 }
4633}
4634
4635static void shutdownCommand(redisClient *c) {
fab43727 4636 if (prepareForShutdown() == REDIS_OK)
4637 exit(0);
4638 addReplySds(c, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
ed9b544e 4639}
4640
4641static void renameGenericCommand(redisClient *c, int nx) {
ed9b544e 4642 robj *o;
4643
4644 /* To use the same key as src and dst is probably an error */
4645 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
c937aa89 4646 addReply(c,shared.sameobjecterr);
ed9b544e 4647 return;
4648 }
4649
dd88747b 4650 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
ed9b544e 4651 return;
dd88747b 4652
ed9b544e 4653 incrRefCount(o);
3305306f 4654 deleteIfVolatile(c->db,c->argv[2]);
4655 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
ed9b544e 4656 if (nx) {
4657 decrRefCount(o);
c937aa89 4658 addReply(c,shared.czero);
ed9b544e 4659 return;
4660 }
3305306f 4661 dictReplace(c->db->dict,c->argv[2],o);
ed9b544e 4662 } else {
4663 incrRefCount(c->argv[2]);
4664 }
3305306f 4665 deleteKey(c->db,c->argv[1]);
ed9b544e 4666 server.dirty++;
c937aa89 4667 addReply(c,nx ? shared.cone : shared.ok);
ed9b544e 4668}
4669
4670static void renameCommand(redisClient *c) {
4671 renameGenericCommand(c,0);
4672}
4673
4674static void renamenxCommand(redisClient *c) {
4675 renameGenericCommand(c,1);
4676}
4677
4678static void moveCommand(redisClient *c) {
3305306f 4679 robj *o;
4680 redisDb *src, *dst;
ed9b544e 4681 int srcid;
4682
4683 /* Obtain source and target DB pointers */
3305306f 4684 src = c->db;
4685 srcid = c->db->id;
ed9b544e 4686 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
c937aa89 4687 addReply(c,shared.outofrangeerr);
ed9b544e 4688 return;
4689 }
3305306f 4690 dst = c->db;
4691 selectDb(c,srcid); /* Back to the source DB */
ed9b544e 4692
4693 /* If the user is moving using as target the same
4694 * DB as the source DB it is probably an error. */
4695 if (src == dst) {
c937aa89 4696 addReply(c,shared.sameobjecterr);
ed9b544e 4697 return;
4698 }
4699
4700 /* Check if the element exists and get a reference */
3305306f 4701 o = lookupKeyWrite(c->db,c->argv[1]);
4702 if (!o) {
c937aa89 4703 addReply(c,shared.czero);
ed9b544e 4704 return;
4705 }
4706
4707 /* Try to add the element to the target DB */
3305306f 4708 deleteIfVolatile(dst,c->argv[1]);
4709 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
c937aa89 4710 addReply(c,shared.czero);
ed9b544e 4711 return;
4712 }
3305306f 4713 incrRefCount(c->argv[1]);
ed9b544e 4714 incrRefCount(o);
4715
4716 /* OK! key moved, free the entry in the source DB */
3305306f 4717 deleteKey(src,c->argv[1]);
ed9b544e 4718 server.dirty++;
c937aa89 4719 addReply(c,shared.cone);
ed9b544e 4720}
4721
4722/* =================================== Lists ================================ */
4723static void pushGenericCommand(redisClient *c, int where) {
4724 robj *lobj;
ed9b544e 4725 list *list;
3305306f 4726
4727 lobj = lookupKeyWrite(c->db,c->argv[1]);
4728 if (lobj == NULL) {
95242ab5 4729 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
520b5a33 4730 addReply(c,shared.cone);
95242ab5 4731 return;
4732 }
ed9b544e 4733 lobj = createListObject();
4734 list = lobj->ptr;
4735 if (where == REDIS_HEAD) {
6b47e12e 4736 listAddNodeHead(list,c->argv[2]);
ed9b544e 4737 } else {
6b47e12e 4738 listAddNodeTail(list,c->argv[2]);
ed9b544e 4739 }
3305306f 4740 dictAdd(c->db->dict,c->argv[1],lobj);
ed9b544e 4741 incrRefCount(c->argv[1]);
4742 incrRefCount(c->argv[2]);
4743 } else {
ed9b544e 4744 if (lobj->type != REDIS_LIST) {
4745 addReply(c,shared.wrongtypeerr);
4746 return;
4747 }
95242ab5 4748 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
520b5a33 4749 addReply(c,shared.cone);
95242ab5 4750 return;
4751 }
ed9b544e 4752 list = lobj->ptr;
4753 if (where == REDIS_HEAD) {
6b47e12e 4754 listAddNodeHead(list,c->argv[2]);
ed9b544e 4755 } else {
6b47e12e 4756 listAddNodeTail(list,c->argv[2]);
ed9b544e 4757 }
4758 incrRefCount(c->argv[2]);
4759 }
4760 server.dirty++;
482b672d 4761 addReplyLongLong(c,listLength(list));
ed9b544e 4762}
4763
4764static void lpushCommand(redisClient *c) {
4765 pushGenericCommand(c,REDIS_HEAD);
4766}
4767
4768static void rpushCommand(redisClient *c) {
4769 pushGenericCommand(c,REDIS_TAIL);
4770}
4771
4772static void llenCommand(redisClient *c) {
3305306f 4773 robj *o;
ed9b544e 4774 list *l;
dd88747b 4775
4776 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
4777 checkType(c,o,REDIS_LIST)) return;
e0a62c7f 4778
dd88747b 4779 l = o->ptr;
4780 addReplyUlong(c,listLength(l));
ed9b544e 4781}
4782
4783static void lindexCommand(redisClient *c) {
3305306f 4784 robj *o;
ed9b544e 4785 int index = atoi(c->argv[2]->ptr);
dd88747b 4786 list *list;
4787 listNode *ln;
4788
4789 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4790 checkType(c,o,REDIS_LIST)) return;
4791 list = o->ptr;
4792
4793 ln = listIndex(list, index);
4794 if (ln == NULL) {
c937aa89 4795 addReply(c,shared.nullbulk);
ed9b544e 4796 } else {
dd88747b 4797 robj *ele = listNodeValue(ln);
4798 addReplyBulk(c,ele);
ed9b544e 4799 }
4800}
4801
4802static void lsetCommand(redisClient *c) {
3305306f 4803 robj *o;
ed9b544e 4804 int index = atoi(c->argv[2]->ptr);
dd88747b 4805 list *list;
4806 listNode *ln;
4807
4808 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL ||
4809 checkType(c,o,REDIS_LIST)) return;
4810 list = o->ptr;
4811
4812 ln = listIndex(list, index);
4813 if (ln == NULL) {
4814 addReply(c,shared.outofrangeerr);
ed9b544e 4815 } else {
dd88747b 4816 robj *ele = listNodeValue(ln);
ed9b544e 4817
dd88747b 4818 decrRefCount(ele);
4819 listNodeValue(ln) = c->argv[3];
4820 incrRefCount(c->argv[3]);
4821 addReply(c,shared.ok);
4822 server.dirty++;
ed9b544e 4823 }
4824}
4825
4826static void popGenericCommand(redisClient *c, int where) {
3305306f 4827 robj *o;
dd88747b 4828 list *list;
4829 listNode *ln;
3305306f 4830
dd88747b 4831 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4832 checkType(c,o,REDIS_LIST)) return;
4833 list = o->ptr;
ed9b544e 4834
dd88747b 4835 if (where == REDIS_HEAD)
4836 ln = listFirst(list);
4837 else
4838 ln = listLast(list);
ed9b544e 4839
dd88747b 4840 if (ln == NULL) {
4841 addReply(c,shared.nullbulk);
4842 } else {
4843 robj *ele = listNodeValue(ln);
4844 addReplyBulk(c,ele);
4845 listDelNode(list,ln);
3ea27d37 4846 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 4847 server.dirty++;
ed9b544e 4848 }
4849}
4850
4851static void lpopCommand(redisClient *c) {
4852 popGenericCommand(c,REDIS_HEAD);
4853}
4854
4855static void rpopCommand(redisClient *c) {
4856 popGenericCommand(c,REDIS_TAIL);
4857}
4858
4859static void lrangeCommand(redisClient *c) {
3305306f 4860 robj *o;
ed9b544e 4861 int start = atoi(c->argv[2]->ptr);
4862 int end = atoi(c->argv[3]->ptr);
dd88747b 4863 int llen;
4864 int rangelen, j;
4865 list *list;
4866 listNode *ln;
4867 robj *ele;
4868
4e27f268 4869 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
4870 || checkType(c,o,REDIS_LIST)) return;
dd88747b 4871 list = o->ptr;
4872 llen = listLength(list);
4873
4874 /* convert negative indexes */
4875 if (start < 0) start = llen+start;
4876 if (end < 0) end = llen+end;
4877 if (start < 0) start = 0;
4878 if (end < 0) end = 0;
4879
4880 /* indexes sanity checks */
4881 if (start > end || start >= llen) {
4882 /* Out of range start or start > end result in empty list */
4883 addReply(c,shared.emptymultibulk);
4884 return;
4885 }
4886 if (end >= llen) end = llen-1;
4887 rangelen = (end-start)+1;
3305306f 4888
dd88747b 4889 /* Return the result in form of a multi-bulk reply */
4890 ln = listIndex(list, start);
4891 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
4892 for (j = 0; j < rangelen; j++) {
4893 ele = listNodeValue(ln);
4894 addReplyBulk(c,ele);
4895 ln = ln->next;
ed9b544e 4896 }
4897}
4898
4899static void ltrimCommand(redisClient *c) {
3305306f 4900 robj *o;
ed9b544e 4901 int start = atoi(c->argv[2]->ptr);
4902 int end = atoi(c->argv[3]->ptr);
dd88747b 4903 int llen;
4904 int j, ltrim, rtrim;
4905 list *list;
4906 listNode *ln;
4907
4908 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.ok)) == NULL ||
4909 checkType(c,o,REDIS_LIST)) return;
4910 list = o->ptr;
4911 llen = listLength(list);
4912
4913 /* convert negative indexes */
4914 if (start < 0) start = llen+start;
4915 if (end < 0) end = llen+end;
4916 if (start < 0) start = 0;
4917 if (end < 0) end = 0;
4918
4919 /* indexes sanity checks */
4920 if (start > end || start >= llen) {
4921 /* Out of range start or start > end result in empty list */
4922 ltrim = llen;
4923 rtrim = 0;
ed9b544e 4924 } else {
dd88747b 4925 if (end >= llen) end = llen-1;
4926 ltrim = start;
4927 rtrim = llen-end-1;
4928 }
ed9b544e 4929
dd88747b 4930 /* Remove list elements to perform the trim */
4931 for (j = 0; j < ltrim; j++) {
4932 ln = listFirst(list);
4933 listDelNode(list,ln);
4934 }
4935 for (j = 0; j < rtrim; j++) {
4936 ln = listLast(list);
4937 listDelNode(list,ln);
ed9b544e 4938 }
3ea27d37 4939 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 4940 server.dirty++;
4941 addReply(c,shared.ok);
ed9b544e 4942}
4943
4944static void lremCommand(redisClient *c) {
3305306f 4945 robj *o;
dd88747b 4946 list *list;
4947 listNode *ln, *next;
4948 int toremove = atoi(c->argv[2]->ptr);
4949 int removed = 0;
4950 int fromtail = 0;
a4d1ba9a 4951
dd88747b 4952 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
4953 checkType(c,o,REDIS_LIST)) return;
4954 list = o->ptr;
4955
4956 if (toremove < 0) {
4957 toremove = -toremove;
4958 fromtail = 1;
4959 }
4960 ln = fromtail ? list->tail : list->head;
4961 while (ln) {
4962 robj *ele = listNodeValue(ln);
4963
4964 next = fromtail ? ln->prev : ln->next;
bf028098 4965 if (equalStringObjects(ele,c->argv[3])) {
dd88747b 4966 listDelNode(list,ln);
4967 server.dirty++;
4968 removed++;
4969 if (toremove && removed == toremove) break;
ed9b544e 4970 }
dd88747b 4971 ln = next;
ed9b544e 4972 }
3ea27d37 4973 if (listLength(list) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 4974 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
ed9b544e 4975}
4976
12f9d551 4977/* This is the semantic of this command:
0f5f7e9a 4978 * RPOPLPUSH srclist dstlist:
12f9d551 4979 * IF LLEN(srclist) > 0
4980 * element = RPOP srclist
4981 * LPUSH dstlist element
4982 * RETURN element
4983 * ELSE
4984 * RETURN nil
4985 * END
4986 * END
4987 *
4988 * The idea is to be able to get an element from a list in a reliable way
4989 * since the element is not just returned but pushed against another list
4990 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4991 */
0f5f7e9a 4992static void rpoplpushcommand(redisClient *c) {
12f9d551 4993 robj *sobj;
dd88747b 4994 list *srclist;
4995 listNode *ln;
4996
4997 if ((sobj = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
4998 checkType(c,sobj,REDIS_LIST)) return;
4999 srclist = sobj->ptr;
5000 ln = listLast(srclist);
12f9d551 5001
dd88747b 5002 if (ln == NULL) {
12f9d551 5003 addReply(c,shared.nullbulk);
5004 } else {
dd88747b 5005 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
5006 robj *ele = listNodeValue(ln);
5007 list *dstlist;
e20fb74f 5008
dd88747b 5009 if (dobj && dobj->type != REDIS_LIST) {
5010 addReply(c,shared.wrongtypeerr);
5011 return;
5012 }
12f9d551 5013
dd88747b 5014 /* Add the element to the target list (unless it's directly
5015 * passed to some BLPOP-ing client */
5016 if (!handleClientsWaitingListPush(c,c->argv[2],ele)) {
5017 if (dobj == NULL) {
5018 /* Create the list if the key does not exist */
5019 dobj = createListObject();
5020 dictAdd(c->db->dict,c->argv[2],dobj);
5021 incrRefCount(c->argv[2]);
12f9d551 5022 }
dd88747b 5023 dstlist = dobj->ptr;
5024 listAddNodeHead(dstlist,ele);
5025 incrRefCount(ele);
12f9d551 5026 }
dd88747b 5027
5028 /* Send the element to the client as reply as well */
5029 addReplyBulk(c,ele);
5030
5031 /* Finally remove the element from the source list */
5032 listDelNode(srclist,ln);
3ea27d37 5033 if (listLength(srclist) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5034 server.dirty++;
12f9d551 5035 }
5036}
5037
ed9b544e 5038/* ==================================== Sets ================================ */
5039
5040static void saddCommand(redisClient *c) {
ed9b544e 5041 robj *set;
5042
3305306f 5043 set = lookupKeyWrite(c->db,c->argv[1]);
5044 if (set == NULL) {
ed9b544e 5045 set = createSetObject();
3305306f 5046 dictAdd(c->db->dict,c->argv[1],set);
ed9b544e 5047 incrRefCount(c->argv[1]);
5048 } else {
ed9b544e 5049 if (set->type != REDIS_SET) {
c937aa89 5050 addReply(c,shared.wrongtypeerr);
ed9b544e 5051 return;
5052 }
5053 }
5054 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
5055 incrRefCount(c->argv[2]);
5056 server.dirty++;
c937aa89 5057 addReply(c,shared.cone);
ed9b544e 5058 } else {
c937aa89 5059 addReply(c,shared.czero);
ed9b544e 5060 }
5061}
5062
5063static void sremCommand(redisClient *c) {
3305306f 5064 robj *set;
ed9b544e 5065
dd88747b 5066 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5067 checkType(c,set,REDIS_SET)) return;
5068
5069 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
5070 server.dirty++;
5071 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
3ea27d37 5072 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5073 addReply(c,shared.cone);
ed9b544e 5074 } else {
dd88747b 5075 addReply(c,shared.czero);
ed9b544e 5076 }
5077}
5078
a4460ef4 5079static void smoveCommand(redisClient *c) {
5080 robj *srcset, *dstset;
5081
5082 srcset = lookupKeyWrite(c->db,c->argv[1]);
5083 dstset = lookupKeyWrite(c->db,c->argv[2]);
5084
5085 /* If the source key does not exist return 0, if it's of the wrong type
5086 * raise an error */
5087 if (srcset == NULL || srcset->type != REDIS_SET) {
5088 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
5089 return;
5090 }
5091 /* Error if the destination key is not a set as well */
5092 if (dstset && dstset->type != REDIS_SET) {
5093 addReply(c,shared.wrongtypeerr);
5094 return;
5095 }
5096 /* Remove the element from the source set */
5097 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
5098 /* Key not found in the src set! return zero */
5099 addReply(c,shared.czero);
5100 return;
5101 }
3ea27d37 5102 if (dictSize((dict*)srcset->ptr) == 0 && srcset != dstset)
5103 deleteKey(c->db,c->argv[1]);
a4460ef4 5104 server.dirty++;
5105 /* Add the element to the destination set */
5106 if (!dstset) {
5107 dstset = createSetObject();
5108 dictAdd(c->db->dict,c->argv[2],dstset);
5109 incrRefCount(c->argv[2]);
5110 }
5111 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
5112 incrRefCount(c->argv[3]);
5113 addReply(c,shared.cone);
5114}
5115
ed9b544e 5116static void sismemberCommand(redisClient *c) {
3305306f 5117 robj *set;
ed9b544e 5118
dd88747b 5119 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5120 checkType(c,set,REDIS_SET)) return;
5121
5122 if (dictFind(set->ptr,c->argv[2]))
5123 addReply(c,shared.cone);
5124 else
c937aa89 5125 addReply(c,shared.czero);
ed9b544e 5126}
5127
5128static void scardCommand(redisClient *c) {
3305306f 5129 robj *o;
ed9b544e 5130 dict *s;
dd88747b 5131
5132 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
5133 checkType(c,o,REDIS_SET)) return;
e0a62c7f 5134
dd88747b 5135 s = o->ptr;
5136 addReplyUlong(c,dictSize(s));
ed9b544e 5137}
5138
12fea928 5139static void spopCommand(redisClient *c) {
5140 robj *set;
5141 dictEntry *de;
5142
dd88747b 5143 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5144 checkType(c,set,REDIS_SET)) return;
5145
5146 de = dictGetRandomKey(set->ptr);
5147 if (de == NULL) {
12fea928 5148 addReply(c,shared.nullbulk);
5149 } else {
dd88747b 5150 robj *ele = dictGetEntryKey(de);
12fea928 5151
dd88747b 5152 addReplyBulk(c,ele);
5153 dictDelete(set->ptr,ele);
5154 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
3ea27d37 5155 if (dictSize((dict*)set->ptr) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5156 server.dirty++;
12fea928 5157 }
5158}
5159
2abb95a9 5160static void srandmemberCommand(redisClient *c) {
5161 robj *set;
5162 dictEntry *de;
5163
dd88747b 5164 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
5165 checkType(c,set,REDIS_SET)) return;
5166
5167 de = dictGetRandomKey(set->ptr);
5168 if (de == NULL) {
2abb95a9 5169 addReply(c,shared.nullbulk);
5170 } else {
dd88747b 5171 robj *ele = dictGetEntryKey(de);
2abb95a9 5172
dd88747b 5173 addReplyBulk(c,ele);
2abb95a9 5174 }
5175}
5176
ed9b544e 5177static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
5178 dict **d1 = (void*) s1, **d2 = (void*) s2;
5179
3305306f 5180 return dictSize(*d1)-dictSize(*d2);
ed9b544e 5181}
5182
682ac724 5183static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
ed9b544e 5184 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5185 dictIterator *di;
5186 dictEntry *de;
5187 robj *lenobj = NULL, *dstset = NULL;
682ac724 5188 unsigned long j, cardinality = 0;
ed9b544e 5189
ed9b544e 5190 for (j = 0; j < setsnum; j++) {
5191 robj *setobj;
3305306f 5192
5193 setobj = dstkey ?
5194 lookupKeyWrite(c->db,setskeys[j]) :
5195 lookupKeyRead(c->db,setskeys[j]);
5196 if (!setobj) {
ed9b544e 5197 zfree(dv);
5faa6025 5198 if (dstkey) {
fdcaae84 5199 if (deleteKey(c->db,dstkey))
5200 server.dirty++;
0d36ded0 5201 addReply(c,shared.czero);
5faa6025 5202 } else {
4e27f268 5203 addReply(c,shared.emptymultibulk);
5faa6025 5204 }
ed9b544e 5205 return;
5206 }
ed9b544e 5207 if (setobj->type != REDIS_SET) {
5208 zfree(dv);
c937aa89 5209 addReply(c,shared.wrongtypeerr);
ed9b544e 5210 return;
5211 }
5212 dv[j] = setobj->ptr;
5213 }
5214 /* Sort sets from the smallest to largest, this will improve our
5215 * algorithm's performace */
5216 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
5217
5218 /* The first thing we should output is the total number of elements...
5219 * since this is a multi-bulk write, but at this stage we don't know
5220 * the intersection set size, so we use a trick, append an empty object
5221 * to the output list and save the pointer to later modify it with the
5222 * right length */
5223 if (!dstkey) {
5224 lenobj = createObject(REDIS_STRING,NULL);
5225 addReply(c,lenobj);
5226 decrRefCount(lenobj);
5227 } else {
5228 /* If we have a target key where to store the resulting set
5229 * create this key with an empty set inside */
5230 dstset = createSetObject();
ed9b544e 5231 }
5232
5233 /* Iterate all the elements of the first (smallest) set, and test
5234 * the element against all the other sets, if at least one set does
5235 * not include the element it is discarded */
5236 di = dictGetIterator(dv[0]);
ed9b544e 5237
5238 while((de = dictNext(di)) != NULL) {
5239 robj *ele;
5240
5241 for (j = 1; j < setsnum; j++)
5242 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
5243 if (j != setsnum)
5244 continue; /* at least one set does not contain the member */
5245 ele = dictGetEntryKey(de);
5246 if (!dstkey) {
dd88747b 5247 addReplyBulk(c,ele);
ed9b544e 5248 cardinality++;
5249 } else {
5250 dictAdd(dstset->ptr,ele,NULL);
5251 incrRefCount(ele);
5252 }
5253 }
5254 dictReleaseIterator(di);
5255
83cdfe18 5256 if (dstkey) {
3ea27d37 5257 /* Store the resulting set into the target, if the intersection
5258 * is not an empty set. */
83cdfe18 5259 deleteKey(c->db,dstkey);
3ea27d37 5260 if (dictSize((dict*)dstset->ptr) > 0) {
5261 dictAdd(c->db->dict,dstkey,dstset);
5262 incrRefCount(dstkey);
482b672d 5263 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
3ea27d37 5264 } else {
5265 decrRefCount(dstset);
d36c4e97 5266 addReply(c,shared.czero);
3ea27d37 5267 }
40d224a9 5268 server.dirty++;
d36c4e97 5269 } else {
5270 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
40d224a9 5271 }
ed9b544e 5272 zfree(dv);
5273}
5274
5275static void sinterCommand(redisClient *c) {
5276 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
5277}
5278
5279static void sinterstoreCommand(redisClient *c) {
5280 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
5281}
5282
f4f56e1d 5283#define REDIS_OP_UNION 0
5284#define REDIS_OP_DIFF 1
2830ca53 5285#define REDIS_OP_INTER 2
f4f56e1d 5286
5287static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
40d224a9 5288 dict **dv = zmalloc(sizeof(dict*)*setsnum);
5289 dictIterator *di;
5290 dictEntry *de;
f4f56e1d 5291 robj *dstset = NULL;
40d224a9 5292 int j, cardinality = 0;
5293
40d224a9 5294 for (j = 0; j < setsnum; j++) {
5295 robj *setobj;
5296
5297 setobj = dstkey ?
5298 lookupKeyWrite(c->db,setskeys[j]) :
5299 lookupKeyRead(c->db,setskeys[j]);
5300 if (!setobj) {
5301 dv[j] = NULL;
5302 continue;
5303 }
5304 if (setobj->type != REDIS_SET) {
5305 zfree(dv);
5306 addReply(c,shared.wrongtypeerr);
5307 return;
5308 }
5309 dv[j] = setobj->ptr;
5310 }
5311
5312 /* We need a temp set object to store our union. If the dstkey
5313 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5314 * this set object will be the resulting object to set into the target key*/
5315 dstset = createSetObject();
5316
40d224a9 5317 /* Iterate all the elements of all the sets, add every element a single
5318 * time to the result set */
5319 for (j = 0; j < setsnum; j++) {
51829ed3 5320 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
40d224a9 5321 if (!dv[j]) continue; /* non existing keys are like empty sets */
5322
5323 di = dictGetIterator(dv[j]);
40d224a9 5324
5325 while((de = dictNext(di)) != NULL) {
5326 robj *ele;
5327
5328 /* dictAdd will not add the same element multiple times */
5329 ele = dictGetEntryKey(de);
f4f56e1d 5330 if (op == REDIS_OP_UNION || j == 0) {
5331 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
5332 incrRefCount(ele);
40d224a9 5333 cardinality++;
5334 }
f4f56e1d 5335 } else if (op == REDIS_OP_DIFF) {
5336 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
5337 cardinality--;
5338 }
40d224a9 5339 }
5340 }
5341 dictReleaseIterator(di);
51829ed3 5342
d36c4e97 5343 /* result set is empty? Exit asap. */
5344 if (op == REDIS_OP_DIFF && cardinality == 0) break;
40d224a9 5345 }
5346
f4f56e1d 5347 /* Output the content of the resulting set, if not in STORE mode */
5348 if (!dstkey) {
5349 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
5350 di = dictGetIterator(dstset->ptr);
f4f56e1d 5351 while((de = dictNext(di)) != NULL) {
5352 robj *ele;
5353
5354 ele = dictGetEntryKey(de);
dd88747b 5355 addReplyBulk(c,ele);
f4f56e1d 5356 }
5357 dictReleaseIterator(di);
d36c4e97 5358 decrRefCount(dstset);
83cdfe18
AG
5359 } else {
5360 /* If we have a target key where to store the resulting set
5361 * create this key with the result set inside */
5362 deleteKey(c->db,dstkey);
3ea27d37 5363 if (dictSize((dict*)dstset->ptr) > 0) {
5364 dictAdd(c->db->dict,dstkey,dstset);
5365 incrRefCount(dstkey);
482b672d 5366 addReplyLongLong(c,dictSize((dict*)dstset->ptr));
3ea27d37 5367 } else {
5368 decrRefCount(dstset);
d36c4e97 5369 addReply(c,shared.czero);
3ea27d37 5370 }
40d224a9 5371 server.dirty++;
5372 }
5373 zfree(dv);
5374}
5375
5376static void sunionCommand(redisClient *c) {
f4f56e1d 5377 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
40d224a9 5378}
5379
5380static void sunionstoreCommand(redisClient *c) {
f4f56e1d 5381 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
5382}
5383
5384static void sdiffCommand(redisClient *c) {
5385 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
5386}
5387
5388static void sdiffstoreCommand(redisClient *c) {
5389 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
40d224a9 5390}
5391
6b47e12e 5392/* ==================================== ZSets =============================== */
5393
5394/* ZSETs are ordered sets using two data structures to hold the same elements
5395 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5396 * data structure.
5397 *
5398 * The elements are added to an hash table mapping Redis objects to scores.
5399 * At the same time the elements are added to a skip list mapping scores
5400 * to Redis objects (so objects are sorted by scores in this "view"). */
5401
5402/* This skiplist implementation is almost a C translation of the original
5403 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5404 * Alternative to Balanced Trees", modified in three ways:
5405 * a) this implementation allows for repeated values.
5406 * b) the comparison is not just by key (our 'score') but by satellite data.
5407 * c) there is a back pointer, so it's a doubly linked list with the back
5408 * pointers being only at "level 1". This allows to traverse the list
5409 * from tail to head, useful for ZREVRANGE. */
5410
5411static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
5412 zskiplistNode *zn = zmalloc(sizeof(*zn));
5413
5414 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
2f4dd7e0 5415 if (level > 1)
2b37892e 5416 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
2f4dd7e0 5417 else
5418 zn->span = NULL;
6b47e12e 5419 zn->score = score;
5420 zn->obj = obj;
5421 return zn;
5422}
5423
5424static zskiplist *zslCreate(void) {
5425 int j;
5426 zskiplist *zsl;
e0a62c7f 5427
6b47e12e 5428 zsl = zmalloc(sizeof(*zsl));
5429 zsl->level = 1;
cc812361 5430 zsl->length = 0;
6b47e12e 5431 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
69d95c3e 5432 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
6b47e12e 5433 zsl->header->forward[j] = NULL;
94e543b5 5434
5435 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5436 if (j < ZSKIPLIST_MAXLEVEL-1)
5437 zsl->header->span[j] = 0;
69d95c3e 5438 }
e3870fab 5439 zsl->header->backward = NULL;
5440 zsl->tail = NULL;
6b47e12e 5441 return zsl;
5442}
5443
fd8ccf44 5444static void zslFreeNode(zskiplistNode *node) {
5445 decrRefCount(node->obj);
ad807e6f 5446 zfree(node->forward);
69d95c3e 5447 zfree(node->span);
fd8ccf44 5448 zfree(node);
5449}
5450
5451static void zslFree(zskiplist *zsl) {
ad807e6f 5452 zskiplistNode *node = zsl->header->forward[0], *next;
fd8ccf44 5453
ad807e6f 5454 zfree(zsl->header->forward);
69d95c3e 5455 zfree(zsl->header->span);
ad807e6f 5456 zfree(zsl->header);
fd8ccf44 5457 while(node) {
599379dd 5458 next = node->forward[0];
fd8ccf44 5459 zslFreeNode(node);
5460 node = next;
5461 }
ad807e6f 5462 zfree(zsl);
fd8ccf44 5463}
5464
6b47e12e 5465static int zslRandomLevel(void) {
5466 int level = 1;
5467 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
5468 level += 1;
10c2baa5 5469 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
6b47e12e 5470}
5471
5472static void zslInsert(zskiplist *zsl, double score, robj *obj) {
5473 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
2b37892e 5474 unsigned int rank[ZSKIPLIST_MAXLEVEL];
6b47e12e 5475 int i, level;
5476
5477 x = zsl->header;
5478 for (i = zsl->level-1; i >= 0; i--) {
2b37892e
PN
5479 /* store rank that is crossed to reach the insert position */
5480 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
69d95c3e 5481
9d60e6e4 5482 while (x->forward[i] &&
5483 (x->forward[i]->score < score ||
5484 (x->forward[i]->score == score &&
69d95c3e 5485 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
a50ea45c 5486 rank[i] += i > 0 ? x->span[i-1] : 1;
6b47e12e 5487 x = x->forward[i];
69d95c3e 5488 }
6b47e12e 5489 update[i] = x;
5490 }
6b47e12e 5491 /* we assume the key is not already inside, since we allow duplicated
5492 * scores, and the re-insertion of score and redis object should never
5493 * happpen since the caller of zslInsert() should test in the hash table
5494 * if the element is already inside or not. */
5495 level = zslRandomLevel();
5496 if (level > zsl->level) {
69d95c3e 5497 for (i = zsl->level; i < level; i++) {
2b37892e 5498 rank[i] = 0;
6b47e12e 5499 update[i] = zsl->header;
2b37892e 5500 update[i]->span[i-1] = zsl->length;
69d95c3e 5501 }
6b47e12e 5502 zsl->level = level;
5503 }
5504 x = zslCreateNode(level,score,obj);
5505 for (i = 0; i < level; i++) {
5506 x->forward[i] = update[i]->forward[i];
5507 update[i]->forward[i] = x;
69d95c3e
PN
5508
5509 /* update span covered by update[i] as x is inserted here */
2b37892e
PN
5510 if (i > 0) {
5511 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
5512 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
5513 }
6b47e12e 5514 }
69d95c3e
PN
5515
5516 /* increment span for untouched levels */
5517 for (i = level; i < zsl->level; i++) {
2b37892e 5518 update[i]->span[i-1]++;
69d95c3e
PN
5519 }
5520
bb975144 5521 x->backward = (update[0] == zsl->header) ? NULL : update[0];
e3870fab 5522 if (x->forward[0])
5523 x->forward[0]->backward = x;
5524 else
5525 zsl->tail = x;
cc812361 5526 zsl->length++;
6b47e12e 5527}
5528
84105336
PN
5529/* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5530void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
5531 int i;
5532 for (i = 0; i < zsl->level; i++) {
5533 if (update[i]->forward[i] == x) {
5534 if (i > 0) {
5535 update[i]->span[i-1] += x->span[i-1] - 1;
5536 }
5537 update[i]->forward[i] = x->forward[i];
5538 } else {
5539 /* invariant: i > 0, because update[0]->forward[0]
5540 * is always equal to x */
5541 update[i]->span[i-1] -= 1;
5542 }
5543 }
5544 if (x->forward[0]) {
5545 x->forward[0]->backward = x->backward;
5546 } else {
5547 zsl->tail = x->backward;
5548 }
5549 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
5550 zsl->level--;
5551 zsl->length--;
5552}
5553
50c55df5 5554/* Delete an element with matching score/object from the skiplist. */
fd8ccf44 5555static int zslDelete(zskiplist *zsl, double score, robj *obj) {
e197b441 5556 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5557 int i;
5558
5559 x = zsl->header;
5560 for (i = zsl->level-1; i >= 0; i--) {
9d60e6e4 5561 while (x->forward[i] &&
5562 (x->forward[i]->score < score ||
5563 (x->forward[i]->score == score &&
5564 compareStringObjects(x->forward[i]->obj,obj) < 0)))
e197b441 5565 x = x->forward[i];
5566 update[i] = x;
5567 }
5568 /* We may have multiple elements with the same score, what we need
5569 * is to find the element with both the right score and object. */
5570 x = x->forward[0];
bf028098 5571 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
84105336 5572 zslDeleteNode(zsl, x, update);
9d60e6e4 5573 zslFreeNode(x);
9d60e6e4 5574 return 1;
5575 } else {
5576 return 0; /* not found */
e197b441 5577 }
5578 return 0; /* not found */
fd8ccf44 5579}
5580
1807985b 5581/* Delete all the elements with score between min and max from the skiplist.
5582 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5583 * Note that this function takes the reference to the hash table view of the
5584 * sorted set, in order to remove the elements from the hash table too. */
f84d3933 5585static unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
1807985b 5586 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5587 unsigned long removed = 0;
5588 int i;
5589
5590 x = zsl->header;
5591 for (i = zsl->level-1; i >= 0; i--) {
5592 while (x->forward[i] && x->forward[i]->score < min)
5593 x = x->forward[i];
5594 update[i] = x;
5595 }
5596 /* We may have multiple elements with the same score, what we need
5597 * is to find the element with both the right score and object. */
5598 x = x->forward[0];
5599 while (x && x->score <= max) {
84105336
PN
5600 zskiplistNode *next = x->forward[0];
5601 zslDeleteNode(zsl, x, update);
1807985b 5602 dictDelete(dict,x->obj);
5603 zslFreeNode(x);
1807985b 5604 removed++;
5605 x = next;
5606 }
5607 return removed; /* not found */
5608}
1807985b 5609
9212eafd 5610/* Delete all the elements with rank between start and end from the skiplist.
2424490f 5611 * Start and end are inclusive. Note that start and end need to be 1-based */
9212eafd
PN
5612static unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
5613 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
5614 unsigned long traversed = 0, removed = 0;
5615 int i;
5616
9212eafd
PN
5617 x = zsl->header;
5618 for (i = zsl->level-1; i >= 0; i--) {
5619 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
5620 traversed += i > 0 ? x->span[i-1] : 1;
5621 x = x->forward[i];
1807985b 5622 }
9212eafd
PN
5623 update[i] = x;
5624 }
5625
5626 traversed++;
5627 x = x->forward[0];
5628 while (x && traversed <= end) {
84105336
PN
5629 zskiplistNode *next = x->forward[0];
5630 zslDeleteNode(zsl, x, update);
1807985b 5631 dictDelete(dict,x->obj);
5632 zslFreeNode(x);
1807985b 5633 removed++;
9212eafd 5634 traversed++;
1807985b 5635 x = next;
5636 }
9212eafd 5637 return removed;
1807985b 5638}
5639
50c55df5 5640/* Find the first node having a score equal or greater than the specified one.
5641 * Returns NULL if there is no match. */
5642static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
5643 zskiplistNode *x;
5644 int i;
5645
5646 x = zsl->header;
5647 for (i = zsl->level-1; i >= 0; i--) {
5648 while (x->forward[i] && x->forward[i]->score < score)
5649 x = x->forward[i];
5650 }
5651 /* We may have multiple elements with the same score, what we need
5652 * is to find the element with both the right score and object. */
5653 return x->forward[0];
5654}
5655
27b0ccca
PN
5656/* Find the rank for an element by both score and key.
5657 * Returns 0 when the element cannot be found, rank otherwise.
5658 * Note that the rank is 1-based due to the span of zsl->header to the
5659 * first element. */
5660static unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
5661 zskiplistNode *x;
5662 unsigned long rank = 0;
5663 int i;
5664
5665 x = zsl->header;
5666 for (i = zsl->level-1; i >= 0; i--) {
5667 while (x->forward[i] &&
5668 (x->forward[i]->score < score ||
5669 (x->forward[i]->score == score &&
5670 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
a50ea45c 5671 rank += i > 0 ? x->span[i-1] : 1;
27b0ccca
PN
5672 x = x->forward[i];
5673 }
5674
5675 /* x might be equal to zsl->header, so test if obj is non-NULL */
bf028098 5676 if (x->obj && equalStringObjects(x->obj,o)) {
27b0ccca
PN
5677 return rank;
5678 }
5679 }
5680 return 0;
5681}
5682
e74825c2
PN
5683/* Finds an element by its rank. The rank argument needs to be 1-based. */
5684zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
5685 zskiplistNode *x;
5686 unsigned long traversed = 0;
5687 int i;
5688
5689 x = zsl->header;
5690 for (i = zsl->level-1; i >= 0; i--) {
dd88747b 5691 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
5692 {
a50ea45c 5693 traversed += i > 0 ? x->span[i-1] : 1;
e74825c2
PN
5694 x = x->forward[i];
5695 }
e74825c2
PN
5696 if (traversed == rank) {
5697 return x;
5698 }
5699 }
5700 return NULL;
5701}
5702
fd8ccf44 5703/* The actual Z-commands implementations */
5704
7db723ad 5705/* This generic command implements both ZADD and ZINCRBY.
e2665397 5706 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
7db723ad 5707 * the increment if the operation is a ZINCRBY (doincrement == 1). */
e2665397 5708static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
fd8ccf44 5709 robj *zsetobj;
5710 zset *zs;
5711 double *score;
5712
e2665397 5713 zsetobj = lookupKeyWrite(c->db,key);
fd8ccf44 5714 if (zsetobj == NULL) {
5715 zsetobj = createZsetObject();
e2665397 5716 dictAdd(c->db->dict,key,zsetobj);
5717 incrRefCount(key);
fd8ccf44 5718 } else {
5719 if (zsetobj->type != REDIS_ZSET) {
5720 addReply(c,shared.wrongtypeerr);
5721 return;
5722 }
5723 }
fd8ccf44 5724 zs = zsetobj->ptr;
e2665397 5725
7db723ad 5726 /* Ok now since we implement both ZADD and ZINCRBY here the code
e2665397 5727 * needs to handle the two different conditions. It's all about setting
5728 * '*score', that is, the new score to set, to the right value. */
5729 score = zmalloc(sizeof(double));
5730 if (doincrement) {
5731 dictEntry *de;
5732
5733 /* Read the old score. If the element was not present starts from 0 */
5734 de = dictFind(zs->dict,ele);
5735 if (de) {
5736 double *oldscore = dictGetEntryVal(de);
5737 *score = *oldscore + scoreval;
5738 } else {
5739 *score = scoreval;
5740 }
5741 } else {
5742 *score = scoreval;
5743 }
5744
5745 /* What follows is a simple remove and re-insert operation that is common
7db723ad 5746 * to both ZADD and ZINCRBY... */
e2665397 5747 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
fd8ccf44 5748 /* case 1: New element */
e2665397 5749 incrRefCount(ele); /* added to hash */
5750 zslInsert(zs->zsl,*score,ele);
5751 incrRefCount(ele); /* added to skiplist */
fd8ccf44 5752 server.dirty++;
e2665397 5753 if (doincrement)
e2665397 5754 addReplyDouble(c,*score);
91d71bfc 5755 else
5756 addReply(c,shared.cone);
fd8ccf44 5757 } else {
5758 dictEntry *de;
5759 double *oldscore;
e0a62c7f 5760
fd8ccf44 5761 /* case 2: Score update operation */
e2665397 5762 de = dictFind(zs->dict,ele);
dfc5e96c 5763 redisAssert(de != NULL);
fd8ccf44 5764 oldscore = dictGetEntryVal(de);
5765 if (*score != *oldscore) {
5766 int deleted;
5767
e2665397 5768 /* Remove and insert the element in the skip list with new score */
5769 deleted = zslDelete(zs->zsl,*oldscore,ele);
dfc5e96c 5770 redisAssert(deleted != 0);
e2665397 5771 zslInsert(zs->zsl,*score,ele);
5772 incrRefCount(ele);
5773 /* Update the score in the hash table */
5774 dictReplace(zs->dict,ele,score);
fd8ccf44 5775 server.dirty++;
2161a965 5776 } else {
5777 zfree(score);
fd8ccf44 5778 }
e2665397 5779 if (doincrement)
5780 addReplyDouble(c,*score);
5781 else
5782 addReply(c,shared.czero);
fd8ccf44 5783 }
5784}
5785
e2665397 5786static void zaddCommand(redisClient *c) {
5787 double scoreval;
5788
bd79a6bd 5789 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
e2665397 5790 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
5791}
5792
7db723ad 5793static void zincrbyCommand(redisClient *c) {
e2665397 5794 double scoreval;
5795
bd79a6bd 5796 if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return;
e2665397 5797 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
5798}
5799
1b7106e7 5800static void zremCommand(redisClient *c) {
5801 robj *zsetobj;
5802 zset *zs;
dd88747b 5803 dictEntry *de;
5804 double *oldscore;
5805 int deleted;
1b7106e7 5806
dd88747b 5807 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5808 checkType(c,zsetobj,REDIS_ZSET)) return;
1b7106e7 5809
dd88747b 5810 zs = zsetobj->ptr;
5811 de = dictFind(zs->dict,c->argv[2]);
5812 if (de == NULL) {
5813 addReply(c,shared.czero);
5814 return;
1b7106e7 5815 }
dd88747b 5816 /* Delete from the skiplist */
5817 oldscore = dictGetEntryVal(de);
5818 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
5819 redisAssert(deleted != 0);
5820
5821 /* Delete from the hash table */
5822 dictDelete(zs->dict,c->argv[2]);
5823 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
3ea27d37 5824 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5825 server.dirty++;
5826 addReply(c,shared.cone);
1b7106e7 5827}
5828
1807985b 5829static void zremrangebyscoreCommand(redisClient *c) {
bbe025e0
AM
5830 double min;
5831 double max;
dd88747b 5832 long deleted;
1807985b 5833 robj *zsetobj;
5834 zset *zs;
5835
bd79a6bd
PN
5836 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
5837 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
bbe025e0 5838
dd88747b 5839 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5840 checkType(c,zsetobj,REDIS_ZSET)) return;
1807985b 5841
dd88747b 5842 zs = zsetobj->ptr;
5843 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
5844 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
3ea27d37 5845 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5846 server.dirty += deleted;
482b672d 5847 addReplyLongLong(c,deleted);
1807985b 5848}
5849
9212eafd 5850static void zremrangebyrankCommand(redisClient *c) {
bbe025e0
AM
5851 long start;
5852 long end;
dd88747b 5853 int llen;
5854 long deleted;
9212eafd
PN
5855 robj *zsetobj;
5856 zset *zs;
5857
bd79a6bd
PN
5858 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
5859 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
bbe025e0 5860
dd88747b 5861 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
5862 checkType(c,zsetobj,REDIS_ZSET)) return;
5863 zs = zsetobj->ptr;
5864 llen = zs->zsl->length;
9212eafd 5865
dd88747b 5866 /* convert negative indexes */
5867 if (start < 0) start = llen+start;
5868 if (end < 0) end = llen+end;
5869 if (start < 0) start = 0;
5870 if (end < 0) end = 0;
9212eafd 5871
dd88747b 5872 /* indexes sanity checks */
5873 if (start > end || start >= llen) {
5874 addReply(c,shared.czero);
5875 return;
9212eafd 5876 }
dd88747b 5877 if (end >= llen) end = llen-1;
5878
5879 /* increment start and end because zsl*Rank functions
5880 * use 1-based rank */
5881 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
5882 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
3ea27d37 5883 if (dictSize(zs->dict) == 0) deleteKey(c->db,c->argv[1]);
dd88747b 5884 server.dirty += deleted;
482b672d 5885 addReplyLongLong(c, deleted);
9212eafd
PN
5886}
5887
8f92e768
PN
5888typedef struct {
5889 dict *dict;
5890 double weight;
5891} zsetopsrc;
5892
5893static int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
5894 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
5895 unsigned long size1, size2;
5896 size1 = d1->dict ? dictSize(d1->dict) : 0;
5897 size2 = d2->dict ? dictSize(d2->dict) : 0;
5898 return size1 - size2;
5899}
5900
d2764cd6
PN
5901#define REDIS_AGGR_SUM 1
5902#define REDIS_AGGR_MIN 2
5903#define REDIS_AGGR_MAX 3
5904
5905inline static void zunionInterAggregate(double *target, double val, int aggregate) {
5906 if (aggregate == REDIS_AGGR_SUM) {
5907 *target = *target + val;
5908 } else if (aggregate == REDIS_AGGR_MIN) {
5909 *target = val < *target ? val : *target;
5910 } else if (aggregate == REDIS_AGGR_MAX) {
5911 *target = val > *target ? val : *target;
5912 } else {
5913 /* safety net */
f83c6cb5 5914 redisPanic("Unknown ZUNION/INTER aggregate type");
d2764cd6
PN
5915 }
5916}
5917
2830ca53 5918static void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
8f92e768 5919 int i, j, zsetnum;
d2764cd6 5920 int aggregate = REDIS_AGGR_SUM;
8f92e768 5921 zsetopsrc *src;
2830ca53
PN
5922 robj *dstobj;
5923 zset *dstzset;
b287c9bb
PN
5924 dictIterator *di;
5925 dictEntry *de;
5926
2830ca53
PN
5927 /* expect zsetnum input keys to be given */
5928 zsetnum = atoi(c->argv[2]->ptr);
5929 if (zsetnum < 1) {
5d373da9 5930 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
2830ca53 5931 return;
b287c9bb 5932 }
2830ca53
PN
5933
5934 /* test if the expected number of keys would overflow */
5935 if (3+zsetnum > c->argc) {
b287c9bb
PN
5936 addReply(c,shared.syntaxerr);
5937 return;
5938 }
5939
2830ca53 5940 /* read keys to be used for input */
b9eed483 5941 src = zmalloc(sizeof(zsetopsrc) * zsetnum);
2830ca53 5942 for (i = 0, j = 3; i < zsetnum; i++, j++) {
b287c9bb
PN
5943 robj *zsetobj = lookupKeyWrite(c->db,c->argv[j]);
5944 if (!zsetobj) {
8f92e768 5945 src[i].dict = NULL;
b287c9bb
PN
5946 } else {
5947 if (zsetobj->type != REDIS_ZSET) {
8f92e768 5948 zfree(src);
b287c9bb
PN
5949 addReply(c,shared.wrongtypeerr);
5950 return;
5951 }
8f92e768 5952 src[i].dict = ((zset*)zsetobj->ptr)->dict;
b287c9bb 5953 }
2830ca53
PN
5954
5955 /* default all weights to 1 */
8f92e768 5956 src[i].weight = 1.0;
b287c9bb
PN
5957 }
5958
2830ca53
PN
5959 /* parse optional extra arguments */
5960 if (j < c->argc) {
d2764cd6 5961 int remaining = c->argc - j;
b287c9bb 5962
2830ca53 5963 while (remaining) {
d2764cd6 5964 if (remaining >= (zsetnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
2830ca53 5965 j++; remaining--;
2830ca53 5966 for (i = 0; i < zsetnum; i++, j++, remaining--) {
bd79a6bd 5967 if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK)
bbe025e0 5968 return;
2830ca53 5969 }
d2764cd6
PN
5970 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
5971 j++; remaining--;
5972 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
5973 aggregate = REDIS_AGGR_SUM;
5974 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
5975 aggregate = REDIS_AGGR_MIN;
5976 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
5977 aggregate = REDIS_AGGR_MAX;
5978 } else {
5979 zfree(src);
5980 addReply(c,shared.syntaxerr);
5981 return;
5982 }
5983 j++; remaining--;
2830ca53 5984 } else {
8f92e768 5985 zfree(src);
2830ca53
PN
5986 addReply(c,shared.syntaxerr);
5987 return;
5988 }
5989 }
5990 }
b287c9bb 5991
d2764cd6
PN
5992 /* sort sets from the smallest to largest, this will improve our
5993 * algorithm's performance */
5994 qsort(src,zsetnum,sizeof(zsetopsrc), qsortCompareZsetopsrcByCardinality);
5995
2830ca53
PN
5996 dstobj = createZsetObject();
5997 dstzset = dstobj->ptr;
5998
5999 if (op == REDIS_OP_INTER) {
8f92e768
PN
6000 /* skip going over all entries if the smallest zset is NULL or empty */
6001 if (src[0].dict && dictSize(src[0].dict) > 0) {
6002 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6003 * from small to large, all src[i > 0].dict are non-empty too */
6004 di = dictGetIterator(src[0].dict);
2830ca53 6005 while((de = dictNext(di)) != NULL) {
d2764cd6
PN
6006 double *score = zmalloc(sizeof(double)), value;
6007 *score = src[0].weight * (*(double*)dictGetEntryVal(de));
2830ca53 6008
d2764cd6
PN
6009 for (j = 1; j < zsetnum; j++) {
6010 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
2830ca53 6011 if (other) {
d2764cd6
PN
6012 value = src[j].weight * (*(double*)dictGetEntryVal(other));
6013 zunionInterAggregate(score, value, aggregate);
2830ca53
PN
6014 } else {
6015 break;
6016 }
6017 }
b287c9bb 6018
2830ca53 6019 /* skip entry when not present in every source dict */
8f92e768 6020 if (j != zsetnum) {
2830ca53
PN
6021 zfree(score);
6022 } else {
6023 robj *o = dictGetEntryKey(de);
6024 dictAdd(dstzset->dict,o,score);
6025 incrRefCount(o); /* added to dictionary */
6026 zslInsert(dstzset->zsl,*score,o);
6027 incrRefCount(o); /* added to skiplist */
b287c9bb
PN
6028 }
6029 }
2830ca53
PN
6030 dictReleaseIterator(di);
6031 }
6032 } else if (op == REDIS_OP_UNION) {
6033 for (i = 0; i < zsetnum; i++) {
8f92e768 6034 if (!src[i].dict) continue;
2830ca53 6035
8f92e768 6036 di = dictGetIterator(src[i].dict);
2830ca53
PN
6037 while((de = dictNext(di)) != NULL) {
6038 /* skip key when already processed */
6039 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
6040
d2764cd6
PN
6041 double *score = zmalloc(sizeof(double)), value;
6042 *score = src[i].weight * (*(double*)dictGetEntryVal(de));
2830ca53 6043
d2764cd6
PN
6044 /* because the zsets are sorted by size, its only possible
6045 * for sets at larger indices to hold this entry */
6046 for (j = (i+1); j < zsetnum; j++) {
6047 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
2830ca53 6048 if (other) {
d2764cd6
PN
6049 value = src[j].weight * (*(double*)dictGetEntryVal(other));
6050 zunionInterAggregate(score, value, aggregate);
2830ca53
PN
6051 }
6052 }
b287c9bb 6053
2830ca53
PN
6054 robj *o = dictGetEntryKey(de);
6055 dictAdd(dstzset->dict,o,score);
6056 incrRefCount(o); /* added to dictionary */
6057 zslInsert(dstzset->zsl,*score,o);
6058 incrRefCount(o); /* added to skiplist */
6059 }
6060 dictReleaseIterator(di);
b287c9bb 6061 }
2830ca53
PN
6062 } else {
6063 /* unknown operator */
6064 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
b287c9bb
PN
6065 }
6066
6067 deleteKey(c->db,dstkey);
3ea27d37 6068 if (dstzset->zsl->length) {
6069 dictAdd(c->db->dict,dstkey,dstobj);
6070 incrRefCount(dstkey);
482b672d 6071 addReplyLongLong(c, dstzset->zsl->length);
3ea27d37 6072 server.dirty++;
6073 } else {
8bca8773 6074 decrRefCount(dstobj);
3ea27d37 6075 addReply(c, shared.czero);
6076 }
8f92e768 6077 zfree(src);
b287c9bb
PN
6078}
6079
5d373da9 6080static void zunionstoreCommand(redisClient *c) {
2830ca53 6081 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
b287c9bb
PN
6082}
6083
5d373da9 6084static void zinterstoreCommand(redisClient *c) {
2830ca53 6085 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
b287c9bb
PN
6086}
6087
e3870fab 6088static void zrangeGenericCommand(redisClient *c, int reverse) {
cc812361 6089 robj *o;
bbe025e0
AM
6090 long start;
6091 long end;
752da584 6092 int withscores = 0;
dd88747b 6093 int llen;
6094 int rangelen, j;
6095 zset *zsetobj;
6096 zskiplist *zsl;
6097 zskiplistNode *ln;
6098 robj *ele;
752da584 6099
bd79a6bd
PN
6100 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
6101 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
bbe025e0 6102
752da584 6103 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
6104 withscores = 1;
6105 } else if (c->argc >= 5) {
6106 addReply(c,shared.syntaxerr);
6107 return;
6108 }
cc812361 6109
4e27f268 6110 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
6111 || checkType(c,o,REDIS_ZSET)) return;
dd88747b 6112 zsetobj = o->ptr;
6113 zsl = zsetobj->zsl;
6114 llen = zsl->length;
cc812361 6115
dd88747b 6116 /* convert negative indexes */
6117 if (start < 0) start = llen+start;
6118 if (end < 0) end = llen+end;
6119 if (start < 0) start = 0;
6120 if (end < 0) end = 0;
cc812361 6121
dd88747b 6122 /* indexes sanity checks */
6123 if (start > end || start >= llen) {
6124 /* Out of range start or start > end result in empty list */
6125 addReply(c,shared.emptymultibulk);
6126 return;
6127 }
6128 if (end >= llen) end = llen-1;
6129 rangelen = (end-start)+1;
cc812361 6130
dd88747b 6131 /* check if starting point is trivial, before searching
6132 * the element in log(N) time */
6133 if (reverse) {
6134 ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start);
6135 } else {
6136 ln = start == 0 ?
6137 zsl->header->forward[0] : zslGetElementByRank(zsl, start+1);
6138 }
cc812361 6139
dd88747b 6140 /* Return the result in form of a multi-bulk reply */
6141 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
6142 withscores ? (rangelen*2) : rangelen));
6143 for (j = 0; j < rangelen; j++) {
6144 ele = ln->obj;
6145 addReplyBulk(c,ele);
6146 if (withscores)
6147 addReplyDouble(c,ln->score);
6148 ln = reverse ? ln->backward : ln->forward[0];
cc812361 6149 }
6150}
6151
e3870fab 6152static void zrangeCommand(redisClient *c) {
6153 zrangeGenericCommand(c,0);
6154}
6155
6156static void zrevrangeCommand(redisClient *c) {
6157 zrangeGenericCommand(c,1);
6158}
6159
f44dd428 6160/* This command implements both ZRANGEBYSCORE and ZCOUNT.
6161 * If justcount is non-zero, just the count is returned. */
6162static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
50c55df5 6163 robj *o;
f44dd428 6164 double min, max;
6165 int minex = 0, maxex = 0; /* are min or max exclusive? */
80181f78 6166 int offset = 0, limit = -1;
0500ef27
SH
6167 int withscores = 0;
6168 int badsyntax = 0;
6169
f44dd428 6170 /* Parse the min-max interval. If one of the values is prefixed
6171 * by the "(" character, it's considered "open". For instance
6172 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6173 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6174 if (((char*)c->argv[2]->ptr)[0] == '(') {
6175 min = strtod((char*)c->argv[2]->ptr+1,NULL);
6176 minex = 1;
6177 } else {
6178 min = strtod(c->argv[2]->ptr,NULL);
6179 }
6180 if (((char*)c->argv[3]->ptr)[0] == '(') {
6181 max = strtod((char*)c->argv[3]->ptr+1,NULL);
6182 maxex = 1;
6183 } else {
6184 max = strtod(c->argv[3]->ptr,NULL);
6185 }
6186
6187 /* Parse "WITHSCORES": note that if the command was called with
6188 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6189 * enter the following paths to parse WITHSCORES and LIMIT. */
0500ef27 6190 if (c->argc == 5 || c->argc == 8) {
3a3978b1 6191 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
6192 withscores = 1;
6193 else
6194 badsyntax = 1;
0500ef27 6195 }
3a3978b1 6196 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
0500ef27 6197 badsyntax = 1;
0500ef27 6198 if (badsyntax) {
454d4e43 6199 addReplySds(c,
6200 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
80181f78 6201 return;
0500ef27
SH
6202 }
6203
f44dd428 6204 /* Parse "LIMIT" */
0500ef27 6205 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
80181f78 6206 addReply(c,shared.syntaxerr);
6207 return;
0500ef27 6208 } else if (c->argc == (7 + withscores)) {
80181f78 6209 offset = atoi(c->argv[5]->ptr);
6210 limit = atoi(c->argv[6]->ptr);
0b13687c 6211 if (offset < 0) offset = 0;
80181f78 6212 }
50c55df5 6213
f44dd428 6214 /* Ok, lookup the key and get the range */
50c55df5 6215 o = lookupKeyRead(c->db,c->argv[1]);
6216 if (o == NULL) {
4e27f268 6217 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
50c55df5 6218 } else {
6219 if (o->type != REDIS_ZSET) {
6220 addReply(c,shared.wrongtypeerr);
6221 } else {
6222 zset *zsetobj = o->ptr;
6223 zskiplist *zsl = zsetobj->zsl;
6224 zskiplistNode *ln;
f44dd428 6225 robj *ele, *lenobj = NULL;
6226 unsigned long rangelen = 0;
50c55df5 6227
f44dd428 6228 /* Get the first node with the score >= min, or with
6229 * score > min if 'minex' is true. */
50c55df5 6230 ln = zslFirstWithScore(zsl,min);
f44dd428 6231 while (minex && ln && ln->score == min) ln = ln->forward[0];
6232
50c55df5 6233 if (ln == NULL) {
6234 /* No element matching the speciifed interval */
f44dd428 6235 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
50c55df5 6236 return;
6237 }
6238
6239 /* We don't know in advance how many matching elements there
6240 * are in the list, so we push this object that will represent
6241 * the multi-bulk length in the output buffer, and will "fix"
6242 * it later */
f44dd428 6243 if (!justcount) {
6244 lenobj = createObject(REDIS_STRING,NULL);
6245 addReply(c,lenobj);
6246 decrRefCount(lenobj);
6247 }
50c55df5 6248
f44dd428 6249 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
80181f78 6250 if (offset) {
6251 offset--;
6252 ln = ln->forward[0];
6253 continue;
6254 }
6255 if (limit == 0) break;
f44dd428 6256 if (!justcount) {
6257 ele = ln->obj;
dd88747b 6258 addReplyBulk(c,ele);
f44dd428 6259 if (withscores)
6260 addReplyDouble(c,ln->score);
6261 }
50c55df5 6262 ln = ln->forward[0];
6263 rangelen++;
80181f78 6264 if (limit > 0) limit--;
50c55df5 6265 }
f44dd428 6266 if (justcount) {
482b672d 6267 addReplyLongLong(c,(long)rangelen);
f44dd428 6268 } else {
6269 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
6270 withscores ? (rangelen*2) : rangelen);
6271 }
50c55df5 6272 }
6273 }
6274}
6275
f44dd428 6276static void zrangebyscoreCommand(redisClient *c) {
6277 genericZrangebyscoreCommand(c,0);
6278}
6279
6280static void zcountCommand(redisClient *c) {
6281 genericZrangebyscoreCommand(c,1);
6282}
6283
3c41331e 6284static void zcardCommand(redisClient *c) {
e197b441 6285 robj *o;
6286 zset *zs;
dd88747b 6287
6288 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6289 checkType(c,o,REDIS_ZSET)) return;
6290
6291 zs = o->ptr;
6292 addReplyUlong(c,zs->zsl->length);
e197b441 6293}
6294
6e333bbe 6295static void zscoreCommand(redisClient *c) {
6296 robj *o;
6297 zset *zs;
dd88747b 6298 dictEntry *de;
6299
6300 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6301 checkType(c,o,REDIS_ZSET)) return;
6302
6303 zs = o->ptr;
6304 de = dictFind(zs->dict,c->argv[2]);
6305 if (!de) {
96d8b4ee 6306 addReply(c,shared.nullbulk);
6e333bbe 6307 } else {
dd88747b 6308 double *score = dictGetEntryVal(de);
6e333bbe 6309
dd88747b 6310 addReplyDouble(c,*score);
6e333bbe 6311 }
6312}
6313
798d9e55 6314static void zrankGenericCommand(redisClient *c, int reverse) {
69d95c3e 6315 robj *o;
dd88747b 6316 zset *zs;
6317 zskiplist *zsl;
6318 dictEntry *de;
6319 unsigned long rank;
6320 double *score;
6321
6322 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6323 checkType(c,o,REDIS_ZSET)) return;
6324
6325 zs = o->ptr;
6326 zsl = zs->zsl;
6327 de = dictFind(zs->dict,c->argv[2]);
6328 if (!de) {
69d95c3e
PN
6329 addReply(c,shared.nullbulk);
6330 return;
6331 }
69d95c3e 6332
dd88747b 6333 score = dictGetEntryVal(de);
6334 rank = zslGetRank(zsl, *score, c->argv[2]);
6335 if (rank) {
6336 if (reverse) {
482b672d 6337 addReplyLongLong(c, zsl->length - rank);
27b0ccca 6338 } else {
482b672d 6339 addReplyLongLong(c, rank-1);
69d95c3e 6340 }
dd88747b 6341 } else {
6342 addReply(c,shared.nullbulk);
978c2c94 6343 }
6344}
6345
798d9e55
PN
6346static void zrankCommand(redisClient *c) {
6347 zrankGenericCommand(c, 0);
6348}
6349
6350static void zrevrankCommand(redisClient *c) {
6351 zrankGenericCommand(c, 1);
6352}
6353
7fb16bac
PN
6354/* ========================= Hashes utility functions ======================= */
6355#define REDIS_HASH_KEY 1
6356#define REDIS_HASH_VALUE 2
978c2c94 6357
7fb16bac
PN
6358/* Check the length of a number of objects to see if we need to convert a
6359 * zipmap to a real hash. Note that we only check string encoded objects
6360 * as their string length can be queried in constant time. */
6361static void hashTryConversion(robj *subject, robj **argv, int start, int end) {
6362 int i;
6363 if (subject->encoding != REDIS_ENCODING_ZIPMAP) return;
978c2c94 6364
7fb16bac
PN
6365 for (i = start; i <= end; i++) {
6366 if (argv[i]->encoding == REDIS_ENCODING_RAW &&
6367 sdslen(argv[i]->ptr) > server.hash_max_zipmap_value)
6368 {
6369 convertToRealHash(subject);
978c2c94 6370 return;
6371 }
6372 }
7fb16bac 6373}
bae2c7ec 6374
97224de7
PN
6375/* Encode given objects in-place when the hash uses a dict. */
6376static void hashTryObjectEncoding(robj *subject, robj **o1, robj **o2) {
6377 if (subject->encoding == REDIS_ENCODING_HT) {
3f973463
PN
6378 if (o1) *o1 = tryObjectEncoding(*o1);
6379 if (o2) *o2 = tryObjectEncoding(*o2);
97224de7
PN
6380 }
6381}
6382
7fb16bac 6383/* Get the value from a hash identified by key. Returns either a string
a3f3af86
PN
6384 * object or NULL if the value cannot be found. The refcount of the object
6385 * is always increased by 1 when the value was found. */
7fb16bac
PN
6386static robj *hashGet(robj *o, robj *key) {
6387 robj *value = NULL;
978c2c94 6388 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
7fb16bac
PN
6389 unsigned char *v;
6390 unsigned int vlen;
6391 key = getDecodedObject(key);
6392 if (zipmapGet(o->ptr,key->ptr,sdslen(key->ptr),&v,&vlen)) {
6393 value = createStringObject((char*)v,vlen);
6394 }
6395 decrRefCount(key);
6396 } else {
6397 dictEntry *de = dictFind(o->ptr,key);
6398 if (de != NULL) {
6399 value = dictGetEntryVal(de);
a3f3af86 6400 incrRefCount(value);
7fb16bac
PN
6401 }
6402 }
6403 return value;
6404}
978c2c94 6405
7fb16bac
PN
6406/* Test if the key exists in the given hash. Returns 1 if the key
6407 * exists and 0 when it doesn't. */
6408static int hashExists(robj *o, robj *key) {
6409 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6410 key = getDecodedObject(key);
6411 if (zipmapExists(o->ptr,key->ptr,sdslen(key->ptr))) {
6412 decrRefCount(key);
6413 return 1;
6414 }
6415 decrRefCount(key);
6416 } else {
6417 if (dictFind(o->ptr,key) != NULL) {
6418 return 1;
6419 }
6420 }
6421 return 0;
6422}
bae2c7ec 6423
7fb16bac
PN
6424/* Add an element, discard the old if the key already exists.
6425 * Return 0 on insert and 1 on update. */
feb8d7e6 6426static int hashSet(robj *o, robj *key, robj *value) {
7fb16bac
PN
6427 int update = 0;
6428 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6429 key = getDecodedObject(key);
6430 value = getDecodedObject(value);
6431 o->ptr = zipmapSet(o->ptr,
6432 key->ptr,sdslen(key->ptr),
6433 value->ptr,sdslen(value->ptr), &update);
6434 decrRefCount(key);
6435 decrRefCount(value);
6436
6437 /* Check if the zipmap needs to be upgraded to a real hash table */
6438 if (zipmapLen(o->ptr) > server.hash_max_zipmap_entries)
bae2c7ec 6439 convertToRealHash(o);
978c2c94 6440 } else {
7fb16bac
PN
6441 if (dictReplace(o->ptr,key,value)) {
6442 /* Insert */
6443 incrRefCount(key);
978c2c94 6444 } else {
7fb16bac 6445 /* Update */
978c2c94 6446 update = 1;
6447 }
7fb16bac 6448 incrRefCount(value);
978c2c94 6449 }
7fb16bac 6450 return update;
978c2c94 6451}
6452
7fb16bac
PN
6453/* Delete an element from a hash.
6454 * Return 1 on deleted and 0 on not found. */
6455static int hashDelete(robj *o, robj *key) {
6456 int deleted = 0;
6457 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
6458 key = getDecodedObject(key);
6459 o->ptr = zipmapDel(o->ptr,key->ptr,sdslen(key->ptr), &deleted);
6460 decrRefCount(key);
6461 } else {
6462 deleted = dictDelete((dict*)o->ptr,key) == DICT_OK;
6463 /* Always check if the dictionary needs a resize after a delete. */
6464 if (deleted && htNeedsResize(o->ptr)) dictResize(o->ptr);
d33278d1 6465 }
7fb16bac
PN
6466 return deleted;
6467}
d33278d1 6468
7fb16bac 6469/* Return the number of elements in a hash. */
c811bb38 6470static unsigned long hashLength(robj *o) {
7fb16bac
PN
6471 return (o->encoding == REDIS_ENCODING_ZIPMAP) ?
6472 zipmapLen((unsigned char*)o->ptr) : dictSize((dict*)o->ptr);
6473}
6474
6475/* Structure to hold hash iteration abstration. Note that iteration over
6476 * hashes involves both fields and values. Because it is possible that
6477 * not both are required, store pointers in the iterator to avoid
6478 * unnecessary memory allocation for fields/values. */
6479typedef struct {
6480 int encoding;
6481 unsigned char *zi;
6482 unsigned char *zk, *zv;
6483 unsigned int zklen, zvlen;
6484
6485 dictIterator *di;
6486 dictEntry *de;
6487} hashIterator;
6488
c44d3b56
PN
6489static hashIterator *hashInitIterator(robj *subject) {
6490 hashIterator *hi = zmalloc(sizeof(hashIterator));
7fb16bac
PN
6491 hi->encoding = subject->encoding;
6492 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6493 hi->zi = zipmapRewind(subject->ptr);
6494 } else if (hi->encoding == REDIS_ENCODING_HT) {
6495 hi->di = dictGetIterator(subject->ptr);
d33278d1 6496 } else {
7fb16bac 6497 redisAssert(NULL);
d33278d1 6498 }
c44d3b56 6499 return hi;
7fb16bac 6500}
d33278d1 6501
7fb16bac
PN
6502static void hashReleaseIterator(hashIterator *hi) {
6503 if (hi->encoding == REDIS_ENCODING_HT) {
6504 dictReleaseIterator(hi->di);
d33278d1 6505 }
c44d3b56 6506 zfree(hi);
7fb16bac 6507}
d33278d1 6508
7fb16bac
PN
6509/* Move to the next entry in the hash. Return REDIS_OK when the next entry
6510 * could be found and REDIS_ERR when the iterator reaches the end. */
c811bb38 6511static int hashNext(hashIterator *hi) {
7fb16bac
PN
6512 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6513 if ((hi->zi = zipmapNext(hi->zi, &hi->zk, &hi->zklen,
6514 &hi->zv, &hi->zvlen)) == NULL) return REDIS_ERR;
6515 } else {
6516 if ((hi->de = dictNext(hi->di)) == NULL) return REDIS_ERR;
6517 }
6518 return REDIS_OK;
6519}
d33278d1 6520
0c390abc 6521/* Get key or value object at current iteration position.
a3f3af86 6522 * This increases the refcount of the field object by 1. */
c811bb38 6523static robj *hashCurrent(hashIterator *hi, int what) {
7fb16bac
PN
6524 robj *o;
6525 if (hi->encoding == REDIS_ENCODING_ZIPMAP) {
6526 if (what & REDIS_HASH_KEY) {
6527 o = createStringObject((char*)hi->zk,hi->zklen);
6528 } else {
6529 o = createStringObject((char*)hi->zv,hi->zvlen);
d33278d1 6530 }
d33278d1 6531 } else {
7fb16bac
PN
6532 if (what & REDIS_HASH_KEY) {
6533 o = dictGetEntryKey(hi->de);
6534 } else {
6535 o = dictGetEntryVal(hi->de);
d33278d1 6536 }
a3f3af86 6537 incrRefCount(o);
d33278d1 6538 }
7fb16bac 6539 return o;
d33278d1
PN
6540}
6541
7fb16bac
PN
6542static robj *hashLookupWriteOrCreate(redisClient *c, robj *key) {
6543 robj *o = lookupKeyWrite(c->db,key);
01426b05
PN
6544 if (o == NULL) {
6545 o = createHashObject();
7fb16bac
PN
6546 dictAdd(c->db->dict,key,o);
6547 incrRefCount(key);
01426b05
PN
6548 } else {
6549 if (o->type != REDIS_HASH) {
6550 addReply(c,shared.wrongtypeerr);
7fb16bac 6551 return NULL;
01426b05
PN
6552 }
6553 }
7fb16bac
PN
6554 return o;
6555}
01426b05 6556
7fb16bac
PN
6557/* ============================= Hash commands ============================== */
6558static void hsetCommand(redisClient *c) {
6e9e463f 6559 int update;
7fb16bac 6560 robj *o;
bbe025e0 6561
7fb16bac
PN
6562 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6563 hashTryConversion(o,c->argv,2,3);
97224de7 6564 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
feb8d7e6 6565 update = hashSet(o,c->argv[2],c->argv[3]);
6e9e463f 6566 addReply(c, update ? shared.czero : shared.cone);
7fb16bac
PN
6567 server.dirty++;
6568}
01426b05 6569
1f1c7695
PN
6570static void hsetnxCommand(redisClient *c) {
6571 robj *o;
6572 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6573 hashTryConversion(o,c->argv,2,3);
6574
6575 if (hashExists(o, c->argv[2])) {
6576 addReply(c, shared.czero);
01426b05 6577 } else {
97224de7 6578 hashTryObjectEncoding(o,&c->argv[2], &c->argv[3]);
feb8d7e6 6579 hashSet(o,c->argv[2],c->argv[3]);
1f1c7695
PN
6580 addReply(c, shared.cone);
6581 server.dirty++;
6582 }
6583}
01426b05 6584
7fb16bac
PN
6585static void hmsetCommand(redisClient *c) {
6586 int i;
6587 robj *o;
01426b05 6588
7fb16bac
PN
6589 if ((c->argc % 2) == 1) {
6590 addReplySds(c,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6591 return;
6592 }
01426b05 6593
7fb16bac
PN
6594 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6595 hashTryConversion(o,c->argv,2,c->argc-1);
6596 for (i = 2; i < c->argc; i += 2) {
97224de7 6597 hashTryObjectEncoding(o,&c->argv[i], &c->argv[i+1]);
feb8d7e6 6598 hashSet(o,c->argv[i],c->argv[i+1]);
7fb16bac
PN
6599 }
6600 addReply(c, shared.ok);
edc2f63a 6601 server.dirty++;
7fb16bac
PN
6602}
6603
6604static void hincrbyCommand(redisClient *c) {
6605 long long value, incr;
6606 robj *o, *current, *new;
6607
bd79a6bd 6608 if (getLongLongFromObjectOrReply(c,c->argv[3],&incr,NULL) != REDIS_OK) return;
7fb16bac
PN
6609 if ((o = hashLookupWriteOrCreate(c,c->argv[1])) == NULL) return;
6610 if ((current = hashGet(o,c->argv[2])) != NULL) {
946342c1
PN
6611 if (getLongLongFromObjectOrReply(c,current,&value,
6612 "hash value is not an integer") != REDIS_OK) {
6613 decrRefCount(current);
6614 return;
6615 }
a3f3af86 6616 decrRefCount(current);
7fb16bac
PN
6617 } else {
6618 value = 0;
01426b05
PN
6619 }
6620
7fb16bac 6621 value += incr;
3f973463
PN
6622 new = createStringObjectFromLongLong(value);
6623 hashTryObjectEncoding(o,&c->argv[2],NULL);
feb8d7e6 6624 hashSet(o,c->argv[2],new);
7fb16bac
PN
6625 decrRefCount(new);
6626 addReplyLongLong(c,value);
01426b05 6627 server.dirty++;
01426b05
PN
6628}
6629
978c2c94 6630static void hgetCommand(redisClient *c) {
7fb16bac 6631 robj *o, *value;
dd88747b 6632 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
6633 checkType(c,o,REDIS_HASH)) return;
6634
7fb16bac
PN
6635 if ((value = hashGet(o,c->argv[2])) != NULL) {
6636 addReplyBulk(c,value);
a3f3af86 6637 decrRefCount(value);
dd88747b 6638 } else {
7fb16bac 6639 addReply(c,shared.nullbulk);
69d95c3e 6640 }
69d95c3e
PN
6641}
6642
09aeb579
PN
6643static void hmgetCommand(redisClient *c) {
6644 int i;
7fb16bac
PN
6645 robj *o, *value;
6646 o = lookupKeyRead(c->db,c->argv[1]);
6647 if (o != NULL && o->type != REDIS_HASH) {
6648 addReply(c,shared.wrongtypeerr);
09aeb579
PN
6649 }
6650
7fb16bac
PN
6651 /* Note the check for o != NULL happens inside the loop. This is
6652 * done because objects that cannot be found are considered to be
6653 * an empty hash. The reply should then be a series of NULLs. */
09aeb579 6654 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-2));
7fb16bac
PN
6655 for (i = 2; i < c->argc; i++) {
6656 if (o != NULL && (value = hashGet(o,c->argv[i])) != NULL) {
6657 addReplyBulk(c,value);
a3f3af86 6658 decrRefCount(value);
7fb16bac
PN
6659 } else {
6660 addReply(c,shared.nullbulk);
09aeb579
PN
6661 }
6662 }
6663}
6664
07efaf74 6665static void hdelCommand(redisClient *c) {
dd88747b 6666 robj *o;
dd88747b 6667 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
6668 checkType(c,o,REDIS_HASH)) return;
07efaf74 6669
7fb16bac
PN
6670 if (hashDelete(o,c->argv[2])) {
6671 if (hashLength(o) == 0) deleteKey(c->db,c->argv[1]);
6672 addReply(c,shared.cone);
6673 server.dirty++;
dd88747b 6674 } else {
7fb16bac 6675 addReply(c,shared.czero);
07efaf74 6676 }
6677}
6678
92b27fe9 6679static void hlenCommand(redisClient *c) {
6680 robj *o;
dd88747b 6681 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
92b27fe9 6682 checkType(c,o,REDIS_HASH)) return;
6683
7fb16bac 6684 addReplyUlong(c,hashLength(o));
92b27fe9 6685}
6686
78409a0f 6687static void genericHgetallCommand(redisClient *c, int flags) {
7fb16bac 6688 robj *o, *lenobj, *obj;
78409a0f 6689 unsigned long count = 0;
c44d3b56 6690 hashIterator *hi;
78409a0f 6691
4e27f268 6692 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
78409a0f 6693 || checkType(c,o,REDIS_HASH)) return;
6694
6695 lenobj = createObject(REDIS_STRING,NULL);
6696 addReply(c,lenobj);
6697 decrRefCount(lenobj);
6698
c44d3b56
PN
6699 hi = hashInitIterator(o);
6700 while (hashNext(hi) != REDIS_ERR) {
7fb16bac 6701 if (flags & REDIS_HASH_KEY) {
c44d3b56 6702 obj = hashCurrent(hi,REDIS_HASH_KEY);
7fb16bac 6703 addReplyBulk(c,obj);
a3f3af86 6704 decrRefCount(obj);
7fb16bac 6705 count++;
78409a0f 6706 }
7fb16bac 6707 if (flags & REDIS_HASH_VALUE) {
c44d3b56 6708 obj = hashCurrent(hi,REDIS_HASH_VALUE);
7fb16bac 6709 addReplyBulk(c,obj);
a3f3af86 6710 decrRefCount(obj);
7fb16bac 6711 count++;
78409a0f 6712 }
78409a0f 6713 }
c44d3b56 6714 hashReleaseIterator(hi);
7fb16bac 6715
78409a0f 6716 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",count);
6717}
6718
6719static void hkeysCommand(redisClient *c) {
7fb16bac 6720 genericHgetallCommand(c,REDIS_HASH_KEY);
78409a0f 6721}
6722
6723static void hvalsCommand(redisClient *c) {
7fb16bac 6724 genericHgetallCommand(c,REDIS_HASH_VALUE);
78409a0f 6725}
6726
6727static void hgetallCommand(redisClient *c) {
7fb16bac 6728 genericHgetallCommand(c,REDIS_HASH_KEY|REDIS_HASH_VALUE);
78409a0f 6729}
6730
a86f14b1 6731static void hexistsCommand(redisClient *c) {
6732 robj *o;
a86f14b1 6733 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
6734 checkType(c,o,REDIS_HASH)) return;
6735
7fb16bac 6736 addReply(c, hashExists(o,c->argv[2]) ? shared.cone : shared.czero);
a86f14b1 6737}
6738
ada386b2 6739static void convertToRealHash(robj *o) {
6740 unsigned char *key, *val, *p, *zm = o->ptr;
6741 unsigned int klen, vlen;
6742 dict *dict = dictCreate(&hashDictType,NULL);
6743
6744 assert(o->type == REDIS_HASH && o->encoding != REDIS_ENCODING_HT);
6745 p = zipmapRewind(zm);
6746 while((p = zipmapNext(p,&key,&klen,&val,&vlen)) != NULL) {
6747 robj *keyobj, *valobj;
6748
6749 keyobj = createStringObject((char*)key,klen);
6750 valobj = createStringObject((char*)val,vlen);
05df7621 6751 keyobj = tryObjectEncoding(keyobj);
6752 valobj = tryObjectEncoding(valobj);
ada386b2 6753 dictAdd(dict,keyobj,valobj);
6754 }
6755 o->encoding = REDIS_ENCODING_HT;
6756 o->ptr = dict;
6757 zfree(zm);
6758}
6759
6b47e12e 6760/* ========================= Non type-specific commands ==================== */
6761
ed9b544e 6762static void flushdbCommand(redisClient *c) {
ca37e9cd 6763 server.dirty += dictSize(c->db->dict);
3305306f 6764 dictEmpty(c->db->dict);
6765 dictEmpty(c->db->expires);
ed9b544e 6766 addReply(c,shared.ok);
ed9b544e 6767}
6768
6769static void flushallCommand(redisClient *c) {
ca37e9cd 6770 server.dirty += emptyDb();
ed9b544e 6771 addReply(c,shared.ok);
500ece7c 6772 if (server.bgsavechildpid != -1) {
6773 kill(server.bgsavechildpid,SIGKILL);
6774 rdbRemoveTempFile(server.bgsavechildpid);
6775 }
f78fd11b 6776 rdbSave(server.dbfilename);
ca37e9cd 6777 server.dirty++;
ed9b544e 6778}
6779
56906eef 6780static redisSortOperation *createSortOperation(int type, robj *pattern) {
ed9b544e 6781 redisSortOperation *so = zmalloc(sizeof(*so));
ed9b544e 6782 so->type = type;
6783 so->pattern = pattern;
6784 return so;
6785}
6786
6787/* Return the value associated to the key with a name obtained
55017f9d
PN
6788 * substituting the first occurence of '*' in 'pattern' with 'subst'.
6789 * The returned object will always have its refcount increased by 1
6790 * when it is non-NULL. */
56906eef 6791static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
6d7d1370 6792 char *p, *f;
ed9b544e 6793 sds spat, ssub;
6d7d1370
PN
6794 robj keyobj, fieldobj, *o;
6795 int prefixlen, sublen, postfixlen, fieldlen;
ed9b544e 6796 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6797 struct {
f1017b3f 6798 long len;
6799 long free;
ed9b544e 6800 char buf[REDIS_SORTKEY_MAX+1];
6d7d1370 6801 } keyname, fieldname;
ed9b544e 6802
28173a49 6803 /* If the pattern is "#" return the substitution object itself in order
6804 * to implement the "SORT ... GET #" feature. */
6805 spat = pattern->ptr;
6806 if (spat[0] == '#' && spat[1] == '\0') {
55017f9d 6807 incrRefCount(subst);
28173a49 6808 return subst;
6809 }
6810
6811 /* The substitution object may be specially encoded. If so we create
9d65a1bb 6812 * a decoded object on the fly. Otherwise getDecodedObject will just
6813 * increment the ref count, that we'll decrement later. */
6814 subst = getDecodedObject(subst);
942a3961 6815
ed9b544e 6816 ssub = subst->ptr;
6817 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
6818 p = strchr(spat,'*');
ed5a857a 6819 if (!p) {
6820 decrRefCount(subst);
6821 return NULL;
6822 }
ed9b544e 6823
6d7d1370
PN
6824 /* Find out if we're dealing with a hash dereference. */
6825 if ((f = strstr(p+1, "->")) != NULL) {
6826 fieldlen = sdslen(spat)-(f-spat);
6827 /* this also copies \0 character */
6828 memcpy(fieldname.buf,f+2,fieldlen-1);
6829 fieldname.len = fieldlen-2;
6830 } else {
6831 fieldlen = 0;
6832 }
6833
ed9b544e 6834 prefixlen = p-spat;
6835 sublen = sdslen(ssub);
6d7d1370 6836 postfixlen = sdslen(spat)-(prefixlen+1)-fieldlen;
ed9b544e 6837 memcpy(keyname.buf,spat,prefixlen);
6838 memcpy(keyname.buf+prefixlen,ssub,sublen);
6839 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
6840 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
6841 keyname.len = prefixlen+sublen+postfixlen;
942a3961 6842 decrRefCount(subst);
6843
6d7d1370
PN
6844 /* Lookup substituted key */
6845 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2));
6846 o = lookupKeyRead(db,&keyobj);
55017f9d
PN
6847 if (o == NULL) return NULL;
6848
6849 if (fieldlen > 0) {
6850 if (o->type != REDIS_HASH || fieldname.len < 1) return NULL;
6d7d1370 6851
705dad38
PN
6852 /* Retrieve value from hash by the field name. This operation
6853 * already increases the refcount of the returned object. */
6d7d1370
PN
6854 initStaticStringObject(fieldobj,((char*)&fieldname)+(sizeof(long)*2));
6855 o = hashGet(o, &fieldobj);
705dad38 6856 } else {
55017f9d 6857 if (o->type != REDIS_STRING) return NULL;
b6f07345 6858
705dad38
PN
6859 /* Every object that this function returns needs to have its refcount
6860 * increased. sortCommand decreases it again. */
6861 incrRefCount(o);
6d7d1370
PN
6862 }
6863
6864 return o;
ed9b544e 6865}
6866
6867/* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6868 * the additional parameter is not standard but a BSD-specific we have to
6869 * pass sorting parameters via the global 'server' structure */
6870static int sortCompare(const void *s1, const void *s2) {
6871 const redisSortObject *so1 = s1, *so2 = s2;
6872 int cmp;
6873
6874 if (!server.sort_alpha) {
6875 /* Numeric sorting. Here it's trivial as we precomputed scores */
6876 if (so1->u.score > so2->u.score) {
6877 cmp = 1;
6878 } else if (so1->u.score < so2->u.score) {
6879 cmp = -1;
6880 } else {
6881 cmp = 0;
6882 }
6883 } else {
6884 /* Alphanumeric sorting */
6885 if (server.sort_bypattern) {
6886 if (!so1->u.cmpobj || !so2->u.cmpobj) {
6887 /* At least one compare object is NULL */
6888 if (so1->u.cmpobj == so2->u.cmpobj)
6889 cmp = 0;
6890 else if (so1->u.cmpobj == NULL)
6891 cmp = -1;
6892 else
6893 cmp = 1;
6894 } else {
6895 /* We have both the objects, use strcoll */
6896 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
6897 }
6898 } else {
08ee9b57 6899 /* Compare elements directly. */
6900 cmp = compareStringObjects(so1->obj,so2->obj);
ed9b544e 6901 }
6902 }
6903 return server.sort_desc ? -cmp : cmp;
6904}
6905
6906/* The SORT command is the most complex command in Redis. Warning: this code
6907 * is optimized for speed and a bit less for readability */
6908static void sortCommand(redisClient *c) {
ed9b544e 6909 list *operations;
6910 int outputlen = 0;
6911 int desc = 0, alpha = 0;
6912 int limit_start = 0, limit_count = -1, start, end;
6913 int j, dontsort = 0, vectorlen;
6914 int getop = 0; /* GET operation counter */
443c6409 6915 robj *sortval, *sortby = NULL, *storekey = NULL;
ed9b544e 6916 redisSortObject *vector; /* Resulting vector to sort */
6917
6918 /* Lookup the key to sort. It must be of the right types */
3305306f 6919 sortval = lookupKeyRead(c->db,c->argv[1]);
6920 if (sortval == NULL) {
4e27f268 6921 addReply(c,shared.emptymultibulk);
ed9b544e 6922 return;
6923 }
a5eb649b 6924 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
6925 sortval->type != REDIS_ZSET)
6926 {
c937aa89 6927 addReply(c,shared.wrongtypeerr);
ed9b544e 6928 return;
6929 }
6930
6931 /* Create a list of operations to perform for every sorted element.
6932 * Operations can be GET/DEL/INCR/DECR */
6933 operations = listCreate();
092dac2a 6934 listSetFreeMethod(operations,zfree);
ed9b544e 6935 j = 2;
6936
6937 /* Now we need to protect sortval incrementing its count, in the future
6938 * SORT may have options able to overwrite/delete keys during the sorting
6939 * and the sorted key itself may get destroied */
6940 incrRefCount(sortval);
6941
6942 /* The SORT command has an SQL-alike syntax, parse it */
6943 while(j < c->argc) {
6944 int leftargs = c->argc-j-1;
6945 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
6946 desc = 0;
6947 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
6948 desc = 1;
6949 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
6950 alpha = 1;
6951 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
6952 limit_start = atoi(c->argv[j+1]->ptr);
6953 limit_count = atoi(c->argv[j+2]->ptr);
6954 j+=2;
443c6409 6955 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
6956 storekey = c->argv[j+1];
6957 j++;
ed9b544e 6958 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
6959 sortby = c->argv[j+1];
6960 /* If the BY pattern does not contain '*', i.e. it is constant,
6961 * we don't need to sort nor to lookup the weight keys. */
6962 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
6963 j++;
6964 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
6965 listAddNodeTail(operations,createSortOperation(
6966 REDIS_SORT_GET,c->argv[j+1]));
6967 getop++;
6968 j++;
ed9b544e 6969 } else {
6970 decrRefCount(sortval);
6971 listRelease(operations);
c937aa89 6972 addReply(c,shared.syntaxerr);
ed9b544e 6973 return;
6974 }
6975 j++;
6976 }
6977
6978 /* Load the sorting vector with all the objects to sort */
a5eb649b 6979 switch(sortval->type) {
6980 case REDIS_LIST: vectorlen = listLength((list*)sortval->ptr); break;
6981 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
6982 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
f83c6cb5 6983 default: vectorlen = 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
a5eb649b 6984 }
ed9b544e 6985 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
ed9b544e 6986 j = 0;
a5eb649b 6987
ed9b544e 6988 if (sortval->type == REDIS_LIST) {
6989 list *list = sortval->ptr;
6208b3a7 6990 listNode *ln;
c7df85a4 6991 listIter li;
6208b3a7 6992
c7df85a4 6993 listRewind(list,&li);
6994 while((ln = listNext(&li))) {
ed9b544e 6995 robj *ele = ln->value;
6996 vector[j].obj = ele;
6997 vector[j].u.score = 0;
6998 vector[j].u.cmpobj = NULL;
ed9b544e 6999 j++;
7000 }
7001 } else {
a5eb649b 7002 dict *set;
ed9b544e 7003 dictIterator *di;
7004 dictEntry *setele;
7005
a5eb649b 7006 if (sortval->type == REDIS_SET) {
7007 set = sortval->ptr;
7008 } else {
7009 zset *zs = sortval->ptr;
7010 set = zs->dict;
7011 }
7012
ed9b544e 7013 di = dictGetIterator(set);
ed9b544e 7014 while((setele = dictNext(di)) != NULL) {
7015 vector[j].obj = dictGetEntryKey(setele);
7016 vector[j].u.score = 0;
7017 vector[j].u.cmpobj = NULL;
7018 j++;
7019 }
7020 dictReleaseIterator(di);
7021 }
dfc5e96c 7022 redisAssert(j == vectorlen);
ed9b544e 7023
7024 /* Now it's time to load the right scores in the sorting vector */
7025 if (dontsort == 0) {
7026 for (j = 0; j < vectorlen; j++) {
6d7d1370 7027 robj *byval;
ed9b544e 7028 if (sortby) {
6d7d1370 7029 /* lookup value to sort by */
3305306f 7030 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
705dad38 7031 if (!byval) continue;
ed9b544e 7032 } else {
6d7d1370
PN
7033 /* use object itself to sort by */
7034 byval = vector[j].obj;
7035 }
7036
7037 if (alpha) {
08ee9b57 7038 if (sortby) vector[j].u.cmpobj = getDecodedObject(byval);
6d7d1370
PN
7039 } else {
7040 if (byval->encoding == REDIS_ENCODING_RAW) {
7041 vector[j].u.score = strtod(byval->ptr,NULL);
16fa22f1 7042 } else if (byval->encoding == REDIS_ENCODING_INT) {
6d7d1370
PN
7043 /* Don't need to decode the object if it's
7044 * integer-encoded (the only encoding supported) so
7045 * far. We can just cast it */
16fa22f1
PN
7046 vector[j].u.score = (long)byval->ptr;
7047 } else {
7048 redisAssert(1 != 1);
942a3961 7049 }
ed9b544e 7050 }
6d7d1370 7051
705dad38
PN
7052 /* when the object was retrieved using lookupKeyByPattern,
7053 * its refcount needs to be decreased. */
7054 if (sortby) {
7055 decrRefCount(byval);
ed9b544e 7056 }
7057 }
7058 }
7059
7060 /* We are ready to sort the vector... perform a bit of sanity check
7061 * on the LIMIT option too. We'll use a partial version of quicksort. */
7062 start = (limit_start < 0) ? 0 : limit_start;
7063 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
7064 if (start >= vectorlen) {
7065 start = vectorlen-1;
7066 end = vectorlen-2;
7067 }
7068 if (end >= vectorlen) end = vectorlen-1;
7069
7070 if (dontsort == 0) {
7071 server.sort_desc = desc;
7072 server.sort_alpha = alpha;
7073 server.sort_bypattern = sortby ? 1 : 0;
5f5b9840 7074 if (sortby && (start != 0 || end != vectorlen-1))
7075 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
7076 else
7077 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
ed9b544e 7078 }
7079
7080 /* Send command output to the output buffer, performing the specified
7081 * GET/DEL/INCR/DECR operations if any. */
7082 outputlen = getop ? getop*(end-start+1) : end-start+1;
443c6409 7083 if (storekey == NULL) {
7084 /* STORE option not specified, sent the sorting result to client */
7085 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
7086 for (j = start; j <= end; j++) {
7087 listNode *ln;
c7df85a4 7088 listIter li;
7089
dd88747b 7090 if (!getop) addReplyBulk(c,vector[j].obj);
c7df85a4 7091 listRewind(operations,&li);
7092 while((ln = listNext(&li))) {
443c6409 7093 redisSortOperation *sop = ln->value;
7094 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7095 vector[j].obj);
7096
7097 if (sop->type == REDIS_SORT_GET) {
55017f9d 7098 if (!val) {
443c6409 7099 addReply(c,shared.nullbulk);
7100 } else {
dd88747b 7101 addReplyBulk(c,val);
55017f9d 7102 decrRefCount(val);
443c6409 7103 }
7104 } else {
dfc5e96c 7105 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
443c6409 7106 }
7107 }
ed9b544e 7108 }
443c6409 7109 } else {
7110 robj *listObject = createListObject();
7111 list *listPtr = (list*) listObject->ptr;
7112
7113 /* STORE option specified, set the sorting result as a List object */
7114 for (j = start; j <= end; j++) {
7115 listNode *ln;
c7df85a4 7116 listIter li;
7117
443c6409 7118 if (!getop) {
7119 listAddNodeTail(listPtr,vector[j].obj);
7120 incrRefCount(vector[j].obj);
7121 }
c7df85a4 7122 listRewind(operations,&li);
7123 while((ln = listNext(&li))) {
443c6409 7124 redisSortOperation *sop = ln->value;
7125 robj *val = lookupKeyByPattern(c->db,sop->pattern,
7126 vector[j].obj);
7127
7128 if (sop->type == REDIS_SORT_GET) {
55017f9d 7129 if (!val) {
443c6409 7130 listAddNodeTail(listPtr,createStringObject("",0));
7131 } else {
55017f9d
PN
7132 /* We should do a incrRefCount on val because it is
7133 * added to the list, but also a decrRefCount because
7134 * it is returned by lookupKeyByPattern. This results
7135 * in doing nothing at all. */
443c6409 7136 listAddNodeTail(listPtr,val);
443c6409 7137 }
ed9b544e 7138 } else {
dfc5e96c 7139 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
ed9b544e 7140 }
ed9b544e 7141 }
ed9b544e 7142 }
121796f7 7143 if (dictReplace(c->db->dict,storekey,listObject)) {
7144 incrRefCount(storekey);
7145 }
443c6409 7146 /* Note: we add 1 because the DB is dirty anyway since even if the
7147 * SORT result is empty a new key is set and maybe the old content
7148 * replaced. */
7149 server.dirty += 1+outputlen;
7150 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
ed9b544e 7151 }
7152
7153 /* Cleanup */
7154 decrRefCount(sortval);
7155 listRelease(operations);
7156 for (j = 0; j < vectorlen; j++) {
16fa22f1 7157 if (alpha && vector[j].u.cmpobj)
ed9b544e 7158 decrRefCount(vector[j].u.cmpobj);
7159 }
7160 zfree(vector);
7161}
7162
ec6c7a1d 7163/* Convert an amount of bytes into a human readable string in the form
7164 * of 100B, 2G, 100M, 4K, and so forth. */
7165static void bytesToHuman(char *s, unsigned long long n) {
7166 double d;
7167
7168 if (n < 1024) {
7169 /* Bytes */
7170 sprintf(s,"%lluB",n);
7171 return;
7172 } else if (n < (1024*1024)) {
7173 d = (double)n/(1024);
7174 sprintf(s,"%.2fK",d);
7175 } else if (n < (1024LL*1024*1024)) {
7176 d = (double)n/(1024*1024);
7177 sprintf(s,"%.2fM",d);
7178 } else if (n < (1024LL*1024*1024*1024)) {
7179 d = (double)n/(1024LL*1024*1024);
b72f6a4b 7180 sprintf(s,"%.2fG",d);
ec6c7a1d 7181 }
7182}
7183
1c85b79f 7184/* Create the string returned by the INFO command. This is decoupled
7185 * by the INFO command itself as we need to report the same information
7186 * on memory corruption problems. */
7187static sds genRedisInfoString(void) {
ed9b544e 7188 sds info;
7189 time_t uptime = time(NULL)-server.stat_starttime;
c3cb078d 7190 int j;
ec6c7a1d 7191 char hmem[64];
55a8298f 7192
b72f6a4b 7193 bytesToHuman(hmem,zmalloc_used_memory());
ed9b544e 7194 info = sdscatprintf(sdsempty(),
7195 "redis_version:%s\r\n"
5436146c
PN
7196 "redis_git_sha1:%s\r\n"
7197 "redis_git_dirty:%d\r\n"
f1017b3f 7198 "arch_bits:%s\r\n"
7a932b74 7199 "multiplexing_api:%s\r\n"
0d7170a4 7200 "process_id:%ld\r\n"
682ac724 7201 "uptime_in_seconds:%ld\r\n"
7202 "uptime_in_days:%ld\r\n"
ed9b544e 7203 "connected_clients:%d\r\n"
7204 "connected_slaves:%d\r\n"
f86a74e9 7205 "blocked_clients:%d\r\n"
5fba9f71 7206 "used_memory:%zu\r\n"
ec6c7a1d 7207 "used_memory_human:%s\r\n"
ed9b544e 7208 "changes_since_last_save:%lld\r\n"
be2bb6b0 7209 "bgsave_in_progress:%d\r\n"
682ac724 7210 "last_save_time:%ld\r\n"
b3fad521 7211 "bgrewriteaof_in_progress:%d\r\n"
ed9b544e 7212 "total_connections_received:%lld\r\n"
7213 "total_commands_processed:%lld\r\n"
2a6a2ed1 7214 "expired_keys:%lld\r\n"
3be2c9d7 7215 "hash_max_zipmap_entries:%zu\r\n"
7216 "hash_max_zipmap_value:%zu\r\n"
ffc6b7f8 7217 "pubsub_channels:%ld\r\n"
7218 "pubsub_patterns:%u\r\n"
7d98e08c 7219 "vm_enabled:%d\r\n"
a0f643ea 7220 "role:%s\r\n"
ed9b544e 7221 ,REDIS_VERSION,
5436146c 7222 REDIS_GIT_SHA1,
274e45e3 7223 strtol(REDIS_GIT_DIRTY,NULL,10) > 0,
f1017b3f 7224 (sizeof(long) == 8) ? "64" : "32",
7a932b74 7225 aeGetApiName(),
0d7170a4 7226 (long) getpid(),
a0f643ea 7227 uptime,
7228 uptime/(3600*24),
ed9b544e 7229 listLength(server.clients)-listLength(server.slaves),
7230 listLength(server.slaves),
d5d55fc3 7231 server.blpop_blocked_clients,
b72f6a4b 7232 zmalloc_used_memory(),
ec6c7a1d 7233 hmem,
ed9b544e 7234 server.dirty,
9d65a1bb 7235 server.bgsavechildpid != -1,
ed9b544e 7236 server.lastsave,
b3fad521 7237 server.bgrewritechildpid != -1,
ed9b544e 7238 server.stat_numconnections,
7239 server.stat_numcommands,
2a6a2ed1 7240 server.stat_expiredkeys,
55a8298f 7241 server.hash_max_zipmap_entries,
7242 server.hash_max_zipmap_value,
ffc6b7f8 7243 dictSize(server.pubsub_channels),
7244 listLength(server.pubsub_patterns),
7d98e08c 7245 server.vm_enabled != 0,
a0f643ea 7246 server.masterhost == NULL ? "master" : "slave"
ed9b544e 7247 );
a0f643ea 7248 if (server.masterhost) {
7249 info = sdscatprintf(info,
7250 "master_host:%s\r\n"
7251 "master_port:%d\r\n"
7252 "master_link_status:%s\r\n"
7253 "master_last_io_seconds_ago:%d\r\n"
7254 ,server.masterhost,
7255 server.masterport,
7256 (server.replstate == REDIS_REPL_CONNECTED) ?
7257 "up" : "down",
f72b934d 7258 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
a0f643ea 7259 );
7260 }
7d98e08c 7261 if (server.vm_enabled) {
1064ef87 7262 lockThreadedIO();
7d98e08c 7263 info = sdscatprintf(info,
7264 "vm_conf_max_memory:%llu\r\n"
7265 "vm_conf_page_size:%llu\r\n"
7266 "vm_conf_pages:%llu\r\n"
7267 "vm_stats_used_pages:%llu\r\n"
7268 "vm_stats_swapped_objects:%llu\r\n"
7269 "vm_stats_swappin_count:%llu\r\n"
7270 "vm_stats_swappout_count:%llu\r\n"
b9bc0eef 7271 "vm_stats_io_newjobs_len:%lu\r\n"
7272 "vm_stats_io_processing_len:%lu\r\n"
7273 "vm_stats_io_processed_len:%lu\r\n"
25fd2cb2 7274 "vm_stats_io_active_threads:%lu\r\n"
d5d55fc3 7275 "vm_stats_blocked_clients:%lu\r\n"
7d98e08c 7276 ,(unsigned long long) server.vm_max_memory,
7277 (unsigned long long) server.vm_page_size,
7278 (unsigned long long) server.vm_pages,
7279 (unsigned long long) server.vm_stats_used_pages,
7280 (unsigned long long) server.vm_stats_swapped_objects,
7281 (unsigned long long) server.vm_stats_swapins,
b9bc0eef 7282 (unsigned long long) server.vm_stats_swapouts,
7283 (unsigned long) listLength(server.io_newjobs),
7284 (unsigned long) listLength(server.io_processing),
7285 (unsigned long) listLength(server.io_processed),
d5d55fc3 7286 (unsigned long) server.io_active_threads,
7287 (unsigned long) server.vm_blocked_clients
7d98e08c 7288 );
1064ef87 7289 unlockThreadedIO();
7d98e08c 7290 }
c3cb078d 7291 for (j = 0; j < server.dbnum; j++) {
7292 long long keys, vkeys;
7293
7294 keys = dictSize(server.db[j].dict);
7295 vkeys = dictSize(server.db[j].expires);
7296 if (keys || vkeys) {
9d65a1bb 7297 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
c3cb078d 7298 j, keys, vkeys);
7299 }
7300 }
1c85b79f 7301 return info;
7302}
7303
7304static void infoCommand(redisClient *c) {
7305 sds info = genRedisInfoString();
83c6a618 7306 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
7307 (unsigned long)sdslen(info)));
ed9b544e 7308 addReplySds(c,info);
70003d28 7309 addReply(c,shared.crlf);
ed9b544e 7310}
7311
3305306f 7312static void monitorCommand(redisClient *c) {
7313 /* ignore MONITOR if aleady slave or in monitor mode */
7314 if (c->flags & REDIS_SLAVE) return;
7315
7316 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
7317 c->slaveseldb = 0;
6b47e12e 7318 listAddNodeTail(server.monitors,c);
3305306f 7319 addReply(c,shared.ok);
7320}
7321
7322/* ================================= Expire ================================= */
7323static int removeExpire(redisDb *db, robj *key) {
7324 if (dictDelete(db->expires,key) == DICT_OK) {
7325 return 1;
7326 } else {
7327 return 0;
7328 }
7329}
7330
7331static int setExpire(redisDb *db, robj *key, time_t when) {
7332 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
7333 return 0;
7334 } else {
7335 incrRefCount(key);
7336 return 1;
7337 }
7338}
7339
bb32ede5 7340/* Return the expire time of the specified key, or -1 if no expire
7341 * is associated with this key (i.e. the key is non volatile) */
7342static time_t getExpire(redisDb *db, robj *key) {
7343 dictEntry *de;
7344
7345 /* No expire? return ASAP */
7346 if (dictSize(db->expires) == 0 ||
7347 (de = dictFind(db->expires,key)) == NULL) return -1;
7348
7349 return (time_t) dictGetEntryVal(de);
7350}
7351
3305306f 7352static int expireIfNeeded(redisDb *db, robj *key) {
7353 time_t when;
7354 dictEntry *de;
7355
7356 /* No expire? return ASAP */
7357 if (dictSize(db->expires) == 0 ||
7358 (de = dictFind(db->expires,key)) == NULL) return 0;
7359
7360 /* Lookup the expire */
7361 when = (time_t) dictGetEntryVal(de);
7362 if (time(NULL) <= when) return 0;
7363
7364 /* Delete the key */
7365 dictDelete(db->expires,key);
2a6a2ed1 7366 server.stat_expiredkeys++;
3305306f 7367 return dictDelete(db->dict,key) == DICT_OK;
7368}
7369
7370static int deleteIfVolatile(redisDb *db, robj *key) {
7371 dictEntry *de;
7372
7373 /* No expire? return ASAP */
7374 if (dictSize(db->expires) == 0 ||
7375 (de = dictFind(db->expires,key)) == NULL) return 0;
7376
7377 /* Delete the key */
0c66a471 7378 server.dirty++;
2a6a2ed1 7379 server.stat_expiredkeys++;
3305306f 7380 dictDelete(db->expires,key);
7381 return dictDelete(db->dict,key) == DICT_OK;
7382}
7383
bbe025e0 7384static void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
3305306f 7385 dictEntry *de;
bbe025e0
AM
7386 time_t seconds;
7387
bd79a6bd 7388 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
bbe025e0
AM
7389
7390 seconds -= offset;
3305306f 7391
802e8373 7392 de = dictFind(c->db->dict,key);
3305306f 7393 if (de == NULL) {
7394 addReply(c,shared.czero);
7395 return;
7396 }
d4dd6556 7397 if (seconds <= 0) {
43e5ccdf 7398 if (deleteKey(c->db,key)) server.dirty++;
7399 addReply(c, shared.cone);
3305306f 7400 return;
7401 } else {
7402 time_t when = time(NULL)+seconds;
802e8373 7403 if (setExpire(c->db,key,when)) {
3305306f 7404 addReply(c,shared.cone);
77423026 7405 server.dirty++;
7406 } else {
3305306f 7407 addReply(c,shared.czero);
77423026 7408 }
3305306f 7409 return;
7410 }
7411}
7412
802e8373 7413static void expireCommand(redisClient *c) {
bbe025e0 7414 expireGenericCommand(c,c->argv[1],c->argv[2],0);
802e8373 7415}
7416
7417static void expireatCommand(redisClient *c) {
bbe025e0 7418 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
802e8373 7419}
7420
fd88489a 7421static void ttlCommand(redisClient *c) {
7422 time_t expire;
7423 int ttl = -1;
7424
7425 expire = getExpire(c->db,c->argv[1]);
7426 if (expire != -1) {
7427 ttl = (int) (expire-time(NULL));
7428 if (ttl < 0) ttl = -1;
7429 }
7430 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
7431}
7432
6e469882 7433/* ================================ MULTI/EXEC ============================== */
7434
7435/* Client state initialization for MULTI/EXEC */
7436static void initClientMultiState(redisClient *c) {
7437 c->mstate.commands = NULL;
7438 c->mstate.count = 0;
7439}
7440
7441/* Release all the resources associated with MULTI/EXEC state */
7442static void freeClientMultiState(redisClient *c) {
7443 int j;
7444
7445 for (j = 0; j < c->mstate.count; j++) {
7446 int i;
7447 multiCmd *mc = c->mstate.commands+j;
7448
7449 for (i = 0; i < mc->argc; i++)
7450 decrRefCount(mc->argv[i]);
7451 zfree(mc->argv);
7452 }
7453 zfree(c->mstate.commands);
7454}
7455
7456/* Add a new command into the MULTI commands queue */
7457static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
7458 multiCmd *mc;
7459 int j;
7460
7461 c->mstate.commands = zrealloc(c->mstate.commands,
7462 sizeof(multiCmd)*(c->mstate.count+1));
7463 mc = c->mstate.commands+c->mstate.count;
7464 mc->cmd = cmd;
7465 mc->argc = c->argc;
7466 mc->argv = zmalloc(sizeof(robj*)*c->argc);
7467 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
7468 for (j = 0; j < c->argc; j++)
7469 incrRefCount(mc->argv[j]);
7470 c->mstate.count++;
7471}
7472
7473static void multiCommand(redisClient *c) {
7474 c->flags |= REDIS_MULTI;
36c548f0 7475 addReply(c,shared.ok);
6e469882 7476}
7477
18b6cb76
DJ
7478static void discardCommand(redisClient *c) {
7479 if (!(c->flags & REDIS_MULTI)) {
7480 addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
7481 return;
7482 }
7483
7484 freeClientMultiState(c);
7485 initClientMultiState(c);
7486 c->flags &= (~REDIS_MULTI);
7487 addReply(c,shared.ok);
7488}
7489
66c8853f 7490/* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7491 * implememntation for more information. */
7492static void execCommandReplicateMulti(redisClient *c) {
7493 struct redisCommand *cmd;
7494 robj *multistring = createStringObject("MULTI",5);
7495
7496 cmd = lookupCommand("multi");
7497 if (server.appendonly)
7498 feedAppendOnlyFile(cmd,c->db->id,&multistring,1);
7499 if (listLength(server.slaves))
7500 replicationFeedSlaves(server.slaves,c->db->id,&multistring,1);
7501 decrRefCount(multistring);
7502}
7503
6e469882 7504static void execCommand(redisClient *c) {
7505 int j;
7506 robj **orig_argv;
7507 int orig_argc;
7508
7509 if (!(c->flags & REDIS_MULTI)) {
7510 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
7511 return;
7512 }
7513
66c8853f 7514 /* Replicate a MULTI request now that we are sure the block is executed.
7515 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7516 * both the AOF and the replication link will have the same consistency
7517 * and atomicity guarantees. */
7518 execCommandReplicateMulti(c);
7519
7520 /* Exec all the queued commands */
6e469882 7521 orig_argv = c->argv;
7522 orig_argc = c->argc;
7523 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
7524 for (j = 0; j < c->mstate.count; j++) {
7525 c->argc = c->mstate.commands[j].argc;
7526 c->argv = c->mstate.commands[j].argv;
7527 call(c,c->mstate.commands[j].cmd);
7528 }
7529 c->argv = orig_argv;
7530 c->argc = orig_argc;
7531 freeClientMultiState(c);
7532 initClientMultiState(c);
7533 c->flags &= (~REDIS_MULTI);
66c8853f 7534 /* Make sure the EXEC command is always replicated / AOF, since we
7535 * always send the MULTI command (we can't know beforehand if the
7536 * next operations will contain at least a modification to the DB). */
7537 server.dirty++;
6e469882 7538}
7539
4409877e 7540/* =========================== Blocking Operations ========================= */
7541
7542/* Currently Redis blocking operations support is limited to list POP ops,
7543 * so the current implementation is not fully generic, but it is also not
7544 * completely specific so it will not require a rewrite to support new
7545 * kind of blocking operations in the future.
7546 *
7547 * Still it's important to note that list blocking operations can be already
7548 * used as a notification mechanism in order to implement other blocking
7549 * operations at application level, so there must be a very strong evidence
7550 * of usefulness and generality before new blocking operations are implemented.
7551 *
7552 * This is how the current blocking POP works, we use BLPOP as example:
7553 * - If the user calls BLPOP and the key exists and contains a non empty list
7554 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7555 * if there is not to block.
7556 * - If instead BLPOP is called and the key does not exists or the list is
7557 * empty we need to block. In order to do so we remove the notification for
7558 * new data to read in the client socket (so that we'll not serve new
7559 * requests if the blocking request is not served). Also we put the client
95242ab5 7560 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
4409877e 7561 * blocking for this keys.
7562 * - If a PUSH operation against a key with blocked clients waiting is
7563 * performed, we serve the first in the list: basically instead to push
7564 * the new element inside the list we return it to the (first / oldest)
7565 * blocking client, unblock the client, and remove it form the list.
7566 *
7567 * The above comment and the source code should be enough in order to understand
7568 * the implementation and modify / fix it later.
7569 */
7570
7571/* Set a client in blocking mode for the specified key, with the specified
7572 * timeout */
b177fd30 7573static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
4409877e 7574 dictEntry *de;
7575 list *l;
b177fd30 7576 int j;
4409877e 7577
b177fd30 7578 c->blockingkeys = zmalloc(sizeof(robj*)*numkeys);
7579 c->blockingkeysnum = numkeys;
4409877e 7580 c->blockingto = timeout;
b177fd30 7581 for (j = 0; j < numkeys; j++) {
7582 /* Add the key in the client structure, to map clients -> keys */
7583 c->blockingkeys[j] = keys[j];
7584 incrRefCount(keys[j]);
4409877e 7585
b177fd30 7586 /* And in the other "side", to map keys -> clients */
7587 de = dictFind(c->db->blockingkeys,keys[j]);
7588 if (de == NULL) {
7589 int retval;
7590
7591 /* For every key we take a list of clients blocked for it */
7592 l = listCreate();
7593 retval = dictAdd(c->db->blockingkeys,keys[j],l);
7594 incrRefCount(keys[j]);
7595 assert(retval == DICT_OK);
7596 } else {
7597 l = dictGetEntryVal(de);
7598 }
7599 listAddNodeTail(l,c);
4409877e 7600 }
b177fd30 7601 /* Mark the client as a blocked client */
4409877e 7602 c->flags |= REDIS_BLOCKED;
d5d55fc3 7603 server.blpop_blocked_clients++;
4409877e 7604}
7605
7606/* Unblock a client that's waiting in a blocking operation such as BLPOP */
b0d8747d 7607static void unblockClientWaitingData(redisClient *c) {
4409877e 7608 dictEntry *de;
7609 list *l;
b177fd30 7610 int j;
4409877e 7611
b177fd30 7612 assert(c->blockingkeys != NULL);
7613 /* The client may wait for multiple keys, so unblock it for every key. */
7614 for (j = 0; j < c->blockingkeysnum; j++) {
7615 /* Remove this client from the list of clients waiting for this key. */
7616 de = dictFind(c->db->blockingkeys,c->blockingkeys[j]);
7617 assert(de != NULL);
7618 l = dictGetEntryVal(de);
7619 listDelNode(l,listSearchKey(l,c));
7620 /* If the list is empty we need to remove it to avoid wasting memory */
7621 if (listLength(l) == 0)
7622 dictDelete(c->db->blockingkeys,c->blockingkeys[j]);
7623 decrRefCount(c->blockingkeys[j]);
7624 }
7625 /* Cleanup the client structure */
7626 zfree(c->blockingkeys);
7627 c->blockingkeys = NULL;
4409877e 7628 c->flags &= (~REDIS_BLOCKED);
d5d55fc3 7629 server.blpop_blocked_clients--;
5921aa36 7630 /* We want to process data if there is some command waiting
b0d8747d 7631 * in the input buffer. Note that this is safe even if
7632 * unblockClientWaitingData() gets called from freeClient() because
7633 * freeClient() will be smart enough to call this function
7634 * *after* c->querybuf was set to NULL. */
4409877e 7635 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
7636}
7637
7638/* This should be called from any function PUSHing into lists.
7639 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7640 * 'ele' is the element pushed.
7641 *
7642 * If the function returns 0 there was no client waiting for a list push
7643 * against this key.
7644 *
7645 * If the function returns 1 there was a client waiting for a list push
7646 * against this key, the element was passed to this client thus it's not
7647 * needed to actually add it to the list and the caller should return asap. */
7648static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
7649 struct dictEntry *de;
7650 redisClient *receiver;
7651 list *l;
7652 listNode *ln;
7653
7654 de = dictFind(c->db->blockingkeys,key);
7655 if (de == NULL) return 0;
7656 l = dictGetEntryVal(de);
7657 ln = listFirst(l);
7658 assert(ln != NULL);
7659 receiver = ln->value;
4409877e 7660
b177fd30 7661 addReplySds(receiver,sdsnew("*2\r\n"));
dd88747b 7662 addReplyBulk(receiver,key);
7663 addReplyBulk(receiver,ele);
b0d8747d 7664 unblockClientWaitingData(receiver);
4409877e 7665 return 1;
7666}
7667
7668/* Blocking RPOP/LPOP */
7669static void blockingPopGenericCommand(redisClient *c, int where) {
7670 robj *o;
7671 time_t timeout;
b177fd30 7672 int j;
4409877e 7673
b177fd30 7674 for (j = 1; j < c->argc-1; j++) {
7675 o = lookupKeyWrite(c->db,c->argv[j]);
7676 if (o != NULL) {
7677 if (o->type != REDIS_LIST) {
7678 addReply(c,shared.wrongtypeerr);
4409877e 7679 return;
b177fd30 7680 } else {
7681 list *list = o->ptr;
7682 if (listLength(list) != 0) {
7683 /* If the list contains elements fall back to the usual
7684 * non-blocking POP operation */
7685 robj *argv[2], **orig_argv;
7686 int orig_argc;
e0a62c7f 7687
b177fd30 7688 /* We need to alter the command arguments before to call
7689 * popGenericCommand() as the command takes a single key. */
7690 orig_argv = c->argv;
7691 orig_argc = c->argc;
7692 argv[1] = c->argv[j];
7693 c->argv = argv;
7694 c->argc = 2;
7695
7696 /* Also the return value is different, we need to output
7697 * the multi bulk reply header and the key name. The
7698 * "real" command will add the last element (the value)
7699 * for us. If this souds like an hack to you it's just
7700 * because it is... */
7701 addReplySds(c,sdsnew("*2\r\n"));
dd88747b 7702 addReplyBulk(c,argv[1]);
b177fd30 7703 popGenericCommand(c,where);
7704
7705 /* Fix the client structure with the original stuff */
7706 c->argv = orig_argv;
7707 c->argc = orig_argc;
7708 return;
7709 }
4409877e 7710 }
7711 }
7712 }
7713 /* If the list is empty or the key does not exists we must block */
b177fd30 7714 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
4409877e 7715 if (timeout > 0) timeout += time(NULL);
b177fd30 7716 blockForKeys(c,c->argv+1,c->argc-2,timeout);
4409877e 7717}
7718
7719static void blpopCommand(redisClient *c) {
7720 blockingPopGenericCommand(c,REDIS_HEAD);
7721}
7722
7723static void brpopCommand(redisClient *c) {
7724 blockingPopGenericCommand(c,REDIS_TAIL);
7725}
7726
ed9b544e 7727/* =============================== Replication ============================= */
7728
a4d1ba9a 7729static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 7730 ssize_t nwritten, ret = size;
7731 time_t start = time(NULL);
7732
7733 timeout++;
7734 while(size) {
7735 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
7736 nwritten = write(fd,ptr,size);
7737 if (nwritten == -1) return -1;
7738 ptr += nwritten;
7739 size -= nwritten;
7740 }
7741 if ((time(NULL)-start) > timeout) {
7742 errno = ETIMEDOUT;
7743 return -1;
7744 }
7745 }
7746 return ret;
7747}
7748
a4d1ba9a 7749static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 7750 ssize_t nread, totread = 0;
7751 time_t start = time(NULL);
7752
7753 timeout++;
7754 while(size) {
7755 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
7756 nread = read(fd,ptr,size);
7757 if (nread == -1) return -1;
7758 ptr += nread;
7759 size -= nread;
7760 totread += nread;
7761 }
7762 if ((time(NULL)-start) > timeout) {
7763 errno = ETIMEDOUT;
7764 return -1;
7765 }
7766 }
7767 return totread;
7768}
7769
7770static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
7771 ssize_t nread = 0;
7772
7773 size--;
7774 while(size) {
7775 char c;
7776
7777 if (syncRead(fd,&c,1,timeout) == -1) return -1;
7778 if (c == '\n') {
7779 *ptr = '\0';
7780 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
7781 return nread;
7782 } else {
7783 *ptr++ = c;
7784 *ptr = '\0';
7785 nread++;
7786 }
7787 }
7788 return nread;
7789}
7790
7791static void syncCommand(redisClient *c) {
40d224a9 7792 /* ignore SYNC if aleady slave or in monitor mode */
7793 if (c->flags & REDIS_SLAVE) return;
7794
7795 /* SYNC can't be issued when the server has pending data to send to
7796 * the client about already issued commands. We need a fresh reply
7797 * buffer registering the differences between the BGSAVE and the current
7798 * dataset, so that we can copy to other slaves if needed. */
7799 if (listLength(c->reply) != 0) {
7800 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7801 return;
7802 }
7803
7804 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
7805 /* Here we need to check if there is a background saving operation
7806 * in progress, or if it is required to start one */
9d65a1bb 7807 if (server.bgsavechildpid != -1) {
40d224a9 7808 /* Ok a background save is in progress. Let's check if it is a good
7809 * one for replication, i.e. if there is another slave that is
7810 * registering differences since the server forked to save */
7811 redisClient *slave;
7812 listNode *ln;
c7df85a4 7813 listIter li;
40d224a9 7814
c7df85a4 7815 listRewind(server.slaves,&li);
7816 while((ln = listNext(&li))) {
40d224a9 7817 slave = ln->value;
7818 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
40d224a9 7819 }
7820 if (ln) {
7821 /* Perfect, the server is already registering differences for
7822 * another slave. Set the right state, and copy the buffer. */
7823 listRelease(c->reply);
7824 c->reply = listDup(slave->reply);
40d224a9 7825 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7826 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
7827 } else {
7828 /* No way, we need to wait for the next BGSAVE in order to
7829 * register differences */
7830 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
7831 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
7832 }
7833 } else {
7834 /* Ok we don't have a BGSAVE in progress, let's start one */
7835 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
7836 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
7837 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
7838 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
7839 return;
7840 }
7841 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7842 }
6208b3a7 7843 c->repldbfd = -1;
40d224a9 7844 c->flags |= REDIS_SLAVE;
7845 c->slaveseldb = 0;
6b47e12e 7846 listAddNodeTail(server.slaves,c);
40d224a9 7847 return;
7848}
7849
6208b3a7 7850static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
7851 redisClient *slave = privdata;
7852 REDIS_NOTUSED(el);
7853 REDIS_NOTUSED(mask);
7854 char buf[REDIS_IOBUF_LEN];
7855 ssize_t nwritten, buflen;
7856
7857 if (slave->repldboff == 0) {
7858 /* Write the bulk write count before to transfer the DB. In theory here
7859 * we don't know how much room there is in the output buffer of the
7860 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7861 * operations) will never be smaller than the few bytes we need. */
7862 sds bulkcount;
7863
7864 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7865 slave->repldbsize);
7866 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
7867 {
7868 sdsfree(bulkcount);
7869 freeClient(slave);
7870 return;
7871 }
7872 sdsfree(bulkcount);
7873 }
7874 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
7875 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
7876 if (buflen <= 0) {
7877 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
7878 (buflen == 0) ? "premature EOF" : strerror(errno));
7879 freeClient(slave);
7880 return;
7881 }
7882 if ((nwritten = write(fd,buf,buflen)) == -1) {
f870935d 7883 redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
6208b3a7 7884 strerror(errno));
7885 freeClient(slave);
7886 return;
7887 }
7888 slave->repldboff += nwritten;
7889 if (slave->repldboff == slave->repldbsize) {
7890 close(slave->repldbfd);
7891 slave->repldbfd = -1;
7892 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
7893 slave->replstate = REDIS_REPL_ONLINE;
7894 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
266373b2 7895 sendReplyToClient, slave) == AE_ERR) {
6208b3a7 7896 freeClient(slave);
7897 return;
7898 }
7899 addReplySds(slave,sdsempty());
7900 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
7901 }
7902}
ed9b544e 7903
a3b21203 7904/* This function is called at the end of every backgrond saving.
7905 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
7906 * otherwise REDIS_ERR is passed to the function.
7907 *
7908 * The goal of this function is to handle slaves waiting for a successful
7909 * background saving in order to perform non-blocking synchronization. */
7910static void updateSlavesWaitingBgsave(int bgsaveerr) {
6208b3a7 7911 listNode *ln;
7912 int startbgsave = 0;
c7df85a4 7913 listIter li;
ed9b544e 7914
c7df85a4 7915 listRewind(server.slaves,&li);
7916 while((ln = listNext(&li))) {
6208b3a7 7917 redisClient *slave = ln->value;
ed9b544e 7918
6208b3a7 7919 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
7920 startbgsave = 1;
7921 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
7922 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
dde65f3f 7923 struct redis_stat buf;
e0a62c7f 7924
6208b3a7 7925 if (bgsaveerr != REDIS_OK) {
7926 freeClient(slave);
7927 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
7928 continue;
7929 }
7930 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
dde65f3f 7931 redis_fstat(slave->repldbfd,&buf) == -1) {
6208b3a7 7932 freeClient(slave);
7933 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
7934 continue;
7935 }
7936 slave->repldboff = 0;
7937 slave->repldbsize = buf.st_size;
7938 slave->replstate = REDIS_REPL_SEND_BULK;
7939 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
266373b2 7940 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
6208b3a7 7941 freeClient(slave);
7942 continue;
7943 }
7944 }
ed9b544e 7945 }
6208b3a7 7946 if (startbgsave) {
7947 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
c7df85a4 7948 listIter li;
7949
7950 listRewind(server.slaves,&li);
6208b3a7 7951 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
c7df85a4 7952 while((ln = listNext(&li))) {
6208b3a7 7953 redisClient *slave = ln->value;
ed9b544e 7954
6208b3a7 7955 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
7956 freeClient(slave);
7957 }
7958 }
7959 }
ed9b544e 7960}
7961
7962static int syncWithMaster(void) {
d0ccebcf 7963 char buf[1024], tmpfile[256], authcmd[1024];
18e61fa2 7964 long dumpsize;
ed9b544e 7965 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
8c5abee8 7966 int dfd, maxtries = 5;
ed9b544e 7967
7968 if (fd == -1) {
7969 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
7970 strerror(errno));
7971 return REDIS_ERR;
7972 }
d0ccebcf 7973
7974 /* AUTH with the master if required. */
7975 if(server.masterauth) {
7976 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
7977 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
7978 close(fd);
7979 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
7980 strerror(errno));
7981 return REDIS_ERR;
7982 }
7983 /* Read the AUTH result. */
7984 if (syncReadLine(fd,buf,1024,3600) == -1) {
7985 close(fd);
7986 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
7987 strerror(errno));
7988 return REDIS_ERR;
7989 }
7990 if (buf[0] != '+') {
7991 close(fd);
7992 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
7993 return REDIS_ERR;
7994 }
7995 }
7996
ed9b544e 7997 /* Issue the SYNC command */
7998 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
7999 close(fd);
8000 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
8001 strerror(errno));
8002 return REDIS_ERR;
8003 }
8004 /* Read the bulk write count */
8c4d91fc 8005 if (syncReadLine(fd,buf,1024,3600) == -1) {
ed9b544e 8006 close(fd);
8007 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
8008 strerror(errno));
8009 return REDIS_ERR;
8010 }
4aa701c1 8011 if (buf[0] != '$') {
8012 close(fd);
8013 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8014 return REDIS_ERR;
8015 }
18e61fa2 8016 dumpsize = strtol(buf+1,NULL,10);
8017 redisLog(REDIS_NOTICE,"Receiving %ld bytes data dump from MASTER",dumpsize);
ed9b544e 8018 /* Read the bulk write data on a temp file */
8c5abee8 8019 while(maxtries--) {
8020 snprintf(tmpfile,256,
8021 "temp-%d.%ld.rdb",(int)time(NULL),(long int)getpid());
8022 dfd = open(tmpfile,O_CREAT|O_WRONLY|O_EXCL,0644);
8023 if (dfd != -1) break;
5de9ad7c 8024 sleep(1);
8c5abee8 8025 }
ed9b544e 8026 if (dfd == -1) {
8027 close(fd);
8028 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
8029 return REDIS_ERR;
8030 }
8031 while(dumpsize) {
8032 int nread, nwritten;
8033
8034 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
8035 if (nread == -1) {
8036 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
8037 strerror(errno));
8038 close(fd);
8039 close(dfd);
8040 return REDIS_ERR;
8041 }
8042 nwritten = write(dfd,buf,nread);
8043 if (nwritten == -1) {
8044 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
8045 close(fd);
8046 close(dfd);
8047 return REDIS_ERR;
8048 }
8049 dumpsize -= nread;
8050 }
8051 close(dfd);
8052 if (rename(tmpfile,server.dbfilename) == -1) {
8053 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
8054 unlink(tmpfile);
8055 close(fd);
8056 return REDIS_ERR;
8057 }
8058 emptyDb();
f78fd11b 8059 if (rdbLoad(server.dbfilename) != REDIS_OK) {
ed9b544e 8060 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
8061 close(fd);
8062 return REDIS_ERR;
8063 }
8064 server.master = createClient(fd);
8065 server.master->flags |= REDIS_MASTER;
179b3952 8066 server.master->authenticated = 1;
ed9b544e 8067 server.replstate = REDIS_REPL_CONNECTED;
8068 return REDIS_OK;
8069}
8070
321b0e13 8071static void slaveofCommand(redisClient *c) {
8072 if (!strcasecmp(c->argv[1]->ptr,"no") &&
8073 !strcasecmp(c->argv[2]->ptr,"one")) {
8074 if (server.masterhost) {
8075 sdsfree(server.masterhost);
8076 server.masterhost = NULL;
8077 if (server.master) freeClient(server.master);
8078 server.replstate = REDIS_REPL_NONE;
8079 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
8080 }
8081 } else {
8082 sdsfree(server.masterhost);
8083 server.masterhost = sdsdup(c->argv[1]->ptr);
8084 server.masterport = atoi(c->argv[2]->ptr);
8085 if (server.master) freeClient(server.master);
8086 server.replstate = REDIS_REPL_CONNECT;
8087 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
8088 server.masterhost, server.masterport);
8089 }
8090 addReply(c,shared.ok);
8091}
8092
3fd78bcd 8093/* ============================ Maxmemory directive ======================== */
8094
a5819310 8095/* Try to free one object form the pre-allocated objects free list.
8096 * This is useful under low mem conditions as by default we take 1 million
8097 * free objects allocated. On success REDIS_OK is returned, otherwise
8098 * REDIS_ERR. */
8099static int tryFreeOneObjectFromFreelist(void) {
f870935d 8100 robj *o;
8101
a5819310 8102 if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
8103 if (listLength(server.objfreelist)) {
8104 listNode *head = listFirst(server.objfreelist);
8105 o = listNodeValue(head);
8106 listDelNode(server.objfreelist,head);
8107 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8108 zfree(o);
8109 return REDIS_OK;
8110 } else {
8111 if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
8112 return REDIS_ERR;
8113 }
f870935d 8114}
8115
3fd78bcd 8116/* This function gets called when 'maxmemory' is set on the config file to limit
8117 * the max memory used by the server, and we are out of memory.
8118 * This function will try to, in order:
8119 *
8120 * - Free objects from the free list
8121 * - Try to remove keys with an EXPIRE set
8122 *
8123 * It is not possible to free enough memory to reach used-memory < maxmemory
8124 * the server will start refusing commands that will enlarge even more the
8125 * memory usage.
8126 */
8127static void freeMemoryIfNeeded(void) {
8128 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
a5819310 8129 int j, k, freed = 0;
8130
8131 if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
8132 for (j = 0; j < server.dbnum; j++) {
8133 int minttl = -1;
8134 robj *minkey = NULL;
8135 struct dictEntry *de;
8136
8137 if (dictSize(server.db[j].expires)) {
8138 freed = 1;
8139 /* From a sample of three keys drop the one nearest to
8140 * the natural expire */
8141 for (k = 0; k < 3; k++) {
8142 time_t t;
8143
8144 de = dictGetRandomKey(server.db[j].expires);
8145 t = (time_t) dictGetEntryVal(de);
8146 if (minttl == -1 || t < minttl) {
8147 minkey = dictGetEntryKey(de);
8148 minttl = t;
3fd78bcd 8149 }
3fd78bcd 8150 }
a5819310 8151 deleteKey(server.db+j,minkey);
3fd78bcd 8152 }
3fd78bcd 8153 }
a5819310 8154 if (!freed) return; /* nothing to free... */
3fd78bcd 8155 }
8156}
8157
f80dff62 8158/* ============================== Append Only file ========================== */
8159
28ed1f33 8160/* Write the append only file buffer on disk.
8161 *
8162 * Since we are required to write the AOF before replying to the client,
8163 * and the only way the client socket can get a write is entering when the
8164 * the event loop, we accumulate all the AOF writes in a memory
8165 * buffer and write it on disk using this function just before entering
8166 * the event loop again. */
8167static void flushAppendOnlyFile(void) {
8168 time_t now;
8169 ssize_t nwritten;
8170
8171 if (sdslen(server.aofbuf) == 0) return;
8172
8173 /* We want to perform a single write. This should be guaranteed atomic
8174 * at least if the filesystem we are writing is a real physical one.
8175 * While this will save us against the server being killed I don't think
8176 * there is much to do about the whole server stopping for power problems
8177 * or alike */
8178 nwritten = write(server.appendfd,server.aofbuf,sdslen(server.aofbuf));
8179 if (nwritten != (signed)sdslen(server.aofbuf)) {
8180 /* Ooops, we are in troubles. The best thing to do for now is
8181 * aborting instead of giving the illusion that everything is
8182 * working as expected. */
8183 if (nwritten == -1) {
8184 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
8185 } else {
8186 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
8187 }
8188 exit(1);
8189 }
8190 sdsfree(server.aofbuf);
8191 server.aofbuf = sdsempty();
8192
8193 /* Fsync if needed */
8194 now = time(NULL);
8195 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
8196 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
8197 now-server.lastfsync > 1))
8198 {
8199 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8200 * flushing metadata. */
8201 aof_fsync(server.appendfd); /* Let's try to get this data on the disk */
8202 server.lastfsync = now;
8203 }
8204}
8205
9376e434
PN
8206static sds catAppendOnlyGenericCommand(sds buf, int argc, robj **argv) {
8207 int j;
8208 buf = sdscatprintf(buf,"*%d\r\n",argc);
8209 for (j = 0; j < argc; j++) {
8210 robj *o = getDecodedObject(argv[j]);
8211 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
8212 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
8213 buf = sdscatlen(buf,"\r\n",2);
8214 decrRefCount(o);
8215 }
8216 return buf;
8217}
8218
8219static sds catAppendOnlyExpireAtCommand(sds buf, robj *key, robj *seconds) {
8220 int argc = 3;
8221 long when;
8222 robj *argv[3];
8223
8224 /* Make sure we can use strtol */
8225 seconds = getDecodedObject(seconds);
8226 when = time(NULL)+strtol(seconds->ptr,NULL,10);
8227 decrRefCount(seconds);
8228
8229 argv[0] = createStringObject("EXPIREAT",8);
8230 argv[1] = key;
8231 argv[2] = createObject(REDIS_STRING,
8232 sdscatprintf(sdsempty(),"%ld",when));
8233 buf = catAppendOnlyGenericCommand(buf, argc, argv);
8234 decrRefCount(argv[0]);
8235 decrRefCount(argv[2]);
8236 return buf;
8237}
8238
f80dff62 8239static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
8240 sds buf = sdsempty();
f80dff62 8241 robj *tmpargv[3];
8242
8243 /* The DB this command was targetting is not the same as the last command
8244 * we appendend. To issue a SELECT command is needed. */
8245 if (dictid != server.appendseldb) {
8246 char seldb[64];
8247
8248 snprintf(seldb,sizeof(seldb),"%d",dictid);
682ac724 8249 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
83c6a618 8250 (unsigned long)strlen(seldb),seldb);
f80dff62 8251 server.appendseldb = dictid;
8252 }
8253
f80dff62 8254 if (cmd->proc == expireCommand) {
9376e434
PN
8255 /* Translate EXPIRE into EXPIREAT */
8256 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8257 } else if (cmd->proc == setexCommand) {
8258 /* Translate SETEX to SET and EXPIREAT */
8259 tmpargv[0] = createStringObject("SET",3);
f80dff62 8260 tmpargv[1] = argv[1];
9376e434
PN
8261 tmpargv[2] = argv[3];
8262 buf = catAppendOnlyGenericCommand(buf,3,tmpargv);
8263 decrRefCount(tmpargv[0]);
8264 buf = catAppendOnlyExpireAtCommand(buf,argv[1],argv[2]);
8265 } else {
8266 buf = catAppendOnlyGenericCommand(buf,argc,argv);
f80dff62 8267 }
8268
28ed1f33 8269 /* Append to the AOF buffer. This will be flushed on disk just before
8270 * of re-entering the event loop, so before the client will get a
8271 * positive reply about the operation performed. */
8272 server.aofbuf = sdscatlen(server.aofbuf,buf,sdslen(buf));
8273
85a83172 8274 /* If a background append only file rewriting is in progress we want to
8275 * accumulate the differences between the child DB and the current one
8276 * in a buffer, so that when the child process will do its work we
8277 * can append the differences to the new append only file. */
8278 if (server.bgrewritechildpid != -1)
8279 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
8280
8281 sdsfree(buf);
f80dff62 8282}
8283
8284/* In Redis commands are always executed in the context of a client, so in
8285 * order to load the append only file we need to create a fake client. */
8286static struct redisClient *createFakeClient(void) {
8287 struct redisClient *c = zmalloc(sizeof(*c));
8288
8289 selectDb(c,0);
8290 c->fd = -1;
8291 c->querybuf = sdsempty();
8292 c->argc = 0;
8293 c->argv = NULL;
8294 c->flags = 0;
9387d17d 8295 /* We set the fake client as a slave waiting for the synchronization
8296 * so that Redis will not try to send replies to this client. */
8297 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
f80dff62 8298 c->reply = listCreate();
8299 listSetFreeMethod(c->reply,decrRefCount);
8300 listSetDupMethod(c->reply,dupClientReplyValue);
4132ad8d 8301 initClientMultiState(c);
f80dff62 8302 return c;
8303}
8304
8305static void freeFakeClient(struct redisClient *c) {
8306 sdsfree(c->querybuf);
8307 listRelease(c->reply);
4132ad8d 8308 freeClientMultiState(c);
f80dff62 8309 zfree(c);
8310}
8311
8312/* Replay the append log file. On error REDIS_OK is returned. On non fatal
8313 * error (the append only file is zero-length) REDIS_ERR is returned. On
8314 * fatal error an error message is logged and the program exists. */
8315int loadAppendOnlyFile(char *filename) {
8316 struct redisClient *fakeClient;
8317 FILE *fp = fopen(filename,"r");
8318 struct redis_stat sb;
b492cf00 8319 unsigned long long loadedkeys = 0;
4132ad8d 8320 int appendonly = server.appendonly;
f80dff62 8321
8322 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
8323 return REDIS_ERR;
8324
8325 if (fp == NULL) {
8326 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
8327 exit(1);
8328 }
8329
4132ad8d
PN
8330 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8331 * to the same file we're about to read. */
8332 server.appendonly = 0;
8333
f80dff62 8334 fakeClient = createFakeClient();
8335 while(1) {
8336 int argc, j;
8337 unsigned long len;
8338 robj **argv;
8339 char buf[128];
8340 sds argsds;
8341 struct redisCommand *cmd;
8342
8343 if (fgets(buf,sizeof(buf),fp) == NULL) {
8344 if (feof(fp))
8345 break;
8346 else
8347 goto readerr;
8348 }
8349 if (buf[0] != '*') goto fmterr;
8350 argc = atoi(buf+1);
8351 argv = zmalloc(sizeof(robj*)*argc);
8352 for (j = 0; j < argc; j++) {
8353 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
8354 if (buf[0] != '$') goto fmterr;
8355 len = strtol(buf+1,NULL,10);
8356 argsds = sdsnewlen(NULL,len);
0f151ef1 8357 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
f80dff62 8358 argv[j] = createObject(REDIS_STRING,argsds);
8359 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
8360 }
8361
8362 /* Command lookup */
8363 cmd = lookupCommand(argv[0]->ptr);
8364 if (!cmd) {
8365 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
8366 exit(1);
8367 }
bdcb92f2 8368 /* Try object encoding */
f80dff62 8369 if (cmd->flags & REDIS_CMD_BULK)
05df7621 8370 argv[argc-1] = tryObjectEncoding(argv[argc-1]);
f80dff62 8371 /* Run the command in the context of a fake client */
8372 fakeClient->argc = argc;
8373 fakeClient->argv = argv;
8374 cmd->proc(fakeClient);
8375 /* Discard the reply objects list from the fake client */
8376 while(listLength(fakeClient->reply))
8377 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
8378 /* Clean up, ready for the next command */
8379 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
8380 zfree(argv);
b492cf00 8381 /* Handle swapping while loading big datasets when VM is on */
8382 loadedkeys++;
8383 if (server.vm_enabled && (loadedkeys % 5000) == 0) {
8384 while (zmalloc_used_memory() > server.vm_max_memory) {
a69a0c9c 8385 if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
b492cf00 8386 }
8387 }
f80dff62 8388 }
4132ad8d
PN
8389
8390 /* This point can only be reached when EOF is reached without errors.
8391 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8392 if (fakeClient->flags & REDIS_MULTI) goto readerr;
8393
f80dff62 8394 fclose(fp);
8395 freeFakeClient(fakeClient);
4132ad8d 8396 server.appendonly = appendonly;
f80dff62 8397 return REDIS_OK;
8398
8399readerr:
8400 if (feof(fp)) {
8401 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
8402 } else {
8403 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
8404 }
8405 exit(1);
8406fmterr:
8407 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
8408 exit(1);
8409}
8410
9d65a1bb 8411/* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
9c8e3cee 8412static int fwriteBulkObject(FILE *fp, robj *obj) {
9d65a1bb 8413 char buf[128];
b9bc0eef 8414 int decrrc = 0;
8415
f2d9f50f 8416 /* Avoid the incr/decr ref count business if possible to help
8417 * copy-on-write (we are often in a child process when this function
8418 * is called).
8419 * Also makes sure that key objects don't get incrRefCount-ed when VM
8420 * is enabled */
8421 if (obj->encoding != REDIS_ENCODING_RAW) {
b9bc0eef 8422 obj = getDecodedObject(obj);
8423 decrrc = 1;
8424 }
9d65a1bb 8425 snprintf(buf,sizeof(buf),"$%ld\r\n",(long)sdslen(obj->ptr));
8426 if (fwrite(buf,strlen(buf),1,fp) == 0) goto err;
e96e4fbf 8427 if (sdslen(obj->ptr) && fwrite(obj->ptr,sdslen(obj->ptr),1,fp) == 0)
8428 goto err;
9d65a1bb 8429 if (fwrite("\r\n",2,1,fp) == 0) goto err;
b9bc0eef 8430 if (decrrc) decrRefCount(obj);
9d65a1bb 8431 return 1;
8432err:
b9bc0eef 8433 if (decrrc) decrRefCount(obj);
9d65a1bb 8434 return 0;
8435}
8436
9c8e3cee 8437/* Write binary-safe string into a file in the bulkformat
8438 * $<count>\r\n<payload>\r\n */
8439static int fwriteBulkString(FILE *fp, char *s, unsigned long len) {
8440 char buf[128];
8441
8442 snprintf(buf,sizeof(buf),"$%ld\r\n",(unsigned long)len);
8443 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8444 if (len && fwrite(s,len,1,fp) == 0) return 0;
8445 if (fwrite("\r\n",2,1,fp) == 0) return 0;
8446 return 1;
8447}
8448
9d65a1bb 8449/* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8450static int fwriteBulkDouble(FILE *fp, double d) {
8451 char buf[128], dbuf[128];
8452
8453 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
8454 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
8455 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8456 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
8457 return 1;
8458}
8459
8460/* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8461static int fwriteBulkLong(FILE *fp, long l) {
8462 char buf[128], lbuf[128];
8463
8464 snprintf(lbuf,sizeof(lbuf),"%ld\r\n",l);
8465 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(lbuf)-2);
8466 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
8467 if (fwrite(lbuf,strlen(lbuf),1,fp) == 0) return 0;
8468 return 1;
8469}
8470
8471/* Write a sequence of commands able to fully rebuild the dataset into
8472 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8473static int rewriteAppendOnlyFile(char *filename) {
8474 dictIterator *di = NULL;
8475 dictEntry *de;
8476 FILE *fp;
8477 char tmpfile[256];
8478 int j;
8479 time_t now = time(NULL);
8480
8481 /* Note that we have to use a different temp name here compared to the
8482 * one used by rewriteAppendOnlyFileBackground() function. */
8483 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
8484 fp = fopen(tmpfile,"w");
8485 if (!fp) {
8486 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
8487 return REDIS_ERR;
8488 }
8489 for (j = 0; j < server.dbnum; j++) {
8490 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
8491 redisDb *db = server.db+j;
8492 dict *d = db->dict;
8493 if (dictSize(d) == 0) continue;
8494 di = dictGetIterator(d);
8495 if (!di) {
8496 fclose(fp);
8497 return REDIS_ERR;
8498 }
8499
8500 /* SELECT the new DB */
8501 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
85a83172 8502 if (fwriteBulkLong(fp,j) == 0) goto werr;
9d65a1bb 8503
8504 /* Iterate this DB writing every entry */
8505 while((de = dictNext(di)) != NULL) {
e7546c63 8506 robj *key, *o;
8507 time_t expiretime;
8508 int swapped;
8509
8510 key = dictGetEntryKey(de);
b9bc0eef 8511 /* If the value for this key is swapped, load a preview in memory.
8512 * We use a "swapped" flag to remember if we need to free the
8513 * value object instead to just increment the ref count anyway
8514 * in order to avoid copy-on-write of pages if we are forked() */
996cb5f7 8515 if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
8516 key->storage == REDIS_VM_SWAPPING) {
e7546c63 8517 o = dictGetEntryVal(de);
8518 swapped = 0;
8519 } else {
8520 o = vmPreviewObject(key);
e7546c63 8521 swapped = 1;
8522 }
8523 expiretime = getExpire(db,key);
9d65a1bb 8524
8525 /* Save the key and associated value */
9d65a1bb 8526 if (o->type == REDIS_STRING) {
8527 /* Emit a SET command */
8528 char cmd[]="*3\r\n$3\r\nSET\r\n";
8529 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8530 /* Key and value */
9c8e3cee 8531 if (fwriteBulkObject(fp,key) == 0) goto werr;
8532 if (fwriteBulkObject(fp,o) == 0) goto werr;
9d65a1bb 8533 } else if (o->type == REDIS_LIST) {
8534 /* Emit the RPUSHes needed to rebuild the list */
8535 list *list = o->ptr;
8536 listNode *ln;
c7df85a4 8537 listIter li;
9d65a1bb 8538
c7df85a4 8539 listRewind(list,&li);
8540 while((ln = listNext(&li))) {
9d65a1bb 8541 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
8542 robj *eleobj = listNodeValue(ln);
8543
8544 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8545 if (fwriteBulkObject(fp,key) == 0) goto werr;
8546 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 8547 }
8548 } else if (o->type == REDIS_SET) {
8549 /* Emit the SADDs needed to rebuild the set */
8550 dict *set = o->ptr;
8551 dictIterator *di = dictGetIterator(set);
8552 dictEntry *de;
8553
8554 while((de = dictNext(di)) != NULL) {
8555 char cmd[]="*3\r\n$4\r\nSADD\r\n";
8556 robj *eleobj = dictGetEntryKey(de);
8557
8558 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8559 if (fwriteBulkObject(fp,key) == 0) goto werr;
8560 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 8561 }
8562 dictReleaseIterator(di);
8563 } else if (o->type == REDIS_ZSET) {
8564 /* Emit the ZADDs needed to rebuild the sorted set */
8565 zset *zs = o->ptr;
8566 dictIterator *di = dictGetIterator(zs->dict);
8567 dictEntry *de;
8568
8569 while((de = dictNext(di)) != NULL) {
8570 char cmd[]="*4\r\n$4\r\nZADD\r\n";
8571 robj *eleobj = dictGetEntryKey(de);
8572 double *score = dictGetEntryVal(de);
8573
8574 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8575 if (fwriteBulkObject(fp,key) == 0) goto werr;
9d65a1bb 8576 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
9c8e3cee 8577 if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
9d65a1bb 8578 }
8579 dictReleaseIterator(di);
9c8e3cee 8580 } else if (o->type == REDIS_HASH) {
8581 char cmd[]="*4\r\n$4\r\nHSET\r\n";
8582
8583 /* Emit the HSETs needed to rebuild the hash */
8584 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
8585 unsigned char *p = zipmapRewind(o->ptr);
8586 unsigned char *field, *val;
8587 unsigned int flen, vlen;
8588
8589 while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
8590 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8591 if (fwriteBulkObject(fp,key) == 0) goto werr;
8592 if (fwriteBulkString(fp,(char*)field,flen) == -1)
8593 return -1;
8594 if (fwriteBulkString(fp,(char*)val,vlen) == -1)
8595 return -1;
8596 }
8597 } else {
8598 dictIterator *di = dictGetIterator(o->ptr);
8599 dictEntry *de;
8600
8601 while((de = dictNext(di)) != NULL) {
8602 robj *field = dictGetEntryKey(de);
8603 robj *val = dictGetEntryVal(de);
8604
8605 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
8606 if (fwriteBulkObject(fp,key) == 0) goto werr;
8607 if (fwriteBulkObject(fp,field) == -1) return -1;
8608 if (fwriteBulkObject(fp,val) == -1) return -1;
8609 }
8610 dictReleaseIterator(di);
8611 }
9d65a1bb 8612 } else {
f83c6cb5 8613 redisPanic("Unknown object type");
9d65a1bb 8614 }
8615 /* Save the expire time */
8616 if (expiretime != -1) {
e96e4fbf 8617 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
9d65a1bb 8618 /* If this key is already expired skip it */
8619 if (expiretime < now) continue;
8620 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
9c8e3cee 8621 if (fwriteBulkObject(fp,key) == 0) goto werr;
9d65a1bb 8622 if (fwriteBulkLong(fp,expiretime) == 0) goto werr;
8623 }
b9bc0eef 8624 if (swapped) decrRefCount(o);
9d65a1bb 8625 }
8626 dictReleaseIterator(di);
8627 }
8628
8629 /* Make sure data will not remain on the OS's output buffers */
8630 fflush(fp);
8631 fsync(fileno(fp));
8632 fclose(fp);
e0a62c7f 8633
9d65a1bb 8634 /* Use RENAME to make sure the DB file is changed atomically only
8635 * if the generate DB file is ok. */
8636 if (rename(tmpfile,filename) == -1) {
8637 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
8638 unlink(tmpfile);
8639 return REDIS_ERR;
8640 }
8641 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
8642 return REDIS_OK;
8643
8644werr:
8645 fclose(fp);
8646 unlink(tmpfile);
e96e4fbf 8647 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
9d65a1bb 8648 if (di) dictReleaseIterator(di);
8649 return REDIS_ERR;
8650}
8651
8652/* This is how rewriting of the append only file in background works:
8653 *
8654 * 1) The user calls BGREWRITEAOF
8655 * 2) Redis calls this function, that forks():
8656 * 2a) the child rewrite the append only file in a temp file.
8657 * 2b) the parent accumulates differences in server.bgrewritebuf.
8658 * 3) When the child finished '2a' exists.
8659 * 4) The parent will trap the exit code, if it's OK, will append the
8660 * data accumulated into server.bgrewritebuf into the temp file, and
8661 * finally will rename(2) the temp file in the actual file name.
8662 * The the new file is reopened as the new append only file. Profit!
8663 */
8664static int rewriteAppendOnlyFileBackground(void) {
8665 pid_t childpid;
8666
8667 if (server.bgrewritechildpid != -1) return REDIS_ERR;
054e426d 8668 if (server.vm_enabled) waitEmptyIOJobsQueue();
9d65a1bb 8669 if ((childpid = fork()) == 0) {
8670 /* Child */
8671 char tmpfile[256];
9d65a1bb 8672
054e426d 8673 if (server.vm_enabled) vmReopenSwapFile();
8674 close(server.fd);
9d65a1bb 8675 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
8676 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
478c2c6f 8677 _exit(0);
9d65a1bb 8678 } else {
478c2c6f 8679 _exit(1);
9d65a1bb 8680 }
8681 } else {
8682 /* Parent */
8683 if (childpid == -1) {
8684 redisLog(REDIS_WARNING,
8685 "Can't rewrite append only file in background: fork: %s",
8686 strerror(errno));
8687 return REDIS_ERR;
8688 }
8689 redisLog(REDIS_NOTICE,
8690 "Background append only file rewriting started by pid %d",childpid);
8691 server.bgrewritechildpid = childpid;
884d4b39 8692 updateDictResizePolicy();
85a83172 8693 /* We set appendseldb to -1 in order to force the next call to the
8694 * feedAppendOnlyFile() to issue a SELECT command, so the differences
8695 * accumulated by the parent into server.bgrewritebuf will start
8696 * with a SELECT statement and it will be safe to merge. */
8697 server.appendseldb = -1;
9d65a1bb 8698 return REDIS_OK;
8699 }
8700 return REDIS_OK; /* unreached */
8701}
8702
8703static void bgrewriteaofCommand(redisClient *c) {
8704 if (server.bgrewritechildpid != -1) {
8705 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
8706 return;
8707 }
8708 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
49b99ab4 8709 char *status = "+Background append only file rewriting started\r\n";
8710 addReplySds(c,sdsnew(status));
9d65a1bb 8711 } else {
8712 addReply(c,shared.err);
8713 }
8714}
8715
8716static void aofRemoveTempFile(pid_t childpid) {
8717 char tmpfile[256];
8718
8719 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
8720 unlink(tmpfile);
8721}
8722
996cb5f7 8723/* Virtual Memory is composed mainly of two subsystems:
8724 * - Blocking Virutal Memory
8725 * - Threaded Virtual Memory I/O
8726 * The two parts are not fully decoupled, but functions are split among two
8727 * different sections of the source code (delimited by comments) in order to
8728 * make more clear what functionality is about the blocking VM and what about
8729 * the threaded (not blocking) VM.
8730 *
8731 * Redis VM design:
8732 *
8733 * Redis VM is a blocking VM (one that blocks reading swapped values from
8734 * disk into memory when a value swapped out is needed in memory) that is made
8735 * unblocking by trying to examine the command argument vector in order to
8736 * load in background values that will likely be needed in order to exec
8737 * the command. The command is executed only once all the relevant keys
8738 * are loaded into memory.
8739 *
8740 * This basically is almost as simple of a blocking VM, but almost as parallel
8741 * as a fully non-blocking VM.
8742 */
8743
2e5eb04e 8744/* Called when the user switches from "appendonly yes" to "appendonly no"
8745 * at runtime using the CONFIG command. */
8746static void stopAppendOnly(void) {
8747 flushAppendOnlyFile();
8748 fsync(server.appendfd);
8749 close(server.appendfd);
8750
8751 server.appendfd = -1;
8752 server.appendseldb = -1;
8753 server.appendonly = 0;
8754 /* rewrite operation in progress? kill it, wait child exit */
8755 if (server.bgsavechildpid != -1) {
8756 int statloc;
8757
30dd89b6 8758 if (kill(server.bgsavechildpid,SIGKILL) != -1)
8759 wait3(&statloc,0,NULL);
2e5eb04e 8760 /* reset the buffer accumulating changes while the child saves */
8761 sdsfree(server.bgrewritebuf);
8762 server.bgrewritebuf = sdsempty();
30dd89b6 8763 server.bgsavechildpid = -1;
2e5eb04e 8764 }
8765}
8766
8767/* Called when the user switches from "appendonly no" to "appendonly yes"
8768 * at runtime using the CONFIG command. */
8769static int startAppendOnly(void) {
8770 server.appendonly = 1;
8771 server.lastfsync = time(NULL);
8772 server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
8773 if (server.appendfd == -1) {
8774 redisLog(REDIS_WARNING,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno));
8775 return REDIS_ERR;
8776 }
8777 if (rewriteAppendOnlyFileBackground() == REDIS_ERR) {
8778 server.appendonly = 0;
8779 close(server.appendfd);
8780 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));
8781 return REDIS_ERR;
8782 }
8783 return REDIS_OK;
8784}
8785
996cb5f7 8786/* =================== Virtual Memory - Blocking Side ====================== */
054e426d 8787
75680a3c 8788static void vmInit(void) {
8789 off_t totsize;
996cb5f7 8790 int pipefds[2];
bcaa7a4f 8791 size_t stacksize;
8b5bb414 8792 struct flock fl;
75680a3c 8793
4ad37480 8794 if (server.vm_max_threads != 0)
8795 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
8796
054e426d 8797 redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
8b5bb414 8798 /* Try to open the old swap file, otherwise create it */
6fa987e3 8799 if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
8800 server.vm_fp = fopen(server.vm_swap_file,"w+b");
8801 }
75680a3c 8802 if (server.vm_fp == NULL) {
6fa987e3 8803 redisLog(REDIS_WARNING,
8b5bb414 8804 "Can't open the swap file: %s. Exiting.",
6fa987e3 8805 strerror(errno));
75680a3c 8806 exit(1);
8807 }
8808 server.vm_fd = fileno(server.vm_fp);
8b5bb414 8809 /* Lock the swap file for writing, this is useful in order to avoid
8810 * another instance to use the same swap file for a config error. */
8811 fl.l_type = F_WRLCK;
8812 fl.l_whence = SEEK_SET;
8813 fl.l_start = fl.l_len = 0;
8814 if (fcntl(server.vm_fd,F_SETLK,&fl) == -1) {
8815 redisLog(REDIS_WARNING,
8816 "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));
8817 exit(1);
8818 }
8819 /* Initialize */
75680a3c 8820 server.vm_next_page = 0;
8821 server.vm_near_pages = 0;
7d98e08c 8822 server.vm_stats_used_pages = 0;
8823 server.vm_stats_swapped_objects = 0;
8824 server.vm_stats_swapouts = 0;
8825 server.vm_stats_swapins = 0;
75680a3c 8826 totsize = server.vm_pages*server.vm_page_size;
8827 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
8828 if (ftruncate(server.vm_fd,totsize) == -1) {
8829 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
8830 strerror(errno));
8831 exit(1);
8832 } else {
8833 redisLog(REDIS_NOTICE,"Swap file allocated with success");
8834 }
7d30035d 8835 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
f870935d 8836 redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
4ef8de8a 8837 (long long) (server.vm_pages+7)/8, server.vm_pages);
7d30035d 8838 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
92f8e882 8839
996cb5f7 8840 /* Initialize threaded I/O (used by Virtual Memory) */
8841 server.io_newjobs = listCreate();
8842 server.io_processing = listCreate();
8843 server.io_processed = listCreate();
d5d55fc3 8844 server.io_ready_clients = listCreate();
92f8e882 8845 pthread_mutex_init(&server.io_mutex,NULL);
a5819310 8846 pthread_mutex_init(&server.obj_freelist_mutex,NULL);
8847 pthread_mutex_init(&server.io_swapfile_mutex,NULL);
92f8e882 8848 server.io_active_threads = 0;
996cb5f7 8849 if (pipe(pipefds) == -1) {
8850 redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
8851 ,strerror(errno));
8852 exit(1);
8853 }
8854 server.io_ready_pipe_read = pipefds[0];
8855 server.io_ready_pipe_write = pipefds[1];
8856 redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
bcaa7a4f 8857 /* LZF requires a lot of stack */
8858 pthread_attr_init(&server.io_threads_attr);
8859 pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
8860 while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
8861 pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
b9bc0eef 8862 /* Listen for events in the threaded I/O pipe */
8863 if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
8864 vmThreadedIOCompletedJob, NULL) == AE_ERR)
8865 oom("creating file event");
75680a3c 8866}
8867
06224fec 8868/* Mark the page as used */
8869static void vmMarkPageUsed(off_t page) {
8870 off_t byte = page/8;
8871 int bit = page&7;
970e10bb 8872 redisAssert(vmFreePage(page) == 1);
06224fec 8873 server.vm_bitmap[byte] |= 1<<bit;
8874}
8875
8876/* Mark N contiguous pages as used, with 'page' being the first. */
8877static void vmMarkPagesUsed(off_t page, off_t count) {
8878 off_t j;
8879
8880 for (j = 0; j < count; j++)
7d30035d 8881 vmMarkPageUsed(page+j);
7d98e08c 8882 server.vm_stats_used_pages += count;
7c775e09 8883 redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
8884 (long long)count, (long long)page);
06224fec 8885}
8886
8887/* Mark the page as free */
8888static void vmMarkPageFree(off_t page) {
8889 off_t byte = page/8;
8890 int bit = page&7;
970e10bb 8891 redisAssert(vmFreePage(page) == 0);
06224fec 8892 server.vm_bitmap[byte] &= ~(1<<bit);
8893}
8894
8895/* Mark N contiguous pages as free, with 'page' being the first. */
8896static void vmMarkPagesFree(off_t page, off_t count) {
8897 off_t j;
8898
8899 for (j = 0; j < count; j++)
7d30035d 8900 vmMarkPageFree(page+j);
7d98e08c 8901 server.vm_stats_used_pages -= count;
7c775e09 8902 redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
8903 (long long)count, (long long)page);
06224fec 8904}
8905
8906/* Test if the page is free */
8907static int vmFreePage(off_t page) {
8908 off_t byte = page/8;
8909 int bit = page&7;
7d30035d 8910 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
06224fec 8911}
8912
8913/* Find N contiguous free pages storing the first page of the cluster in *first.
e0a62c7f 8914 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
3a66edc7 8915 * REDIS_ERR is returned.
06224fec 8916 *
8917 * This function uses a simple algorithm: we try to allocate
8918 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
8919 * again from the start of the swap file searching for free spaces.
8920 *
8921 * If it looks pretty clear that there are no free pages near our offset
8922 * we try to find less populated places doing a forward jump of
8923 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
8924 * without hurry, and then we jump again and so forth...
e0a62c7f 8925 *
06224fec 8926 * This function can be improved using a free list to avoid to guess
8927 * too much, since we could collect data about freed pages.
8928 *
8929 * note: I implemented this function just after watching an episode of
8930 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
8931 */
c7df85a4 8932static int vmFindContiguousPages(off_t *first, off_t n) {
06224fec 8933 off_t base, offset = 0, since_jump = 0, numfree = 0;
8934
8935 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
8936 server.vm_near_pages = 0;
8937 server.vm_next_page = 0;
8938 }
8939 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
8940 base = server.vm_next_page;
8941
8942 while(offset < server.vm_pages) {
8943 off_t this = base+offset;
8944
8945 /* If we overflow, restart from page zero */
8946 if (this >= server.vm_pages) {
8947 this -= server.vm_pages;
8948 if (this == 0) {
8949 /* Just overflowed, what we found on tail is no longer
8950 * interesting, as it's no longer contiguous. */
8951 numfree = 0;
8952 }
8953 }
8954 if (vmFreePage(this)) {
8955 /* This is a free page */
8956 numfree++;
8957 /* Already got N free pages? Return to the caller, with success */
8958 if (numfree == n) {
7d30035d 8959 *first = this-(n-1);
8960 server.vm_next_page = this+1;
7c775e09 8961 redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
3a66edc7 8962 return REDIS_OK;
06224fec 8963 }
8964 } else {
8965 /* The current one is not a free page */
8966 numfree = 0;
8967 }
8968
8969 /* Fast-forward if the current page is not free and we already
8970 * searched enough near this place. */
8971 since_jump++;
8972 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
8973 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
8974 since_jump = 0;
8975 /* Note that even if we rewind after the jump, we are don't need
8976 * to make sure numfree is set to zero as we only jump *if* it
8977 * is set to zero. */
8978 } else {
8979 /* Otherwise just check the next page */
8980 offset++;
8981 }
8982 }
3a66edc7 8983 return REDIS_ERR;
8984}
8985
a5819310 8986/* Write the specified object at the specified page of the swap file */
8987static int vmWriteObjectOnSwap(robj *o, off_t page) {
8988 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
8989 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
8990 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
8991 redisLog(REDIS_WARNING,
9ebed7cf 8992 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
a5819310 8993 strerror(errno));
8994 return REDIS_ERR;
8995 }
8996 rdbSaveObject(server.vm_fp,o);
ba76a8f9 8997 fflush(server.vm_fp);
a5819310 8998 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
8999 return REDIS_OK;
9000}
9001
3a66edc7 9002/* Swap the 'val' object relative to 'key' into disk. Store all the information
9003 * needed to later retrieve the object into the key object.
9004 * If we can't find enough contiguous empty pages to swap the object on disk
9005 * REDIS_ERR is returned. */
a69a0c9c 9006static int vmSwapObjectBlocking(robj *key, robj *val) {
b9bc0eef 9007 off_t pages = rdbSavedObjectPages(val,NULL);
3a66edc7 9008 off_t page;
9009
9010 assert(key->storage == REDIS_VM_MEMORY);
4ef8de8a 9011 assert(key->refcount == 1);
3a66edc7 9012 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return REDIS_ERR;
a5819310 9013 if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return REDIS_ERR;
3a66edc7 9014 key->vm.page = page;
9015 key->vm.usedpages = pages;
9016 key->storage = REDIS_VM_SWAPPED;
d894161b 9017 key->vtype = val->type;
3a66edc7 9018 decrRefCount(val); /* Deallocate the object from memory. */
9019 vmMarkPagesUsed(page,pages);
7d30035d 9020 redisLog(REDIS_DEBUG,"VM: object %s swapped out at %lld (%lld pages)",
9021 (unsigned char*) key->ptr,
9022 (unsigned long long) page, (unsigned long long) pages);
7d98e08c 9023 server.vm_stats_swapped_objects++;
9024 server.vm_stats_swapouts++;
3a66edc7 9025 return REDIS_OK;
9026}
9027
a5819310 9028static robj *vmReadObjectFromSwap(off_t page, int type) {
9029 robj *o;
3a66edc7 9030
a5819310 9031 if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
9032 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
3a66edc7 9033 redisLog(REDIS_WARNING,
d5d55fc3 9034 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
3a66edc7 9035 strerror(errno));
478c2c6f 9036 _exit(1);
3a66edc7 9037 }
a5819310 9038 o = rdbLoadObject(type,server.vm_fp);
9039 if (o == NULL) {
d5d55fc3 9040 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
478c2c6f 9041 _exit(1);
3a66edc7 9042 }
a5819310 9043 if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
9044 return o;
9045}
9046
9047/* Load the value object relative to the 'key' object from swap to memory.
9048 * The newly allocated object is returned.
9049 *
9050 * If preview is true the unserialized object is returned to the caller but
9051 * no changes are made to the key object, nor the pages are marked as freed */
9052static robj *vmGenericLoadObject(robj *key, int preview) {
9053 robj *val;
9054
d5d55fc3 9055 redisAssert(key->storage == REDIS_VM_SWAPPED || key->storage == REDIS_VM_LOADING);
a5819310 9056 val = vmReadObjectFromSwap(key->vm.page,key->vtype);
7e69548d 9057 if (!preview) {
9058 key->storage = REDIS_VM_MEMORY;
9059 key->vm.atime = server.unixtime;
9060 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9061 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk",
9062 (unsigned char*) key->ptr);
7d98e08c 9063 server.vm_stats_swapped_objects--;
38aba9a1 9064 } else {
9065 redisLog(REDIS_DEBUG, "VM: object %s previewed from disk",
9066 (unsigned char*) key->ptr);
7e69548d 9067 }
7d98e08c 9068 server.vm_stats_swapins++;
3a66edc7 9069 return val;
06224fec 9070}
9071
7e69548d 9072/* Plain object loading, from swap to memory */
9073static robj *vmLoadObject(robj *key) {
996cb5f7 9074 /* If we are loading the object in background, stop it, we
9075 * need to load this object synchronously ASAP. */
9076 if (key->storage == REDIS_VM_LOADING)
9077 vmCancelThreadedIOJob(key);
7e69548d 9078 return vmGenericLoadObject(key,0);
9079}
9080
9081/* Just load the value on disk, without to modify the key.
9082 * This is useful when we want to perform some operation on the value
9083 * without to really bring it from swap to memory, like while saving the
9084 * dataset or rewriting the append only log. */
9085static robj *vmPreviewObject(robj *key) {
9086 return vmGenericLoadObject(key,1);
9087}
9088
4ef8de8a 9089/* How a good candidate is this object for swapping?
9090 * The better candidate it is, the greater the returned value.
9091 *
9092 * Currently we try to perform a fast estimation of the object size in
9093 * memory, and combine it with aging informations.
9094 *
9095 * Basically swappability = idle-time * log(estimated size)
9096 *
9097 * Bigger objects are preferred over smaller objects, but not
9098 * proportionally, this is why we use the logarithm. This algorithm is
9099 * just a first try and will probably be tuned later. */
9100static double computeObjectSwappability(robj *o) {
9101 time_t age = server.unixtime - o->vm.atime;
9102 long asize = 0;
9103 list *l;
9104 dict *d;
9105 struct dictEntry *de;
9106 int z;
9107
9108 if (age <= 0) return 0;
9109 switch(o->type) {
9110 case REDIS_STRING:
9111 if (o->encoding != REDIS_ENCODING_RAW) {
9112 asize = sizeof(*o);
9113 } else {
9114 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
9115 }
9116 break;
9117 case REDIS_LIST:
9118 l = o->ptr;
9119 listNode *ln = listFirst(l);
9120
9121 asize = sizeof(list);
9122 if (ln) {
9123 robj *ele = ln->value;
9124 long elesize;
9125
9126 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9127 (sizeof(*o)+sdslen(ele->ptr)) :
9128 sizeof(*o);
9129 asize += (sizeof(listNode)+elesize)*listLength(l);
9130 }
9131 break;
9132 case REDIS_SET:
9133 case REDIS_ZSET:
9134 z = (o->type == REDIS_ZSET);
9135 d = z ? ((zset*)o->ptr)->dict : o->ptr;
9136
9137 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9138 if (z) asize += sizeof(zset)-sizeof(dict);
9139 if (dictSize(d)) {
9140 long elesize;
9141 robj *ele;
9142
9143 de = dictGetRandomKey(d);
9144 ele = dictGetEntryKey(de);
9145 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9146 (sizeof(*o)+sdslen(ele->ptr)) :
9147 sizeof(*o);
9148 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9149 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
9150 }
9151 break;
a97b9060 9152 case REDIS_HASH:
9153 if (o->encoding == REDIS_ENCODING_ZIPMAP) {
9154 unsigned char *p = zipmapRewind((unsigned char*)o->ptr);
9155 unsigned int len = zipmapLen((unsigned char*)o->ptr);
9156 unsigned int klen, vlen;
9157 unsigned char *key, *val;
9158
9159 if ((p = zipmapNext(p,&key,&klen,&val,&vlen)) == NULL) {
9160 klen = 0;
9161 vlen = 0;
9162 }
9163 asize = len*(klen+vlen+3);
9164 } else if (o->encoding == REDIS_ENCODING_HT) {
9165 d = o->ptr;
9166 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
9167 if (dictSize(d)) {
9168 long elesize;
9169 robj *ele;
9170
9171 de = dictGetRandomKey(d);
9172 ele = dictGetEntryKey(de);
9173 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9174 (sizeof(*o)+sdslen(ele->ptr)) :
9175 sizeof(*o);
9176 ele = dictGetEntryVal(de);
9177 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
9178 (sizeof(*o)+sdslen(ele->ptr)) :
9179 sizeof(*o);
9180 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
9181 }
9182 }
9183 break;
4ef8de8a 9184 }
c8c72447 9185 return (double)age*log(1+asize);
4ef8de8a 9186}
9187
9188/* Try to swap an object that's a good candidate for swapping.
9189 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
a69a0c9c 9190 * to swap any object at all.
9191 *
9192 * If 'usethreaded' is true, Redis will try to swap the object in background
9193 * using I/O threads. */
9194static int vmSwapOneObject(int usethreads) {
4ef8de8a 9195 int j, i;
9196 struct dictEntry *best = NULL;
9197 double best_swappability = 0;
b9bc0eef 9198 redisDb *best_db = NULL;
4ef8de8a 9199 robj *key, *val;
9200
9201 for (j = 0; j < server.dbnum; j++) {
9202 redisDb *db = server.db+j;
b72f6a4b 9203 /* Why maxtries is set to 100?
9204 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9205 * are swappable objects */
b0d8747d 9206 int maxtries = 100;
4ef8de8a 9207
9208 if (dictSize(db->dict) == 0) continue;
9209 for (i = 0; i < 5; i++) {
9210 dictEntry *de;
9211 double swappability;
9212
e3cadb8a 9213 if (maxtries) maxtries--;
4ef8de8a 9214 de = dictGetRandomKey(db->dict);
9215 key = dictGetEntryKey(de);
9216 val = dictGetEntryVal(de);
1064ef87 9217 /* Only swap objects that are currently in memory.
9218 *
9219 * Also don't swap shared objects if threaded VM is on, as we
9220 * try to ensure that the main thread does not touch the
9221 * object while the I/O thread is using it, but we can't
9222 * control other keys without adding additional mutex. */
9223 if (key->storage != REDIS_VM_MEMORY ||
9224 (server.vm_max_threads != 0 && val->refcount != 1)) {
e3cadb8a 9225 if (maxtries) i--; /* don't count this try */
9226 continue;
9227 }
4ef8de8a 9228 swappability = computeObjectSwappability(val);
9229 if (!best || swappability > best_swappability) {
9230 best = de;
9231 best_swappability = swappability;
b9bc0eef 9232 best_db = db;
4ef8de8a 9233 }
9234 }
9235 }
7c775e09 9236 if (best == NULL) return REDIS_ERR;
4ef8de8a 9237 key = dictGetEntryKey(best);
9238 val = dictGetEntryVal(best);
9239
e3cadb8a 9240 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
4ef8de8a 9241 key->ptr, best_swappability);
9242
9243 /* Unshare the key if needed */
9244 if (key->refcount > 1) {
9245 robj *newkey = dupStringObject(key);
9246 decrRefCount(key);
9247 key = dictGetEntryKey(best) = newkey;
9248 }
9249 /* Swap it */
a69a0c9c 9250 if (usethreads) {
b9bc0eef 9251 vmSwapObjectThreaded(key,val,best_db);
4ef8de8a 9252 return REDIS_OK;
9253 } else {
a69a0c9c 9254 if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
9255 dictGetEntryVal(best) = NULL;
9256 return REDIS_OK;
9257 } else {
9258 return REDIS_ERR;
9259 }
4ef8de8a 9260 }
9261}
9262
a69a0c9c 9263static int vmSwapOneObjectBlocking() {
9264 return vmSwapOneObject(0);
9265}
9266
9267static int vmSwapOneObjectThreaded() {
9268 return vmSwapOneObject(1);
9269}
9270
7e69548d 9271/* Return true if it's safe to swap out objects in a given moment.
9272 * Basically we don't want to swap objects out while there is a BGSAVE
9273 * or a BGAEOREWRITE running in backgroud. */
9274static int vmCanSwapOut(void) {
9275 return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
9276}
9277
1b03836c 9278/* Delete a key if swapped. Returns 1 if the key was found, was swapped
9279 * and was deleted. Otherwise 0 is returned. */
9280static int deleteIfSwapped(redisDb *db, robj *key) {
9281 dictEntry *de;
9282 robj *foundkey;
9283
9284 if ((de = dictFind(db->dict,key)) == NULL) return 0;
9285 foundkey = dictGetEntryKey(de);
9286 if (foundkey->storage == REDIS_VM_MEMORY) return 0;
9287 deleteKey(db,key);
9288 return 1;
9289}
9290
996cb5f7 9291/* =================== Virtual Memory - Threaded I/O ======================= */
9292
b9bc0eef 9293static void freeIOJob(iojob *j) {
d5d55fc3 9294 if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
9295 j->type == REDIS_IOJOB_DO_SWAP ||
9296 j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
b9bc0eef 9297 decrRefCount(j->val);
78ebe4c8 9298 /* We don't decrRefCount the j->key field as we did't incremented
9299 * the count creating IO Jobs. This is because the key field here is
9300 * just used as an indentifier and if a key is removed the Job should
9301 * never be touched again. */
b9bc0eef 9302 zfree(j);
9303}
9304
996cb5f7 9305/* Every time a thread finished a Job, it writes a byte into the write side
9306 * of an unix pipe in order to "awake" the main thread, and this function
9307 * is called. */
9308static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
9309 int mask)
9310{
9311 char buf[1];
b0d8747d 9312 int retval, processed = 0, toprocess = -1, trytoswap = 1;
996cb5f7 9313 REDIS_NOTUSED(el);
9314 REDIS_NOTUSED(mask);
9315 REDIS_NOTUSED(privdata);
9316
9317 /* For every byte we read in the read side of the pipe, there is one
9318 * I/O job completed to process. */
9319 while((retval = read(fd,buf,1)) == 1) {
b9bc0eef 9320 iojob *j;
9321 listNode *ln;
9322 robj *key;
9323 struct dictEntry *de;
9324
996cb5f7 9325 redisLog(REDIS_DEBUG,"Processing I/O completed job");
b9bc0eef 9326
9327 /* Get the processed element (the oldest one) */
9328 lockThreadedIO();
1064ef87 9329 assert(listLength(server.io_processed) != 0);
f6c0bba8 9330 if (toprocess == -1) {
9331 toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
9332 if (toprocess <= 0) toprocess = 1;
9333 }
b9bc0eef 9334 ln = listFirst(server.io_processed);
9335 j = ln->value;
9336 listDelNode(server.io_processed,ln);
9337 unlockThreadedIO();
9338 /* If this job is marked as canceled, just ignore it */
9339 if (j->canceled) {
9340 freeIOJob(j);
9341 continue;
9342 }
9343 /* Post process it in the main thread, as there are things we
9344 * can do just here to avoid race conditions and/or invasive locks */
6c96ba7d 9345 redisLog(REDIS_DEBUG,"Job %p type: %d, key at %p (%s) refcount: %d\n", (void*) j, j->type, (void*)j->key, (char*)j->key->ptr, j->key->refcount);
b9bc0eef 9346 de = dictFind(j->db->dict,j->key);
9347 assert(de != NULL);
9348 key = dictGetEntryKey(de);
9349 if (j->type == REDIS_IOJOB_LOAD) {
d5d55fc3 9350 redisDb *db;
9351
b9bc0eef 9352 /* Key loaded, bring it at home */
9353 key->storage = REDIS_VM_MEMORY;
9354 key->vm.atime = server.unixtime;
9355 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
9356 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
9357 (unsigned char*) key->ptr);
9358 server.vm_stats_swapped_objects--;
9359 server.vm_stats_swapins++;
d5d55fc3 9360 dictGetEntryVal(de) = j->val;
9361 incrRefCount(j->val);
9362 db = j->db;
b9bc0eef 9363 freeIOJob(j);
d5d55fc3 9364 /* Handle clients waiting for this key to be loaded. */
9365 handleClientsBlockedOnSwappedKey(db,key);
b9bc0eef 9366 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9367 /* Now we know the amount of pages required to swap this object.
9368 * Let's find some space for it, and queue this task again
9369 * rebranded as REDIS_IOJOB_DO_SWAP. */
054e426d 9370 if (!vmCanSwapOut() ||
9371 vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
9372 {
9373 /* Ooops... no space or we can't swap as there is
9374 * a fork()ed Redis trying to save stuff on disk. */
b9bc0eef 9375 freeIOJob(j);
054e426d 9376 key->storage = REDIS_VM_MEMORY; /* undo operation */
b9bc0eef 9377 } else {
c7df85a4 9378 /* Note that we need to mark this pages as used now,
9379 * if the job will be canceled, we'll mark them as freed
9380 * again. */
9381 vmMarkPagesUsed(j->page,j->pages);
b9bc0eef 9382 j->type = REDIS_IOJOB_DO_SWAP;
9383 lockThreadedIO();
9384 queueIOJob(j);
9385 unlockThreadedIO();
9386 }
9387 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
9388 robj *val;
9389
9390 /* Key swapped. We can finally free some memory. */
6c96ba7d 9391 if (key->storage != REDIS_VM_SWAPPING) {
9392 printf("key->storage: %d\n",key->storage);
9393 printf("key->name: %s\n",(char*)key->ptr);
9394 printf("key->refcount: %d\n",key->refcount);
9395 printf("val: %p\n",(void*)j->val);
9396 printf("val->type: %d\n",j->val->type);
9397 printf("val->ptr: %s\n",(char*)j->val->ptr);
9398 }
9399 redisAssert(key->storage == REDIS_VM_SWAPPING);
b9bc0eef 9400 val = dictGetEntryVal(de);
9401 key->vm.page = j->page;
9402 key->vm.usedpages = j->pages;
9403 key->storage = REDIS_VM_SWAPPED;
9404 key->vtype = j->val->type;
9405 decrRefCount(val); /* Deallocate the object from memory. */
f11b8647 9406 dictGetEntryVal(de) = NULL;
b9bc0eef 9407 redisLog(REDIS_DEBUG,
9408 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9409 (unsigned char*) key->ptr,
9410 (unsigned long long) j->page, (unsigned long long) j->pages);
9411 server.vm_stats_swapped_objects++;
9412 server.vm_stats_swapouts++;
9413 freeIOJob(j);
f11b8647 9414 /* Put a few more swap requests in queue if we are still
9415 * out of memory */
b0d8747d 9416 if (trytoswap && vmCanSwapOut() &&
9417 zmalloc_used_memory() > server.vm_max_memory)
9418 {
f11b8647 9419 int more = 1;
9420 while(more) {
9421 lockThreadedIO();
9422 more = listLength(server.io_newjobs) <
9423 (unsigned) server.vm_max_threads;
9424 unlockThreadedIO();
9425 /* Don't waste CPU time if swappable objects are rare. */
b0d8747d 9426 if (vmSwapOneObjectThreaded() == REDIS_ERR) {
9427 trytoswap = 0;
9428 break;
9429 }
f11b8647 9430 }
9431 }
b9bc0eef 9432 }
c953f24b 9433 processed++;
f6c0bba8 9434 if (processed == toprocess) return;
996cb5f7 9435 }
9436 if (retval < 0 && errno != EAGAIN) {
9437 redisLog(REDIS_WARNING,
9438 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9439 strerror(errno));
9440 }
9441}
9442
9443static void lockThreadedIO(void) {
9444 pthread_mutex_lock(&server.io_mutex);
9445}
9446
9447static void unlockThreadedIO(void) {
9448 pthread_mutex_unlock(&server.io_mutex);
9449}
9450
9451/* Remove the specified object from the threaded I/O queue if still not
9452 * processed, otherwise make sure to flag it as canceled. */
9453static void vmCancelThreadedIOJob(robj *o) {
9454 list *lists[3] = {
6c96ba7d 9455 server.io_newjobs, /* 0 */
9456 server.io_processing, /* 1 */
9457 server.io_processed /* 2 */
996cb5f7 9458 };
9459 int i;
9460
9461 assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
2e111efe 9462again:
996cb5f7 9463 lockThreadedIO();
9464 /* Search for a matching key in one of the queues */
9465 for (i = 0; i < 3; i++) {
9466 listNode *ln;
c7df85a4 9467 listIter li;
996cb5f7 9468
c7df85a4 9469 listRewind(lists[i],&li);
9470 while ((ln = listNext(&li)) != NULL) {
996cb5f7 9471 iojob *job = ln->value;
9472
6c96ba7d 9473 if (job->canceled) continue; /* Skip this, already canceled. */
78ebe4c8 9474 if (job->key == o) {
970e10bb 9475 redisLog(REDIS_DEBUG,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
9476 (void*)job, (char*)o->ptr, job->type, i);
427a2153 9477 /* Mark the pages as free since the swap didn't happened
9478 * or happened but is now discarded. */
970e10bb 9479 if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
427a2153 9480 vmMarkPagesFree(job->page,job->pages);
9481 /* Cancel the job. It depends on the list the job is
9482 * living in. */
996cb5f7 9483 switch(i) {
9484 case 0: /* io_newjobs */
6c96ba7d 9485 /* If the job was yet not processed the best thing to do
996cb5f7 9486 * is to remove it from the queue at all */
6c96ba7d 9487 freeIOJob(job);
996cb5f7 9488 listDelNode(lists[i],ln);
9489 break;
9490 case 1: /* io_processing */
d5d55fc3 9491 /* Oh Shi- the thread is messing with the Job:
9492 *
9493 * Probably it's accessing the object if this is a
9494 * PREPARE_SWAP or DO_SWAP job.
9495 * If it's a LOAD job it may be reading from disk and
9496 * if we don't wait for the job to terminate before to
9497 * cancel it, maybe in a few microseconds data can be
9498 * corrupted in this pages. So the short story is:
9499 *
9500 * Better to wait for the job to move into the
9501 * next queue (processed)... */
9502
9503 /* We try again and again until the job is completed. */
9504 unlockThreadedIO();
9505 /* But let's wait some time for the I/O thread
9506 * to finish with this job. After all this condition
9507 * should be very rare. */
9508 usleep(1);
9509 goto again;
996cb5f7 9510 case 2: /* io_processed */
2e111efe 9511 /* The job was already processed, that's easy...
9512 * just mark it as canceled so that we'll ignore it
9513 * when processing completed jobs. */
996cb5f7 9514 job->canceled = 1;
9515 break;
9516 }
c7df85a4 9517 /* Finally we have to adjust the storage type of the object
9518 * in order to "UNDO" the operaiton. */
996cb5f7 9519 if (o->storage == REDIS_VM_LOADING)
9520 o->storage = REDIS_VM_SWAPPED;
9521 else if (o->storage == REDIS_VM_SWAPPING)
9522 o->storage = REDIS_VM_MEMORY;
9523 unlockThreadedIO();
9524 return;
9525 }
9526 }
9527 }
9528 unlockThreadedIO();
9529 assert(1 != 1); /* We should never reach this */
9530}
9531
b9bc0eef 9532static void *IOThreadEntryPoint(void *arg) {
9533 iojob *j;
9534 listNode *ln;
9535 REDIS_NOTUSED(arg);
9536
9537 pthread_detach(pthread_self());
9538 while(1) {
9539 /* Get a new job to process */
9540 lockThreadedIO();
9541 if (listLength(server.io_newjobs) == 0) {
9542 /* No new jobs in queue, exit. */
9ebed7cf 9543 redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
9544 (long) pthread_self());
b9bc0eef 9545 server.io_active_threads--;
9546 unlockThreadedIO();
9547 return NULL;
9548 }
9549 ln = listFirst(server.io_newjobs);
9550 j = ln->value;
9551 listDelNode(server.io_newjobs,ln);
9552 /* Add the job in the processing queue */
9553 j->thread = pthread_self();
9554 listAddNodeTail(server.io_processing,j);
9555 ln = listLast(server.io_processing); /* We use ln later to remove it */
9556 unlockThreadedIO();
9ebed7cf 9557 redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
9558 (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
b9bc0eef 9559
9560 /* Process the Job */
9561 if (j->type == REDIS_IOJOB_LOAD) {
d5d55fc3 9562 j->val = vmReadObjectFromSwap(j->page,j->key->vtype);
b9bc0eef 9563 } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
9564 FILE *fp = fopen("/dev/null","w+");
9565 j->pages = rdbSavedObjectPages(j->val,fp);
9566 fclose(fp);
9567 } else if (j->type == REDIS_IOJOB_DO_SWAP) {
a5819310 9568 if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
9569 j->canceled = 1;
b9bc0eef 9570 }
9571
9572 /* Done: insert the job into the processed queue */
9ebed7cf 9573 redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
9574 (long) pthread_self(), (void*)j, (char*)j->key->ptr);
b9bc0eef 9575 lockThreadedIO();
9576 listDelNode(server.io_processing,ln);
9577 listAddNodeTail(server.io_processed,j);
9578 unlockThreadedIO();
e0a62c7f 9579
b9bc0eef 9580 /* Signal the main thread there is new stuff to process */
9581 assert(write(server.io_ready_pipe_write,"x",1) == 1);
9582 }
9583 return NULL; /* never reached */
9584}
9585
9586static void spawnIOThread(void) {
9587 pthread_t thread;
478c2c6f 9588 sigset_t mask, omask;
a97b9060 9589 int err;
b9bc0eef 9590
478c2c6f 9591 sigemptyset(&mask);
9592 sigaddset(&mask,SIGCHLD);
9593 sigaddset(&mask,SIGHUP);
9594 sigaddset(&mask,SIGPIPE);
9595 pthread_sigmask(SIG_SETMASK, &mask, &omask);
a97b9060 9596 while ((err = pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL)) != 0) {
9597 redisLog(REDIS_WARNING,"Unable to spawn an I/O thread: %s",
9598 strerror(err));
9599 usleep(1000000);
9600 }
478c2c6f 9601 pthread_sigmask(SIG_SETMASK, &omask, NULL);
b9bc0eef 9602 server.io_active_threads++;
9603}
9604
4ee9488d 9605/* We need to wait for the last thread to exit before we are able to
9606 * fork() in order to BGSAVE or BGREWRITEAOF. */
054e426d 9607static void waitEmptyIOJobsQueue(void) {
4ee9488d 9608 while(1) {
76b7233a 9609 int io_processed_len;
9610
4ee9488d 9611 lockThreadedIO();
054e426d 9612 if (listLength(server.io_newjobs) == 0 &&
9613 listLength(server.io_processing) == 0 &&
9614 server.io_active_threads == 0)
9615 {
4ee9488d 9616 unlockThreadedIO();
9617 return;
9618 }
76b7233a 9619 /* While waiting for empty jobs queue condition we post-process some
9620 * finshed job, as I/O threads may be hanging trying to write against
9621 * the io_ready_pipe_write FD but there are so much pending jobs that
9622 * it's blocking. */
9623 io_processed_len = listLength(server.io_processed);
4ee9488d 9624 unlockThreadedIO();
76b7233a 9625 if (io_processed_len) {
9626 vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
9627 usleep(1000); /* 1 millisecond */
9628 } else {
9629 usleep(10000); /* 10 milliseconds */
9630 }
4ee9488d 9631 }
9632}
9633
054e426d 9634static void vmReopenSwapFile(void) {
478c2c6f 9635 /* Note: we don't close the old one as we are in the child process
9636 * and don't want to mess at all with the original file object. */
054e426d 9637 server.vm_fp = fopen(server.vm_swap_file,"r+b");
9638 if (server.vm_fp == NULL) {
9639 redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
9640 server.vm_swap_file);
478c2c6f 9641 _exit(1);
054e426d 9642 }
9643 server.vm_fd = fileno(server.vm_fp);
9644}
9645
b9bc0eef 9646/* This function must be called while with threaded IO locked */
9647static void queueIOJob(iojob *j) {
6c96ba7d 9648 redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
9649 (void*)j, j->type, (char*)j->key->ptr);
b9bc0eef 9650 listAddNodeTail(server.io_newjobs,j);
9651 if (server.io_active_threads < server.vm_max_threads)
9652 spawnIOThread();
9653}
9654
9655static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
9656 iojob *j;
e0a62c7f 9657
b9bc0eef 9658 assert(key->storage == REDIS_VM_MEMORY);
9659 assert(key->refcount == 1);
9660
9661 j = zmalloc(sizeof(*j));
9662 j->type = REDIS_IOJOB_PREPARE_SWAP;
9663 j->db = db;
78ebe4c8 9664 j->key = key;
b9bc0eef 9665 j->val = val;
9666 incrRefCount(val);
9667 j->canceled = 0;
9668 j->thread = (pthread_t) -1;
f11b8647 9669 key->storage = REDIS_VM_SWAPPING;
b9bc0eef 9670
9671 lockThreadedIO();
9672 queueIOJob(j);
9673 unlockThreadedIO();
9674 return REDIS_OK;
9675}
9676
b0d8747d 9677/* ============ Virtual Memory - Blocking clients on missing keys =========== */
9678
d5d55fc3 9679/* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
9680 * If there is not already a job loading the key, it is craeted.
9681 * The key is added to the io_keys list in the client structure, and also
9682 * in the hash table mapping swapped keys to waiting clients, that is,
9683 * server.io_waited_keys. */
9684static int waitForSwappedKey(redisClient *c, robj *key) {
9685 struct dictEntry *de;
9686 robj *o;
9687 list *l;
9688
9689 /* If the key does not exist or is already in RAM we don't need to
9690 * block the client at all. */
9691 de = dictFind(c->db->dict,key);
9692 if (de == NULL) return 0;
9693 o = dictGetEntryKey(de);
9694 if (o->storage == REDIS_VM_MEMORY) {
9695 return 0;
9696 } else if (o->storage == REDIS_VM_SWAPPING) {
9697 /* We were swapping the key, undo it! */
9698 vmCancelThreadedIOJob(o);
9699 return 0;
9700 }
e0a62c7f 9701
d5d55fc3 9702 /* OK: the key is either swapped, or being loaded just now. */
9703
9704 /* Add the key to the list of keys this client is waiting for.
9705 * This maps clients to keys they are waiting for. */
9706 listAddNodeTail(c->io_keys,key);
9707 incrRefCount(key);
9708
9709 /* Add the client to the swapped keys => clients waiting map. */
9710 de = dictFind(c->db->io_keys,key);
9711 if (de == NULL) {
9712 int retval;
9713
9714 /* For every key we take a list of clients blocked for it */
9715 l = listCreate();
9716 retval = dictAdd(c->db->io_keys,key,l);
9717 incrRefCount(key);
9718 assert(retval == DICT_OK);
9719 } else {
9720 l = dictGetEntryVal(de);
9721 }
9722 listAddNodeTail(l,c);
9723
9724 /* Are we already loading the key from disk? If not create a job */
9725 if (o->storage == REDIS_VM_SWAPPED) {
9726 iojob *j;
9727
9728 o->storage = REDIS_VM_LOADING;
9729 j = zmalloc(sizeof(*j));
9730 j->type = REDIS_IOJOB_LOAD;
9731 j->db = c->db;
78ebe4c8 9732 j->key = o;
d5d55fc3 9733 j->key->vtype = o->vtype;
9734 j->page = o->vm.page;
9735 j->val = NULL;
9736 j->canceled = 0;
9737 j->thread = (pthread_t) -1;
9738 lockThreadedIO();
9739 queueIOJob(j);
9740 unlockThreadedIO();
9741 }
9742 return 1;
9743}
9744
6f078746
PN
9745/* Preload keys for any command with first, last and step values for
9746 * the command keys prototype, as defined in the command table. */
9747static void waitForMultipleSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
9748 int j, last;
9749 if (cmd->vm_firstkey == 0) return;
9750 last = cmd->vm_lastkey;
9751 if (last < 0) last = argc+last;
9752 for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep) {
9753 redisAssert(j < argc);
9754 waitForSwappedKey(c,argv[j]);
9755 }
9756}
9757
5d373da9 9758/* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
739ba0d2
PN
9759 * Note that the number of keys to preload is user-defined, so we need to
9760 * apply a sanity check against argc. */
ca1788b5 9761static void zunionInterBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
76583ea4 9762 int i, num;
ca1788b5 9763 REDIS_NOTUSED(cmd);
ca1788b5
PN
9764
9765 num = atoi(argv[2]->ptr);
739ba0d2 9766 if (num > (argc-3)) return;
76583ea4 9767 for (i = 0; i < num; i++) {
ca1788b5 9768 waitForSwappedKey(c,argv[3+i]);
76583ea4
PN
9769 }
9770}
9771
3805e04f
PN
9772/* Preload keys needed to execute the entire MULTI/EXEC block.
9773 *
9774 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
9775 * and will block the client when any command requires a swapped out value. */
9776static void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int argc, robj **argv) {
9777 int i, margc;
9778 struct redisCommand *mcmd;
9779 robj **margv;
9780 REDIS_NOTUSED(cmd);
9781 REDIS_NOTUSED(argc);
9782 REDIS_NOTUSED(argv);
9783
9784 if (!(c->flags & REDIS_MULTI)) return;
9785 for (i = 0; i < c->mstate.count; i++) {
9786 mcmd = c->mstate.commands[i].cmd;
9787 margc = c->mstate.commands[i].argc;
9788 margv = c->mstate.commands[i].argv;
9789
9790 if (mcmd->vm_preload_proc != NULL) {
9791 mcmd->vm_preload_proc(c,mcmd,margc,margv);
9792 } else {
9793 waitForMultipleSwappedKeys(c,mcmd,margc,margv);
9794 }
76583ea4
PN
9795 }
9796}
9797
b0d8747d 9798/* Is this client attempting to run a command against swapped keys?
d5d55fc3 9799 * If so, block it ASAP, load the keys in background, then resume it.
b0d8747d 9800 *
d5d55fc3 9801 * The important idea about this function is that it can fail! If keys will
9802 * still be swapped when the client is resumed, this key lookups will
9803 * just block loading keys from disk. In practical terms this should only
9804 * happen with SORT BY command or if there is a bug in this function.
9805 *
9806 * Return 1 if the client is marked as blocked, 0 if the client can
9807 * continue as the keys it is going to access appear to be in memory. */
0a6f3f0f 9808static int blockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd) {
76583ea4 9809 if (cmd->vm_preload_proc != NULL) {
ca1788b5 9810 cmd->vm_preload_proc(c,cmd,c->argc,c->argv);
76583ea4 9811 } else {
6f078746 9812 waitForMultipleSwappedKeys(c,cmd,c->argc,c->argv);
76583ea4
PN
9813 }
9814
d5d55fc3 9815 /* If the client was blocked for at least one key, mark it as blocked. */
9816 if (listLength(c->io_keys)) {
9817 c->flags |= REDIS_IO_WAIT;
9818 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
9819 server.vm_blocked_clients++;
9820 return 1;
9821 } else {
9822 return 0;
9823 }
9824}
9825
9826/* Remove the 'key' from the list of blocked keys for a given client.
9827 *
9828 * The function returns 1 when there are no longer blocking keys after
9829 * the current one was removed (and the client can be unblocked). */
9830static int dontWaitForSwappedKey(redisClient *c, robj *key) {
9831 list *l;
9832 listNode *ln;
9833 listIter li;
9834 struct dictEntry *de;
9835
9836 /* Remove the key from the list of keys this client is waiting for. */
9837 listRewind(c->io_keys,&li);
9838 while ((ln = listNext(&li)) != NULL) {
bf028098 9839 if (equalStringObjects(ln->value,key)) {
d5d55fc3 9840 listDelNode(c->io_keys,ln);
9841 break;
9842 }
9843 }
9844 assert(ln != NULL);
9845
9846 /* Remove the client form the key => waiting clients map. */
9847 de = dictFind(c->db->io_keys,key);
9848 assert(de != NULL);
9849 l = dictGetEntryVal(de);
9850 ln = listSearchKey(l,c);
9851 assert(ln != NULL);
9852 listDelNode(l,ln);
9853 if (listLength(l) == 0)
9854 dictDelete(c->db->io_keys,key);
9855
9856 return listLength(c->io_keys) == 0;
9857}
9858
9859static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
9860 struct dictEntry *de;
9861 list *l;
9862 listNode *ln;
9863 int len;
9864
9865 de = dictFind(db->io_keys,key);
9866 if (!de) return;
9867
9868 l = dictGetEntryVal(de);
9869 len = listLength(l);
9870 /* Note: we can't use something like while(listLength(l)) as the list
9871 * can be freed by the calling function when we remove the last element. */
9872 while (len--) {
9873 ln = listFirst(l);
9874 redisClient *c = ln->value;
9875
9876 if (dontWaitForSwappedKey(c,key)) {
9877 /* Put the client in the list of clients ready to go as we
9878 * loaded all the keys about it. */
9879 listAddNodeTail(server.io_ready_clients,c);
9880 }
9881 }
b0d8747d 9882}
b0d8747d 9883
500ece7c 9884/* =========================== Remote Configuration ========================= */
9885
9886static void configSetCommand(redisClient *c) {
9887 robj *o = getDecodedObject(c->argv[3]);
2e5eb04e 9888 long long ll;
9889
500ece7c 9890 if (!strcasecmp(c->argv[2]->ptr,"dbfilename")) {
9891 zfree(server.dbfilename);
9892 server.dbfilename = zstrdup(o->ptr);
9893 } else if (!strcasecmp(c->argv[2]->ptr,"requirepass")) {
9894 zfree(server.requirepass);
9895 server.requirepass = zstrdup(o->ptr);
9896 } else if (!strcasecmp(c->argv[2]->ptr,"masterauth")) {
9897 zfree(server.masterauth);
9898 server.masterauth = zstrdup(o->ptr);
9899 } else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
2e5eb04e 9900 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
9901 ll < 0) goto badfmt;
9902 server.maxmemory = ll;
9903 } else if (!strcasecmp(c->argv[2]->ptr,"timeout")) {
9904 if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
9905 ll < 0 || ll > LONG_MAX) goto badfmt;
9906 server.maxidletime = ll;
1b677732 9907 } else if (!strcasecmp(c->argv[2]->ptr,"appendfsync")) {
9908 if (!strcasecmp(o->ptr,"no")) {
9909 server.appendfsync = APPENDFSYNC_NO;
9910 } else if (!strcasecmp(o->ptr,"everysec")) {
9911 server.appendfsync = APPENDFSYNC_EVERYSEC;
9912 } else if (!strcasecmp(o->ptr,"always")) {
9913 server.appendfsync = APPENDFSYNC_ALWAYS;
9914 } else {
9915 goto badfmt;
9916 }
2e5eb04e 9917 } else if (!strcasecmp(c->argv[2]->ptr,"appendonly")) {
9918 int old = server.appendonly;
9919 int new = yesnotoi(o->ptr);
9920
9921 if (new == -1) goto badfmt;
9922 if (old != new) {
9923 if (new == 0) {
9924 stopAppendOnly();
9925 } else {
9926 if (startAppendOnly() == REDIS_ERR) {
9927 addReplySds(c,sdscatprintf(sdsempty(),
9928 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
9929 decrRefCount(o);
9930 return;
9931 }
9932 }
9933 }
a34e0a25 9934 } else if (!strcasecmp(c->argv[2]->ptr,"save")) {
9935 int vlen, j;
9936 sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
9937
9938 /* Perform sanity check before setting the new config:
9939 * - Even number of args
9940 * - Seconds >= 1, changes >= 0 */
9941 if (vlen & 1) {
9942 sdsfreesplitres(v,vlen);
9943 goto badfmt;
9944 }
9945 for (j = 0; j < vlen; j++) {
9946 char *eptr;
9947 long val;
9948
9949 val = strtoll(v[j], &eptr, 10);
9950 if (eptr[0] != '\0' ||
9951 ((j & 1) == 0 && val < 1) ||
9952 ((j & 1) == 1 && val < 0)) {
9953 sdsfreesplitres(v,vlen);
9954 goto badfmt;
9955 }
9956 }
9957 /* Finally set the new config */
9958 resetServerSaveParams();
9959 for (j = 0; j < vlen; j += 2) {
9960 time_t seconds;
9961 int changes;
9962
9963 seconds = strtoll(v[j],NULL,10);
9964 changes = strtoll(v[j+1],NULL,10);
9965 appendServerSaveParams(seconds, changes);
9966 }
9967 sdsfreesplitres(v,vlen);
500ece7c 9968 } else {
9969 addReplySds(c,sdscatprintf(sdsempty(),
9970 "-ERR not supported CONFIG parameter %s\r\n",
9971 (char*)c->argv[2]->ptr));
9972 decrRefCount(o);
9973 return;
9974 }
9975 decrRefCount(o);
9976 addReply(c,shared.ok);
a34e0a25 9977 return;
9978
9979badfmt: /* Bad format errors */
9980 addReplySds(c,sdscatprintf(sdsempty(),
9981 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
9982 (char*)o->ptr,
9983 (char*)c->argv[2]->ptr));
9984 decrRefCount(o);
500ece7c 9985}
9986
9987static void configGetCommand(redisClient *c) {
9988 robj *o = getDecodedObject(c->argv[2]);
9989 robj *lenobj = createObject(REDIS_STRING,NULL);
9990 char *pattern = o->ptr;
9991 int matches = 0;
9992
9993 addReply(c,lenobj);
9994 decrRefCount(lenobj);
9995
9996 if (stringmatch(pattern,"dbfilename",0)) {
9997 addReplyBulkCString(c,"dbfilename");
9998 addReplyBulkCString(c,server.dbfilename);
9999 matches++;
10000 }
10001 if (stringmatch(pattern,"requirepass",0)) {
10002 addReplyBulkCString(c,"requirepass");
10003 addReplyBulkCString(c,server.requirepass);
10004 matches++;
10005 }
10006 if (stringmatch(pattern,"masterauth",0)) {
10007 addReplyBulkCString(c,"masterauth");
10008 addReplyBulkCString(c,server.masterauth);
10009 matches++;
10010 }
10011 if (stringmatch(pattern,"maxmemory",0)) {
10012 char buf[128];
10013
2e5eb04e 10014 ll2string(buf,128,server.maxmemory);
500ece7c 10015 addReplyBulkCString(c,"maxmemory");
10016 addReplyBulkCString(c,buf);
10017 matches++;
10018 }
2e5eb04e 10019 if (stringmatch(pattern,"timeout",0)) {
10020 char buf[128];
10021
10022 ll2string(buf,128,server.maxidletime);
10023 addReplyBulkCString(c,"timeout");
10024 addReplyBulkCString(c,buf);
10025 matches++;
10026 }
10027 if (stringmatch(pattern,"appendonly",0)) {
10028 addReplyBulkCString(c,"appendonly");
10029 addReplyBulkCString(c,server.appendonly ? "yes" : "no");
10030 matches++;
10031 }
1b677732 10032 if (stringmatch(pattern,"appendfsync",0)) {
10033 char *policy;
10034
10035 switch(server.appendfsync) {
10036 case APPENDFSYNC_NO: policy = "no"; break;
10037 case APPENDFSYNC_EVERYSEC: policy = "everysec"; break;
10038 case APPENDFSYNC_ALWAYS: policy = "always"; break;
10039 default: policy = "unknown"; break; /* too harmless to panic */
10040 }
10041 addReplyBulkCString(c,"appendfsync");
10042 addReplyBulkCString(c,policy);
10043 matches++;
10044 }
a34e0a25 10045 if (stringmatch(pattern,"save",0)) {
10046 sds buf = sdsempty();
10047 int j;
10048
10049 for (j = 0; j < server.saveparamslen; j++) {
10050 buf = sdscatprintf(buf,"%ld %d",
10051 server.saveparams[j].seconds,
10052 server.saveparams[j].changes);
10053 if (j != server.saveparamslen-1)
10054 buf = sdscatlen(buf," ",1);
10055 }
10056 addReplyBulkCString(c,"save");
10057 addReplyBulkCString(c,buf);
10058 sdsfree(buf);
10059 matches++;
10060 }
500ece7c 10061 decrRefCount(o);
10062 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",matches*2);
10063}
10064
10065static void configCommand(redisClient *c) {
10066 if (!strcasecmp(c->argv[1]->ptr,"set")) {
10067 if (c->argc != 4) goto badarity;
10068 configSetCommand(c);
10069 } else if (!strcasecmp(c->argv[1]->ptr,"get")) {
10070 if (c->argc != 3) goto badarity;
10071 configGetCommand(c);
10072 } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) {
10073 if (c->argc != 2) goto badarity;
10074 server.stat_numcommands = 0;
10075 server.stat_numconnections = 0;
10076 server.stat_expiredkeys = 0;
10077 server.stat_starttime = time(NULL);
10078 addReply(c,shared.ok);
10079 } else {
10080 addReplySds(c,sdscatprintf(sdsempty(),
10081 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10082 }
10083 return;
10084
10085badarity:
10086 addReplySds(c,sdscatprintf(sdsempty(),
10087 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10088 (char*) c->argv[1]->ptr));
10089}
10090
befec3cd 10091/* =========================== Pubsub implementation ======================== */
10092
ffc6b7f8 10093static void freePubsubPattern(void *p) {
10094 pubsubPattern *pat = p;
10095
10096 decrRefCount(pat->pattern);
10097 zfree(pat);
10098}
10099
10100static int listMatchPubsubPattern(void *a, void *b) {
10101 pubsubPattern *pa = a, *pb = b;
10102
10103 return (pa->client == pb->client) &&
bf028098 10104 (equalStringObjects(pa->pattern,pb->pattern));
ffc6b7f8 10105}
10106
10107/* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10108 * 0 if the client was already subscribed to that channel. */
10109static int pubsubSubscribeChannel(redisClient *c, robj *channel) {
befec3cd 10110 struct dictEntry *de;
10111 list *clients = NULL;
10112 int retval = 0;
10113
ffc6b7f8 10114 /* Add the channel to the client -> channels hash table */
10115 if (dictAdd(c->pubsub_channels,channel,NULL) == DICT_OK) {
befec3cd 10116 retval = 1;
ffc6b7f8 10117 incrRefCount(channel);
10118 /* Add the client to the channel -> list of clients hash table */
10119 de = dictFind(server.pubsub_channels,channel);
befec3cd 10120 if (de == NULL) {
10121 clients = listCreate();
ffc6b7f8 10122 dictAdd(server.pubsub_channels,channel,clients);
10123 incrRefCount(channel);
befec3cd 10124 } else {
10125 clients = dictGetEntryVal(de);
10126 }
10127 listAddNodeTail(clients,c);
10128 }
10129 /* Notify the client */
10130 addReply(c,shared.mbulk3);
10131 addReply(c,shared.subscribebulk);
ffc6b7f8 10132 addReplyBulk(c,channel);
482b672d 10133 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
befec3cd 10134 return retval;
10135}
10136
ffc6b7f8 10137/* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10138 * 0 if the client was not subscribed to the specified channel. */
10139static int pubsubUnsubscribeChannel(redisClient *c, robj *channel, int notify) {
befec3cd 10140 struct dictEntry *de;
10141 list *clients;
10142 listNode *ln;
10143 int retval = 0;
10144
ffc6b7f8 10145 /* Remove the channel from the client -> channels hash table */
10146 incrRefCount(channel); /* channel may be just a pointer to the same object
201037f5 10147 we have in the hash tables. Protect it... */
ffc6b7f8 10148 if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
befec3cd 10149 retval = 1;
ffc6b7f8 10150 /* Remove the client from the channel -> clients list hash table */
10151 de = dictFind(server.pubsub_channels,channel);
befec3cd 10152 assert(de != NULL);
10153 clients = dictGetEntryVal(de);
10154 ln = listSearchKey(clients,c);
10155 assert(ln != NULL);
10156 listDelNode(clients,ln);
ff767a75 10157 if (listLength(clients) == 0) {
10158 /* Free the list and associated hash entry at all if this was
10159 * the latest client, so that it will be possible to abuse
ffc6b7f8 10160 * Redis PUBSUB creating millions of channels. */
10161 dictDelete(server.pubsub_channels,channel);
ff767a75 10162 }
befec3cd 10163 }
10164 /* Notify the client */
10165 if (notify) {
10166 addReply(c,shared.mbulk3);
10167 addReply(c,shared.unsubscribebulk);
ffc6b7f8 10168 addReplyBulk(c,channel);
482b672d 10169 addReplyLongLong(c,dictSize(c->pubsub_channels)+
ffc6b7f8 10170 listLength(c->pubsub_patterns));
10171
10172 }
10173 decrRefCount(channel); /* it is finally safe to release it */
10174 return retval;
10175}
10176
10177/* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10178static int pubsubSubscribePattern(redisClient *c, robj *pattern) {
10179 int retval = 0;
10180
10181 if (listSearchKey(c->pubsub_patterns,pattern) == NULL) {
10182 retval = 1;
10183 pubsubPattern *pat;
10184 listAddNodeTail(c->pubsub_patterns,pattern);
10185 incrRefCount(pattern);
10186 pat = zmalloc(sizeof(*pat));
10187 pat->pattern = getDecodedObject(pattern);
10188 pat->client = c;
10189 listAddNodeTail(server.pubsub_patterns,pat);
10190 }
10191 /* Notify the client */
10192 addReply(c,shared.mbulk3);
10193 addReply(c,shared.psubscribebulk);
10194 addReplyBulk(c,pattern);
482b672d 10195 addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
ffc6b7f8 10196 return retval;
10197}
10198
10199/* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10200 * 0 if the client was not subscribed to the specified channel. */
10201static int pubsubUnsubscribePattern(redisClient *c, robj *pattern, int notify) {
10202 listNode *ln;
10203 pubsubPattern pat;
10204 int retval = 0;
10205
10206 incrRefCount(pattern); /* Protect the object. May be the same we remove */
10207 if ((ln = listSearchKey(c->pubsub_patterns,pattern)) != NULL) {
10208 retval = 1;
10209 listDelNode(c->pubsub_patterns,ln);
10210 pat.client = c;
10211 pat.pattern = pattern;
10212 ln = listSearchKey(server.pubsub_patterns,&pat);
10213 listDelNode(server.pubsub_patterns,ln);
10214 }
10215 /* Notify the client */
10216 if (notify) {
10217 addReply(c,shared.mbulk3);
10218 addReply(c,shared.punsubscribebulk);
10219 addReplyBulk(c,pattern);
482b672d 10220 addReplyLongLong(c,dictSize(c->pubsub_channels)+
ffc6b7f8 10221 listLength(c->pubsub_patterns));
befec3cd 10222 }
ffc6b7f8 10223 decrRefCount(pattern);
befec3cd 10224 return retval;
10225}
10226
ffc6b7f8 10227/* Unsubscribe from all the channels. Return the number of channels the
10228 * client was subscribed from. */
10229static int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
10230 dictIterator *di = dictGetIterator(c->pubsub_channels);
befec3cd 10231 dictEntry *de;
10232 int count = 0;
10233
10234 while((de = dictNext(di)) != NULL) {
ffc6b7f8 10235 robj *channel = dictGetEntryKey(de);
befec3cd 10236
ffc6b7f8 10237 count += pubsubUnsubscribeChannel(c,channel,notify);
befec3cd 10238 }
10239 dictReleaseIterator(di);
10240 return count;
10241}
10242
ffc6b7f8 10243/* Unsubscribe from all the patterns. Return the number of patterns the
10244 * client was subscribed from. */
10245static int pubsubUnsubscribeAllPatterns(redisClient *c, int notify) {
10246 listNode *ln;
10247 listIter li;
10248 int count = 0;
10249
10250 listRewind(c->pubsub_patterns,&li);
10251 while ((ln = listNext(&li)) != NULL) {
10252 robj *pattern = ln->value;
10253
10254 count += pubsubUnsubscribePattern(c,pattern,notify);
10255 }
10256 return count;
10257}
10258
befec3cd 10259/* Publish a message */
ffc6b7f8 10260static int pubsubPublishMessage(robj *channel, robj *message) {
befec3cd 10261 int receivers = 0;
10262 struct dictEntry *de;
ffc6b7f8 10263 listNode *ln;
10264 listIter li;
befec3cd 10265
ffc6b7f8 10266 /* Send to clients listening for that channel */
10267 de = dictFind(server.pubsub_channels,channel);
befec3cd 10268 if (de) {
10269 list *list = dictGetEntryVal(de);
10270 listNode *ln;
10271 listIter li;
10272
10273 listRewind(list,&li);
10274 while ((ln = listNext(&li)) != NULL) {
10275 redisClient *c = ln->value;
10276
10277 addReply(c,shared.mbulk3);
10278 addReply(c,shared.messagebulk);
ffc6b7f8 10279 addReplyBulk(c,channel);
befec3cd 10280 addReplyBulk(c,message);
10281 receivers++;
10282 }
10283 }
ffc6b7f8 10284 /* Send to clients listening to matching channels */
10285 if (listLength(server.pubsub_patterns)) {
10286 listRewind(server.pubsub_patterns,&li);
10287 channel = getDecodedObject(channel);
10288 while ((ln = listNext(&li)) != NULL) {
10289 pubsubPattern *pat = ln->value;
10290
10291 if (stringmatchlen((char*)pat->pattern->ptr,
10292 sdslen(pat->pattern->ptr),
10293 (char*)channel->ptr,
10294 sdslen(channel->ptr),0)) {
c8d0ea0e 10295 addReply(pat->client,shared.mbulk4);
10296 addReply(pat->client,shared.pmessagebulk);
10297 addReplyBulk(pat->client,pat->pattern);
ffc6b7f8 10298 addReplyBulk(pat->client,channel);
10299 addReplyBulk(pat->client,message);
10300 receivers++;
10301 }
10302 }
10303 decrRefCount(channel);
10304 }
befec3cd 10305 return receivers;
10306}
10307
10308static void subscribeCommand(redisClient *c) {
10309 int j;
10310
10311 for (j = 1; j < c->argc; j++)
ffc6b7f8 10312 pubsubSubscribeChannel(c,c->argv[j]);
befec3cd 10313}
10314
10315static void unsubscribeCommand(redisClient *c) {
10316 if (c->argc == 1) {
ffc6b7f8 10317 pubsubUnsubscribeAllChannels(c,1);
10318 return;
10319 } else {
10320 int j;
10321
10322 for (j = 1; j < c->argc; j++)
10323 pubsubUnsubscribeChannel(c,c->argv[j],1);
10324 }
10325}
10326
10327static void psubscribeCommand(redisClient *c) {
10328 int j;
10329
10330 for (j = 1; j < c->argc; j++)
10331 pubsubSubscribePattern(c,c->argv[j]);
10332}
10333
10334static void punsubscribeCommand(redisClient *c) {
10335 if (c->argc == 1) {
10336 pubsubUnsubscribeAllPatterns(c,1);
befec3cd 10337 return;
10338 } else {
10339 int j;
10340
10341 for (j = 1; j < c->argc; j++)
ffc6b7f8 10342 pubsubUnsubscribePattern(c,c->argv[j],1);
befec3cd 10343 }
10344}
10345
10346static void publishCommand(redisClient *c) {
10347 int receivers = pubsubPublishMessage(c->argv[1],c->argv[2]);
482b672d 10348 addReplyLongLong(c,receivers);
befec3cd 10349}
10350
7f957c92 10351/* ================================= Debugging ============================== */
10352
ba798261 10353/* Compute the sha1 of string at 's' with 'len' bytes long.
10354 * The SHA1 is then xored againt the string pointed by digest.
10355 * Since xor is commutative, this operation is used in order to
10356 * "add" digests relative to unordered elements.
10357 *
10358 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10359static void xorDigest(unsigned char *digest, void *ptr, size_t len) {
10360 SHA1_CTX ctx;
10361 unsigned char hash[20], *s = ptr;
10362 int j;
10363
10364 SHA1Init(&ctx);
10365 SHA1Update(&ctx,s,len);
10366 SHA1Final(hash,&ctx);
10367
10368 for (j = 0; j < 20; j++)
10369 digest[j] ^= hash[j];
10370}
10371
10372static void xorObjectDigest(unsigned char *digest, robj *o) {
10373 o = getDecodedObject(o);
10374 xorDigest(digest,o->ptr,sdslen(o->ptr));
10375 decrRefCount(o);
10376}
10377
10378/* This function instead of just computing the SHA1 and xoring it
10379 * against diget, also perform the digest of "digest" itself and
10380 * replace the old value with the new one.
10381 *
10382 * So the final digest will be:
10383 *
10384 * digest = SHA1(digest xor SHA1(data))
10385 *
10386 * This function is used every time we want to preserve the order so
10387 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
10388 *
10389 * Also note that mixdigest("foo") followed by mixdigest("bar")
10390 * will lead to a different digest compared to "fo", "obar".
10391 */
10392static void mixDigest(unsigned char *digest, void *ptr, size_t len) {
10393 SHA1_CTX ctx;
10394 char *s = ptr;
10395
10396 xorDigest(digest,s,len);
10397 SHA1Init(&ctx);
10398 SHA1Update(&ctx,digest,20);
10399 SHA1Final(digest,&ctx);
10400}
10401
10402static void mixObjectDigest(unsigned char *digest, robj *o) {
10403 o = getDecodedObject(o);
10404 mixDigest(digest,o->ptr,sdslen(o->ptr));
10405 decrRefCount(o);
10406}
10407
10408/* Compute the dataset digest. Since keys, sets elements, hashes elements
10409 * are not ordered, we use a trick: every aggregate digest is the xor
10410 * of the digests of their elements. This way the order will not change
10411 * the result. For list instead we use a feedback entering the output digest
10412 * as input in order to ensure that a different ordered list will result in
10413 * a different digest. */
10414static void computeDatasetDigest(unsigned char *final) {
10415 unsigned char digest[20];
10416 char buf[128];
10417 dictIterator *di = NULL;
10418 dictEntry *de;
10419 int j;
10420 uint32_t aux;
10421
10422 memset(final,0,20); /* Start with a clean result */
10423
10424 for (j = 0; j < server.dbnum; j++) {
10425 redisDb *db = server.db+j;
10426
10427 if (dictSize(db->dict) == 0) continue;
10428 di = dictGetIterator(db->dict);
10429
10430 /* hash the DB id, so the same dataset moved in a different
10431 * DB will lead to a different digest */
10432 aux = htonl(j);
10433 mixDigest(final,&aux,sizeof(aux));
10434
10435 /* Iterate this DB writing every entry */
10436 while((de = dictNext(di)) != NULL) {
cbae1d34 10437 robj *key, *o, *kcopy;
ba798261 10438 time_t expiretime;
10439
10440 memset(digest,0,20); /* This key-val digest */
10441 key = dictGetEntryKey(de);
cbae1d34 10442
10443 if (!server.vm_enabled) {
10444 mixObjectDigest(digest,key);
ba798261 10445 o = dictGetEntryVal(de);
ba798261 10446 } else {
cbae1d34 10447 /* Don't work with the key directly as when VM is active
10448 * this is unsafe: TODO: fix decrRefCount to check if the
10449 * count really reached 0 to avoid this mess */
10450 kcopy = dupStringObject(key);
10451 mixObjectDigest(digest,kcopy);
10452 o = lookupKeyRead(db,kcopy);
10453 decrRefCount(kcopy);
ba798261 10454 }
10455 aux = htonl(o->type);
10456 mixDigest(digest,&aux,sizeof(aux));
10457 expiretime = getExpire(db,key);
10458
10459 /* Save the key and associated value */
10460 if (o->type == REDIS_STRING) {
10461 mixObjectDigest(digest,o);
10462 } else if (o->type == REDIS_LIST) {
10463 list *list = o->ptr;
10464 listNode *ln;
10465 listIter li;
10466
10467 listRewind(list,&li);
10468 while((ln = listNext(&li))) {
10469 robj *eleobj = listNodeValue(ln);
10470
10471 mixObjectDigest(digest,eleobj);
10472 }
10473 } else if (o->type == REDIS_SET) {
10474 dict *set = o->ptr;
10475 dictIterator *di = dictGetIterator(set);
10476 dictEntry *de;
10477
10478 while((de = dictNext(di)) != NULL) {
10479 robj *eleobj = dictGetEntryKey(de);
10480
10481 xorObjectDigest(digest,eleobj);
10482 }
10483 dictReleaseIterator(di);
10484 } else if (o->type == REDIS_ZSET) {
10485 zset *zs = o->ptr;
10486 dictIterator *di = dictGetIterator(zs->dict);
10487 dictEntry *de;
10488
10489 while((de = dictNext(di)) != NULL) {
10490 robj *eleobj = dictGetEntryKey(de);
10491 double *score = dictGetEntryVal(de);
10492 unsigned char eledigest[20];
10493
10494 snprintf(buf,sizeof(buf),"%.17g",*score);
10495 memset(eledigest,0,20);
10496 mixObjectDigest(eledigest,eleobj);
10497 mixDigest(eledigest,buf,strlen(buf));
10498 xorDigest(digest,eledigest,20);
10499 }
10500 dictReleaseIterator(di);
10501 } else if (o->type == REDIS_HASH) {
10502 hashIterator *hi;
10503 robj *obj;
10504
10505 hi = hashInitIterator(o);
10506 while (hashNext(hi) != REDIS_ERR) {
10507 unsigned char eledigest[20];
10508
10509 memset(eledigest,0,20);
10510 obj = hashCurrent(hi,REDIS_HASH_KEY);
10511 mixObjectDigest(eledigest,obj);
10512 decrRefCount(obj);
10513 obj = hashCurrent(hi,REDIS_HASH_VALUE);
10514 mixObjectDigest(eledigest,obj);
10515 decrRefCount(obj);
10516 xorDigest(digest,eledigest,20);
10517 }
10518 hashReleaseIterator(hi);
10519 } else {
10520 redisPanic("Unknown object type");
10521 }
ba798261 10522 /* If the key has an expire, add it to the mix */
10523 if (expiretime != -1) xorDigest(digest,"!!expire!!",10);
10524 /* We can finally xor the key-val digest to the final digest */
10525 xorDigest(final,digest,20);
10526 }
10527 dictReleaseIterator(di);
10528 }
10529}
10530
7f957c92 10531static void debugCommand(redisClient *c) {
10532 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
10533 *((char*)-1) = 'x';
210e29f7 10534 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
10535 if (rdbSave(server.dbfilename) != REDIS_OK) {
10536 addReply(c,shared.err);
10537 return;
10538 }
10539 emptyDb();
10540 if (rdbLoad(server.dbfilename) != REDIS_OK) {
10541 addReply(c,shared.err);
10542 return;
10543 }
10544 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
10545 addReply(c,shared.ok);
71c2b467 10546 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
10547 emptyDb();
10548 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
10549 addReply(c,shared.err);
10550 return;
10551 }
10552 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
10553 addReply(c,shared.ok);
333298da 10554 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
10555 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
10556 robj *key, *val;
10557
10558 if (!de) {
10559 addReply(c,shared.nokeyerr);
10560 return;
10561 }
10562 key = dictGetEntryKey(de);
10563 val = dictGetEntryVal(de);
59146ef3 10564 if (!server.vm_enabled || (key->storage == REDIS_VM_MEMORY ||
10565 key->storage == REDIS_VM_SWAPPING)) {
07efaf74 10566 char *strenc;
10567 char buf[128];
10568
10569 if (val->encoding < (sizeof(strencoding)/sizeof(char*))) {
10570 strenc = strencoding[val->encoding];
10571 } else {
10572 snprintf(buf,64,"unknown encoding %d\n", val->encoding);
10573 strenc = buf;
10574 }
ace06542 10575 addReplySds(c,sdscatprintf(sdsempty(),
10576 "+Key at:%p refcount:%d, value at:%p refcount:%d "
07efaf74 10577 "encoding:%s serializedlength:%lld\r\n",
682ac724 10578 (void*)key, key->refcount, (void*)val, val->refcount,
07efaf74 10579 strenc, (long long) rdbSavedObjectLen(val,NULL)));
ace06542 10580 } else {
10581 addReplySds(c,sdscatprintf(sdsempty(),
10582 "+Key at:%p refcount:%d, value swapped at: page %llu "
10583 "using %llu pages\r\n",
10584 (void*)key, key->refcount, (unsigned long long) key->vm.page,
10585 (unsigned long long) key->vm.usedpages));
10586 }
78ebe4c8 10587 } else if (!strcasecmp(c->argv[1]->ptr,"swapin") && c->argc == 3) {
10588 lookupKeyRead(c->db,c->argv[2]);
10589 addReply(c,shared.ok);
7d30035d 10590 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
10591 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
10592 robj *key, *val;
10593
10594 if (!server.vm_enabled) {
10595 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
10596 return;
10597 }
10598 if (!de) {
10599 addReply(c,shared.nokeyerr);
10600 return;
10601 }
10602 key = dictGetEntryKey(de);
10603 val = dictGetEntryVal(de);
4ef8de8a 10604 /* If the key is shared we want to create a copy */
10605 if (key->refcount > 1) {
10606 robj *newkey = dupStringObject(key);
10607 decrRefCount(key);
10608 key = dictGetEntryKey(de) = newkey;
10609 }
10610 /* Swap it */
7d30035d 10611 if (key->storage != REDIS_VM_MEMORY) {
10612 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
a69a0c9c 10613 } else if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
7d30035d 10614 dictGetEntryVal(de) = NULL;
10615 addReply(c,shared.ok);
10616 } else {
10617 addReply(c,shared.err);
10618 }
59305dc7 10619 } else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
10620 long keys, j;
10621 robj *key, *val;
10622 char buf[128];
10623
10624 if (getLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != REDIS_OK)
10625 return;
10626 for (j = 0; j < keys; j++) {
10627 snprintf(buf,sizeof(buf),"key:%lu",j);
10628 key = createStringObject(buf,strlen(buf));
10629 if (lookupKeyRead(c->db,key) != NULL) {
10630 decrRefCount(key);
10631 continue;
10632 }
10633 snprintf(buf,sizeof(buf),"value:%lu",j);
10634 val = createStringObject(buf,strlen(buf));
10635 dictAdd(c->db->dict,key,val);
10636 }
10637 addReply(c,shared.ok);
ba798261 10638 } else if (!strcasecmp(c->argv[1]->ptr,"digest") && c->argc == 2) {
10639 unsigned char digest[20];
10640 sds d = sdsnew("+");
10641 int j;
10642
10643 computeDatasetDigest(digest);
10644 for (j = 0; j < 20; j++)
10645 d = sdscatprintf(d, "%02x",digest[j]);
10646
10647 d = sdscatlen(d,"\r\n",2);
10648 addReplySds(c,d);
7f957c92 10649 } else {
333298da 10650 addReplySds(c,sdsnew(
bdcb92f2 10651 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
7f957c92 10652 }
10653}
56906eef 10654
6c96ba7d 10655static void _redisAssert(char *estr, char *file, int line) {
dfc5e96c 10656 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
fdfb02e7 10657 redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
dfc5e96c 10658#ifdef HAVE_BACKTRACE
10659 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
10660 *((char*)-1) = 'x';
10661#endif
10662}
10663
c651fd9e 10664static void _redisPanic(char *msg, char *file, int line) {
10665 redisLog(REDIS_WARNING,"!!! Software Failure. Press left mouse button to continue");
17772754 10666 redisLog(REDIS_WARNING,"Guru Meditation: %s #%s:%d",msg,file,line);
c651fd9e 10667#ifdef HAVE_BACKTRACE
10668 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
10669 *((char*)-1) = 'x';
10670#endif
10671}
10672
bcfc686d 10673/* =================================== Main! ================================ */
56906eef 10674
bcfc686d 10675#ifdef __linux__
10676int linuxOvercommitMemoryValue(void) {
10677 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
10678 char buf[64];
56906eef 10679
bcfc686d 10680 if (!fp) return -1;
10681 if (fgets(buf,64,fp) == NULL) {
10682 fclose(fp);
10683 return -1;
10684 }
10685 fclose(fp);
56906eef 10686
bcfc686d 10687 return atoi(buf);
10688}
10689
10690void linuxOvercommitMemoryWarning(void) {
10691 if (linuxOvercommitMemoryValue() == 0) {
7ccd2d0a 10692 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 10693 }
10694}
10695#endif /* __linux__ */
10696
10697static void daemonize(void) {
10698 int fd;
10699 FILE *fp;
10700
10701 if (fork() != 0) exit(0); /* parent exits */
10702 setsid(); /* create a new session */
10703
10704 /* Every output goes to /dev/null. If Redis is daemonized but
10705 * the 'logfile' is set to 'stdout' in the configuration file
10706 * it will not log at all. */
10707 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
10708 dup2(fd, STDIN_FILENO);
10709 dup2(fd, STDOUT_FILENO);
10710 dup2(fd, STDERR_FILENO);
10711 if (fd > STDERR_FILENO) close(fd);
10712 }
10713 /* Try to write the pid file */
10714 fp = fopen(server.pidfile,"w");
10715 if (fp) {
10716 fprintf(fp,"%d\n",getpid());
10717 fclose(fp);
56906eef 10718 }
56906eef 10719}
10720
42ab0172
AO
10721static void version() {
10722 printf("Redis server version %s\n", REDIS_VERSION);
10723 exit(0);
10724}
10725
723fb69b
AO
10726static void usage() {
10727 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
e9409273 10728 fprintf(stderr," ./redis-server - (read config from stdin)\n");
723fb69b
AO
10729 exit(1);
10730}
10731
bcfc686d 10732int main(int argc, char **argv) {
9651a787 10733 time_t start;
10734
bcfc686d 10735 initServerConfig();
10736 if (argc == 2) {
44efe66e 10737 if (strcmp(argv[1], "-v") == 0 ||
10738 strcmp(argv[1], "--version") == 0) version();
10739 if (strcmp(argv[1], "--help") == 0) usage();
bcfc686d 10740 resetServerSaveParams();
10741 loadServerConfig(argv[1]);
723fb69b
AO
10742 } else if ((argc > 2)) {
10743 usage();
bcfc686d 10744 } else {
10745 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'");
10746 }
bcfc686d 10747 if (server.daemonize) daemonize();
71c54b21 10748 initServer();
bcfc686d 10749 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
10750#ifdef __linux__
10751 linuxOvercommitMemoryWarning();
10752#endif
9651a787 10753 start = time(NULL);
bcfc686d 10754 if (server.appendonly) {
10755 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
9651a787 10756 redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
bcfc686d 10757 } else {
10758 if (rdbLoad(server.dbfilename) == REDIS_OK)
9651a787 10759 redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
bcfc686d 10760 }
bcfc686d 10761 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
d5d55fc3 10762 aeSetBeforeSleepProc(server.el,beforeSleep);
bcfc686d 10763 aeMain(server.el);
10764 aeDeleteEventLoop(server.el);
10765 return 0;
10766}
10767
10768/* ============================= Backtrace support ========================= */
10769
10770#ifdef HAVE_BACKTRACE
10771static char *findFuncName(void *pointer, unsigned long *offset);
10772
56906eef 10773static void *getMcontextEip(ucontext_t *uc) {
10774#if defined(__FreeBSD__)
10775 return (void*) uc->uc_mcontext.mc_eip;
10776#elif defined(__dietlibc__)
10777 return (void*) uc->uc_mcontext.eip;
06db1f50 10778#elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
da0a1620 10779 #if __x86_64__
10780 return (void*) uc->uc_mcontext->__ss.__rip;
10781 #else
56906eef 10782 return (void*) uc->uc_mcontext->__ss.__eip;
da0a1620 10783 #endif
06db1f50 10784#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
cb7e07cc 10785 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
06db1f50 10786 return (void*) uc->uc_mcontext->__ss.__rip;
cbc59b38 10787 #else
10788 return (void*) uc->uc_mcontext->__ss.__eip;
e0a62c7f 10789 #endif
54bac49d 10790#elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
c04c9ac9 10791 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
b91cf5ef 10792#elif defined(__ia64__) /* Linux IA64 */
10793 return (void*) uc->uc_mcontext.sc_ip;
10794#else
10795 return NULL;
56906eef 10796#endif
10797}
10798
10799static void segvHandler(int sig, siginfo_t *info, void *secret) {
10800 void *trace[100];
10801 char **messages = NULL;
10802 int i, trace_size = 0;
10803 unsigned long offset=0;
56906eef 10804 ucontext_t *uc = (ucontext_t*) secret;
1c85b79f 10805 sds infostring;
56906eef 10806 REDIS_NOTUSED(info);
10807
10808 redisLog(REDIS_WARNING,
10809 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
1c85b79f 10810 infostring = genRedisInfoString();
10811 redisLog(REDIS_WARNING, "%s",infostring);
10812 /* It's not safe to sdsfree() the returned string under memory
10813 * corruption conditions. Let it leak as we are going to abort */
e0a62c7f 10814
56906eef 10815 trace_size = backtrace(trace, 100);
de96dbfe 10816 /* overwrite sigaction with caller's address */
b91cf5ef 10817 if (getMcontextEip(uc) != NULL) {
10818 trace[1] = getMcontextEip(uc);
10819 }
56906eef 10820 messages = backtrace_symbols(trace, trace_size);
fe3bbfbe 10821
d76412d1 10822 for (i=1; i<trace_size; ++i) {
56906eef 10823 char *fn = findFuncName(trace[i], &offset), *p;
10824
10825 p = strchr(messages[i],'+');
10826 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
10827 redisLog(REDIS_WARNING,"%s", messages[i]);
10828 } else {
10829 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
10830 }
10831 }
b177fd30 10832 /* free(messages); Don't call free() with possibly corrupted memory. */
478c2c6f 10833 _exit(0);
fe3bbfbe 10834}
56906eef 10835
fab43727 10836static void sigtermHandler(int sig) {
10837 REDIS_NOTUSED(sig);
b58ba105 10838
fab43727 10839 redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
10840 server.shutdown_asap = 1;
b58ba105
AM
10841}
10842
56906eef 10843static void setupSigSegvAction(void) {
10844 struct sigaction act;
10845
10846 sigemptyset (&act.sa_mask);
10847 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
10848 * is used. Otherwise, sa_handler is used */
10849 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
10850 act.sa_sigaction = segvHandler;
10851 sigaction (SIGSEGV, &act, NULL);
10852 sigaction (SIGBUS, &act, NULL);
12fea928 10853 sigaction (SIGFPE, &act, NULL);
10854 sigaction (SIGILL, &act, NULL);
10855 sigaction (SIGBUS, &act, NULL);
b58ba105
AM
10856
10857 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
fab43727 10858 act.sa_handler = sigtermHandler;
b58ba105 10859 sigaction (SIGTERM, &act, NULL);
e65fdc78 10860 return;
56906eef 10861}
e65fdc78 10862
bcfc686d 10863#include "staticsymbols.h"
10864/* This function try to convert a pointer into a function name. It's used in
10865 * oreder to provide a backtrace under segmentation fault that's able to
10866 * display functions declared as static (otherwise the backtrace is useless). */
10867static char *findFuncName(void *pointer, unsigned long *offset){
10868 int i, ret = -1;
10869 unsigned long off, minoff = 0;
ed9b544e 10870
bcfc686d 10871 /* Try to match against the Symbol with the smallest offset */
10872 for (i=0; symsTable[i].pointer; i++) {
10873 unsigned long lp = (unsigned long) pointer;
0bc03378 10874
bcfc686d 10875 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
10876 off=lp-symsTable[i].pointer;
10877 if (ret < 0 || off < minoff) {
10878 minoff=off;
10879 ret=i;
10880 }
10881 }
0bc03378 10882 }
bcfc686d 10883 if (ret == -1) return NULL;
10884 *offset = minoff;
10885 return symsTable[ret].name;
0bc03378 10886}
bcfc686d 10887#else /* HAVE_BACKTRACE */
10888static void setupSigSegvAction(void) {
0bc03378 10889}
bcfc686d 10890#endif /* HAVE_BACKTRACE */
0bc03378 10891
ed9b544e 10892
ed9b544e 10893
bcfc686d 10894/* The End */
10895
10896
ed9b544e 10897