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