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