]> git.saurik.com Git - redis.git/blame - redis.c
basic VM mostly working!
[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;
9d65a1bb 2193 listAddNodeTail(c->reply,getDecodedObject(obj));
ed9b544e 2194}
2195
2196static void addReplySds(redisClient *c, sds s) {
2197 robj *o = createObject(REDIS_STRING,s);
2198 addReply(c,o);
2199 decrRefCount(o);
2200}
2201
e2665397 2202static void addReplyDouble(redisClient *c, double d) {
2203 char buf[128];
2204
2205 snprintf(buf,sizeof(buf),"%.17g",d);
682ac724 2206 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
83c6a618 2207 (unsigned long) strlen(buf),buf));
e2665397 2208}
2209
942a3961 2210static void addReplyBulkLen(redisClient *c, robj *obj) {
2211 size_t len;
2212
2213 if (obj->encoding == REDIS_ENCODING_RAW) {
2214 len = sdslen(obj->ptr);
2215 } else {
2216 long n = (long)obj->ptr;
2217
e054afda 2218 /* Compute how many bytes will take this integer as a radix 10 string */
942a3961 2219 len = 1;
2220 if (n < 0) {
2221 len++;
2222 n = -n;
2223 }
2224 while((n = n/10) != 0) {
2225 len++;
2226 }
2227 }
83c6a618 2228 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len));
942a3961 2229}
2230
ed9b544e 2231static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
2232 int cport, cfd;
2233 char cip[128];
285add55 2234 redisClient *c;
ed9b544e 2235 REDIS_NOTUSED(el);
2236 REDIS_NOTUSED(mask);
2237 REDIS_NOTUSED(privdata);
2238
2239 cfd = anetAccept(server.neterr, fd, cip, &cport);
2240 if (cfd == AE_ERR) {
2241 redisLog(REDIS_DEBUG,"Accepting client connection: %s", server.neterr);
2242 return;
2243 }
2244 redisLog(REDIS_DEBUG,"Accepted %s:%d", cip, cport);
285add55 2245 if ((c = createClient(cfd)) == NULL) {
ed9b544e 2246 redisLog(REDIS_WARNING,"Error allocating resoures for the client");
2247 close(cfd); /* May be already closed, just ingore errors */
2248 return;
2249 }
285add55 2250 /* If maxclient directive is set and this is one client more... close the
2251 * connection. Note that we create the client instead to check before
2252 * for this condition, since now the socket is already set in nonblocking
2253 * mode and we can send an error for free using the Kernel I/O */
2254 if (server.maxclients && listLength(server.clients) > server.maxclients) {
2255 char *err = "-ERR max number of clients reached\r\n";
2256
2257 /* That's a best effort error message, don't check write errors */
fee803ba 2258 if (write(c->fd,err,strlen(err)) == -1) {
2259 /* Nothing to do, Just to avoid the warning... */
2260 }
285add55 2261 freeClient(c);
2262 return;
2263 }
ed9b544e 2264 server.stat_numconnections++;
2265}
2266
2267/* ======================= Redis objects implementation ===================== */
2268
2269static robj *createObject(int type, void *ptr) {
2270 robj *o;
2271
2272 if (listLength(server.objfreelist)) {
2273 listNode *head = listFirst(server.objfreelist);
2274 o = listNodeValue(head);
2275 listDelNode(server.objfreelist,head);
2276 } else {
75680a3c 2277 if (server.vm_enabled) {
2278 o = zmalloc(sizeof(*o));
2279 } else {
2280 o = zmalloc(sizeof(*o)-sizeof(struct redisObjectVM));
2281 }
ed9b544e 2282 }
ed9b544e 2283 o->type = type;
942a3961 2284 o->encoding = REDIS_ENCODING_RAW;
ed9b544e 2285 o->ptr = ptr;
2286 o->refcount = 1;
3a66edc7 2287 if (server.vm_enabled) {
2288 o->vm.atime = server.unixtime;
2289 o->storage = REDIS_VM_MEMORY;
2290 }
ed9b544e 2291 return o;
2292}
2293
2294static robj *createStringObject(char *ptr, size_t len) {
2295 return createObject(REDIS_STRING,sdsnewlen(ptr,len));
2296}
2297
4ef8de8a 2298static robj *dupStringObject(robj *o) {
2299 return createStringObject(o->ptr,sdslen(o->ptr));
2300}
2301
ed9b544e 2302static robj *createListObject(void) {
2303 list *l = listCreate();
2304
ed9b544e 2305 listSetFreeMethod(l,decrRefCount);
2306 return createObject(REDIS_LIST,l);
2307}
2308
2309static robj *createSetObject(void) {
2310 dict *d = dictCreate(&setDictType,NULL);
ed9b544e 2311 return createObject(REDIS_SET,d);
2312}
2313
1812e024 2314static robj *createZsetObject(void) {
6b47e12e 2315 zset *zs = zmalloc(sizeof(*zs));
2316
2317 zs->dict = dictCreate(&zsetDictType,NULL);
2318 zs->zsl = zslCreate();
2319 return createObject(REDIS_ZSET,zs);
1812e024 2320}
2321
ed9b544e 2322static void freeStringObject(robj *o) {
942a3961 2323 if (o->encoding == REDIS_ENCODING_RAW) {
2324 sdsfree(o->ptr);
2325 }
ed9b544e 2326}
2327
2328static void freeListObject(robj *o) {
2329 listRelease((list*) o->ptr);
2330}
2331
2332static void freeSetObject(robj *o) {
2333 dictRelease((dict*) o->ptr);
2334}
2335
fd8ccf44 2336static void freeZsetObject(robj *o) {
2337 zset *zs = o->ptr;
2338
2339 dictRelease(zs->dict);
2340 zslFree(zs->zsl);
2341 zfree(zs);
2342}
2343
ed9b544e 2344static void freeHashObject(robj *o) {
2345 dictRelease((dict*) o->ptr);
2346}
2347
2348static void incrRefCount(robj *o) {
a35ddf12 2349 assert(!server.vm_enabled || o->storage == REDIS_VM_MEMORY);
ed9b544e 2350 o->refcount++;
2351}
2352
2353static void decrRefCount(void *obj) {
2354 robj *o = obj;
94754ccc 2355
a35ddf12 2356 /* REDIS_VM_SWAPPED */
2357 if (server.vm_enabled && o->storage == REDIS_VM_SWAPPED) {
2358 assert(o->refcount == 1);
2359 assert(o->type == REDIS_STRING);
2360 freeStringObject(o);
2361 vmMarkPagesFree(o->vm.page,o->vm.usedpages);
2362 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
2363 !listAddNodeHead(server.objfreelist,o))
2364 zfree(o);
2365 return;
2366 }
2367 /* REDIS_VM_MEMORY */
ed9b544e 2368 if (--(o->refcount) == 0) {
2369 switch(o->type) {
2370 case REDIS_STRING: freeStringObject(o); break;
2371 case REDIS_LIST: freeListObject(o); break;
2372 case REDIS_SET: freeSetObject(o); break;
fd8ccf44 2373 case REDIS_ZSET: freeZsetObject(o); break;
ed9b544e 2374 case REDIS_HASH: freeHashObject(o); break;
dfc5e96c 2375 default: redisAssert(0 != 0); break;
ed9b544e 2376 }
2377 if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
2378 !listAddNodeHead(server.objfreelist,o))
2379 zfree(o);
2380 }
2381}
2382
942a3961 2383static robj *lookupKey(redisDb *db, robj *key) {
2384 dictEntry *de = dictFind(db->dict,key);
3a66edc7 2385 if (de) {
55cf8433 2386 robj *key = dictGetEntryKey(de);
2387 robj *val = dictGetEntryVal(de);
3a66edc7 2388
55cf8433 2389 if (server.vm_enabled) {
2390 if (key->storage == REDIS_VM_MEMORY) {
2391 /* Update the access time of the key for the aging algorithm. */
2392 key->vm.atime = server.unixtime;
2393 } else {
2394 /* Our value was swapped on disk. Bring it at home. */
2395 assert(val == NULL);
2396 val = vmLoadObject(key);
2397 dictGetEntryVal(de) = val;
2398 }
2399 }
2400 return val;
3a66edc7 2401 } else {
2402 return NULL;
2403 }
942a3961 2404}
2405
2406static robj *lookupKeyRead(redisDb *db, robj *key) {
2407 expireIfNeeded(db,key);
2408 return lookupKey(db,key);
2409}
2410
2411static robj *lookupKeyWrite(redisDb *db, robj *key) {
2412 deleteIfVolatile(db,key);
2413 return lookupKey(db,key);
2414}
2415
2416static int deleteKey(redisDb *db, robj *key) {
2417 int retval;
2418
2419 /* We need to protect key from destruction: after the first dictDelete()
2420 * it may happen that 'key' is no longer valid if we don't increment
2421 * it's count. This may happen when we get the object reference directly
2422 * from the hash table with dictRandomKey() or dict iterators */
2423 incrRefCount(key);
2424 if (dictSize(db->expires)) dictDelete(db->expires,key);
2425 retval = dictDelete(db->dict,key);
2426 decrRefCount(key);
2427
2428 return retval == DICT_OK;
2429}
2430
10c43610 2431/* Try to share an object against the shared objects pool */
2432static robj *tryObjectSharing(robj *o) {
2433 struct dictEntry *de;
2434 unsigned long c;
2435
3305306f 2436 if (o == NULL || server.shareobjects == 0) return o;
10c43610 2437
dfc5e96c 2438 redisAssert(o->type == REDIS_STRING);
10c43610 2439 de = dictFind(server.sharingpool,o);
2440 if (de) {
2441 robj *shared = dictGetEntryKey(de);
2442
2443 c = ((unsigned long) dictGetEntryVal(de))+1;
2444 dictGetEntryVal(de) = (void*) c;
2445 incrRefCount(shared);
2446 decrRefCount(o);
2447 return shared;
2448 } else {
2449 /* Here we are using a stream algorihtm: Every time an object is
2450 * shared we increment its count, everytime there is a miss we
2451 * recrement the counter of a random object. If this object reaches
2452 * zero we remove the object and put the current object instead. */
3305306f 2453 if (dictSize(server.sharingpool) >=
10c43610 2454 server.sharingpoolsize) {
2455 de = dictGetRandomKey(server.sharingpool);
dfc5e96c 2456 redisAssert(de != NULL);
10c43610 2457 c = ((unsigned long) dictGetEntryVal(de))-1;
2458 dictGetEntryVal(de) = (void*) c;
2459 if (c == 0) {
2460 dictDelete(server.sharingpool,de->key);
2461 }
2462 } else {
2463 c = 0; /* If the pool is empty we want to add this object */
2464 }
2465 if (c == 0) {
2466 int retval;
2467
2468 retval = dictAdd(server.sharingpool,o,(void*)1);
dfc5e96c 2469 redisAssert(retval == DICT_OK);
10c43610 2470 incrRefCount(o);
2471 }
2472 return o;
2473 }
2474}
2475
724a51b1 2476/* Check if the nul-terminated string 's' can be represented by a long
2477 * (that is, is a number that fits into long without any other space or
2478 * character before or after the digits).
2479 *
2480 * If so, the function returns REDIS_OK and *longval is set to the value
2481 * of the number. Otherwise REDIS_ERR is returned */
f69f2cba 2482static int isStringRepresentableAsLong(sds s, long *longval) {
724a51b1 2483 char buf[32], *endptr;
2484 long value;
2485 int slen;
2486
2487 value = strtol(s, &endptr, 10);
2488 if (endptr[0] != '\0') return REDIS_ERR;
2489 slen = snprintf(buf,32,"%ld",value);
2490
2491 /* If the number converted back into a string is not identical
2492 * then it's not possible to encode the string as integer */
f69f2cba 2493 if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
724a51b1 2494 if (longval) *longval = value;
2495 return REDIS_OK;
2496}
2497
942a3961 2498/* Try to encode a string object in order to save space */
2499static int tryObjectEncoding(robj *o) {
2500 long value;
942a3961 2501 sds s = o->ptr;
3305306f 2502
942a3961 2503 if (o->encoding != REDIS_ENCODING_RAW)
2504 return REDIS_ERR; /* Already encoded */
3305306f 2505
942a3961 2506 /* It's not save to encode shared objects: shared objects can be shared
2507 * everywhere in the "object space" of Redis. Encoded objects can only
2508 * appear as "values" (and not, for instance, as keys) */
2509 if (o->refcount > 1) return REDIS_ERR;
3305306f 2510
942a3961 2511 /* Currently we try to encode only strings */
dfc5e96c 2512 redisAssert(o->type == REDIS_STRING);
94754ccc 2513
724a51b1 2514 /* Check if we can represent this string as a long integer */
2515 if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return REDIS_ERR;
942a3961 2516
2517 /* Ok, this object can be encoded */
2518 o->encoding = REDIS_ENCODING_INT;
2519 sdsfree(o->ptr);
2520 o->ptr = (void*) value;
2521 return REDIS_OK;
2522}
2523
9d65a1bb 2524/* Get a decoded version of an encoded object (returned as a new object).
2525 * If the object is already raw-encoded just increment the ref count. */
2526static robj *getDecodedObject(robj *o) {
942a3961 2527 robj *dec;
2528
9d65a1bb 2529 if (o->encoding == REDIS_ENCODING_RAW) {
2530 incrRefCount(o);
2531 return o;
2532 }
942a3961 2533 if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
2534 char buf[32];
2535
2536 snprintf(buf,32,"%ld",(long)o->ptr);
2537 dec = createStringObject(buf,strlen(buf));
2538 return dec;
2539 } else {
dfc5e96c 2540 redisAssert(1 != 1);
942a3961 2541 }
3305306f 2542}
2543
d7f43c08 2544/* Compare two string objects via strcmp() or alike.
2545 * Note that the objects may be integer-encoded. In such a case we
2546 * use snprintf() to get a string representation of the numbers on the stack
1fd9bc8a 2547 * and compare the strings, it's much faster than calling getDecodedObject().
2548 *
2549 * Important note: if objects are not integer encoded, but binary-safe strings,
2550 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2551 * binary safe. */
724a51b1 2552static int compareStringObjects(robj *a, robj *b) {
dfc5e96c 2553 redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
d7f43c08 2554 char bufa[128], bufb[128], *astr, *bstr;
2555 int bothsds = 1;
724a51b1 2556
e197b441 2557 if (a == b) return 0;
d7f43c08 2558 if (a->encoding != REDIS_ENCODING_RAW) {
2559 snprintf(bufa,sizeof(bufa),"%ld",(long) a->ptr);
2560 astr = bufa;
2561 bothsds = 0;
724a51b1 2562 } else {
d7f43c08 2563 astr = a->ptr;
724a51b1 2564 }
d7f43c08 2565 if (b->encoding != REDIS_ENCODING_RAW) {
2566 snprintf(bufb,sizeof(bufb),"%ld",(long) b->ptr);
2567 bstr = bufb;
2568 bothsds = 0;
2569 } else {
2570 bstr = b->ptr;
2571 }
2572 return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
724a51b1 2573}
2574
0ea663ea 2575static size_t stringObjectLen(robj *o) {
dfc5e96c 2576 redisAssert(o->type == REDIS_STRING);
0ea663ea 2577 if (o->encoding == REDIS_ENCODING_RAW) {
2578 return sdslen(o->ptr);
2579 } else {
2580 char buf[32];
2581
2582 return snprintf(buf,32,"%ld",(long)o->ptr);
2583 }
2584}
2585
06233c45 2586/*============================ RDB saving/loading =========================== */
ed9b544e 2587
f78fd11b 2588static int rdbSaveType(FILE *fp, unsigned char type) {
2589 if (fwrite(&type,1,1,fp) == 0) return -1;
2590 return 0;
2591}
2592
bb32ede5 2593static int rdbSaveTime(FILE *fp, time_t t) {
2594 int32_t t32 = (int32_t) t;
2595 if (fwrite(&t32,4,1,fp) == 0) return -1;
2596 return 0;
2597}
2598
e3566d4b 2599/* check rdbLoadLen() comments for more info */
f78fd11b 2600static int rdbSaveLen(FILE *fp, uint32_t len) {
2601 unsigned char buf[2];
2602
2603 if (len < (1<<6)) {
2604 /* Save a 6 bit len */
10c43610 2605 buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
f78fd11b 2606 if (fwrite(buf,1,1,fp) == 0) return -1;
2607 } else if (len < (1<<14)) {
2608 /* Save a 14 bit len */
10c43610 2609 buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
f78fd11b 2610 buf[1] = len&0xFF;
17be1a4a 2611 if (fwrite(buf,2,1,fp) == 0) return -1;
f78fd11b 2612 } else {
2613 /* Save a 32 bit len */
10c43610 2614 buf[0] = (REDIS_RDB_32BITLEN<<6);
f78fd11b 2615 if (fwrite(buf,1,1,fp) == 0) return -1;
2616 len = htonl(len);
2617 if (fwrite(&len,4,1,fp) == 0) return -1;
2618 }
2619 return 0;
2620}
2621
e3566d4b 2622/* String objects in the form "2391" "-100" without any space and with a
2623 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2624 * encoded as integers to save space */
56906eef 2625static int rdbTryIntegerEncoding(sds s, unsigned char *enc) {
e3566d4b 2626 long long value;
2627 char *endptr, buf[32];
2628
2629 /* Check if it's possible to encode this value as a number */
2630 value = strtoll(s, &endptr, 10);
2631 if (endptr[0] != '\0') return 0;
2632 snprintf(buf,32,"%lld",value);
2633
2634 /* If the number converted back into a string is not identical
2635 * then it's not possible to encode the string as integer */
2636 if (strlen(buf) != sdslen(s) || memcmp(buf,s,sdslen(s))) return 0;
2637
2638 /* Finally check if it fits in our ranges */
2639 if (value >= -(1<<7) && value <= (1<<7)-1) {
2640 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
2641 enc[1] = value&0xFF;
2642 return 2;
2643 } else if (value >= -(1<<15) && value <= (1<<15)-1) {
2644 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
2645 enc[1] = value&0xFF;
2646 enc[2] = (value>>8)&0xFF;
2647 return 3;
2648 } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
2649 enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
2650 enc[1] = value&0xFF;
2651 enc[2] = (value>>8)&0xFF;
2652 enc[3] = (value>>16)&0xFF;
2653 enc[4] = (value>>24)&0xFF;
2654 return 5;
2655 } else {
2656 return 0;
2657 }
2658}
2659
774e3047 2660static int rdbSaveLzfStringObject(FILE *fp, robj *obj) {
2661 unsigned int comprlen, outlen;
2662 unsigned char byte;
2663 void *out;
2664
2665 /* We require at least four bytes compression for this to be worth it */
2666 outlen = sdslen(obj->ptr)-4;
2667 if (outlen <= 0) return 0;
3a2694c4 2668 if ((out = zmalloc(outlen+1)) == NULL) return 0;
774e3047 2669 comprlen = lzf_compress(obj->ptr, sdslen(obj->ptr), out, outlen);
2670 if (comprlen == 0) {
88e85998 2671 zfree(out);
774e3047 2672 return 0;
2673 }
2674 /* Data compressed! Let's save it on disk */
2675 byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
2676 if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
2677 if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
2678 if (rdbSaveLen(fp,sdslen(obj->ptr)) == -1) goto writeerr;
2679 if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
88e85998 2680 zfree(out);
774e3047 2681 return comprlen;
2682
2683writeerr:
88e85998 2684 zfree(out);
774e3047 2685 return -1;
2686}
2687
e3566d4b 2688/* Save a string objet as [len][data] on disk. If the object is a string
2689 * representation of an integer value we try to safe it in a special form */
942a3961 2690static int rdbSaveStringObjectRaw(FILE *fp, robj *obj) {
2691 size_t len;
e3566d4b 2692 int enclen;
10c43610 2693
942a3961 2694 len = sdslen(obj->ptr);
2695
774e3047 2696 /* Try integer encoding */
e3566d4b 2697 if (len <= 11) {
2698 unsigned char buf[5];
2699 if ((enclen = rdbTryIntegerEncoding(obj->ptr,buf)) > 0) {
2700 if (fwrite(buf,enclen,1,fp) == 0) return -1;
2701 return 0;
2702 }
2703 }
774e3047 2704
2705 /* Try LZF compression - under 20 bytes it's unable to compress even
88e85998 2706 * aaaaaaaaaaaaaaaaaa so skip it */
121f70cf 2707 if (server.rdbcompression && len > 20) {
774e3047 2708 int retval;
2709
2710 retval = rdbSaveLzfStringObject(fp,obj);
2711 if (retval == -1) return -1;
2712 if (retval > 0) return 0;
2713 /* retval == 0 means data can't be compressed, save the old way */
2714 }
2715
2716 /* Store verbatim */
10c43610 2717 if (rdbSaveLen(fp,len) == -1) return -1;
2718 if (len && fwrite(obj->ptr,len,1,fp) == 0) return -1;
2719 return 0;
2720}
2721
942a3961 2722/* Like rdbSaveStringObjectRaw() but handle encoded objects */
2723static int rdbSaveStringObject(FILE *fp, robj *obj) {
2724 int retval;
942a3961 2725
9d65a1bb 2726 obj = getDecodedObject(obj);
2727 retval = rdbSaveStringObjectRaw(fp,obj);
2728 decrRefCount(obj);
2729 return retval;
942a3961 2730}
2731
a7866db6 2732/* Save a double value. Doubles are saved as strings prefixed by an unsigned
2733 * 8 bit integer specifing the length of the representation.
2734 * This 8 bit integer has special values in order to specify the following
2735 * conditions:
2736 * 253: not a number
2737 * 254: + inf
2738 * 255: - inf
2739 */
2740static int rdbSaveDoubleValue(FILE *fp, double val) {
2741 unsigned char buf[128];
2742 int len;
2743
2744 if (isnan(val)) {
2745 buf[0] = 253;
2746 len = 1;
2747 } else if (!isfinite(val)) {
2748 len = 1;
2749 buf[0] = (val < 0) ? 255 : 254;
2750 } else {
eaa256ad 2751 snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
6c446631 2752 buf[0] = strlen((char*)buf+1);
a7866db6 2753 len = buf[0]+1;
2754 }
2755 if (fwrite(buf,len,1,fp) == 0) return -1;
2756 return 0;
2757}
2758
06233c45 2759/* Save a Redis object. */
2760static int rdbSaveObject(FILE *fp, robj *o) {
2761 if (o->type == REDIS_STRING) {
2762 /* Save a string value */
2763 if (rdbSaveStringObject(fp,o) == -1) return -1;
2764 } else if (o->type == REDIS_LIST) {
2765 /* Save a list value */
2766 list *list = o->ptr;
2767 listNode *ln;
2768
2769 listRewind(list);
2770 if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
2771 while((ln = listYield(list))) {
2772 robj *eleobj = listNodeValue(ln);
2773
2774 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
2775 }
2776 } else if (o->type == REDIS_SET) {
2777 /* Save a set value */
2778 dict *set = o->ptr;
2779 dictIterator *di = dictGetIterator(set);
2780 dictEntry *de;
2781
2782 if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
2783 while((de = dictNext(di)) != NULL) {
2784 robj *eleobj = dictGetEntryKey(de);
2785
2786 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
2787 }
2788 dictReleaseIterator(di);
2789 } else if (o->type == REDIS_ZSET) {
2790 /* Save a set value */
2791 zset *zs = o->ptr;
2792 dictIterator *di = dictGetIterator(zs->dict);
2793 dictEntry *de;
2794
2795 if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
2796 while((de = dictNext(di)) != NULL) {
2797 robj *eleobj = dictGetEntryKey(de);
2798 double *score = dictGetEntryVal(de);
2799
2800 if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
2801 if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
2802 }
2803 dictReleaseIterator(di);
2804 } else {
2805 redisAssert(0 != 0);
2806 }
2807 return 0;
2808}
2809
2810/* Return the length the object will have on disk if saved with
2811 * the rdbSaveObject() function. Currently we use a trick to get
2812 * this length with very little changes to the code. In the future
2813 * we could switch to a faster solution. */
2814static off_t rdbSavedObjectLen(robj *o) {
2815 static FILE *fp = NULL;
2816
2817 if (fp == NULL) fp = fopen("/dev/null","w");
2818 assert(fp != NULL);
2819
2820 rewind(fp);
2821 assert(rdbSaveObject(fp,o) != 1);
2822 return ftello(fp);
2823}
2824
06224fec 2825/* Return the number of pages required to save this object in the swap file */
2826static off_t rdbSavedObjectPages(robj *o) {
2827 off_t bytes = rdbSavedObjectLen(o);
2828
2829 return (bytes+(server.vm_page_size-1))/server.vm_page_size;
2830}
2831
ed9b544e 2832/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
f78fd11b 2833static int rdbSave(char *filename) {
ed9b544e 2834 dictIterator *di = NULL;
2835 dictEntry *de;
ed9b544e 2836 FILE *fp;
2837 char tmpfile[256];
2838 int j;
bb32ede5 2839 time_t now = time(NULL);
ed9b544e 2840
a3b21203 2841 snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
ed9b544e 2842 fp = fopen(tmpfile,"w");
2843 if (!fp) {
2844 redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
2845 return REDIS_ERR;
2846 }
f78fd11b 2847 if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
ed9b544e 2848 for (j = 0; j < server.dbnum; j++) {
bb32ede5 2849 redisDb *db = server.db+j;
2850 dict *d = db->dict;
3305306f 2851 if (dictSize(d) == 0) continue;
ed9b544e 2852 di = dictGetIterator(d);
2853 if (!di) {
2854 fclose(fp);
2855 return REDIS_ERR;
2856 }
2857
2858 /* Write the SELECT DB opcode */
f78fd11b 2859 if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
2860 if (rdbSaveLen(fp,j) == -1) goto werr;
ed9b544e 2861
2862 /* Iterate this DB writing every entry */
2863 while((de = dictNext(di)) != NULL) {
2864 robj *key = dictGetEntryKey(de);
2865 robj *o = dictGetEntryVal(de);
bb32ede5 2866 time_t expiretime = getExpire(db,key);
2867
2868 /* Save the expire time */
2869 if (expiretime != -1) {
2870 /* If this key is already expired skip it */
2871 if (expiretime < now) continue;
2872 if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
2873 if (rdbSaveTime(fp,expiretime) == -1) goto werr;
2874 }
2875 /* Save the key and associated value */
f78fd11b 2876 if (rdbSaveType(fp,o->type) == -1) goto werr;
10c43610 2877 if (rdbSaveStringObject(fp,key) == -1) goto werr;
06233c45 2878 /* Save the actual value */
2879 if (rdbSaveObject(fp,o) == -1) goto werr;
ed9b544e 2880 }
2881 dictReleaseIterator(di);
2882 }
2883 /* EOF opcode */
f78fd11b 2884 if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;
2885
2886 /* Make sure data will not remain on the OS's output buffers */
ed9b544e 2887 fflush(fp);
2888 fsync(fileno(fp));
2889 fclose(fp);
2890
2891 /* Use RENAME to make sure the DB file is changed atomically only
2892 * if the generate DB file is ok. */
2893 if (rename(tmpfile,filename) == -1) {
325d1eb4 2894 redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
ed9b544e 2895 unlink(tmpfile);
2896 return REDIS_ERR;
2897 }
2898 redisLog(REDIS_NOTICE,"DB saved on disk");
2899 server.dirty = 0;
2900 server.lastsave = time(NULL);
2901 return REDIS_OK;
2902
2903werr:
2904 fclose(fp);
2905 unlink(tmpfile);
2906 redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
2907 if (di) dictReleaseIterator(di);
2908 return REDIS_ERR;
2909}
2910
f78fd11b 2911static int rdbSaveBackground(char *filename) {
ed9b544e 2912 pid_t childpid;
2913
9d65a1bb 2914 if (server.bgsavechildpid != -1) return REDIS_ERR;
ed9b544e 2915 if ((childpid = fork()) == 0) {
2916 /* Child */
2917 close(server.fd);
f78fd11b 2918 if (rdbSave(filename) == REDIS_OK) {
ed9b544e 2919 exit(0);
2920 } else {
2921 exit(1);
2922 }
2923 } else {
2924 /* Parent */
5a7c647e 2925 if (childpid == -1) {
2926 redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
2927 strerror(errno));
2928 return REDIS_ERR;
2929 }
ed9b544e 2930 redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
9f3c422c 2931 server.bgsavechildpid = childpid;
ed9b544e 2932 return REDIS_OK;
2933 }
2934 return REDIS_OK; /* unreached */
2935}
2936
a3b21203 2937static void rdbRemoveTempFile(pid_t childpid) {
2938 char tmpfile[256];
2939
2940 snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
2941 unlink(tmpfile);
2942}
2943
f78fd11b 2944static int rdbLoadType(FILE *fp) {
2945 unsigned char type;
7b45bfb2 2946 if (fread(&type,1,1,fp) == 0) return -1;
2947 return type;
2948}
2949
bb32ede5 2950static time_t rdbLoadTime(FILE *fp) {
2951 int32_t t32;
2952 if (fread(&t32,4,1,fp) == 0) return -1;
2953 return (time_t) t32;
2954}
2955
e3566d4b 2956/* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
2957 * of this file for a description of how this are stored on disk.
2958 *
2959 * isencoded is set to 1 if the readed length is not actually a length but
2960 * an "encoding type", check the above comments for more info */
c78a8ccc 2961static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
f78fd11b 2962 unsigned char buf[2];
2963 uint32_t len;
c78a8ccc 2964 int type;
f78fd11b 2965
e3566d4b 2966 if (isencoded) *isencoded = 0;
c78a8ccc 2967 if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
2968 type = (buf[0]&0xC0)>>6;
2969 if (type == REDIS_RDB_6BITLEN) {
2970 /* Read a 6 bit len */
2971 return buf[0]&0x3F;
2972 } else if (type == REDIS_RDB_ENCVAL) {
2973 /* Read a 6 bit len encoding type */
2974 if (isencoded) *isencoded = 1;
2975 return buf[0]&0x3F;
2976 } else if (type == REDIS_RDB_14BITLEN) {
2977 /* Read a 14 bit len */
2978 if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
2979 return ((buf[0]&0x3F)<<8)|buf[1];
2980 } else {
2981 /* Read a 32 bit len */
f78fd11b 2982 if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
2983 return ntohl(len);
f78fd11b 2984 }
f78fd11b 2985}
2986
e3566d4b 2987static robj *rdbLoadIntegerObject(FILE *fp, int enctype) {
2988 unsigned char enc[4];
2989 long long val;
2990
2991 if (enctype == REDIS_RDB_ENC_INT8) {
2992 if (fread(enc,1,1,fp) == 0) return NULL;
2993 val = (signed char)enc[0];
2994 } else if (enctype == REDIS_RDB_ENC_INT16) {
2995 uint16_t v;
2996 if (fread(enc,2,1,fp) == 0) return NULL;
2997 v = enc[0]|(enc[1]<<8);
2998 val = (int16_t)v;
2999 } else if (enctype == REDIS_RDB_ENC_INT32) {
3000 uint32_t v;
3001 if (fread(enc,4,1,fp) == 0) return NULL;
3002 v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
3003 val = (int32_t)v;
3004 } else {
3005 val = 0; /* anti-warning */
dfc5e96c 3006 redisAssert(0!=0);
e3566d4b 3007 }
3008 return createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",val));
3009}
3010
c78a8ccc 3011static robj *rdbLoadLzfStringObject(FILE*fp) {
88e85998 3012 unsigned int len, clen;
3013 unsigned char *c = NULL;
3014 sds val = NULL;
3015
c78a8ccc 3016 if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3017 if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
88e85998 3018 if ((c = zmalloc(clen)) == NULL) goto err;
3019 if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
3020 if (fread(c,clen,1,fp) == 0) goto err;
3021 if (lzf_decompress(c,clen,val,len) == 0) goto err;
5109cdff 3022 zfree(c);
88e85998 3023 return createObject(REDIS_STRING,val);
3024err:
3025 zfree(c);
3026 sdsfree(val);
3027 return NULL;
3028}
3029
c78a8ccc 3030static robj *rdbLoadStringObject(FILE*fp) {
e3566d4b 3031 int isencoded;
3032 uint32_t len;
f78fd11b 3033 sds val;
3034
c78a8ccc 3035 len = rdbLoadLen(fp,&isencoded);
e3566d4b 3036 if (isencoded) {
3037 switch(len) {
3038 case REDIS_RDB_ENC_INT8:
3039 case REDIS_RDB_ENC_INT16:
3040 case REDIS_RDB_ENC_INT32:
3305306f 3041 return tryObjectSharing(rdbLoadIntegerObject(fp,len));
88e85998 3042 case REDIS_RDB_ENC_LZF:
c78a8ccc 3043 return tryObjectSharing(rdbLoadLzfStringObject(fp));
e3566d4b 3044 default:
dfc5e96c 3045 redisAssert(0!=0);
e3566d4b 3046 }
3047 }
3048
f78fd11b 3049 if (len == REDIS_RDB_LENERR) return NULL;
3050 val = sdsnewlen(NULL,len);
3051 if (len && fread(val,len,1,fp) == 0) {
3052 sdsfree(val);
3053 return NULL;
3054 }
10c43610 3055 return tryObjectSharing(createObject(REDIS_STRING,val));
f78fd11b 3056}
3057
a7866db6 3058/* For information about double serialization check rdbSaveDoubleValue() */
3059static int rdbLoadDoubleValue(FILE *fp, double *val) {
3060 char buf[128];
3061 unsigned char len;
3062
3063 if (fread(&len,1,1,fp) == 0) return -1;
3064 switch(len) {
3065 case 255: *val = R_NegInf; return 0;
3066 case 254: *val = R_PosInf; return 0;
3067 case 253: *val = R_Nan; return 0;
3068 default:
3069 if (fread(buf,len,1,fp) == 0) return -1;
231d758e 3070 buf[len] = '\0';
a7866db6 3071 sscanf(buf, "%lg", val);
3072 return 0;
3073 }
3074}
3075
c78a8ccc 3076/* Load a Redis object of the specified type from the specified file.
3077 * On success a newly allocated object is returned, otherwise NULL. */
3078static robj *rdbLoadObject(int type, FILE *fp) {
3079 robj *o;
3080
3081 if (type == REDIS_STRING) {
3082 /* Read string value */
3083 if ((o = rdbLoadStringObject(fp)) == NULL) return NULL;
3084 tryObjectEncoding(o);
3085 } else if (type == REDIS_LIST || type == REDIS_SET) {
3086 /* Read list/set value */
3087 uint32_t listlen;
3088
3089 if ((listlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3090 o = (type == REDIS_LIST) ? createListObject() : createSetObject();
3091 /* Load every single element of the list/set */
3092 while(listlen--) {
3093 robj *ele;
3094
3095 if ((ele = rdbLoadStringObject(fp)) == NULL) return NULL;
3096 tryObjectEncoding(ele);
3097 if (type == REDIS_LIST) {
3098 listAddNodeTail((list*)o->ptr,ele);
3099 } else {
3100 dictAdd((dict*)o->ptr,ele,NULL);
3101 }
3102 }
3103 } else if (type == REDIS_ZSET) {
3104 /* Read list/set value */
3105 uint32_t zsetlen;
3106 zset *zs;
3107
3108 if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3109 o = createZsetObject();
3110 zs = o->ptr;
3111 /* Load every single element of the list/set */
3112 while(zsetlen--) {
3113 robj *ele;
3114 double *score = zmalloc(sizeof(double));
3115
3116 if ((ele = rdbLoadStringObject(fp)) == NULL) return NULL;
3117 tryObjectEncoding(ele);
3118 if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
3119 dictAdd(zs->dict,ele,score);
3120 zslInsert(zs->zsl,*score,ele);
3121 incrRefCount(ele); /* added to skiplist */
3122 }
3123 } else {
3124 redisAssert(0 != 0);
3125 }
3126 return o;
3127}
3128
f78fd11b 3129static int rdbLoad(char *filename) {
ed9b544e 3130 FILE *fp;
f78fd11b 3131 robj *keyobj = NULL;
3132 uint32_t dbid;
bb32ede5 3133 int type, retval, rdbver;
3305306f 3134 dict *d = server.db[0].dict;
bb32ede5 3135 redisDb *db = server.db+0;
f78fd11b 3136 char buf[1024];
bb32ede5 3137 time_t expiretime = -1, now = time(NULL);
3138
ed9b544e 3139 fp = fopen(filename,"r");
3140 if (!fp) return REDIS_ERR;
3141 if (fread(buf,9,1,fp) == 0) goto eoferr;
f78fd11b 3142 buf[9] = '\0';
3143 if (memcmp(buf,"REDIS",5) != 0) {
ed9b544e 3144 fclose(fp);
3145 redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
3146 return REDIS_ERR;
3147 }
f78fd11b 3148 rdbver = atoi(buf+5);
c78a8ccc 3149 if (rdbver != 1) {
f78fd11b 3150 fclose(fp);
3151 redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
3152 return REDIS_ERR;
3153 }
ed9b544e 3154 while(1) {
3155 robj *o;
3156
3157 /* Read type. */
f78fd11b 3158 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
bb32ede5 3159 if (type == REDIS_EXPIRETIME) {
3160 if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
3161 /* We read the time so we need to read the object type again */
3162 if ((type = rdbLoadType(fp)) == -1) goto eoferr;
3163 }
ed9b544e 3164 if (type == REDIS_EOF) break;
3165 /* Handle SELECT DB opcode as a special case */
3166 if (type == REDIS_SELECTDB) {
c78a8ccc 3167 if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
e3566d4b 3168 goto eoferr;
ed9b544e 3169 if (dbid >= (unsigned)server.dbnum) {
f78fd11b 3170 redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
ed9b544e 3171 exit(1);
3172 }
bb32ede5 3173 db = server.db+dbid;
3174 d = db->dict;
ed9b544e 3175 continue;
3176 }
3177 /* Read key */
c78a8ccc 3178 if ((keyobj = rdbLoadStringObject(fp)) == NULL) goto eoferr;
3179 /* Read value */
3180 if ((o = rdbLoadObject(type,fp)) == NULL) goto eoferr;
ed9b544e 3181 /* Add the new object in the hash table */
f78fd11b 3182 retval = dictAdd(d,keyobj,o);
ed9b544e 3183 if (retval == DICT_ERR) {
f78fd11b 3184 redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj->ptr);
ed9b544e 3185 exit(1);
3186 }
bb32ede5 3187 /* Set the expire time if needed */
3188 if (expiretime != -1) {
3189 setExpire(db,keyobj,expiretime);
3190 /* Delete this key if already expired */
3191 if (expiretime < now) deleteKey(db,keyobj);
3192 expiretime = -1;
3193 }
f78fd11b 3194 keyobj = o = NULL;
ed9b544e 3195 }
3196 fclose(fp);
3197 return REDIS_OK;
3198
3199eoferr: /* unexpected end of file is handled here with a fatal exit */
e3566d4b 3200 if (keyobj) decrRefCount(keyobj);
f80dff62 3201 redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
ed9b544e 3202 exit(1);
3203 return REDIS_ERR; /* Just to avoid warning */
3204}
3205
3206/*================================== Commands =============================== */
3207
abcb223e 3208static void authCommand(redisClient *c) {
2e77c2ee 3209 if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
abcb223e
BH
3210 c->authenticated = 1;
3211 addReply(c,shared.ok);
3212 } else {
3213 c->authenticated = 0;
fa4c0aba 3214 addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
abcb223e
BH
3215 }
3216}
3217
ed9b544e 3218static void pingCommand(redisClient *c) {
3219 addReply(c,shared.pong);
3220}
3221
3222static void echoCommand(redisClient *c) {
942a3961 3223 addReplyBulkLen(c,c->argv[1]);
ed9b544e 3224 addReply(c,c->argv[1]);
3225 addReply(c,shared.crlf);
3226}
3227
3228/*=================================== Strings =============================== */
3229
3230static void setGenericCommand(redisClient *c, int nx) {
3231 int retval;
3232
333fd216 3233 if (nx) deleteIfVolatile(c->db,c->argv[1]);
3305306f 3234 retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
ed9b544e 3235 if (retval == DICT_ERR) {
3236 if (!nx) {
3305306f 3237 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
ed9b544e 3238 incrRefCount(c->argv[2]);
3239 } else {
c937aa89 3240 addReply(c,shared.czero);
ed9b544e 3241 return;
3242 }
3243 } else {
3244 incrRefCount(c->argv[1]);
3245 incrRefCount(c->argv[2]);
3246 }
3247 server.dirty++;
3305306f 3248 removeExpire(c->db,c->argv[1]);
c937aa89 3249 addReply(c, nx ? shared.cone : shared.ok);
ed9b544e 3250}
3251
3252static void setCommand(redisClient *c) {
a4d1ba9a 3253 setGenericCommand(c,0);
ed9b544e 3254}
3255
3256static void setnxCommand(redisClient *c) {
a4d1ba9a 3257 setGenericCommand(c,1);
ed9b544e 3258}
3259
322fc7d8 3260static int getGenericCommand(redisClient *c) {
3305306f 3261 robj *o = lookupKeyRead(c->db,c->argv[1]);
3262
3263 if (o == NULL) {
c937aa89 3264 addReply(c,shared.nullbulk);
322fc7d8 3265 return REDIS_OK;
ed9b544e 3266 } else {
ed9b544e 3267 if (o->type != REDIS_STRING) {
c937aa89 3268 addReply(c,shared.wrongtypeerr);
322fc7d8 3269 return REDIS_ERR;
ed9b544e 3270 } else {
942a3961 3271 addReplyBulkLen(c,o);
ed9b544e 3272 addReply(c,o);
3273 addReply(c,shared.crlf);
322fc7d8 3274 return REDIS_OK;
ed9b544e 3275 }
3276 }
3277}
3278
322fc7d8 3279static void getCommand(redisClient *c) {
3280 getGenericCommand(c);
3281}
3282
f6b141c5 3283static void getsetCommand(redisClient *c) {
322fc7d8 3284 if (getGenericCommand(c) == REDIS_ERR) return;
a431eb74 3285 if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
3286 dictReplace(c->db->dict,c->argv[1],c->argv[2]);
3287 } else {
3288 incrRefCount(c->argv[1]);
3289 }
3290 incrRefCount(c->argv[2]);
3291 server.dirty++;
3292 removeExpire(c->db,c->argv[1]);
3293}
3294
70003d28 3295static void mgetCommand(redisClient *c) {
70003d28 3296 int j;
3297
c937aa89 3298 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
70003d28 3299 for (j = 1; j < c->argc; j++) {
3305306f 3300 robj *o = lookupKeyRead(c->db,c->argv[j]);
3301 if (o == NULL) {
c937aa89 3302 addReply(c,shared.nullbulk);
70003d28 3303 } else {
70003d28 3304 if (o->type != REDIS_STRING) {
c937aa89 3305 addReply(c,shared.nullbulk);
70003d28 3306 } else {
942a3961 3307 addReplyBulkLen(c,o);
70003d28 3308 addReply(c,o);
3309 addReply(c,shared.crlf);
3310 }
3311 }
3312 }
3313}
3314
6c446631 3315static void msetGenericCommand(redisClient *c, int nx) {
906573e7 3316 int j, busykeys = 0;
6c446631 3317
3318 if ((c->argc % 2) == 0) {
454d4e43 3319 addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
6c446631 3320 return;
3321 }
3322 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3323 * set nothing at all if at least one already key exists. */
3324 if (nx) {
3325 for (j = 1; j < c->argc; j += 2) {
906573e7 3326 if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
3327 busykeys++;
6c446631 3328 }
3329 }
3330 }
906573e7 3331 if (busykeys) {
3332 addReply(c, shared.czero);
3333 return;
3334 }
6c446631 3335
3336 for (j = 1; j < c->argc; j += 2) {
3337 int retval;
3338
17511391 3339 tryObjectEncoding(c->argv[j+1]);
6c446631 3340 retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
3341 if (retval == DICT_ERR) {
3342 dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
3343 incrRefCount(c->argv[j+1]);
3344 } else {
3345 incrRefCount(c->argv[j]);
3346 incrRefCount(c->argv[j+1]);
3347 }
3348 removeExpire(c->db,c->argv[j]);
3349 }
3350 server.dirty += (c->argc-1)/2;
3351 addReply(c, nx ? shared.cone : shared.ok);
3352}
3353
3354static void msetCommand(redisClient *c) {
3355 msetGenericCommand(c,0);
3356}
3357
3358static void msetnxCommand(redisClient *c) {
3359 msetGenericCommand(c,1);
3360}
3361
d68ed120 3362static void incrDecrCommand(redisClient *c, long long incr) {
ed9b544e 3363 long long value;
3364 int retval;
3365 robj *o;
3366
3305306f 3367 o = lookupKeyWrite(c->db,c->argv[1]);
3368 if (o == NULL) {
ed9b544e 3369 value = 0;
3370 } else {
ed9b544e 3371 if (o->type != REDIS_STRING) {
3372 value = 0;
3373 } else {
3374 char *eptr;
3375
942a3961 3376 if (o->encoding == REDIS_ENCODING_RAW)
3377 value = strtoll(o->ptr, &eptr, 10);
3378 else if (o->encoding == REDIS_ENCODING_INT)
3379 value = (long)o->ptr;
3380 else
dfc5e96c 3381 redisAssert(1 != 1);
ed9b544e 3382 }
3383 }
3384
3385 value += incr;
3386 o = createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",value));
942a3961 3387 tryObjectEncoding(o);
3305306f 3388 retval = dictAdd(c->db->dict,c->argv[1],o);
ed9b544e 3389 if (retval == DICT_ERR) {
3305306f 3390 dictReplace(c->db->dict,c->argv[1],o);
3391 removeExpire(c->db,c->argv[1]);
ed9b544e 3392 } else {
3393 incrRefCount(c->argv[1]);
3394 }
3395 server.dirty++;
c937aa89 3396 addReply(c,shared.colon);
ed9b544e 3397 addReply(c,o);
3398 addReply(c,shared.crlf);
3399}
3400
3401static void incrCommand(redisClient *c) {
a4d1ba9a 3402 incrDecrCommand(c,1);
ed9b544e 3403}
3404
3405static void decrCommand(redisClient *c) {
a4d1ba9a 3406 incrDecrCommand(c,-1);
ed9b544e 3407}
3408
3409static void incrbyCommand(redisClient *c) {
d68ed120 3410 long long incr = strtoll(c->argv[2]->ptr, NULL, 10);
a4d1ba9a 3411 incrDecrCommand(c,incr);
ed9b544e 3412}
3413
3414static void decrbyCommand(redisClient *c) {
d68ed120 3415 long long incr = strtoll(c->argv[2]->ptr, NULL, 10);
a4d1ba9a 3416 incrDecrCommand(c,-incr);
ed9b544e 3417}
3418
3419/* ========================= Type agnostic commands ========================= */
3420
3421static void delCommand(redisClient *c) {
5109cdff 3422 int deleted = 0, j;
3423
3424 for (j = 1; j < c->argc; j++) {
3425 if (deleteKey(c->db,c->argv[j])) {
3426 server.dirty++;
3427 deleted++;
3428 }
3429 }
3430 switch(deleted) {
3431 case 0:
c937aa89 3432 addReply(c,shared.czero);
5109cdff 3433 break;
3434 case 1:
3435 addReply(c,shared.cone);
3436 break;
3437 default:
3438 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",deleted));
3439 break;
ed9b544e 3440 }
3441}
3442
3443static void existsCommand(redisClient *c) {
3305306f 3444 addReply(c,lookupKeyRead(c->db,c->argv[1]) ? shared.cone : shared.czero);
ed9b544e 3445}
3446
3447static void selectCommand(redisClient *c) {
3448 int id = atoi(c->argv[1]->ptr);
3449
3450 if (selectDb(c,id) == REDIS_ERR) {
774e3047 3451 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
ed9b544e 3452 } else {
3453 addReply(c,shared.ok);
3454 }
3455}
3456
3457static void randomkeyCommand(redisClient *c) {
3458 dictEntry *de;
3305306f 3459
3460 while(1) {
3461 de = dictGetRandomKey(c->db->dict);
ce7bef07 3462 if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
3305306f 3463 }
ed9b544e 3464 if (de == NULL) {
ce7bef07 3465 addReply(c,shared.plus);
ed9b544e 3466 addReply(c,shared.crlf);
3467 } else {
c937aa89 3468 addReply(c,shared.plus);
ed9b544e 3469 addReply(c,dictGetEntryKey(de));
3470 addReply(c,shared.crlf);
3471 }
3472}
3473
3474static void keysCommand(redisClient *c) {
3475 dictIterator *di;
3476 dictEntry *de;
3477 sds pattern = c->argv[1]->ptr;
3478 int plen = sdslen(pattern);
682ac724 3479 unsigned long numkeys = 0, keyslen = 0;
ed9b544e 3480 robj *lenobj = createObject(REDIS_STRING,NULL);
3481
3305306f 3482 di = dictGetIterator(c->db->dict);
ed9b544e 3483 addReply(c,lenobj);
3484 decrRefCount(lenobj);
3485 while((de = dictNext(di)) != NULL) {
3486 robj *keyobj = dictGetEntryKey(de);
3305306f 3487
ed9b544e 3488 sds key = keyobj->ptr;
3489 if ((pattern[0] == '*' && pattern[1] == '\0') ||
3490 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
3305306f 3491 if (expireIfNeeded(c->db,keyobj) == 0) {
3492 if (numkeys != 0)
3493 addReply(c,shared.space);
3494 addReply(c,keyobj);
3495 numkeys++;
3496 keyslen += sdslen(key);
3497 }
ed9b544e 3498 }
3499 }
3500 dictReleaseIterator(di);
c937aa89 3501 lenobj->ptr = sdscatprintf(sdsempty(),"$%lu\r\n",keyslen+(numkeys ? (numkeys-1) : 0));
ed9b544e 3502 addReply(c,shared.crlf);
3503}
3504
3505static void dbsizeCommand(redisClient *c) {
3506 addReplySds(c,
3305306f 3507 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
ed9b544e 3508}
3509
3510static void lastsaveCommand(redisClient *c) {
3511 addReplySds(c,
c937aa89 3512 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
ed9b544e 3513}
3514
3515static void typeCommand(redisClient *c) {
3305306f 3516 robj *o;
ed9b544e 3517 char *type;
3305306f 3518
3519 o = lookupKeyRead(c->db,c->argv[1]);
3520 if (o == NULL) {
c937aa89 3521 type = "+none";
ed9b544e 3522 } else {
ed9b544e 3523 switch(o->type) {
c937aa89 3524 case REDIS_STRING: type = "+string"; break;
3525 case REDIS_LIST: type = "+list"; break;
3526 case REDIS_SET: type = "+set"; break;
412a8bce 3527 case REDIS_ZSET: type = "+zset"; break;
ed9b544e 3528 default: type = "unknown"; break;
3529 }
3530 }
3531 addReplySds(c,sdsnew(type));
3532 addReply(c,shared.crlf);
3533}
3534
3535static void saveCommand(redisClient *c) {
9d65a1bb 3536 if (server.bgsavechildpid != -1) {
05557f6d 3537 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
3538 return;
3539 }
f78fd11b 3540 if (rdbSave(server.dbfilename) == REDIS_OK) {
ed9b544e 3541 addReply(c,shared.ok);
3542 } else {
3543 addReply(c,shared.err);
3544 }
3545}
3546
3547static void bgsaveCommand(redisClient *c) {
9d65a1bb 3548 if (server.bgsavechildpid != -1) {
ed9b544e 3549 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
3550 return;
3551 }
f78fd11b 3552 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
49b99ab4 3553 char *status = "+Background saving started\r\n";
3554 addReplySds(c,sdsnew(status));
ed9b544e 3555 } else {
3556 addReply(c,shared.err);
3557 }
3558}
3559
3560static void shutdownCommand(redisClient *c) {
3561 redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
a3b21203 3562 /* Kill the saving child if there is a background saving in progress.
3563 We want to avoid race conditions, for instance our saving child may
3564 overwrite the synchronous saving did by SHUTDOWN. */
9d65a1bb 3565 if (server.bgsavechildpid != -1) {
9f3c422c 3566 redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
3567 kill(server.bgsavechildpid,SIGKILL);
a3b21203 3568 rdbRemoveTempFile(server.bgsavechildpid);
9f3c422c 3569 }
ac945e2d 3570 if (server.appendonly) {
3571 /* Append only file: fsync() the AOF and exit */
3572 fsync(server.appendfd);
3573 exit(0);
ed9b544e 3574 } else {
ac945e2d 3575 /* Snapshotting. Perform a SYNC SAVE and exit */
3576 if (rdbSave(server.dbfilename) == REDIS_OK) {
3577 if (server.daemonize)
3578 unlink(server.pidfile);
3579 redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
3580 redisLog(REDIS_WARNING,"Server exit now, bye bye...");
3581 exit(0);
3582 } else {
3583 /* Ooops.. error saving! The best we can do is to continue operating.
3584 * Note that if there was a background saving process, in the next
3585 * cron() Redis will be notified that the background saving aborted,
3586 * handling special stuff like slaves pending for synchronization... */
3587 redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
3588 addReplySds(c,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3589 }
ed9b544e 3590 }
3591}
3592
3593static void renameGenericCommand(redisClient *c, int nx) {
ed9b544e 3594 robj *o;
3595
3596 /* To use the same key as src and dst is probably an error */
3597 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
c937aa89 3598 addReply(c,shared.sameobjecterr);
ed9b544e 3599 return;
3600 }
3601
3305306f 3602 o = lookupKeyWrite(c->db,c->argv[1]);
3603 if (o == NULL) {
c937aa89 3604 addReply(c,shared.nokeyerr);
ed9b544e 3605 return;
3606 }
ed9b544e 3607 incrRefCount(o);
3305306f 3608 deleteIfVolatile(c->db,c->argv[2]);
3609 if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
ed9b544e 3610 if (nx) {
3611 decrRefCount(o);
c937aa89 3612 addReply(c,shared.czero);
ed9b544e 3613 return;
3614 }
3305306f 3615 dictReplace(c->db->dict,c->argv[2],o);
ed9b544e 3616 } else {
3617 incrRefCount(c->argv[2]);
3618 }
3305306f 3619 deleteKey(c->db,c->argv[1]);
ed9b544e 3620 server.dirty++;
c937aa89 3621 addReply(c,nx ? shared.cone : shared.ok);
ed9b544e 3622}
3623
3624static void renameCommand(redisClient *c) {
3625 renameGenericCommand(c,0);
3626}
3627
3628static void renamenxCommand(redisClient *c) {
3629 renameGenericCommand(c,1);
3630}
3631
3632static void moveCommand(redisClient *c) {
3305306f 3633 robj *o;
3634 redisDb *src, *dst;
ed9b544e 3635 int srcid;
3636
3637 /* Obtain source and target DB pointers */
3305306f 3638 src = c->db;
3639 srcid = c->db->id;
ed9b544e 3640 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
c937aa89 3641 addReply(c,shared.outofrangeerr);
ed9b544e 3642 return;
3643 }
3305306f 3644 dst = c->db;
3645 selectDb(c,srcid); /* Back to the source DB */
ed9b544e 3646
3647 /* If the user is moving using as target the same
3648 * DB as the source DB it is probably an error. */
3649 if (src == dst) {
c937aa89 3650 addReply(c,shared.sameobjecterr);
ed9b544e 3651 return;
3652 }
3653
3654 /* Check if the element exists and get a reference */
3305306f 3655 o = lookupKeyWrite(c->db,c->argv[1]);
3656 if (!o) {
c937aa89 3657 addReply(c,shared.czero);
ed9b544e 3658 return;
3659 }
3660
3661 /* Try to add the element to the target DB */
3305306f 3662 deleteIfVolatile(dst,c->argv[1]);
3663 if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
c937aa89 3664 addReply(c,shared.czero);
ed9b544e 3665 return;
3666 }
3305306f 3667 incrRefCount(c->argv[1]);
ed9b544e 3668 incrRefCount(o);
3669
3670 /* OK! key moved, free the entry in the source DB */
3305306f 3671 deleteKey(src,c->argv[1]);
ed9b544e 3672 server.dirty++;
c937aa89 3673 addReply(c,shared.cone);
ed9b544e 3674}
3675
3676/* =================================== Lists ================================ */
3677static void pushGenericCommand(redisClient *c, int where) {
3678 robj *lobj;
ed9b544e 3679 list *list;
3305306f 3680
3681 lobj = lookupKeyWrite(c->db,c->argv[1]);
3682 if (lobj == NULL) {
95242ab5 3683 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
3684 addReply(c,shared.ok);
3685 return;
3686 }
ed9b544e 3687 lobj = createListObject();
3688 list = lobj->ptr;
3689 if (where == REDIS_HEAD) {
6b47e12e 3690 listAddNodeHead(list,c->argv[2]);
ed9b544e 3691 } else {
6b47e12e 3692 listAddNodeTail(list,c->argv[2]);
ed9b544e 3693 }
3305306f 3694 dictAdd(c->db->dict,c->argv[1],lobj);
ed9b544e 3695 incrRefCount(c->argv[1]);
3696 incrRefCount(c->argv[2]);
3697 } else {
ed9b544e 3698 if (lobj->type != REDIS_LIST) {
3699 addReply(c,shared.wrongtypeerr);
3700 return;
3701 }
95242ab5 3702 if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
3703 addReply(c,shared.ok);
3704 return;
3705 }
ed9b544e 3706 list = lobj->ptr;
3707 if (where == REDIS_HEAD) {
6b47e12e 3708 listAddNodeHead(list,c->argv[2]);
ed9b544e 3709 } else {
6b47e12e 3710 listAddNodeTail(list,c->argv[2]);
ed9b544e 3711 }
3712 incrRefCount(c->argv[2]);
3713 }
3714 server.dirty++;
3715 addReply(c,shared.ok);
3716}
3717
3718static void lpushCommand(redisClient *c) {
3719 pushGenericCommand(c,REDIS_HEAD);
3720}
3721
3722static void rpushCommand(redisClient *c) {
3723 pushGenericCommand(c,REDIS_TAIL);
3724}
3725
3726static void llenCommand(redisClient *c) {
3305306f 3727 robj *o;
ed9b544e 3728 list *l;
3729
3305306f 3730 o = lookupKeyRead(c->db,c->argv[1]);
3731 if (o == NULL) {
c937aa89 3732 addReply(c,shared.czero);
ed9b544e 3733 return;
3734 } else {
ed9b544e 3735 if (o->type != REDIS_LIST) {
c937aa89 3736 addReply(c,shared.wrongtypeerr);
ed9b544e 3737 } else {
3738 l = o->ptr;
c937aa89 3739 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",listLength(l)));
ed9b544e 3740 }
3741 }
3742}
3743
3744static void lindexCommand(redisClient *c) {
3305306f 3745 robj *o;
ed9b544e 3746 int index = atoi(c->argv[2]->ptr);
3747
3305306f 3748 o = lookupKeyRead(c->db,c->argv[1]);
3749 if (o == NULL) {
c937aa89 3750 addReply(c,shared.nullbulk);
ed9b544e 3751 } else {
ed9b544e 3752 if (o->type != REDIS_LIST) {
c937aa89 3753 addReply(c,shared.wrongtypeerr);
ed9b544e 3754 } else {
3755 list *list = o->ptr;
3756 listNode *ln;
3757
3758 ln = listIndex(list, index);
3759 if (ln == NULL) {
c937aa89 3760 addReply(c,shared.nullbulk);
ed9b544e 3761 } else {
3762 robj *ele = listNodeValue(ln);
942a3961 3763 addReplyBulkLen(c,ele);
ed9b544e 3764 addReply(c,ele);
3765 addReply(c,shared.crlf);
3766 }
3767 }
3768 }
3769}
3770
3771static void lsetCommand(redisClient *c) {
3305306f 3772 robj *o;
ed9b544e 3773 int index = atoi(c->argv[2]->ptr);
3774
3305306f 3775 o = lookupKeyWrite(c->db,c->argv[1]);
3776 if (o == NULL) {
ed9b544e 3777 addReply(c,shared.nokeyerr);
3778 } else {
ed9b544e 3779 if (o->type != REDIS_LIST) {
3780 addReply(c,shared.wrongtypeerr);
3781 } else {
3782 list *list = o->ptr;
3783 listNode *ln;
3784
3785 ln = listIndex(list, index);
3786 if (ln == NULL) {
c937aa89 3787 addReply(c,shared.outofrangeerr);
ed9b544e 3788 } else {
3789 robj *ele = listNodeValue(ln);
3790
3791 decrRefCount(ele);
3792 listNodeValue(ln) = c->argv[3];
3793 incrRefCount(c->argv[3]);
3794 addReply(c,shared.ok);
3795 server.dirty++;
3796 }
3797 }
3798 }
3799}
3800
3801static void popGenericCommand(redisClient *c, int where) {
3305306f 3802 robj *o;
3803
3804 o = lookupKeyWrite(c->db,c->argv[1]);
3805 if (o == NULL) {
c937aa89 3806 addReply(c,shared.nullbulk);
ed9b544e 3807 } else {
ed9b544e 3808 if (o->type != REDIS_LIST) {
c937aa89 3809 addReply(c,shared.wrongtypeerr);
ed9b544e 3810 } else {
3811 list *list = o->ptr;
3812 listNode *ln;
3813
3814 if (where == REDIS_HEAD)
3815 ln = listFirst(list);
3816 else
3817 ln = listLast(list);
3818
3819 if (ln == NULL) {
c937aa89 3820 addReply(c,shared.nullbulk);
ed9b544e 3821 } else {
3822 robj *ele = listNodeValue(ln);
942a3961 3823 addReplyBulkLen(c,ele);
ed9b544e 3824 addReply(c,ele);
3825 addReply(c,shared.crlf);
3826 listDelNode(list,ln);
3827 server.dirty++;
3828 }
3829 }
3830 }
3831}
3832
3833static void lpopCommand(redisClient *c) {
3834 popGenericCommand(c,REDIS_HEAD);
3835}
3836
3837static void rpopCommand(redisClient *c) {
3838 popGenericCommand(c,REDIS_TAIL);
3839}
3840
3841static void lrangeCommand(redisClient *c) {
3305306f 3842 robj *o;
ed9b544e 3843 int start = atoi(c->argv[2]->ptr);
3844 int end = atoi(c->argv[3]->ptr);
3305306f 3845
3846 o = lookupKeyRead(c->db,c->argv[1]);
3847 if (o == NULL) {
c937aa89 3848 addReply(c,shared.nullmultibulk);
ed9b544e 3849 } else {
ed9b544e 3850 if (o->type != REDIS_LIST) {
c937aa89 3851 addReply(c,shared.wrongtypeerr);
ed9b544e 3852 } else {
3853 list *list = o->ptr;
3854 listNode *ln;
3855 int llen = listLength(list);
3856 int rangelen, j;
3857 robj *ele;
3858
3859 /* convert negative indexes */
3860 if (start < 0) start = llen+start;
3861 if (end < 0) end = llen+end;
3862 if (start < 0) start = 0;
3863 if (end < 0) end = 0;
3864
3865 /* indexes sanity checks */
3866 if (start > end || start >= llen) {
3867 /* Out of range start or start > end result in empty list */
c937aa89 3868 addReply(c,shared.emptymultibulk);
ed9b544e 3869 return;
3870 }
3871 if (end >= llen) end = llen-1;
3872 rangelen = (end-start)+1;
3873
3874 /* Return the result in form of a multi-bulk reply */
3875 ln = listIndex(list, start);
c937aa89 3876 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
ed9b544e 3877 for (j = 0; j < rangelen; j++) {
3878 ele = listNodeValue(ln);
942a3961 3879 addReplyBulkLen(c,ele);
ed9b544e 3880 addReply(c,ele);
3881 addReply(c,shared.crlf);
3882 ln = ln->next;
3883 }
3884 }
3885 }
3886}
3887
3888static void ltrimCommand(redisClient *c) {
3305306f 3889 robj *o;
ed9b544e 3890 int start = atoi(c->argv[2]->ptr);
3891 int end = atoi(c->argv[3]->ptr);
3892
3305306f 3893 o = lookupKeyWrite(c->db,c->argv[1]);
3894 if (o == NULL) {
ab9d4cb1 3895 addReply(c,shared.ok);
ed9b544e 3896 } else {
ed9b544e 3897 if (o->type != REDIS_LIST) {
3898 addReply(c,shared.wrongtypeerr);
3899 } else {
3900 list *list = o->ptr;
3901 listNode *ln;
3902 int llen = listLength(list);
3903 int j, ltrim, rtrim;
3904
3905 /* convert negative indexes */
3906 if (start < 0) start = llen+start;
3907 if (end < 0) end = llen+end;
3908 if (start < 0) start = 0;
3909 if (end < 0) end = 0;
3910
3911 /* indexes sanity checks */
3912 if (start > end || start >= llen) {
3913 /* Out of range start or start > end result in empty list */
3914 ltrim = llen;
3915 rtrim = 0;
3916 } else {
3917 if (end >= llen) end = llen-1;
3918 ltrim = start;
3919 rtrim = llen-end-1;
3920 }
3921
3922 /* Remove list elements to perform the trim */
3923 for (j = 0; j < ltrim; j++) {
3924 ln = listFirst(list);
3925 listDelNode(list,ln);
3926 }
3927 for (j = 0; j < rtrim; j++) {
3928 ln = listLast(list);
3929 listDelNode(list,ln);
3930 }
ed9b544e 3931 server.dirty++;
e59229a2 3932 addReply(c,shared.ok);
ed9b544e 3933 }
3934 }
3935}
3936
3937static void lremCommand(redisClient *c) {
3305306f 3938 robj *o;
ed9b544e 3939
3305306f 3940 o = lookupKeyWrite(c->db,c->argv[1]);
3941 if (o == NULL) {
33c08b39 3942 addReply(c,shared.czero);
ed9b544e 3943 } else {
ed9b544e 3944 if (o->type != REDIS_LIST) {
c937aa89 3945 addReply(c,shared.wrongtypeerr);
ed9b544e 3946 } else {
3947 list *list = o->ptr;
3948 listNode *ln, *next;
3949 int toremove = atoi(c->argv[2]->ptr);
3950 int removed = 0;
3951 int fromtail = 0;
3952
3953 if (toremove < 0) {
3954 toremove = -toremove;
3955 fromtail = 1;
3956 }
3957 ln = fromtail ? list->tail : list->head;
3958 while (ln) {
ed9b544e 3959 robj *ele = listNodeValue(ln);
a4d1ba9a 3960
3961 next = fromtail ? ln->prev : ln->next;
724a51b1 3962 if (compareStringObjects(ele,c->argv[3]) == 0) {
ed9b544e 3963 listDelNode(list,ln);
3964 server.dirty++;
3965 removed++;
3966 if (toremove && removed == toremove) break;
3967 }
3968 ln = next;
3969 }
c937aa89 3970 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
ed9b544e 3971 }
3972 }
3973}
3974
12f9d551 3975/* This is the semantic of this command:
0f5f7e9a 3976 * RPOPLPUSH srclist dstlist:
12f9d551 3977 * IF LLEN(srclist) > 0
3978 * element = RPOP srclist
3979 * LPUSH dstlist element
3980 * RETURN element
3981 * ELSE
3982 * RETURN nil
3983 * END
3984 * END
3985 *
3986 * The idea is to be able to get an element from a list in a reliable way
3987 * since the element is not just returned but pushed against another list
3988 * as well. This command was originally proposed by Ezra Zygmuntowicz.
3989 */
0f5f7e9a 3990static void rpoplpushcommand(redisClient *c) {
12f9d551 3991 robj *sobj;
3992
3993 sobj = lookupKeyWrite(c->db,c->argv[1]);
3994 if (sobj == NULL) {
3995 addReply(c,shared.nullbulk);
3996 } else {
3997 if (sobj->type != REDIS_LIST) {
3998 addReply(c,shared.wrongtypeerr);
3999 } else {
4000 list *srclist = sobj->ptr;
4001 listNode *ln = listLast(srclist);
4002
4003 if (ln == NULL) {
4004 addReply(c,shared.nullbulk);
4005 } else {
4006 robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
4007 robj *ele = listNodeValue(ln);
4008 list *dstlist;
4009
e20fb74f 4010 if (dobj && dobj->type != REDIS_LIST) {
12f9d551 4011 addReply(c,shared.wrongtypeerr);
4012 return;
4013 }
e20fb74f 4014
4015 /* Add the element to the target list (unless it's directly
4016 * passed to some BLPOP-ing client */
4017 if (!handleClientsWaitingListPush(c,c->argv[2],ele)) {
4018 if (dobj == NULL) {
4019 /* Create the list if the key does not exist */
4020 dobj = createListObject();
4021 dictAdd(c->db->dict,c->argv[2],dobj);
4022 incrRefCount(c->argv[2]);
4023 }
4024 dstlist = dobj->ptr;
4025 listAddNodeHead(dstlist,ele);
4026 incrRefCount(ele);
4027 }
12f9d551 4028
4029 /* Send the element to the client as reply as well */
4030 addReplyBulkLen(c,ele);
4031 addReply(c,ele);
4032 addReply(c,shared.crlf);
4033
4034 /* Finally remove the element from the source list */
4035 listDelNode(srclist,ln);
4036 server.dirty++;
4037 }
4038 }
4039 }
4040}
4041
4042
ed9b544e 4043/* ==================================== Sets ================================ */
4044
4045static void saddCommand(redisClient *c) {
ed9b544e 4046 robj *set;
4047
3305306f 4048 set = lookupKeyWrite(c->db,c->argv[1]);
4049 if (set == NULL) {
ed9b544e 4050 set = createSetObject();
3305306f 4051 dictAdd(c->db->dict,c->argv[1],set);
ed9b544e 4052 incrRefCount(c->argv[1]);
4053 } else {
ed9b544e 4054 if (set->type != REDIS_SET) {
c937aa89 4055 addReply(c,shared.wrongtypeerr);
ed9b544e 4056 return;
4057 }
4058 }
4059 if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
4060 incrRefCount(c->argv[2]);
4061 server.dirty++;
c937aa89 4062 addReply(c,shared.cone);
ed9b544e 4063 } else {
c937aa89 4064 addReply(c,shared.czero);
ed9b544e 4065 }
4066}
4067
4068static void sremCommand(redisClient *c) {
3305306f 4069 robj *set;
ed9b544e 4070
3305306f 4071 set = lookupKeyWrite(c->db,c->argv[1]);
4072 if (set == NULL) {
c937aa89 4073 addReply(c,shared.czero);
ed9b544e 4074 } else {
ed9b544e 4075 if (set->type != REDIS_SET) {
c937aa89 4076 addReply(c,shared.wrongtypeerr);
ed9b544e 4077 return;
4078 }
4079 if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
4080 server.dirty++;
12fea928 4081 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
c937aa89 4082 addReply(c,shared.cone);
ed9b544e 4083 } else {
c937aa89 4084 addReply(c,shared.czero);
ed9b544e 4085 }
4086 }
4087}
4088
a4460ef4 4089static void smoveCommand(redisClient *c) {
4090 robj *srcset, *dstset;
4091
4092 srcset = lookupKeyWrite(c->db,c->argv[1]);
4093 dstset = lookupKeyWrite(c->db,c->argv[2]);
4094
4095 /* If the source key does not exist return 0, if it's of the wrong type
4096 * raise an error */
4097 if (srcset == NULL || srcset->type != REDIS_SET) {
4098 addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
4099 return;
4100 }
4101 /* Error if the destination key is not a set as well */
4102 if (dstset && dstset->type != REDIS_SET) {
4103 addReply(c,shared.wrongtypeerr);
4104 return;
4105 }
4106 /* Remove the element from the source set */
4107 if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
4108 /* Key not found in the src set! return zero */
4109 addReply(c,shared.czero);
4110 return;
4111 }
4112 server.dirty++;
4113 /* Add the element to the destination set */
4114 if (!dstset) {
4115 dstset = createSetObject();
4116 dictAdd(c->db->dict,c->argv[2],dstset);
4117 incrRefCount(c->argv[2]);
4118 }
4119 if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
4120 incrRefCount(c->argv[3]);
4121 addReply(c,shared.cone);
4122}
4123
ed9b544e 4124static void sismemberCommand(redisClient *c) {
3305306f 4125 robj *set;
ed9b544e 4126
3305306f 4127 set = lookupKeyRead(c->db,c->argv[1]);
4128 if (set == NULL) {
c937aa89 4129 addReply(c,shared.czero);
ed9b544e 4130 } else {
ed9b544e 4131 if (set->type != REDIS_SET) {
c937aa89 4132 addReply(c,shared.wrongtypeerr);
ed9b544e 4133 return;
4134 }
4135 if (dictFind(set->ptr,c->argv[2]))
c937aa89 4136 addReply(c,shared.cone);
ed9b544e 4137 else
c937aa89 4138 addReply(c,shared.czero);
ed9b544e 4139 }
4140}
4141
4142static void scardCommand(redisClient *c) {
3305306f 4143 robj *o;
ed9b544e 4144 dict *s;
4145
3305306f 4146 o = lookupKeyRead(c->db,c->argv[1]);
4147 if (o == NULL) {
c937aa89 4148 addReply(c,shared.czero);
ed9b544e 4149 return;
4150 } else {
ed9b544e 4151 if (o->type != REDIS_SET) {
c937aa89 4152 addReply(c,shared.wrongtypeerr);
ed9b544e 4153 } else {
4154 s = o->ptr;
682ac724 4155 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",
3305306f 4156 dictSize(s)));
ed9b544e 4157 }
4158 }
4159}
4160
12fea928 4161static void spopCommand(redisClient *c) {
4162 robj *set;
4163 dictEntry *de;
4164
4165 set = lookupKeyWrite(c->db,c->argv[1]);
4166 if (set == NULL) {
4167 addReply(c,shared.nullbulk);
4168 } else {
4169 if (set->type != REDIS_SET) {
4170 addReply(c,shared.wrongtypeerr);
4171 return;
4172 }
4173 de = dictGetRandomKey(set->ptr);
4174 if (de == NULL) {
4175 addReply(c,shared.nullbulk);
4176 } else {
4177 robj *ele = dictGetEntryKey(de);
4178
942a3961 4179 addReplyBulkLen(c,ele);
12fea928 4180 addReply(c,ele);
4181 addReply(c,shared.crlf);
4182 dictDelete(set->ptr,ele);
4183 if (htNeedsResize(set->ptr)) dictResize(set->ptr);
4184 server.dirty++;
4185 }
4186 }
4187}
4188
2abb95a9 4189static void srandmemberCommand(redisClient *c) {
4190 robj *set;
4191 dictEntry *de;
4192
4193 set = lookupKeyRead(c->db,c->argv[1]);
4194 if (set == NULL) {
4195 addReply(c,shared.nullbulk);
4196 } else {
4197 if (set->type != REDIS_SET) {
4198 addReply(c,shared.wrongtypeerr);
4199 return;
4200 }
4201 de = dictGetRandomKey(set->ptr);
4202 if (de == NULL) {
4203 addReply(c,shared.nullbulk);
4204 } else {
4205 robj *ele = dictGetEntryKey(de);
4206
4207 addReplyBulkLen(c,ele);
4208 addReply(c,ele);
4209 addReply(c,shared.crlf);
4210 }
4211 }
4212}
4213
ed9b544e 4214static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
4215 dict **d1 = (void*) s1, **d2 = (void*) s2;
4216
3305306f 4217 return dictSize(*d1)-dictSize(*d2);
ed9b544e 4218}
4219
682ac724 4220static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
ed9b544e 4221 dict **dv = zmalloc(sizeof(dict*)*setsnum);
4222 dictIterator *di;
4223 dictEntry *de;
4224 robj *lenobj = NULL, *dstset = NULL;
682ac724 4225 unsigned long j, cardinality = 0;
ed9b544e 4226
ed9b544e 4227 for (j = 0; j < setsnum; j++) {
4228 robj *setobj;
3305306f 4229
4230 setobj = dstkey ?
4231 lookupKeyWrite(c->db,setskeys[j]) :
4232 lookupKeyRead(c->db,setskeys[j]);
4233 if (!setobj) {
ed9b544e 4234 zfree(dv);
5faa6025 4235 if (dstkey) {
fdcaae84 4236 if (deleteKey(c->db,dstkey))
4237 server.dirty++;
0d36ded0 4238 addReply(c,shared.czero);
5faa6025 4239 } else {
4240 addReply(c,shared.nullmultibulk);
4241 }
ed9b544e 4242 return;
4243 }
ed9b544e 4244 if (setobj->type != REDIS_SET) {
4245 zfree(dv);
c937aa89 4246 addReply(c,shared.wrongtypeerr);
ed9b544e 4247 return;
4248 }
4249 dv[j] = setobj->ptr;
4250 }
4251 /* Sort sets from the smallest to largest, this will improve our
4252 * algorithm's performace */
4253 qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);
4254
4255 /* The first thing we should output is the total number of elements...
4256 * since this is a multi-bulk write, but at this stage we don't know
4257 * the intersection set size, so we use a trick, append an empty object
4258 * to the output list and save the pointer to later modify it with the
4259 * right length */
4260 if (!dstkey) {
4261 lenobj = createObject(REDIS_STRING,NULL);
4262 addReply(c,lenobj);
4263 decrRefCount(lenobj);
4264 } else {
4265 /* If we have a target key where to store the resulting set
4266 * create this key with an empty set inside */
4267 dstset = createSetObject();
ed9b544e 4268 }
4269
4270 /* Iterate all the elements of the first (smallest) set, and test
4271 * the element against all the other sets, if at least one set does
4272 * not include the element it is discarded */
4273 di = dictGetIterator(dv[0]);
ed9b544e 4274
4275 while((de = dictNext(di)) != NULL) {
4276 robj *ele;
4277
4278 for (j = 1; j < setsnum; j++)
4279 if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
4280 if (j != setsnum)
4281 continue; /* at least one set does not contain the member */
4282 ele = dictGetEntryKey(de);
4283 if (!dstkey) {
942a3961 4284 addReplyBulkLen(c,ele);
ed9b544e 4285 addReply(c,ele);
4286 addReply(c,shared.crlf);
4287 cardinality++;
4288 } else {
4289 dictAdd(dstset->ptr,ele,NULL);
4290 incrRefCount(ele);
4291 }
4292 }
4293 dictReleaseIterator(di);
4294
83cdfe18
AG
4295 if (dstkey) {
4296 /* Store the resulting set into the target */
4297 deleteKey(c->db,dstkey);
4298 dictAdd(c->db->dict,dstkey,dstset);
4299 incrRefCount(dstkey);
4300 }
4301
40d224a9 4302 if (!dstkey) {
682ac724 4303 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
40d224a9 4304 } else {
682ac724 4305 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",
03fd01c7 4306 dictSize((dict*)dstset->ptr)));
40d224a9 4307 server.dirty++;
4308 }
ed9b544e 4309 zfree(dv);
4310}
4311
4312static void sinterCommand(redisClient *c) {
4313 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
4314}
4315
4316static void sinterstoreCommand(redisClient *c) {
4317 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
4318}
4319
f4f56e1d 4320#define REDIS_OP_UNION 0
4321#define REDIS_OP_DIFF 1
4322
4323static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
40d224a9 4324 dict **dv = zmalloc(sizeof(dict*)*setsnum);
4325 dictIterator *di;
4326 dictEntry *de;
f4f56e1d 4327 robj *dstset = NULL;
40d224a9 4328 int j, cardinality = 0;
4329
40d224a9 4330 for (j = 0; j < setsnum; j++) {
4331 robj *setobj;
4332
4333 setobj = dstkey ?
4334 lookupKeyWrite(c->db,setskeys[j]) :
4335 lookupKeyRead(c->db,setskeys[j]);
4336 if (!setobj) {
4337 dv[j] = NULL;
4338 continue;
4339 }
4340 if (setobj->type != REDIS_SET) {
4341 zfree(dv);
4342 addReply(c,shared.wrongtypeerr);
4343 return;
4344 }
4345 dv[j] = setobj->ptr;
4346 }
4347
4348 /* We need a temp set object to store our union. If the dstkey
4349 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4350 * this set object will be the resulting object to set into the target key*/
4351 dstset = createSetObject();
4352
40d224a9 4353 /* Iterate all the elements of all the sets, add every element a single
4354 * time to the result set */
4355 for (j = 0; j < setsnum; j++) {
51829ed3 4356 if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
40d224a9 4357 if (!dv[j]) continue; /* non existing keys are like empty sets */
4358
4359 di = dictGetIterator(dv[j]);
40d224a9 4360
4361 while((de = dictNext(di)) != NULL) {
4362 robj *ele;
4363
4364 /* dictAdd will not add the same element multiple times */
4365 ele = dictGetEntryKey(de);
f4f56e1d 4366 if (op == REDIS_OP_UNION || j == 0) {
4367 if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
4368 incrRefCount(ele);
40d224a9 4369 cardinality++;
4370 }
f4f56e1d 4371 } else if (op == REDIS_OP_DIFF) {
4372 if (dictDelete(dstset->ptr,ele) == DICT_OK) {
4373 cardinality--;
4374 }
40d224a9 4375 }
4376 }
4377 dictReleaseIterator(di);
51829ed3
AG
4378
4379 if (op == REDIS_OP_DIFF && cardinality == 0) break; /* result set is empty */
40d224a9 4380 }
4381
f4f56e1d 4382 /* Output the content of the resulting set, if not in STORE mode */
4383 if (!dstkey) {
4384 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
4385 di = dictGetIterator(dstset->ptr);
f4f56e1d 4386 while((de = dictNext(di)) != NULL) {
4387 robj *ele;
4388
4389 ele = dictGetEntryKey(de);
942a3961 4390 addReplyBulkLen(c,ele);
f4f56e1d 4391 addReply(c,ele);
4392 addReply(c,shared.crlf);
4393 }
4394 dictReleaseIterator(di);
83cdfe18
AG
4395 } else {
4396 /* If we have a target key where to store the resulting set
4397 * create this key with the result set inside */
4398 deleteKey(c->db,dstkey);
4399 dictAdd(c->db->dict,dstkey,dstset);
4400 incrRefCount(dstkey);
f4f56e1d 4401 }
4402
4403 /* Cleanup */
40d224a9 4404 if (!dstkey) {
40d224a9 4405 decrRefCount(dstset);
4406 } else {
682ac724 4407 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",
03fd01c7 4408 dictSize((dict*)dstset->ptr)));
40d224a9 4409 server.dirty++;
4410 }
4411 zfree(dv);
4412}
4413
4414static void sunionCommand(redisClient *c) {
f4f56e1d 4415 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
40d224a9 4416}
4417
4418static void sunionstoreCommand(redisClient *c) {
f4f56e1d 4419 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
4420}
4421
4422static void sdiffCommand(redisClient *c) {
4423 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
4424}
4425
4426static void sdiffstoreCommand(redisClient *c) {
4427 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
40d224a9 4428}
4429
6b47e12e 4430/* ==================================== ZSets =============================== */
4431
4432/* ZSETs are ordered sets using two data structures to hold the same elements
4433 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4434 * data structure.
4435 *
4436 * The elements are added to an hash table mapping Redis objects to scores.
4437 * At the same time the elements are added to a skip list mapping scores
4438 * to Redis objects (so objects are sorted by scores in this "view"). */
4439
4440/* This skiplist implementation is almost a C translation of the original
4441 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4442 * Alternative to Balanced Trees", modified in three ways:
4443 * a) this implementation allows for repeated values.
4444 * b) the comparison is not just by key (our 'score') but by satellite data.
4445 * c) there is a back pointer, so it's a doubly linked list with the back
4446 * pointers being only at "level 1". This allows to traverse the list
4447 * from tail to head, useful for ZREVRANGE. */
4448
4449static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
4450 zskiplistNode *zn = zmalloc(sizeof(*zn));
4451
4452 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
4453 zn->score = score;
4454 zn->obj = obj;
4455 return zn;
4456}
4457
4458static zskiplist *zslCreate(void) {
4459 int j;
4460 zskiplist *zsl;
4461
4462 zsl = zmalloc(sizeof(*zsl));
4463 zsl->level = 1;
cc812361 4464 zsl->length = 0;
6b47e12e 4465 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
4466 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++)
4467 zsl->header->forward[j] = NULL;
e3870fab 4468 zsl->header->backward = NULL;
4469 zsl->tail = NULL;
6b47e12e 4470 return zsl;
4471}
4472
fd8ccf44 4473static void zslFreeNode(zskiplistNode *node) {
4474 decrRefCount(node->obj);
ad807e6f 4475 zfree(node->forward);
fd8ccf44 4476 zfree(node);
4477}
4478
4479static void zslFree(zskiplist *zsl) {
ad807e6f 4480 zskiplistNode *node = zsl->header->forward[0], *next;
fd8ccf44 4481
ad807e6f 4482 zfree(zsl->header->forward);
4483 zfree(zsl->header);
fd8ccf44 4484 while(node) {
599379dd 4485 next = node->forward[0];
fd8ccf44 4486 zslFreeNode(node);
4487 node = next;
4488 }
ad807e6f 4489 zfree(zsl);
fd8ccf44 4490}
4491
6b47e12e 4492static int zslRandomLevel(void) {
4493 int level = 1;
4494 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
4495 level += 1;
4496 return level;
4497}
4498
4499static void zslInsert(zskiplist *zsl, double score, robj *obj) {
4500 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
4501 int i, level;
4502
4503 x = zsl->header;
4504 for (i = zsl->level-1; i >= 0; i--) {
9d60e6e4 4505 while (x->forward[i] &&
4506 (x->forward[i]->score < score ||
4507 (x->forward[i]->score == score &&
4508 compareStringObjects(x->forward[i]->obj,obj) < 0)))
6b47e12e 4509 x = x->forward[i];
4510 update[i] = x;
4511 }
6b47e12e 4512 /* we assume the key is not already inside, since we allow duplicated
4513 * scores, and the re-insertion of score and redis object should never
4514 * happpen since the caller of zslInsert() should test in the hash table
4515 * if the element is already inside or not. */
4516 level = zslRandomLevel();
4517 if (level > zsl->level) {
4518 for (i = zsl->level; i < level; i++)
4519 update[i] = zsl->header;
4520 zsl->level = level;
4521 }
4522 x = zslCreateNode(level,score,obj);
4523 for (i = 0; i < level; i++) {
4524 x->forward[i] = update[i]->forward[i];
4525 update[i]->forward[i] = x;
4526 }
bb975144 4527 x->backward = (update[0] == zsl->header) ? NULL : update[0];
e3870fab 4528 if (x->forward[0])
4529 x->forward[0]->backward = x;
4530 else
4531 zsl->tail = x;
cc812361 4532 zsl->length++;
6b47e12e 4533}
4534
50c55df5 4535/* Delete an element with matching score/object from the skiplist. */
fd8ccf44 4536static int zslDelete(zskiplist *zsl, double score, robj *obj) {
e197b441 4537 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
4538 int i;
4539
4540 x = zsl->header;
4541 for (i = zsl->level-1; i >= 0; i--) {
9d60e6e4 4542 while (x->forward[i] &&
4543 (x->forward[i]->score < score ||
4544 (x->forward[i]->score == score &&
4545 compareStringObjects(x->forward[i]->obj,obj) < 0)))
e197b441 4546 x = x->forward[i];
4547 update[i] = x;
4548 }
4549 /* We may have multiple elements with the same score, what we need
4550 * is to find the element with both the right score and object. */
4551 x = x->forward[0];
50c55df5 4552 if (x && score == x->score && compareStringObjects(x->obj,obj) == 0) {
9d60e6e4 4553 for (i = 0; i < zsl->level; i++) {
4554 if (update[i]->forward[i] != x) break;
4555 update[i]->forward[i] = x->forward[i];
4556 }
4557 if (x->forward[0]) {
4558 x->forward[0]->backward = (x->backward == zsl->header) ?
4559 NULL : x->backward;
e197b441 4560 } else {
9d60e6e4 4561 zsl->tail = x->backward;
e197b441 4562 }
9d60e6e4 4563 zslFreeNode(x);
4564 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
4565 zsl->level--;
4566 zsl->length--;
4567 return 1;
4568 } else {
4569 return 0; /* not found */
e197b441 4570 }
4571 return 0; /* not found */
fd8ccf44 4572}
4573
1807985b 4574/* Delete all the elements with score between min and max from the skiplist.
4575 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4576 * Note that this function takes the reference to the hash table view of the
4577 * sorted set, in order to remove the elements from the hash table too. */
4578static unsigned long zslDeleteRange(zskiplist *zsl, double min, double max, dict *dict) {
4579 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
4580 unsigned long removed = 0;
4581 int i;
4582
4583 x = zsl->header;
4584 for (i = zsl->level-1; i >= 0; i--) {
4585 while (x->forward[i] && x->forward[i]->score < min)
4586 x = x->forward[i];
4587 update[i] = x;
4588 }
4589 /* We may have multiple elements with the same score, what we need
4590 * is to find the element with both the right score and object. */
4591 x = x->forward[0];
4592 while (x && x->score <= max) {
4593 zskiplistNode *next;
4594
4595 for (i = 0; i < zsl->level; i++) {
4596 if (update[i]->forward[i] != x) break;
4597 update[i]->forward[i] = x->forward[i];
4598 }
4599 if (x->forward[0]) {
4600 x->forward[0]->backward = (x->backward == zsl->header) ?
4601 NULL : x->backward;
4602 } else {
4603 zsl->tail = x->backward;
4604 }
4605 next = x->forward[0];
4606 dictDelete(dict,x->obj);
4607 zslFreeNode(x);
4608 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
4609 zsl->level--;
4610 zsl->length--;
4611 removed++;
4612 x = next;
4613 }
4614 return removed; /* not found */
4615}
4616
50c55df5 4617/* Find the first node having a score equal or greater than the specified one.
4618 * Returns NULL if there is no match. */
4619static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
4620 zskiplistNode *x;
4621 int i;
4622
4623 x = zsl->header;
4624 for (i = zsl->level-1; i >= 0; i--) {
4625 while (x->forward[i] && x->forward[i]->score < score)
4626 x = x->forward[i];
4627 }
4628 /* We may have multiple elements with the same score, what we need
4629 * is to find the element with both the right score and object. */
4630 return x->forward[0];
4631}
4632
fd8ccf44 4633/* The actual Z-commands implementations */
4634
7db723ad 4635/* This generic command implements both ZADD and ZINCRBY.
e2665397 4636 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
7db723ad 4637 * the increment if the operation is a ZINCRBY (doincrement == 1). */
e2665397 4638static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
fd8ccf44 4639 robj *zsetobj;
4640 zset *zs;
4641 double *score;
4642
e2665397 4643 zsetobj = lookupKeyWrite(c->db,key);
fd8ccf44 4644 if (zsetobj == NULL) {
4645 zsetobj = createZsetObject();
e2665397 4646 dictAdd(c->db->dict,key,zsetobj);
4647 incrRefCount(key);
fd8ccf44 4648 } else {
4649 if (zsetobj->type != REDIS_ZSET) {
4650 addReply(c,shared.wrongtypeerr);
4651 return;
4652 }
4653 }
fd8ccf44 4654 zs = zsetobj->ptr;
e2665397 4655
7db723ad 4656 /* Ok now since we implement both ZADD and ZINCRBY here the code
e2665397 4657 * needs to handle the two different conditions. It's all about setting
4658 * '*score', that is, the new score to set, to the right value. */
4659 score = zmalloc(sizeof(double));
4660 if (doincrement) {
4661 dictEntry *de;
4662
4663 /* Read the old score. If the element was not present starts from 0 */
4664 de = dictFind(zs->dict,ele);
4665 if (de) {
4666 double *oldscore = dictGetEntryVal(de);
4667 *score = *oldscore + scoreval;
4668 } else {
4669 *score = scoreval;
4670 }
4671 } else {
4672 *score = scoreval;
4673 }
4674
4675 /* What follows is a simple remove and re-insert operation that is common
7db723ad 4676 * to both ZADD and ZINCRBY... */
e2665397 4677 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
fd8ccf44 4678 /* case 1: New element */
e2665397 4679 incrRefCount(ele); /* added to hash */
4680 zslInsert(zs->zsl,*score,ele);
4681 incrRefCount(ele); /* added to skiplist */
fd8ccf44 4682 server.dirty++;
e2665397 4683 if (doincrement)
e2665397 4684 addReplyDouble(c,*score);
91d71bfc 4685 else
4686 addReply(c,shared.cone);
fd8ccf44 4687 } else {
4688 dictEntry *de;
4689 double *oldscore;
4690
4691 /* case 2: Score update operation */
e2665397 4692 de = dictFind(zs->dict,ele);
dfc5e96c 4693 redisAssert(de != NULL);
fd8ccf44 4694 oldscore = dictGetEntryVal(de);
4695 if (*score != *oldscore) {
4696 int deleted;
4697
e2665397 4698 /* Remove and insert the element in the skip list with new score */
4699 deleted = zslDelete(zs->zsl,*oldscore,ele);
dfc5e96c 4700 redisAssert(deleted != 0);
e2665397 4701 zslInsert(zs->zsl,*score,ele);
4702 incrRefCount(ele);
4703 /* Update the score in the hash table */
4704 dictReplace(zs->dict,ele,score);
fd8ccf44 4705 server.dirty++;
2161a965 4706 } else {
4707 zfree(score);
fd8ccf44 4708 }
e2665397 4709 if (doincrement)
4710 addReplyDouble(c,*score);
4711 else
4712 addReply(c,shared.czero);
fd8ccf44 4713 }
4714}
4715
e2665397 4716static void zaddCommand(redisClient *c) {
4717 double scoreval;
4718
4719 scoreval = strtod(c->argv[2]->ptr,NULL);
4720 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
4721}
4722
7db723ad 4723static void zincrbyCommand(redisClient *c) {
e2665397 4724 double scoreval;
4725
4726 scoreval = strtod(c->argv[2]->ptr,NULL);
4727 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
4728}
4729
1b7106e7 4730static void zremCommand(redisClient *c) {
4731 robj *zsetobj;
4732 zset *zs;
4733
4734 zsetobj = lookupKeyWrite(c->db,c->argv[1]);
4735 if (zsetobj == NULL) {
4736 addReply(c,shared.czero);
4737 } else {
4738 dictEntry *de;
4739 double *oldscore;
4740 int deleted;
4741
4742 if (zsetobj->type != REDIS_ZSET) {
4743 addReply(c,shared.wrongtypeerr);
4744 return;
4745 }
4746 zs = zsetobj->ptr;
4747 de = dictFind(zs->dict,c->argv[2]);
4748 if (de == NULL) {
4749 addReply(c,shared.czero);
4750 return;
4751 }
4752 /* Delete from the skiplist */
4753 oldscore = dictGetEntryVal(de);
4754 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
dfc5e96c 4755 redisAssert(deleted != 0);
1b7106e7 4756
4757 /* Delete from the hash table */
4758 dictDelete(zs->dict,c->argv[2]);
4759 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
4760 server.dirty++;
4761 addReply(c,shared.cone);
4762 }
4763}
4764
1807985b 4765static void zremrangebyscoreCommand(redisClient *c) {
4766 double min = strtod(c->argv[2]->ptr,NULL);
4767 double max = strtod(c->argv[3]->ptr,NULL);
4768 robj *zsetobj;
4769 zset *zs;
4770
4771 zsetobj = lookupKeyWrite(c->db,c->argv[1]);
4772 if (zsetobj == NULL) {
4773 addReply(c,shared.czero);
4774 } else {
4775 long deleted;
4776
4777 if (zsetobj->type != REDIS_ZSET) {
4778 addReply(c,shared.wrongtypeerr);
4779 return;
4780 }
4781 zs = zsetobj->ptr;
4782 deleted = zslDeleteRange(zs->zsl,min,max,zs->dict);
4783 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
4784 server.dirty += deleted;
4785 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",deleted));
4786 }
4787}
4788
e3870fab 4789static void zrangeGenericCommand(redisClient *c, int reverse) {
cc812361 4790 robj *o;
4791 int start = atoi(c->argv[2]->ptr);
4792 int end = atoi(c->argv[3]->ptr);
752da584 4793 int withscores = 0;
4794
4795 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
4796 withscores = 1;
4797 } else if (c->argc >= 5) {
4798 addReply(c,shared.syntaxerr);
4799 return;
4800 }
cc812361 4801
4802 o = lookupKeyRead(c->db,c->argv[1]);
4803 if (o == NULL) {
4804 addReply(c,shared.nullmultibulk);
4805 } else {
4806 if (o->type != REDIS_ZSET) {
4807 addReply(c,shared.wrongtypeerr);
4808 } else {
4809 zset *zsetobj = o->ptr;
4810 zskiplist *zsl = zsetobj->zsl;
4811 zskiplistNode *ln;
4812
4813 int llen = zsl->length;
4814 int rangelen, j;
4815 robj *ele;
4816
4817 /* convert negative indexes */
4818 if (start < 0) start = llen+start;
4819 if (end < 0) end = llen+end;
4820 if (start < 0) start = 0;
4821 if (end < 0) end = 0;
4822
4823 /* indexes sanity checks */
4824 if (start > end || start >= llen) {
4825 /* Out of range start or start > end result in empty list */
4826 addReply(c,shared.emptymultibulk);
4827 return;
4828 }
4829 if (end >= llen) end = llen-1;
4830 rangelen = (end-start)+1;
4831
4832 /* Return the result in form of a multi-bulk reply */
e3870fab 4833 if (reverse) {
4834 ln = zsl->tail;
4835 while (start--)
4836 ln = ln->backward;
4837 } else {
4838 ln = zsl->header->forward[0];
4839 while (start--)
4840 ln = ln->forward[0];
4841 }
cc812361 4842
752da584 4843 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
4844 withscores ? (rangelen*2) : rangelen));
cc812361 4845 for (j = 0; j < rangelen; j++) {
0aad7a19 4846 ele = ln->obj;
cc812361 4847 addReplyBulkLen(c,ele);
4848 addReply(c,ele);
4849 addReply(c,shared.crlf);
752da584 4850 if (withscores)
4851 addReplyDouble(c,ln->score);
e3870fab 4852 ln = reverse ? ln->backward : ln->forward[0];
cc812361 4853 }
4854 }
4855 }
4856}
4857
e3870fab 4858static void zrangeCommand(redisClient *c) {
4859 zrangeGenericCommand(c,0);
4860}
4861
4862static void zrevrangeCommand(redisClient *c) {
4863 zrangeGenericCommand(c,1);
4864}
4865
50c55df5 4866static void zrangebyscoreCommand(redisClient *c) {
4867 robj *o;
4868 double min = strtod(c->argv[2]->ptr,NULL);
4869 double max = strtod(c->argv[3]->ptr,NULL);
80181f78 4870 int offset = 0, limit = -1;
4871
4872 if (c->argc != 4 && c->argc != 7) {
454d4e43 4873 addReplySds(c,
4874 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
80181f78 4875 return;
4876 } else if (c->argc == 7 && strcasecmp(c->argv[4]->ptr,"limit")) {
4877 addReply(c,shared.syntaxerr);
4878 return;
4879 } else if (c->argc == 7) {
4880 offset = atoi(c->argv[5]->ptr);
4881 limit = atoi(c->argv[6]->ptr);
0b13687c 4882 if (offset < 0) offset = 0;
80181f78 4883 }
50c55df5 4884
4885 o = lookupKeyRead(c->db,c->argv[1]);
4886 if (o == NULL) {
4887 addReply(c,shared.nullmultibulk);
4888 } else {
4889 if (o->type != REDIS_ZSET) {
4890 addReply(c,shared.wrongtypeerr);
4891 } else {
4892 zset *zsetobj = o->ptr;
4893 zskiplist *zsl = zsetobj->zsl;
4894 zskiplistNode *ln;
4895 robj *ele, *lenobj;
4896 unsigned int rangelen = 0;
4897
4898 /* Get the first node with the score >= min */
4899 ln = zslFirstWithScore(zsl,min);
4900 if (ln == NULL) {
4901 /* No element matching the speciifed interval */
4902 addReply(c,shared.emptymultibulk);
4903 return;
4904 }
4905
4906 /* We don't know in advance how many matching elements there
4907 * are in the list, so we push this object that will represent
4908 * the multi-bulk length in the output buffer, and will "fix"
4909 * it later */
4910 lenobj = createObject(REDIS_STRING,NULL);
4911 addReply(c,lenobj);
c74e7c77 4912 decrRefCount(lenobj);
50c55df5 4913
dbbc7285 4914 while(ln && ln->score <= max) {
80181f78 4915 if (offset) {
4916 offset--;
4917 ln = ln->forward[0];
4918 continue;
4919 }
4920 if (limit == 0) break;
50c55df5 4921 ele = ln->obj;
4922 addReplyBulkLen(c,ele);
4923 addReply(c,ele);
4924 addReply(c,shared.crlf);
4925 ln = ln->forward[0];
4926 rangelen++;
80181f78 4927 if (limit > 0) limit--;
50c55df5 4928 }
4929 lenobj->ptr = sdscatprintf(sdsempty(),"*%d\r\n",rangelen);
4930 }
4931 }
4932}
4933
3c41331e 4934static void zcardCommand(redisClient *c) {
e197b441 4935 robj *o;
4936 zset *zs;
4937
4938 o = lookupKeyRead(c->db,c->argv[1]);
4939 if (o == NULL) {
4940 addReply(c,shared.czero);
4941 return;
4942 } else {
4943 if (o->type != REDIS_ZSET) {
4944 addReply(c,shared.wrongtypeerr);
4945 } else {
4946 zs = o->ptr;
682ac724 4947 addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",zs->zsl->length));
e197b441 4948 }
4949 }
4950}
4951
6e333bbe 4952static void zscoreCommand(redisClient *c) {
4953 robj *o;
4954 zset *zs;
4955
4956 o = lookupKeyRead(c->db,c->argv[1]);
4957 if (o == NULL) {
96d8b4ee 4958 addReply(c,shared.nullbulk);
6e333bbe 4959 return;
4960 } else {
4961 if (o->type != REDIS_ZSET) {
4962 addReply(c,shared.wrongtypeerr);
4963 } else {
4964 dictEntry *de;
4965
4966 zs = o->ptr;
4967 de = dictFind(zs->dict,c->argv[2]);
4968 if (!de) {
4969 addReply(c,shared.nullbulk);
4970 } else {
6e333bbe 4971 double *score = dictGetEntryVal(de);
4972
e2665397 4973 addReplyDouble(c,*score);
6e333bbe 4974 }
4975 }
4976 }
4977}
4978
6b47e12e 4979/* ========================= Non type-specific commands ==================== */
4980
ed9b544e 4981static void flushdbCommand(redisClient *c) {
ca37e9cd 4982 server.dirty += dictSize(c->db->dict);
3305306f 4983 dictEmpty(c->db->dict);
4984 dictEmpty(c->db->expires);
ed9b544e 4985 addReply(c,shared.ok);
ed9b544e 4986}
4987
4988static void flushallCommand(redisClient *c) {
ca37e9cd 4989 server.dirty += emptyDb();
ed9b544e 4990 addReply(c,shared.ok);
f78fd11b 4991 rdbSave(server.dbfilename);
ca37e9cd 4992 server.dirty++;
ed9b544e 4993}
4994
56906eef 4995static redisSortOperation *createSortOperation(int type, robj *pattern) {
ed9b544e 4996 redisSortOperation *so = zmalloc(sizeof(*so));
ed9b544e 4997 so->type = type;
4998 so->pattern = pattern;
4999 return so;
5000}
5001
5002/* Return the value associated to the key with a name obtained
5003 * substituting the first occurence of '*' in 'pattern' with 'subst' */
56906eef 5004static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
ed9b544e 5005 char *p;
5006 sds spat, ssub;
5007 robj keyobj;
5008 int prefixlen, sublen, postfixlen;
ed9b544e 5009 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5010 struct {
f1017b3f 5011 long len;
5012 long free;
ed9b544e 5013 char buf[REDIS_SORTKEY_MAX+1];
5014 } keyname;
5015
28173a49 5016 /* If the pattern is "#" return the substitution object itself in order
5017 * to implement the "SORT ... GET #" feature. */
5018 spat = pattern->ptr;
5019 if (spat[0] == '#' && spat[1] == '\0') {
5020 return subst;
5021 }
5022
5023 /* The substitution object may be specially encoded. If so we create
9d65a1bb 5024 * a decoded object on the fly. Otherwise getDecodedObject will just
5025 * increment the ref count, that we'll decrement later. */
5026 subst = getDecodedObject(subst);
942a3961 5027
ed9b544e 5028 ssub = subst->ptr;
5029 if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
5030 p = strchr(spat,'*');
ed5a857a 5031 if (!p) {
5032 decrRefCount(subst);
5033 return NULL;
5034 }
ed9b544e 5035
5036 prefixlen = p-spat;
5037 sublen = sdslen(ssub);
5038 postfixlen = sdslen(spat)-(prefixlen+1);
5039 memcpy(keyname.buf,spat,prefixlen);
5040 memcpy(keyname.buf+prefixlen,ssub,sublen);
5041 memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
5042 keyname.buf[prefixlen+sublen+postfixlen] = '\0';
5043 keyname.len = prefixlen+sublen+postfixlen;
5044
dfc5e96c 5045 initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2))
942a3961 5046 decrRefCount(subst);
5047
a4d1ba9a 5048 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
3305306f 5049 return lookupKeyRead(db,&keyobj);
ed9b544e 5050}
5051
5052/* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5053 * the additional parameter is not standard but a BSD-specific we have to
5054 * pass sorting parameters via the global 'server' structure */
5055static int sortCompare(const void *s1, const void *s2) {
5056 const redisSortObject *so1 = s1, *so2 = s2;
5057 int cmp;
5058
5059 if (!server.sort_alpha) {
5060 /* Numeric sorting. Here it's trivial as we precomputed scores */
5061 if (so1->u.score > so2->u.score) {
5062 cmp = 1;
5063 } else if (so1->u.score < so2->u.score) {
5064 cmp = -1;
5065 } else {
5066 cmp = 0;
5067 }
5068 } else {
5069 /* Alphanumeric sorting */
5070 if (server.sort_bypattern) {
5071 if (!so1->u.cmpobj || !so2->u.cmpobj) {
5072 /* At least one compare object is NULL */
5073 if (so1->u.cmpobj == so2->u.cmpobj)
5074 cmp = 0;
5075 else if (so1->u.cmpobj == NULL)
5076 cmp = -1;
5077 else
5078 cmp = 1;
5079 } else {
5080 /* We have both the objects, use strcoll */
5081 cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
5082 }
5083 } else {
5084 /* Compare elements directly */
9d65a1bb 5085 robj *dec1, *dec2;
5086
5087 dec1 = getDecodedObject(so1->obj);
5088 dec2 = getDecodedObject(so2->obj);
5089 cmp = strcoll(dec1->ptr,dec2->ptr);
5090 decrRefCount(dec1);
5091 decrRefCount(dec2);
ed9b544e 5092 }
5093 }
5094 return server.sort_desc ? -cmp : cmp;
5095}
5096
5097/* The SORT command is the most complex command in Redis. Warning: this code
5098 * is optimized for speed and a bit less for readability */
5099static void sortCommand(redisClient *c) {
ed9b544e 5100 list *operations;
5101 int outputlen = 0;
5102 int desc = 0, alpha = 0;
5103 int limit_start = 0, limit_count = -1, start, end;
5104 int j, dontsort = 0, vectorlen;
5105 int getop = 0; /* GET operation counter */
443c6409 5106 robj *sortval, *sortby = NULL, *storekey = NULL;
ed9b544e 5107 redisSortObject *vector; /* Resulting vector to sort */
5108
5109 /* Lookup the key to sort. It must be of the right types */
3305306f 5110 sortval = lookupKeyRead(c->db,c->argv[1]);
5111 if (sortval == NULL) {
d922ae65 5112 addReply(c,shared.nullmultibulk);
ed9b544e 5113 return;
5114 }
a5eb649b 5115 if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
5116 sortval->type != REDIS_ZSET)
5117 {
c937aa89 5118 addReply(c,shared.wrongtypeerr);
ed9b544e 5119 return;
5120 }
5121
5122 /* Create a list of operations to perform for every sorted element.
5123 * Operations can be GET/DEL/INCR/DECR */
5124 operations = listCreate();
092dac2a 5125 listSetFreeMethod(operations,zfree);
ed9b544e 5126 j = 2;
5127
5128 /* Now we need to protect sortval incrementing its count, in the future
5129 * SORT may have options able to overwrite/delete keys during the sorting
5130 * and the sorted key itself may get destroied */
5131 incrRefCount(sortval);
5132
5133 /* The SORT command has an SQL-alike syntax, parse it */
5134 while(j < c->argc) {
5135 int leftargs = c->argc-j-1;
5136 if (!strcasecmp(c->argv[j]->ptr,"asc")) {
5137 desc = 0;
5138 } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
5139 desc = 1;
5140 } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
5141 alpha = 1;
5142 } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
5143 limit_start = atoi(c->argv[j+1]->ptr);
5144 limit_count = atoi(c->argv[j+2]->ptr);
5145 j+=2;
443c6409 5146 } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
5147 storekey = c->argv[j+1];
5148 j++;
ed9b544e 5149 } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
5150 sortby = c->argv[j+1];
5151 /* If the BY pattern does not contain '*', i.e. it is constant,
5152 * we don't need to sort nor to lookup the weight keys. */
5153 if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
5154 j++;
5155 } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
5156 listAddNodeTail(operations,createSortOperation(
5157 REDIS_SORT_GET,c->argv[j+1]));
5158 getop++;
5159 j++;
ed9b544e 5160 } else {
5161 decrRefCount(sortval);
5162 listRelease(operations);
c937aa89 5163 addReply(c,shared.syntaxerr);
ed9b544e 5164 return;
5165 }
5166 j++;
5167 }
5168
5169 /* Load the sorting vector with all the objects to sort */
a5eb649b 5170 switch(sortval->type) {
5171 case REDIS_LIST: vectorlen = listLength((list*)sortval->ptr); break;
5172 case REDIS_SET: vectorlen = dictSize((dict*)sortval->ptr); break;
5173 case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
dfc5e96c 5174 default: vectorlen = 0; redisAssert(0); /* Avoid GCC warning */
a5eb649b 5175 }
ed9b544e 5176 vector = zmalloc(sizeof(redisSortObject)*vectorlen);
ed9b544e 5177 j = 0;
a5eb649b 5178
ed9b544e 5179 if (sortval->type == REDIS_LIST) {
5180 list *list = sortval->ptr;
6208b3a7 5181 listNode *ln;
5182
5183 listRewind(list);
5184 while((ln = listYield(list))) {
ed9b544e 5185 robj *ele = ln->value;
5186 vector[j].obj = ele;
5187 vector[j].u.score = 0;
5188 vector[j].u.cmpobj = NULL;
ed9b544e 5189 j++;
5190 }
5191 } else {
a5eb649b 5192 dict *set;
ed9b544e 5193 dictIterator *di;
5194 dictEntry *setele;
5195
a5eb649b 5196 if (sortval->type == REDIS_SET) {
5197 set = sortval->ptr;
5198 } else {
5199 zset *zs = sortval->ptr;
5200 set = zs->dict;
5201 }
5202
ed9b544e 5203 di = dictGetIterator(set);
ed9b544e 5204 while((setele = dictNext(di)) != NULL) {
5205 vector[j].obj = dictGetEntryKey(setele);
5206 vector[j].u.score = 0;
5207 vector[j].u.cmpobj = NULL;
5208 j++;
5209 }
5210 dictReleaseIterator(di);
5211 }
dfc5e96c 5212 redisAssert(j == vectorlen);
ed9b544e 5213
5214 /* Now it's time to load the right scores in the sorting vector */
5215 if (dontsort == 0) {
5216 for (j = 0; j < vectorlen; j++) {
5217 if (sortby) {
5218 robj *byval;
5219
3305306f 5220 byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
ed9b544e 5221 if (!byval || byval->type != REDIS_STRING) continue;
5222 if (alpha) {
9d65a1bb 5223 vector[j].u.cmpobj = getDecodedObject(byval);
ed9b544e 5224 } else {
942a3961 5225 if (byval->encoding == REDIS_ENCODING_RAW) {
5226 vector[j].u.score = strtod(byval->ptr,NULL);
5227 } else {
9d65a1bb 5228 /* Don't need to decode the object if it's
5229 * integer-encoded (the only encoding supported) so
5230 * far. We can just cast it */
f1017b3f 5231 if (byval->encoding == REDIS_ENCODING_INT) {
942a3961 5232 vector[j].u.score = (long)byval->ptr;
f1017b3f 5233 } else
dfc5e96c 5234 redisAssert(1 != 1);
942a3961 5235 }
ed9b544e 5236 }
5237 } else {
942a3961 5238 if (!alpha) {
5239 if (vector[j].obj->encoding == REDIS_ENCODING_RAW)
5240 vector[j].u.score = strtod(vector[j].obj->ptr,NULL);
5241 else {
5242 if (vector[j].obj->encoding == REDIS_ENCODING_INT)
5243 vector[j].u.score = (long) vector[j].obj->ptr;
5244 else
dfc5e96c 5245 redisAssert(1 != 1);
942a3961 5246 }
5247 }
ed9b544e 5248 }
5249 }
5250 }
5251
5252 /* We are ready to sort the vector... perform a bit of sanity check
5253 * on the LIMIT option too. We'll use a partial version of quicksort. */
5254 start = (limit_start < 0) ? 0 : limit_start;
5255 end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
5256 if (start >= vectorlen) {
5257 start = vectorlen-1;
5258 end = vectorlen-2;
5259 }
5260 if (end >= vectorlen) end = vectorlen-1;
5261
5262 if (dontsort == 0) {
5263 server.sort_desc = desc;
5264 server.sort_alpha = alpha;
5265 server.sort_bypattern = sortby ? 1 : 0;
5f5b9840 5266 if (sortby && (start != 0 || end != vectorlen-1))
5267 pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
5268 else
5269 qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
ed9b544e 5270 }
5271
5272 /* Send command output to the output buffer, performing the specified
5273 * GET/DEL/INCR/DECR operations if any. */
5274 outputlen = getop ? getop*(end-start+1) : end-start+1;
443c6409 5275 if (storekey == NULL) {
5276 /* STORE option not specified, sent the sorting result to client */
5277 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
5278 for (j = start; j <= end; j++) {
5279 listNode *ln;
5280 if (!getop) {
5281 addReplyBulkLen(c,vector[j].obj);
5282 addReply(c,vector[j].obj);
5283 addReply(c,shared.crlf);
5284 }
5285 listRewind(operations);
5286 while((ln = listYield(operations))) {
5287 redisSortOperation *sop = ln->value;
5288 robj *val = lookupKeyByPattern(c->db,sop->pattern,
5289 vector[j].obj);
5290
5291 if (sop->type == REDIS_SORT_GET) {
5292 if (!val || val->type != REDIS_STRING) {
5293 addReply(c,shared.nullbulk);
5294 } else {
5295 addReplyBulkLen(c,val);
5296 addReply(c,val);
5297 addReply(c,shared.crlf);
5298 }
5299 } else {
dfc5e96c 5300 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
443c6409 5301 }
5302 }
ed9b544e 5303 }
443c6409 5304 } else {
5305 robj *listObject = createListObject();
5306 list *listPtr = (list*) listObject->ptr;
5307
5308 /* STORE option specified, set the sorting result as a List object */
5309 for (j = start; j <= end; j++) {
5310 listNode *ln;
5311 if (!getop) {
5312 listAddNodeTail(listPtr,vector[j].obj);
5313 incrRefCount(vector[j].obj);
5314 }
5315 listRewind(operations);
5316 while((ln = listYield(operations))) {
5317 redisSortOperation *sop = ln->value;
5318 robj *val = lookupKeyByPattern(c->db,sop->pattern,
5319 vector[j].obj);
5320
5321 if (sop->type == REDIS_SORT_GET) {
5322 if (!val || val->type != REDIS_STRING) {
5323 listAddNodeTail(listPtr,createStringObject("",0));
5324 } else {
5325 listAddNodeTail(listPtr,val);
5326 incrRefCount(val);
5327 }
ed9b544e 5328 } else {
dfc5e96c 5329 redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
ed9b544e 5330 }
ed9b544e 5331 }
ed9b544e 5332 }
121796f7 5333 if (dictReplace(c->db->dict,storekey,listObject)) {
5334 incrRefCount(storekey);
5335 }
443c6409 5336 /* Note: we add 1 because the DB is dirty anyway since even if the
5337 * SORT result is empty a new key is set and maybe the old content
5338 * replaced. */
5339 server.dirty += 1+outputlen;
5340 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
ed9b544e 5341 }
5342
5343 /* Cleanup */
5344 decrRefCount(sortval);
5345 listRelease(operations);
5346 for (j = 0; j < vectorlen; j++) {
5347 if (sortby && alpha && vector[j].u.cmpobj)
5348 decrRefCount(vector[j].u.cmpobj);
5349 }
5350 zfree(vector);
5351}
5352
1c85b79f 5353/* Create the string returned by the INFO command. This is decoupled
5354 * by the INFO command itself as we need to report the same information
5355 * on memory corruption problems. */
5356static sds genRedisInfoString(void) {
ed9b544e 5357 sds info;
5358 time_t uptime = time(NULL)-server.stat_starttime;
c3cb078d 5359 int j;
ed9b544e 5360
5361 info = sdscatprintf(sdsempty(),
5362 "redis_version:%s\r\n"
f1017b3f 5363 "arch_bits:%s\r\n"
7a932b74 5364 "multiplexing_api:%s\r\n"
682ac724 5365 "uptime_in_seconds:%ld\r\n"
5366 "uptime_in_days:%ld\r\n"
ed9b544e 5367 "connected_clients:%d\r\n"
5368 "connected_slaves:%d\r\n"
f86a74e9 5369 "blocked_clients:%d\r\n"
5fba9f71 5370 "used_memory:%zu\r\n"
ed9b544e 5371 "changes_since_last_save:%lld\r\n"
be2bb6b0 5372 "bgsave_in_progress:%d\r\n"
682ac724 5373 "last_save_time:%ld\r\n"
b3fad521 5374 "bgrewriteaof_in_progress:%d\r\n"
ed9b544e 5375 "total_connections_received:%lld\r\n"
5376 "total_commands_processed:%lld\r\n"
a0f643ea 5377 "role:%s\r\n"
ed9b544e 5378 ,REDIS_VERSION,
f1017b3f 5379 (sizeof(long) == 8) ? "64" : "32",
7a932b74 5380 aeGetApiName(),
a0f643ea 5381 uptime,
5382 uptime/(3600*24),
ed9b544e 5383 listLength(server.clients)-listLength(server.slaves),
5384 listLength(server.slaves),
f86a74e9 5385 server.blockedclients,
ed9b544e 5386 server.usedmemory,
5387 server.dirty,
9d65a1bb 5388 server.bgsavechildpid != -1,
ed9b544e 5389 server.lastsave,
b3fad521 5390 server.bgrewritechildpid != -1,
ed9b544e 5391 server.stat_numconnections,
5392 server.stat_numcommands,
a0f643ea 5393 server.masterhost == NULL ? "master" : "slave"
ed9b544e 5394 );
a0f643ea 5395 if (server.masterhost) {
5396 info = sdscatprintf(info,
5397 "master_host:%s\r\n"
5398 "master_port:%d\r\n"
5399 "master_link_status:%s\r\n"
5400 "master_last_io_seconds_ago:%d\r\n"
5401 ,server.masterhost,
5402 server.masterport,
5403 (server.replstate == REDIS_REPL_CONNECTED) ?
5404 "up" : "down",
f72b934d 5405 server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
a0f643ea 5406 );
5407 }
c3cb078d 5408 for (j = 0; j < server.dbnum; j++) {
5409 long long keys, vkeys;
5410
5411 keys = dictSize(server.db[j].dict);
5412 vkeys = dictSize(server.db[j].expires);
5413 if (keys || vkeys) {
9d65a1bb 5414 info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
c3cb078d 5415 j, keys, vkeys);
5416 }
5417 }
1c85b79f 5418 return info;
5419}
5420
5421static void infoCommand(redisClient *c) {
5422 sds info = genRedisInfoString();
83c6a618 5423 addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
5424 (unsigned long)sdslen(info)));
ed9b544e 5425 addReplySds(c,info);
70003d28 5426 addReply(c,shared.crlf);
ed9b544e 5427}
5428
3305306f 5429static void monitorCommand(redisClient *c) {
5430 /* ignore MONITOR if aleady slave or in monitor mode */
5431 if (c->flags & REDIS_SLAVE) return;
5432
5433 c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
5434 c->slaveseldb = 0;
6b47e12e 5435 listAddNodeTail(server.monitors,c);
3305306f 5436 addReply(c,shared.ok);
5437}
5438
5439/* ================================= Expire ================================= */
5440static int removeExpire(redisDb *db, robj *key) {
5441 if (dictDelete(db->expires,key) == DICT_OK) {
5442 return 1;
5443 } else {
5444 return 0;
5445 }
5446}
5447
5448static int setExpire(redisDb *db, robj *key, time_t when) {
5449 if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
5450 return 0;
5451 } else {
5452 incrRefCount(key);
5453 return 1;
5454 }
5455}
5456
bb32ede5 5457/* Return the expire time of the specified key, or -1 if no expire
5458 * is associated with this key (i.e. the key is non volatile) */
5459static time_t getExpire(redisDb *db, robj *key) {
5460 dictEntry *de;
5461
5462 /* No expire? return ASAP */
5463 if (dictSize(db->expires) == 0 ||
5464 (de = dictFind(db->expires,key)) == NULL) return -1;
5465
5466 return (time_t) dictGetEntryVal(de);
5467}
5468
3305306f 5469static int expireIfNeeded(redisDb *db, robj *key) {
5470 time_t when;
5471 dictEntry *de;
5472
5473 /* No expire? return ASAP */
5474 if (dictSize(db->expires) == 0 ||
5475 (de = dictFind(db->expires,key)) == NULL) return 0;
5476
5477 /* Lookup the expire */
5478 when = (time_t) dictGetEntryVal(de);
5479 if (time(NULL) <= when) return 0;
5480
5481 /* Delete the key */
5482 dictDelete(db->expires,key);
5483 return dictDelete(db->dict,key) == DICT_OK;
5484}
5485
5486static int deleteIfVolatile(redisDb *db, robj *key) {
5487 dictEntry *de;
5488
5489 /* No expire? return ASAP */
5490 if (dictSize(db->expires) == 0 ||
5491 (de = dictFind(db->expires,key)) == NULL) return 0;
5492
5493 /* Delete the key */
0c66a471 5494 server.dirty++;
3305306f 5495 dictDelete(db->expires,key);
5496 return dictDelete(db->dict,key) == DICT_OK;
5497}
5498
802e8373 5499static void expireGenericCommand(redisClient *c, robj *key, time_t seconds) {
3305306f 5500 dictEntry *de;
3305306f 5501
802e8373 5502 de = dictFind(c->db->dict,key);
3305306f 5503 if (de == NULL) {
5504 addReply(c,shared.czero);
5505 return;
5506 }
43e5ccdf 5507 if (seconds < 0) {
5508 if (deleteKey(c->db,key)) server.dirty++;
5509 addReply(c, shared.cone);
3305306f 5510 return;
5511 } else {
5512 time_t when = time(NULL)+seconds;
802e8373 5513 if (setExpire(c->db,key,when)) {
3305306f 5514 addReply(c,shared.cone);
77423026 5515 server.dirty++;
5516 } else {
3305306f 5517 addReply(c,shared.czero);
77423026 5518 }
3305306f 5519 return;
5520 }
5521}
5522
802e8373 5523static void expireCommand(redisClient *c) {
5524 expireGenericCommand(c,c->argv[1],strtol(c->argv[2]->ptr,NULL,10));
5525}
5526
5527static void expireatCommand(redisClient *c) {
5528 expireGenericCommand(c,c->argv[1],strtol(c->argv[2]->ptr,NULL,10)-time(NULL));
5529}
5530
fd88489a 5531static void ttlCommand(redisClient *c) {
5532 time_t expire;
5533 int ttl = -1;
5534
5535 expire = getExpire(c->db,c->argv[1]);
5536 if (expire != -1) {
5537 ttl = (int) (expire-time(NULL));
5538 if (ttl < 0) ttl = -1;
5539 }
5540 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
5541}
5542
6e469882 5543/* ================================ MULTI/EXEC ============================== */
5544
5545/* Client state initialization for MULTI/EXEC */
5546static void initClientMultiState(redisClient *c) {
5547 c->mstate.commands = NULL;
5548 c->mstate.count = 0;
5549}
5550
5551/* Release all the resources associated with MULTI/EXEC state */
5552static void freeClientMultiState(redisClient *c) {
5553 int j;
5554
5555 for (j = 0; j < c->mstate.count; j++) {
5556 int i;
5557 multiCmd *mc = c->mstate.commands+j;
5558
5559 for (i = 0; i < mc->argc; i++)
5560 decrRefCount(mc->argv[i]);
5561 zfree(mc->argv);
5562 }
5563 zfree(c->mstate.commands);
5564}
5565
5566/* Add a new command into the MULTI commands queue */
5567static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
5568 multiCmd *mc;
5569 int j;
5570
5571 c->mstate.commands = zrealloc(c->mstate.commands,
5572 sizeof(multiCmd)*(c->mstate.count+1));
5573 mc = c->mstate.commands+c->mstate.count;
5574 mc->cmd = cmd;
5575 mc->argc = c->argc;
5576 mc->argv = zmalloc(sizeof(robj*)*c->argc);
5577 memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
5578 for (j = 0; j < c->argc; j++)
5579 incrRefCount(mc->argv[j]);
5580 c->mstate.count++;
5581}
5582
5583static void multiCommand(redisClient *c) {
5584 c->flags |= REDIS_MULTI;
36c548f0 5585 addReply(c,shared.ok);
6e469882 5586}
5587
5588static void execCommand(redisClient *c) {
5589 int j;
5590 robj **orig_argv;
5591 int orig_argc;
5592
5593 if (!(c->flags & REDIS_MULTI)) {
5594 addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
5595 return;
5596 }
5597
5598 orig_argv = c->argv;
5599 orig_argc = c->argc;
5600 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
5601 for (j = 0; j < c->mstate.count; j++) {
5602 c->argc = c->mstate.commands[j].argc;
5603 c->argv = c->mstate.commands[j].argv;
5604 call(c,c->mstate.commands[j].cmd);
5605 }
5606 c->argv = orig_argv;
5607 c->argc = orig_argc;
5608 freeClientMultiState(c);
5609 initClientMultiState(c);
5610 c->flags &= (~REDIS_MULTI);
5611}
5612
4409877e 5613/* =========================== Blocking Operations ========================= */
5614
5615/* Currently Redis blocking operations support is limited to list POP ops,
5616 * so the current implementation is not fully generic, but it is also not
5617 * completely specific so it will not require a rewrite to support new
5618 * kind of blocking operations in the future.
5619 *
5620 * Still it's important to note that list blocking operations can be already
5621 * used as a notification mechanism in order to implement other blocking
5622 * operations at application level, so there must be a very strong evidence
5623 * of usefulness and generality before new blocking operations are implemented.
5624 *
5625 * This is how the current blocking POP works, we use BLPOP as example:
5626 * - If the user calls BLPOP and the key exists and contains a non empty list
5627 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5628 * if there is not to block.
5629 * - If instead BLPOP is called and the key does not exists or the list is
5630 * empty we need to block. In order to do so we remove the notification for
5631 * new data to read in the client socket (so that we'll not serve new
5632 * requests if the blocking request is not served). Also we put the client
95242ab5 5633 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
4409877e 5634 * blocking for this keys.
5635 * - If a PUSH operation against a key with blocked clients waiting is
5636 * performed, we serve the first in the list: basically instead to push
5637 * the new element inside the list we return it to the (first / oldest)
5638 * blocking client, unblock the client, and remove it form the list.
5639 *
5640 * The above comment and the source code should be enough in order to understand
5641 * the implementation and modify / fix it later.
5642 */
5643
5644/* Set a client in blocking mode for the specified key, with the specified
5645 * timeout */
b177fd30 5646static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
4409877e 5647 dictEntry *de;
5648 list *l;
b177fd30 5649 int j;
4409877e 5650
b177fd30 5651 c->blockingkeys = zmalloc(sizeof(robj*)*numkeys);
5652 c->blockingkeysnum = numkeys;
4409877e 5653 c->blockingto = timeout;
b177fd30 5654 for (j = 0; j < numkeys; j++) {
5655 /* Add the key in the client structure, to map clients -> keys */
5656 c->blockingkeys[j] = keys[j];
5657 incrRefCount(keys[j]);
4409877e 5658
b177fd30 5659 /* And in the other "side", to map keys -> clients */
5660 de = dictFind(c->db->blockingkeys,keys[j]);
5661 if (de == NULL) {
5662 int retval;
5663
5664 /* For every key we take a list of clients blocked for it */
5665 l = listCreate();
5666 retval = dictAdd(c->db->blockingkeys,keys[j],l);
5667 incrRefCount(keys[j]);
5668 assert(retval == DICT_OK);
5669 } else {
5670 l = dictGetEntryVal(de);
5671 }
5672 listAddNodeTail(l,c);
4409877e 5673 }
b177fd30 5674 /* Mark the client as a blocked client */
4409877e 5675 c->flags |= REDIS_BLOCKED;
5676 aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
f86a74e9 5677 server.blockedclients++;
4409877e 5678}
5679
5680/* Unblock a client that's waiting in a blocking operation such as BLPOP */
5681static void unblockClient(redisClient *c) {
5682 dictEntry *de;
5683 list *l;
b177fd30 5684 int j;
4409877e 5685
b177fd30 5686 assert(c->blockingkeys != NULL);
5687 /* The client may wait for multiple keys, so unblock it for every key. */
5688 for (j = 0; j < c->blockingkeysnum; j++) {
5689 /* Remove this client from the list of clients waiting for this key. */
5690 de = dictFind(c->db->blockingkeys,c->blockingkeys[j]);
5691 assert(de != NULL);
5692 l = dictGetEntryVal(de);
5693 listDelNode(l,listSearchKey(l,c));
5694 /* If the list is empty we need to remove it to avoid wasting memory */
5695 if (listLength(l) == 0)
5696 dictDelete(c->db->blockingkeys,c->blockingkeys[j]);
5697 decrRefCount(c->blockingkeys[j]);
5698 }
5699 /* Cleanup the client structure */
5700 zfree(c->blockingkeys);
5701 c->blockingkeys = NULL;
4409877e 5702 c->flags &= (~REDIS_BLOCKED);
f86a74e9 5703 server.blockedclients--;
4409877e 5704 /* Ok now we are ready to get read events from socket, note that we
5705 * can't trap errors here as it's possible that unblockClients() is
5706 * called from freeClient() itself, and the only thing we can do
5707 * if we failed to register the READABLE event is to kill the client.
5708 * Still the following function should never fail in the real world as
5709 * we are sure the file descriptor is sane, and we exit on out of mem. */
5710 aeCreateFileEvent(server.el, c->fd, AE_READABLE, readQueryFromClient, c);
5711 /* As a final step we want to process data if there is some command waiting
5712 * in the input buffer. Note that this is safe even if unblockClient()
5713 * gets called from freeClient() because freeClient() will be smart
5714 * enough to call this function *after* c->querybuf was set to NULL. */
5715 if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
5716}
5717
5718/* This should be called from any function PUSHing into lists.
5719 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5720 * 'ele' is the element pushed.
5721 *
5722 * If the function returns 0 there was no client waiting for a list push
5723 * against this key.
5724 *
5725 * If the function returns 1 there was a client waiting for a list push
5726 * against this key, the element was passed to this client thus it's not
5727 * needed to actually add it to the list and the caller should return asap. */
5728static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
5729 struct dictEntry *de;
5730 redisClient *receiver;
5731 list *l;
5732 listNode *ln;
5733
5734 de = dictFind(c->db->blockingkeys,key);
5735 if (de == NULL) return 0;
5736 l = dictGetEntryVal(de);
5737 ln = listFirst(l);
5738 assert(ln != NULL);
5739 receiver = ln->value;
4409877e 5740
b177fd30 5741 addReplySds(receiver,sdsnew("*2\r\n"));
5742 addReplyBulkLen(receiver,key);
5743 addReply(receiver,key);
5744 addReply(receiver,shared.crlf);
4409877e 5745 addReplyBulkLen(receiver,ele);
5746 addReply(receiver,ele);
5747 addReply(receiver,shared.crlf);
5748 unblockClient(receiver);
5749 return 1;
5750}
5751
5752/* Blocking RPOP/LPOP */
5753static void blockingPopGenericCommand(redisClient *c, int where) {
5754 robj *o;
5755 time_t timeout;
b177fd30 5756 int j;
4409877e 5757
b177fd30 5758 for (j = 1; j < c->argc-1; j++) {
5759 o = lookupKeyWrite(c->db,c->argv[j]);
5760 if (o != NULL) {
5761 if (o->type != REDIS_LIST) {
5762 addReply(c,shared.wrongtypeerr);
4409877e 5763 return;
b177fd30 5764 } else {
5765 list *list = o->ptr;
5766 if (listLength(list) != 0) {
5767 /* If the list contains elements fall back to the usual
5768 * non-blocking POP operation */
5769 robj *argv[2], **orig_argv;
5770 int orig_argc;
5771
5772 /* We need to alter the command arguments before to call
5773 * popGenericCommand() as the command takes a single key. */
5774 orig_argv = c->argv;
5775 orig_argc = c->argc;
5776 argv[1] = c->argv[j];
5777 c->argv = argv;
5778 c->argc = 2;
5779
5780 /* Also the return value is different, we need to output
5781 * the multi bulk reply header and the key name. The
5782 * "real" command will add the last element (the value)
5783 * for us. If this souds like an hack to you it's just
5784 * because it is... */
5785 addReplySds(c,sdsnew("*2\r\n"));
5786 addReplyBulkLen(c,argv[1]);
5787 addReply(c,argv[1]);
5788 addReply(c,shared.crlf);
5789 popGenericCommand(c,where);
5790
5791 /* Fix the client structure with the original stuff */
5792 c->argv = orig_argv;
5793 c->argc = orig_argc;
5794 return;
5795 }
4409877e 5796 }
5797 }
5798 }
5799 /* If the list is empty or the key does not exists we must block */
b177fd30 5800 timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
4409877e 5801 if (timeout > 0) timeout += time(NULL);
b177fd30 5802 blockForKeys(c,c->argv+1,c->argc-2,timeout);
4409877e 5803}
5804
5805static void blpopCommand(redisClient *c) {
5806 blockingPopGenericCommand(c,REDIS_HEAD);
5807}
5808
5809static void brpopCommand(redisClient *c) {
5810 blockingPopGenericCommand(c,REDIS_TAIL);
5811}
5812
ed9b544e 5813/* =============================== Replication ============================= */
5814
a4d1ba9a 5815static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 5816 ssize_t nwritten, ret = size;
5817 time_t start = time(NULL);
5818
5819 timeout++;
5820 while(size) {
5821 if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
5822 nwritten = write(fd,ptr,size);
5823 if (nwritten == -1) return -1;
5824 ptr += nwritten;
5825 size -= nwritten;
5826 }
5827 if ((time(NULL)-start) > timeout) {
5828 errno = ETIMEDOUT;
5829 return -1;
5830 }
5831 }
5832 return ret;
5833}
5834
a4d1ba9a 5835static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
ed9b544e 5836 ssize_t nread, totread = 0;
5837 time_t start = time(NULL);
5838
5839 timeout++;
5840 while(size) {
5841 if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
5842 nread = read(fd,ptr,size);
5843 if (nread == -1) return -1;
5844 ptr += nread;
5845 size -= nread;
5846 totread += nread;
5847 }
5848 if ((time(NULL)-start) > timeout) {
5849 errno = ETIMEDOUT;
5850 return -1;
5851 }
5852 }
5853 return totread;
5854}
5855
5856static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
5857 ssize_t nread = 0;
5858
5859 size--;
5860 while(size) {
5861 char c;
5862
5863 if (syncRead(fd,&c,1,timeout) == -1) return -1;
5864 if (c == '\n') {
5865 *ptr = '\0';
5866 if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
5867 return nread;
5868 } else {
5869 *ptr++ = c;
5870 *ptr = '\0';
5871 nread++;
5872 }
5873 }
5874 return nread;
5875}
5876
5877static void syncCommand(redisClient *c) {
40d224a9 5878 /* ignore SYNC if aleady slave or in monitor mode */
5879 if (c->flags & REDIS_SLAVE) return;
5880
5881 /* SYNC can't be issued when the server has pending data to send to
5882 * the client about already issued commands. We need a fresh reply
5883 * buffer registering the differences between the BGSAVE and the current
5884 * dataset, so that we can copy to other slaves if needed. */
5885 if (listLength(c->reply) != 0) {
5886 addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
5887 return;
5888 }
5889
5890 redisLog(REDIS_NOTICE,"Slave ask for synchronization");
5891 /* Here we need to check if there is a background saving operation
5892 * in progress, or if it is required to start one */
9d65a1bb 5893 if (server.bgsavechildpid != -1) {
40d224a9 5894 /* Ok a background save is in progress. Let's check if it is a good
5895 * one for replication, i.e. if there is another slave that is
5896 * registering differences since the server forked to save */
5897 redisClient *slave;
5898 listNode *ln;
5899
6208b3a7 5900 listRewind(server.slaves);
5901 while((ln = listYield(server.slaves))) {
40d224a9 5902 slave = ln->value;
5903 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
40d224a9 5904 }
5905 if (ln) {
5906 /* Perfect, the server is already registering differences for
5907 * another slave. Set the right state, and copy the buffer. */
5908 listRelease(c->reply);
5909 c->reply = listDup(slave->reply);
40d224a9 5910 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
5911 redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
5912 } else {
5913 /* No way, we need to wait for the next BGSAVE in order to
5914 * register differences */
5915 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
5916 redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
5917 }
5918 } else {
5919 /* Ok we don't have a BGSAVE in progress, let's start one */
5920 redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
5921 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
5922 redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
5923 addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
5924 return;
5925 }
5926 c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
5927 }
6208b3a7 5928 c->repldbfd = -1;
40d224a9 5929 c->flags |= REDIS_SLAVE;
5930 c->slaveseldb = 0;
6b47e12e 5931 listAddNodeTail(server.slaves,c);
40d224a9 5932 return;
5933}
5934
6208b3a7 5935static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
5936 redisClient *slave = privdata;
5937 REDIS_NOTUSED(el);
5938 REDIS_NOTUSED(mask);
5939 char buf[REDIS_IOBUF_LEN];
5940 ssize_t nwritten, buflen;
5941
5942 if (slave->repldboff == 0) {
5943 /* Write the bulk write count before to transfer the DB. In theory here
5944 * we don't know how much room there is in the output buffer of the
5945 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
5946 * operations) will never be smaller than the few bytes we need. */
5947 sds bulkcount;
5948
5949 bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
5950 slave->repldbsize);
5951 if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
5952 {
5953 sdsfree(bulkcount);
5954 freeClient(slave);
5955 return;
5956 }
5957 sdsfree(bulkcount);
5958 }
5959 lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
5960 buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
5961 if (buflen <= 0) {
5962 redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
5963 (buflen == 0) ? "premature EOF" : strerror(errno));
5964 freeClient(slave);
5965 return;
5966 }
5967 if ((nwritten = write(fd,buf,buflen)) == -1) {
5968 redisLog(REDIS_DEBUG,"Write error sending DB to slave: %s",
5969 strerror(errno));
5970 freeClient(slave);
5971 return;
5972 }
5973 slave->repldboff += nwritten;
5974 if (slave->repldboff == slave->repldbsize) {
5975 close(slave->repldbfd);
5976 slave->repldbfd = -1;
5977 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
5978 slave->replstate = REDIS_REPL_ONLINE;
5979 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
266373b2 5980 sendReplyToClient, slave) == AE_ERR) {
6208b3a7 5981 freeClient(slave);
5982 return;
5983 }
5984 addReplySds(slave,sdsempty());
5985 redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
5986 }
5987}
ed9b544e 5988
a3b21203 5989/* This function is called at the end of every backgrond saving.
5990 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
5991 * otherwise REDIS_ERR is passed to the function.
5992 *
5993 * The goal of this function is to handle slaves waiting for a successful
5994 * background saving in order to perform non-blocking synchronization. */
5995static void updateSlavesWaitingBgsave(int bgsaveerr) {
6208b3a7 5996 listNode *ln;
5997 int startbgsave = 0;
ed9b544e 5998
6208b3a7 5999 listRewind(server.slaves);
6000 while((ln = listYield(server.slaves))) {
6001 redisClient *slave = ln->value;
ed9b544e 6002
6208b3a7 6003 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
6004 startbgsave = 1;
6005 slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
6006 } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
dde65f3f 6007 struct redis_stat buf;
6208b3a7 6008
6009 if (bgsaveerr != REDIS_OK) {
6010 freeClient(slave);
6011 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
6012 continue;
6013 }
6014 if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
dde65f3f 6015 redis_fstat(slave->repldbfd,&buf) == -1) {
6208b3a7 6016 freeClient(slave);
6017 redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
6018 continue;
6019 }
6020 slave->repldboff = 0;
6021 slave->repldbsize = buf.st_size;
6022 slave->replstate = REDIS_REPL_SEND_BULK;
6023 aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
266373b2 6024 if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
6208b3a7 6025 freeClient(slave);
6026 continue;
6027 }
6028 }
ed9b544e 6029 }
6208b3a7 6030 if (startbgsave) {
6031 if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
6032 listRewind(server.slaves);
6033 redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
6034 while((ln = listYield(server.slaves))) {
6035 redisClient *slave = ln->value;
ed9b544e 6036
6208b3a7 6037 if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
6038 freeClient(slave);
6039 }
6040 }
6041 }
ed9b544e 6042}
6043
6044static int syncWithMaster(void) {
d0ccebcf 6045 char buf[1024], tmpfile[256], authcmd[1024];
ed9b544e 6046 int dumpsize;
6047 int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
6048 int dfd;
6049
6050 if (fd == -1) {
6051 redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
6052 strerror(errno));
6053 return REDIS_ERR;
6054 }
d0ccebcf 6055
6056 /* AUTH with the master if required. */
6057 if(server.masterauth) {
6058 snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
6059 if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
6060 close(fd);
6061 redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
6062 strerror(errno));
6063 return REDIS_ERR;
6064 }
6065 /* Read the AUTH result. */
6066 if (syncReadLine(fd,buf,1024,3600) == -1) {
6067 close(fd);
6068 redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
6069 strerror(errno));
6070 return REDIS_ERR;
6071 }
6072 if (buf[0] != '+') {
6073 close(fd);
6074 redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
6075 return REDIS_ERR;
6076 }
6077 }
6078
ed9b544e 6079 /* Issue the SYNC command */
6080 if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
6081 close(fd);
6082 redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
6083 strerror(errno));
6084 return REDIS_ERR;
6085 }
6086 /* Read the bulk write count */
8c4d91fc 6087 if (syncReadLine(fd,buf,1024,3600) == -1) {
ed9b544e 6088 close(fd);
6089 redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
6090 strerror(errno));
6091 return REDIS_ERR;
6092 }
4aa701c1 6093 if (buf[0] != '$') {
6094 close(fd);
6095 redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6096 return REDIS_ERR;
6097 }
c937aa89 6098 dumpsize = atoi(buf+1);
ed9b544e 6099 redisLog(REDIS_NOTICE,"Receiving %d bytes data dump from MASTER",dumpsize);
6100 /* Read the bulk write data on a temp file */
6101 snprintf(tmpfile,256,"temp-%d.%ld.rdb",(int)time(NULL),(long int)random());
6102 dfd = open(tmpfile,O_CREAT|O_WRONLY,0644);
6103 if (dfd == -1) {
6104 close(fd);
6105 redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
6106 return REDIS_ERR;
6107 }
6108 while(dumpsize) {
6109 int nread, nwritten;
6110
6111 nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
6112 if (nread == -1) {
6113 redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
6114 strerror(errno));
6115 close(fd);
6116 close(dfd);
6117 return REDIS_ERR;
6118 }
6119 nwritten = write(dfd,buf,nread);
6120 if (nwritten == -1) {
6121 redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
6122 close(fd);
6123 close(dfd);
6124 return REDIS_ERR;
6125 }
6126 dumpsize -= nread;
6127 }
6128 close(dfd);
6129 if (rename(tmpfile,server.dbfilename) == -1) {
6130 redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
6131 unlink(tmpfile);
6132 close(fd);
6133 return REDIS_ERR;
6134 }
6135 emptyDb();
f78fd11b 6136 if (rdbLoad(server.dbfilename) != REDIS_OK) {
ed9b544e 6137 redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
6138 close(fd);
6139 return REDIS_ERR;
6140 }
6141 server.master = createClient(fd);
6142 server.master->flags |= REDIS_MASTER;
179b3952 6143 server.master->authenticated = 1;
ed9b544e 6144 server.replstate = REDIS_REPL_CONNECTED;
6145 return REDIS_OK;
6146}
6147
321b0e13 6148static void slaveofCommand(redisClient *c) {
6149 if (!strcasecmp(c->argv[1]->ptr,"no") &&
6150 !strcasecmp(c->argv[2]->ptr,"one")) {
6151 if (server.masterhost) {
6152 sdsfree(server.masterhost);
6153 server.masterhost = NULL;
6154 if (server.master) freeClient(server.master);
6155 server.replstate = REDIS_REPL_NONE;
6156 redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
6157 }
6158 } else {
6159 sdsfree(server.masterhost);
6160 server.masterhost = sdsdup(c->argv[1]->ptr);
6161 server.masterport = atoi(c->argv[2]->ptr);
6162 if (server.master) freeClient(server.master);
6163 server.replstate = REDIS_REPL_CONNECT;
6164 redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
6165 server.masterhost, server.masterport);
6166 }
6167 addReply(c,shared.ok);
6168}
6169
3fd78bcd 6170/* ============================ Maxmemory directive ======================== */
6171
6172/* This function gets called when 'maxmemory' is set on the config file to limit
6173 * the max memory used by the server, and we are out of memory.
6174 * This function will try to, in order:
6175 *
6176 * - Free objects from the free list
6177 * - Try to remove keys with an EXPIRE set
6178 *
6179 * It is not possible to free enough memory to reach used-memory < maxmemory
6180 * the server will start refusing commands that will enlarge even more the
6181 * memory usage.
6182 */
6183static void freeMemoryIfNeeded(void) {
6184 while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
6185 if (listLength(server.objfreelist)) {
6186 robj *o;
6187
6188 listNode *head = listFirst(server.objfreelist);
6189 o = listNodeValue(head);
6190 listDelNode(server.objfreelist,head);
6191 zfree(o);
6192 } else {
6193 int j, k, freed = 0;
6194
6195 for (j = 0; j < server.dbnum; j++) {
6196 int minttl = -1;
6197 robj *minkey = NULL;
6198 struct dictEntry *de;
6199
6200 if (dictSize(server.db[j].expires)) {
6201 freed = 1;
6202 /* From a sample of three keys drop the one nearest to
6203 * the natural expire */
6204 for (k = 0; k < 3; k++) {
6205 time_t t;
6206
6207 de = dictGetRandomKey(server.db[j].expires);
6208 t = (time_t) dictGetEntryVal(de);
6209 if (minttl == -1 || t < minttl) {
6210 minkey = dictGetEntryKey(de);
6211 minttl = t;
6212 }
6213 }
6214 deleteKey(server.db+j,minkey);
6215 }
6216 }
6217 if (!freed) return; /* nothing to free... */
6218 }
6219 }
6220}
6221
f80dff62 6222/* ============================== Append Only file ========================== */
6223
6224static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
6225 sds buf = sdsempty();
6226 int j;
6227 ssize_t nwritten;
6228 time_t now;
6229 robj *tmpargv[3];
6230
6231 /* The DB this command was targetting is not the same as the last command
6232 * we appendend. To issue a SELECT command is needed. */
6233 if (dictid != server.appendseldb) {
6234 char seldb[64];
6235
6236 snprintf(seldb,sizeof(seldb),"%d",dictid);
682ac724 6237 buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
83c6a618 6238 (unsigned long)strlen(seldb),seldb);
f80dff62 6239 server.appendseldb = dictid;
6240 }
6241
6242 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6243 * EXPIREs into EXPIREATs calls */
6244 if (cmd->proc == expireCommand) {
6245 long when;
6246
6247 tmpargv[0] = createStringObject("EXPIREAT",8);
6248 tmpargv[1] = argv[1];
6249 incrRefCount(argv[1]);
6250 when = time(NULL)+strtol(argv[2]->ptr,NULL,10);
6251 tmpargv[2] = createObject(REDIS_STRING,
6252 sdscatprintf(sdsempty(),"%ld",when));
6253 argv = tmpargv;
6254 }
6255
6256 /* Append the actual command */
6257 buf = sdscatprintf(buf,"*%d\r\n",argc);
6258 for (j = 0; j < argc; j++) {
6259 robj *o = argv[j];
6260
9d65a1bb 6261 o = getDecodedObject(o);
83c6a618 6262 buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
f80dff62 6263 buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
6264 buf = sdscatlen(buf,"\r\n",2);
9d65a1bb 6265 decrRefCount(o);
f80dff62 6266 }
6267
6268 /* Free the objects from the modified argv for EXPIREAT */
6269 if (cmd->proc == expireCommand) {
6270 for (j = 0; j < 3; j++)
6271 decrRefCount(argv[j]);
6272 }
6273
6274 /* We want to perform a single write. This should be guaranteed atomic
6275 * at least if the filesystem we are writing is a real physical one.
6276 * While this will save us against the server being killed I don't think
6277 * there is much to do about the whole server stopping for power problems
6278 * or alike */
6279 nwritten = write(server.appendfd,buf,sdslen(buf));
6280 if (nwritten != (signed)sdslen(buf)) {
6281 /* Ooops, we are in troubles. The best thing to do for now is
6282 * to simply exit instead to give the illusion that everything is
6283 * working as expected. */
6284 if (nwritten == -1) {
6285 redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
6286 } else {
6287 redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
6288 }
6289 exit(1);
6290 }
85a83172 6291 /* If a background append only file rewriting is in progress we want to
6292 * accumulate the differences between the child DB and the current one
6293 * in a buffer, so that when the child process will do its work we
6294 * can append the differences to the new append only file. */
6295 if (server.bgrewritechildpid != -1)
6296 server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));
6297
6298 sdsfree(buf);
f80dff62 6299 now = time(NULL);
6300 if (server.appendfsync == APPENDFSYNC_ALWAYS ||
6301 (server.appendfsync == APPENDFSYNC_EVERYSEC &&
6302 now-server.lastfsync > 1))
6303 {
6304 fsync(server.appendfd); /* Let's try to get this data on the disk */
6305 server.lastfsync = now;
6306 }
6307}
6308
6309/* In Redis commands are always executed in the context of a client, so in
6310 * order to load the append only file we need to create a fake client. */
6311static struct redisClient *createFakeClient(void) {
6312 struct redisClient *c = zmalloc(sizeof(*c));
6313
6314 selectDb(c,0);
6315 c->fd = -1;
6316 c->querybuf = sdsempty();
6317 c->argc = 0;
6318 c->argv = NULL;
6319 c->flags = 0;
9387d17d 6320 /* We set the fake client as a slave waiting for the synchronization
6321 * so that Redis will not try to send replies to this client. */
6322 c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
f80dff62 6323 c->reply = listCreate();
6324 listSetFreeMethod(c->reply,decrRefCount);
6325 listSetDupMethod(c->reply,dupClientReplyValue);
6326 return c;
6327}
6328
6329static void freeFakeClient(struct redisClient *c) {
6330 sdsfree(c->querybuf);
6331 listRelease(c->reply);
6332 zfree(c);
6333}
6334
6335/* Replay the append log file. On error REDIS_OK is returned. On non fatal
6336 * error (the append only file is zero-length) REDIS_ERR is returned. On
6337 * fatal error an error message is logged and the program exists. */
6338int loadAppendOnlyFile(char *filename) {
6339 struct redisClient *fakeClient;
6340 FILE *fp = fopen(filename,"r");
6341 struct redis_stat sb;
6342
6343 if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
6344 return REDIS_ERR;
6345
6346 if (fp == NULL) {
6347 redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
6348 exit(1);
6349 }
6350
6351 fakeClient = createFakeClient();
6352 while(1) {
6353 int argc, j;
6354 unsigned long len;
6355 robj **argv;
6356 char buf[128];
6357 sds argsds;
6358 struct redisCommand *cmd;
6359
6360 if (fgets(buf,sizeof(buf),fp) == NULL) {
6361 if (feof(fp))
6362 break;
6363 else
6364 goto readerr;
6365 }
6366 if (buf[0] != '*') goto fmterr;
6367 argc = atoi(buf+1);
6368 argv = zmalloc(sizeof(robj*)*argc);
6369 for (j = 0; j < argc; j++) {
6370 if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
6371 if (buf[0] != '$') goto fmterr;
6372 len = strtol(buf+1,NULL,10);
6373 argsds = sdsnewlen(NULL,len);
0f151ef1 6374 if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
f80dff62 6375 argv[j] = createObject(REDIS_STRING,argsds);
6376 if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
6377 }
6378
6379 /* Command lookup */
6380 cmd = lookupCommand(argv[0]->ptr);
6381 if (!cmd) {
6382 redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
6383 exit(1);
6384 }
6385 /* Try object sharing and encoding */
6386 if (server.shareobjects) {
6387 int j;
6388 for(j = 1; j < argc; j++)
6389 argv[j] = tryObjectSharing(argv[j]);
6390 }
6391 if (cmd->flags & REDIS_CMD_BULK)
6392 tryObjectEncoding(argv[argc-1]);
6393 /* Run the command in the context of a fake client */
6394 fakeClient->argc = argc;
6395 fakeClient->argv = argv;
6396 cmd->proc(fakeClient);
6397 /* Discard the reply objects list from the fake client */
6398 while(listLength(fakeClient->reply))
6399 listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
6400 /* Clean up, ready for the next command */
6401 for (j = 0; j < argc; j++) decrRefCount(argv[j]);
6402 zfree(argv);
6403 }
6404 fclose(fp);
6405 freeFakeClient(fakeClient);
6406 return REDIS_OK;
6407
6408readerr:
6409 if (feof(fp)) {
6410 redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
6411 } else {
6412 redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
6413 }
6414 exit(1);
6415fmterr:
6416 redisLog(REDIS_WARNING,"Bad file format reading the append only file");
6417 exit(1);
6418}
6419
9d65a1bb 6420/* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6421static int fwriteBulk(FILE *fp, robj *obj) {
6422 char buf[128];
6423 obj = getDecodedObject(obj);
6424 snprintf(buf,sizeof(buf),"$%ld\r\n",(long)sdslen(obj->ptr));
6425 if (fwrite(buf,strlen(buf),1,fp) == 0) goto err;
e96e4fbf 6426 if (sdslen(obj->ptr) && fwrite(obj->ptr,sdslen(obj->ptr),1,fp) == 0)
6427 goto err;
9d65a1bb 6428 if (fwrite("\r\n",2,1,fp) == 0) goto err;
6429 decrRefCount(obj);
6430 return 1;
6431err:
6432 decrRefCount(obj);
6433 return 0;
6434}
6435
6436/* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6437static int fwriteBulkDouble(FILE *fp, double d) {
6438 char buf[128], dbuf[128];
6439
6440 snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
6441 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
6442 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
6443 if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
6444 return 1;
6445}
6446
6447/* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6448static int fwriteBulkLong(FILE *fp, long l) {
6449 char buf[128], lbuf[128];
6450
6451 snprintf(lbuf,sizeof(lbuf),"%ld\r\n",l);
6452 snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(lbuf)-2);
6453 if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
6454 if (fwrite(lbuf,strlen(lbuf),1,fp) == 0) return 0;
6455 return 1;
6456}
6457
6458/* Write a sequence of commands able to fully rebuild the dataset into
6459 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6460static int rewriteAppendOnlyFile(char *filename) {
6461 dictIterator *di = NULL;
6462 dictEntry *de;
6463 FILE *fp;
6464 char tmpfile[256];
6465 int j;
6466 time_t now = time(NULL);
6467
6468 /* Note that we have to use a different temp name here compared to the
6469 * one used by rewriteAppendOnlyFileBackground() function. */
6470 snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
6471 fp = fopen(tmpfile,"w");
6472 if (!fp) {
6473 redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
6474 return REDIS_ERR;
6475 }
6476 for (j = 0; j < server.dbnum; j++) {
6477 char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
6478 redisDb *db = server.db+j;
6479 dict *d = db->dict;
6480 if (dictSize(d) == 0) continue;
6481 di = dictGetIterator(d);
6482 if (!di) {
6483 fclose(fp);
6484 return REDIS_ERR;
6485 }
6486
6487 /* SELECT the new DB */
6488 if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
85a83172 6489 if (fwriteBulkLong(fp,j) == 0) goto werr;
9d65a1bb 6490
6491 /* Iterate this DB writing every entry */
6492 while((de = dictNext(di)) != NULL) {
6493 robj *key = dictGetEntryKey(de);
6494 robj *o = dictGetEntryVal(de);
6495 time_t expiretime = getExpire(db,key);
6496
6497 /* Save the key and associated value */
9d65a1bb 6498 if (o->type == REDIS_STRING) {
6499 /* Emit a SET command */
6500 char cmd[]="*3\r\n$3\r\nSET\r\n";
6501 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
6502 /* Key and value */
6503 if (fwriteBulk(fp,key) == 0) goto werr;
6504 if (fwriteBulk(fp,o) == 0) goto werr;
6505 } else if (o->type == REDIS_LIST) {
6506 /* Emit the RPUSHes needed to rebuild the list */
6507 list *list = o->ptr;
6508 listNode *ln;
6509
6510 listRewind(list);
6511 while((ln = listYield(list))) {
6512 char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
6513 robj *eleobj = listNodeValue(ln);
6514
6515 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
6516 if (fwriteBulk(fp,key) == 0) goto werr;
6517 if (fwriteBulk(fp,eleobj) == 0) goto werr;
6518 }
6519 } else if (o->type == REDIS_SET) {
6520 /* Emit the SADDs needed to rebuild the set */
6521 dict *set = o->ptr;
6522 dictIterator *di = dictGetIterator(set);
6523 dictEntry *de;
6524
6525 while((de = dictNext(di)) != NULL) {
6526 char cmd[]="*3\r\n$4\r\nSADD\r\n";
6527 robj *eleobj = dictGetEntryKey(de);
6528
6529 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
6530 if (fwriteBulk(fp,key) == 0) goto werr;
6531 if (fwriteBulk(fp,eleobj) == 0) goto werr;
6532 }
6533 dictReleaseIterator(di);
6534 } else if (o->type == REDIS_ZSET) {
6535 /* Emit the ZADDs needed to rebuild the sorted set */
6536 zset *zs = o->ptr;
6537 dictIterator *di = dictGetIterator(zs->dict);
6538 dictEntry *de;
6539
6540 while((de = dictNext(di)) != NULL) {
6541 char cmd[]="*4\r\n$4\r\nZADD\r\n";
6542 robj *eleobj = dictGetEntryKey(de);
6543 double *score = dictGetEntryVal(de);
6544
6545 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
6546 if (fwriteBulk(fp,key) == 0) goto werr;
6547 if (fwriteBulkDouble(fp,*score) == 0) goto werr;
6548 if (fwriteBulk(fp,eleobj) == 0) goto werr;
6549 }
6550 dictReleaseIterator(di);
6551 } else {
dfc5e96c 6552 redisAssert(0 != 0);
9d65a1bb 6553 }
6554 /* Save the expire time */
6555 if (expiretime != -1) {
e96e4fbf 6556 char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
9d65a1bb 6557 /* If this key is already expired skip it */
6558 if (expiretime < now) continue;
6559 if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
6560 if (fwriteBulk(fp,key) == 0) goto werr;
6561 if (fwriteBulkLong(fp,expiretime) == 0) goto werr;
6562 }
6563 }
6564 dictReleaseIterator(di);
6565 }
6566
6567 /* Make sure data will not remain on the OS's output buffers */
6568 fflush(fp);
6569 fsync(fileno(fp));
6570 fclose(fp);
6571
6572 /* Use RENAME to make sure the DB file is changed atomically only
6573 * if the generate DB file is ok. */
6574 if (rename(tmpfile,filename) == -1) {
6575 redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
6576 unlink(tmpfile);
6577 return REDIS_ERR;
6578 }
6579 redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
6580 return REDIS_OK;
6581
6582werr:
6583 fclose(fp);
6584 unlink(tmpfile);
e96e4fbf 6585 redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
9d65a1bb 6586 if (di) dictReleaseIterator(di);
6587 return REDIS_ERR;
6588}
6589
6590/* This is how rewriting of the append only file in background works:
6591 *
6592 * 1) The user calls BGREWRITEAOF
6593 * 2) Redis calls this function, that forks():
6594 * 2a) the child rewrite the append only file in a temp file.
6595 * 2b) the parent accumulates differences in server.bgrewritebuf.
6596 * 3) When the child finished '2a' exists.
6597 * 4) The parent will trap the exit code, if it's OK, will append the
6598 * data accumulated into server.bgrewritebuf into the temp file, and
6599 * finally will rename(2) the temp file in the actual file name.
6600 * The the new file is reopened as the new append only file. Profit!
6601 */
6602static int rewriteAppendOnlyFileBackground(void) {
6603 pid_t childpid;
6604
6605 if (server.bgrewritechildpid != -1) return REDIS_ERR;
6606 if ((childpid = fork()) == 0) {
6607 /* Child */
6608 char tmpfile[256];
6609 close(server.fd);
6610
6611 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6612 if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
6613 exit(0);
6614 } else {
6615 exit(1);
6616 }
6617 } else {
6618 /* Parent */
6619 if (childpid == -1) {
6620 redisLog(REDIS_WARNING,
6621 "Can't rewrite append only file in background: fork: %s",
6622 strerror(errno));
6623 return REDIS_ERR;
6624 }
6625 redisLog(REDIS_NOTICE,
6626 "Background append only file rewriting started by pid %d",childpid);
6627 server.bgrewritechildpid = childpid;
85a83172 6628 /* We set appendseldb to -1 in order to force the next call to the
6629 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6630 * accumulated by the parent into server.bgrewritebuf will start
6631 * with a SELECT statement and it will be safe to merge. */
6632 server.appendseldb = -1;
9d65a1bb 6633 return REDIS_OK;
6634 }
6635 return REDIS_OK; /* unreached */
6636}
6637
6638static void bgrewriteaofCommand(redisClient *c) {
6639 if (server.bgrewritechildpid != -1) {
6640 addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6641 return;
6642 }
6643 if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
49b99ab4 6644 char *status = "+Background append only file rewriting started\r\n";
6645 addReplySds(c,sdsnew(status));
9d65a1bb 6646 } else {
6647 addReply(c,shared.err);
6648 }
6649}
6650
6651static void aofRemoveTempFile(pid_t childpid) {
6652 char tmpfile[256];
6653
6654 snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
6655 unlink(tmpfile);
6656}
6657
75680a3c 6658/* =============================== Virtual Memory =========================== */
6659static void vmInit(void) {
6660 off_t totsize;
6661
6662 server.vm_fp = fopen("/tmp/redisvm","w+b");
6663 if (server.vm_fp == NULL) {
6664 redisLog(REDIS_WARNING,"Impossible to open the swap file. Exiting.");
6665 exit(1);
6666 }
6667 server.vm_fd = fileno(server.vm_fp);
6668 server.vm_next_page = 0;
6669 server.vm_near_pages = 0;
6670 totsize = server.vm_pages*server.vm_page_size;
6671 redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
6672 if (ftruncate(server.vm_fd,totsize) == -1) {
6673 redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
6674 strerror(errno));
6675 exit(1);
6676 } else {
6677 redisLog(REDIS_NOTICE,"Swap file allocated with success");
6678 }
7d30035d 6679 server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
4ef8de8a 6680 redisLog(REDIS_DEBUG,"Allocated %lld bytes page table for %lld pages",
6681 (long long) (server.vm_pages+7)/8, server.vm_pages);
7d30035d 6682 memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
75680a3c 6683 /* Try to remove the swap file, so the OS will really delete it from the
6684 * file system when Redis exists. */
6685 unlink("/tmp/redisvm");
6686}
6687
06224fec 6688/* Mark the page as used */
6689static void vmMarkPageUsed(off_t page) {
6690 off_t byte = page/8;
6691 int bit = page&7;
6692 server.vm_bitmap[byte] |= 1<<bit;
4ef8de8a 6693 printf("Mark used: %lld (byte:%lld bit:%d)\n", (long long)page,
6694 (long long)byte, bit);
06224fec 6695}
6696
6697/* Mark N contiguous pages as used, with 'page' being the first. */
6698static void vmMarkPagesUsed(off_t page, off_t count) {
6699 off_t j;
6700
6701 for (j = 0; j < count; j++)
7d30035d 6702 vmMarkPageUsed(page+j);
06224fec 6703}
6704
6705/* Mark the page as free */
6706static void vmMarkPageFree(off_t page) {
6707 off_t byte = page/8;
6708 int bit = page&7;
6709 server.vm_bitmap[byte] &= ~(1<<bit);
6710}
6711
6712/* Mark N contiguous pages as free, with 'page' being the first. */
6713static void vmMarkPagesFree(off_t page, off_t count) {
6714 off_t j;
6715
6716 for (j = 0; j < count; j++)
7d30035d 6717 vmMarkPageFree(page+j);
06224fec 6718}
6719
6720/* Test if the page is free */
6721static int vmFreePage(off_t page) {
6722 off_t byte = page/8;
6723 int bit = page&7;
7d30035d 6724 return (server.vm_bitmap[byte] & (1<<bit)) == 0;
06224fec 6725}
6726
6727/* Find N contiguous free pages storing the first page of the cluster in *first.
3a66edc7 6728 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
6729 * REDIS_ERR is returned.
06224fec 6730 *
6731 * This function uses a simple algorithm: we try to allocate
6732 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
6733 * again from the start of the swap file searching for free spaces.
6734 *
6735 * If it looks pretty clear that there are no free pages near our offset
6736 * we try to find less populated places doing a forward jump of
6737 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
6738 * without hurry, and then we jump again and so forth...
6739 *
6740 * This function can be improved using a free list to avoid to guess
6741 * too much, since we could collect data about freed pages.
6742 *
6743 * note: I implemented this function just after watching an episode of
6744 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
6745 */
6746static int vmFindContiguousPages(off_t *first, int n) {
6747 off_t base, offset = 0, since_jump = 0, numfree = 0;
6748
6749 if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
6750 server.vm_near_pages = 0;
6751 server.vm_next_page = 0;
6752 }
6753 server.vm_near_pages++; /* Yet another try for pages near to the old ones */
6754 base = server.vm_next_page;
6755
6756 while(offset < server.vm_pages) {
6757 off_t this = base+offset;
6758
7d30035d 6759 printf("THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
06224fec 6760 /* If we overflow, restart from page zero */
6761 if (this >= server.vm_pages) {
6762 this -= server.vm_pages;
6763 if (this == 0) {
6764 /* Just overflowed, what we found on tail is no longer
6765 * interesting, as it's no longer contiguous. */
6766 numfree = 0;
6767 }
6768 }
6769 if (vmFreePage(this)) {
6770 /* This is a free page */
6771 numfree++;
6772 /* Already got N free pages? Return to the caller, with success */
6773 if (numfree == n) {
7d30035d 6774 *first = this-(n-1);
6775 server.vm_next_page = this+1;
3a66edc7 6776 return REDIS_OK;
06224fec 6777 }
6778 } else {
6779 /* The current one is not a free page */
6780 numfree = 0;
6781 }
6782
6783 /* Fast-forward if the current page is not free and we already
6784 * searched enough near this place. */
6785 since_jump++;
6786 if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
6787 offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
6788 since_jump = 0;
6789 /* Note that even if we rewind after the jump, we are don't need
6790 * to make sure numfree is set to zero as we only jump *if* it
6791 * is set to zero. */
6792 } else {
6793 /* Otherwise just check the next page */
6794 offset++;
6795 }
6796 }
3a66edc7 6797 return REDIS_ERR;
6798}
6799
6800/* Swap the 'val' object relative to 'key' into disk. Store all the information
6801 * needed to later retrieve the object into the key object.
6802 * If we can't find enough contiguous empty pages to swap the object on disk
6803 * REDIS_ERR is returned. */
6804static int vmSwapObject(robj *key, robj *val) {
6805 off_t pages = rdbSavedObjectPages(val);
6806 off_t page;
6807
6808 assert(key->storage == REDIS_VM_MEMORY);
4ef8de8a 6809 assert(key->refcount == 1);
3a66edc7 6810 if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return REDIS_ERR;
6811 if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
6812 redisLog(REDIS_WARNING,
6813 "Critical VM problem in vmSwapObject(): can't seek: %s",
6814 strerror(errno));
6815 return REDIS_ERR;
6816 }
6817 rdbSaveObject(server.vm_fp,val);
6818 key->vm.page = page;
6819 key->vm.usedpages = pages;
6820 key->storage = REDIS_VM_SWAPPED;
d894161b 6821 key->vtype = val->type;
3a66edc7 6822 decrRefCount(val); /* Deallocate the object from memory. */
6823 vmMarkPagesUsed(page,pages);
7d30035d 6824 redisLog(REDIS_DEBUG,"VM: object %s swapped out at %lld (%lld pages)",
6825 (unsigned char*) key->ptr,
6826 (unsigned long long) page, (unsigned long long) pages);
3a66edc7 6827 return REDIS_OK;
6828}
6829
6830/* Load the value object relative to the 'key' object from swap to memory.
6831 * The newly allocated object is returned. */
6832static robj *vmLoadObject(robj *key) {
6833 robj *val;
6834
6835 assert(key->storage == REDIS_VM_SWAPPED);
6836 if (fseeko(server.vm_fp,key->vm.page*server.vm_page_size,SEEK_SET) == -1) {
6837 redisLog(REDIS_WARNING,
6838 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
6839 strerror(errno));
6840 exit(1);
6841 }
d894161b 6842 val = rdbLoadObject(key->vtype,server.vm_fp);
3a66edc7 6843 if (val == NULL) {
6844 redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno));
6845 exit(1);
6846 }
6847 key->storage = REDIS_VM_MEMORY;
6848 key->vm.atime = server.unixtime;
6849 vmMarkPagesFree(key->vm.page,key->vm.usedpages);
7d30035d 6850 redisLog(REDIS_DEBUG, "VM: object %s loaded from disk",
6851 (unsigned char*) key->ptr);
3a66edc7 6852 return val;
06224fec 6853}
6854
4ef8de8a 6855/* How a good candidate is this object for swapping?
6856 * The better candidate it is, the greater the returned value.
6857 *
6858 * Currently we try to perform a fast estimation of the object size in
6859 * memory, and combine it with aging informations.
6860 *
6861 * Basically swappability = idle-time * log(estimated size)
6862 *
6863 * Bigger objects are preferred over smaller objects, but not
6864 * proportionally, this is why we use the logarithm. This algorithm is
6865 * just a first try and will probably be tuned later. */
6866static double computeObjectSwappability(robj *o) {
6867 time_t age = server.unixtime - o->vm.atime;
6868 long asize = 0;
6869 list *l;
6870 dict *d;
6871 struct dictEntry *de;
6872 int z;
6873
6874 if (age <= 0) return 0;
6875 switch(o->type) {
6876 case REDIS_STRING:
6877 if (o->encoding != REDIS_ENCODING_RAW) {
6878 asize = sizeof(*o);
6879 } else {
6880 asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
6881 }
6882 break;
6883 case REDIS_LIST:
6884 l = o->ptr;
6885 listNode *ln = listFirst(l);
6886
6887 asize = sizeof(list);
6888 if (ln) {
6889 robj *ele = ln->value;
6890 long elesize;
6891
6892 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
6893 (sizeof(*o)+sdslen(ele->ptr)) :
6894 sizeof(*o);
6895 asize += (sizeof(listNode)+elesize)*listLength(l);
6896 }
6897 break;
6898 case REDIS_SET:
6899 case REDIS_ZSET:
6900 z = (o->type == REDIS_ZSET);
6901 d = z ? ((zset*)o->ptr)->dict : o->ptr;
6902
6903 asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
6904 if (z) asize += sizeof(zset)-sizeof(dict);
6905 if (dictSize(d)) {
6906 long elesize;
6907 robj *ele;
6908
6909 de = dictGetRandomKey(d);
6910 ele = dictGetEntryKey(de);
6911 elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
6912 (sizeof(*o)+sdslen(ele->ptr)) :
6913 sizeof(*o);
6914 asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
6915 if (z) asize += sizeof(zskiplistNode)*dictSize(d);
6916 }
6917 break;
6918 }
6919 return (double)asize*log(1+asize);
6920}
6921
6922/* Try to swap an object that's a good candidate for swapping.
6923 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
6924 * to swap any object at all. */
6925static int vmSwapOneObject(void) {
6926 int j, i;
6927 struct dictEntry *best = NULL;
6928 double best_swappability = 0;
6929 robj *key, *val;
6930
6931 for (j = 0; j < server.dbnum; j++) {
6932 redisDb *db = server.db+j;
6933
6934 if (dictSize(db->dict) == 0) continue;
6935 for (i = 0; i < 5; i++) {
6936 dictEntry *de;
6937 double swappability;
6938
6939 de = dictGetRandomKey(db->dict);
6940 key = dictGetEntryKey(de);
6941 val = dictGetEntryVal(de);
6942 if (key->storage != REDIS_VM_MEMORY) continue;
6943 swappability = computeObjectSwappability(val);
6944 if (!best || swappability > best_swappability) {
6945 best = de;
6946 best_swappability = swappability;
6947 }
6948 }
6949 }
6950 if (best == NULL) return REDIS_ERR;
6951 key = dictGetEntryKey(best);
6952 val = dictGetEntryVal(best);
6953
6954 redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f\n",
6955 key->ptr, best_swappability);
6956
6957 /* Unshare the key if needed */
6958 if (key->refcount > 1) {
6959 robj *newkey = dupStringObject(key);
6960 decrRefCount(key);
6961 key = dictGetEntryKey(best) = newkey;
6962 }
6963 /* Swap it */
6964 if (vmSwapObject(key,val) == REDIS_OK) {
6965 dictGetEntryVal(best) = NULL;
6966 return REDIS_OK;
6967 } else {
6968 return REDIS_ERR;
6969 }
6970}
6971
7f957c92 6972/* ================================= Debugging ============================== */
6973
6974static void debugCommand(redisClient *c) {
6975 if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
6976 *((char*)-1) = 'x';
210e29f7 6977 } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
6978 if (rdbSave(server.dbfilename) != REDIS_OK) {
6979 addReply(c,shared.err);
6980 return;
6981 }
6982 emptyDb();
6983 if (rdbLoad(server.dbfilename) != REDIS_OK) {
6984 addReply(c,shared.err);
6985 return;
6986 }
6987 redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
6988 addReply(c,shared.ok);
71c2b467 6989 } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
6990 emptyDb();
6991 if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
6992 addReply(c,shared.err);
6993 return;
6994 }
6995 redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
6996 addReply(c,shared.ok);
333298da 6997 } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
6998 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
6999 robj *key, *val;
7000
7001 if (!de) {
7002 addReply(c,shared.nokeyerr);
7003 return;
7004 }
7005 key = dictGetEntryKey(de);
7006 val = dictGetEntryVal(de);
7007 addReplySds(c,sdscatprintf(sdsempty(),
06233c45 7008 "+Key at:%p refcount:%d, value at:%p refcount:%d encoding:%d serializedlength:%lld\r\n",
682ac724 7009 (void*)key, key->refcount, (void*)val, val->refcount,
06233c45 7010 val->encoding, rdbSavedObjectLen(val)));
7d30035d 7011 } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
7012 dictEntry *de = dictFind(c->db->dict,c->argv[2]);
7013 robj *key, *val;
7014
7015 if (!server.vm_enabled) {
7016 addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7017 return;
7018 }
7019 if (!de) {
7020 addReply(c,shared.nokeyerr);
7021 return;
7022 }
7023 key = dictGetEntryKey(de);
7024 val = dictGetEntryVal(de);
4ef8de8a 7025 /* If the key is shared we want to create a copy */
7026 if (key->refcount > 1) {
7027 robj *newkey = dupStringObject(key);
7028 decrRefCount(key);
7029 key = dictGetEntryKey(de) = newkey;
7030 }
7031 /* Swap it */
7d30035d 7032 if (key->storage != REDIS_VM_MEMORY) {
7033 addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
7034 } else if (vmSwapObject(key,val) == REDIS_OK) {
7035 dictGetEntryVal(de) = NULL;
7036 addReply(c,shared.ok);
7037 } else {
7038 addReply(c,shared.err);
7039 }
7f957c92 7040 } else {
333298da 7041 addReplySds(c,sdsnew(
7d30035d 7042 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7f957c92 7043 }
7044}
56906eef 7045
dfc5e96c 7046static void _redisAssert(char *estr) {
7047 redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
7048 redisLog(REDIS_WARNING,"==> %s\n",estr);
7049#ifdef HAVE_BACKTRACE
7050 redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
7051 *((char*)-1) = 'x';
7052#endif
7053}
7054
bcfc686d 7055/* =================================== Main! ================================ */
56906eef 7056
bcfc686d 7057#ifdef __linux__
7058int linuxOvercommitMemoryValue(void) {
7059 FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
7060 char buf[64];
56906eef 7061
bcfc686d 7062 if (!fp) return -1;
7063 if (fgets(buf,64,fp) == NULL) {
7064 fclose(fp);
7065 return -1;
7066 }
7067 fclose(fp);
56906eef 7068
bcfc686d 7069 return atoi(buf);
7070}
7071
7072void linuxOvercommitMemoryWarning(void) {
7073 if (linuxOvercommitMemoryValue() == 0) {
7074 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.");
7075 }
7076}
7077#endif /* __linux__ */
7078
7079static void daemonize(void) {
7080 int fd;
7081 FILE *fp;
7082
7083 if (fork() != 0) exit(0); /* parent exits */
71c54b21 7084 printf("New pid: %d\n", getpid());
bcfc686d 7085 setsid(); /* create a new session */
7086
7087 /* Every output goes to /dev/null. If Redis is daemonized but
7088 * the 'logfile' is set to 'stdout' in the configuration file
7089 * it will not log at all. */
7090 if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
7091 dup2(fd, STDIN_FILENO);
7092 dup2(fd, STDOUT_FILENO);
7093 dup2(fd, STDERR_FILENO);
7094 if (fd > STDERR_FILENO) close(fd);
7095 }
7096 /* Try to write the pid file */
7097 fp = fopen(server.pidfile,"w");
7098 if (fp) {
7099 fprintf(fp,"%d\n",getpid());
7100 fclose(fp);
56906eef 7101 }
56906eef 7102}
7103
bcfc686d 7104int main(int argc, char **argv) {
7105 initServerConfig();
7106 if (argc == 2) {
7107 resetServerSaveParams();
7108 loadServerConfig(argv[1]);
7109 } else if (argc > 2) {
7110 fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
7111 exit(1);
7112 } else {
7113 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'");
7114 }
bcfc686d 7115 if (server.daemonize) daemonize();
71c54b21 7116 initServer();
bcfc686d 7117 redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
7118#ifdef __linux__
7119 linuxOvercommitMemoryWarning();
7120#endif
7121 if (server.appendonly) {
7122 if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
7123 redisLog(REDIS_NOTICE,"DB loaded from append only file");
7124 } else {
7125 if (rdbLoad(server.dbfilename) == REDIS_OK)
7126 redisLog(REDIS_NOTICE,"DB loaded from disk");
7127 }
7128 if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
266373b2 7129 acceptHandler, NULL) == AE_ERR) oom("creating file event");
bcfc686d 7130 redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
7131 aeMain(server.el);
7132 aeDeleteEventLoop(server.el);
7133 return 0;
7134}
7135
7136/* ============================= Backtrace support ========================= */
7137
7138#ifdef HAVE_BACKTRACE
7139static char *findFuncName(void *pointer, unsigned long *offset);
7140
56906eef 7141static void *getMcontextEip(ucontext_t *uc) {
7142#if defined(__FreeBSD__)
7143 return (void*) uc->uc_mcontext.mc_eip;
7144#elif defined(__dietlibc__)
7145 return (void*) uc->uc_mcontext.eip;
06db1f50 7146#elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
da0a1620 7147 #if __x86_64__
7148 return (void*) uc->uc_mcontext->__ss.__rip;
7149 #else
56906eef 7150 return (void*) uc->uc_mcontext->__ss.__eip;
da0a1620 7151 #endif
06db1f50 7152#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
cb7e07cc 7153 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
06db1f50 7154 return (void*) uc->uc_mcontext->__ss.__rip;
cbc59b38 7155 #else
7156 return (void*) uc->uc_mcontext->__ss.__eip;
7157 #endif
c04c9ac9 7158#elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
7159 return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
b91cf5ef 7160#elif defined(__ia64__) /* Linux IA64 */
7161 return (void*) uc->uc_mcontext.sc_ip;
7162#else
7163 return NULL;
56906eef 7164#endif
7165}
7166
7167static void segvHandler(int sig, siginfo_t *info, void *secret) {
7168 void *trace[100];
7169 char **messages = NULL;
7170 int i, trace_size = 0;
7171 unsigned long offset=0;
56906eef 7172 ucontext_t *uc = (ucontext_t*) secret;
1c85b79f 7173 sds infostring;
56906eef 7174 REDIS_NOTUSED(info);
7175
7176 redisLog(REDIS_WARNING,
7177 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
1c85b79f 7178 infostring = genRedisInfoString();
7179 redisLog(REDIS_WARNING, "%s",infostring);
7180 /* It's not safe to sdsfree() the returned string under memory
7181 * corruption conditions. Let it leak as we are going to abort */
56906eef 7182
7183 trace_size = backtrace(trace, 100);
de96dbfe 7184 /* overwrite sigaction with caller's address */
b91cf5ef 7185 if (getMcontextEip(uc) != NULL) {
7186 trace[1] = getMcontextEip(uc);
7187 }
56906eef 7188 messages = backtrace_symbols(trace, trace_size);
fe3bbfbe 7189
d76412d1 7190 for (i=1; i<trace_size; ++i) {
56906eef 7191 char *fn = findFuncName(trace[i], &offset), *p;
7192
7193 p = strchr(messages[i],'+');
7194 if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
7195 redisLog(REDIS_WARNING,"%s", messages[i]);
7196 } else {
7197 redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
7198 }
7199 }
b177fd30 7200 /* free(messages); Don't call free() with possibly corrupted memory. */
56906eef 7201 exit(0);
fe3bbfbe 7202}
56906eef 7203
7204static void setupSigSegvAction(void) {
7205 struct sigaction act;
7206
7207 sigemptyset (&act.sa_mask);
7208 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
7209 * is used. Otherwise, sa_handler is used */
7210 act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
7211 act.sa_sigaction = segvHandler;
7212 sigaction (SIGSEGV, &act, NULL);
7213 sigaction (SIGBUS, &act, NULL);
12fea928 7214 sigaction (SIGFPE, &act, NULL);
7215 sigaction (SIGILL, &act, NULL);
7216 sigaction (SIGBUS, &act, NULL);
e65fdc78 7217 return;
56906eef 7218}
e65fdc78 7219
bcfc686d 7220#include "staticsymbols.h"
7221/* This function try to convert a pointer into a function name. It's used in
7222 * oreder to provide a backtrace under segmentation fault that's able to
7223 * display functions declared as static (otherwise the backtrace is useless). */
7224static char *findFuncName(void *pointer, unsigned long *offset){
7225 int i, ret = -1;
7226 unsigned long off, minoff = 0;
ed9b544e 7227
bcfc686d 7228 /* Try to match against the Symbol with the smallest offset */
7229 for (i=0; symsTable[i].pointer; i++) {
7230 unsigned long lp = (unsigned long) pointer;
0bc03378 7231
bcfc686d 7232 if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
7233 off=lp-symsTable[i].pointer;
7234 if (ret < 0 || off < minoff) {
7235 minoff=off;
7236 ret=i;
7237 }
7238 }
0bc03378 7239 }
bcfc686d 7240 if (ret == -1) return NULL;
7241 *offset = minoff;
7242 return symsTable[ret].name;
0bc03378 7243}
bcfc686d 7244#else /* HAVE_BACKTRACE */
7245static void setupSigSegvAction(void) {
0bc03378 7246}
bcfc686d 7247#endif /* HAVE_BACKTRACE */
0bc03378 7248
ed9b544e 7249
ed9b544e 7250
bcfc686d 7251/* The End */
7252
7253
ed9b544e 7254