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