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