redis.c 288.5 KB
Newer Older
A
antirez 已提交
1
/*
2
 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
A
antirez 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of Redis nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

30
#define REDIS_VERSION "1.3.3"
31 32

#include "fmacros.h"
A
antirez 已提交
33
#include "config.h"
A
antirez 已提交
34 35 36 37 38 39

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
H
hrothgar 已提交
40
#define __USE_POSIX199309
A
antirez 已提交
41
#include <signal.h>
A
antirez 已提交
42 43

#ifdef HAVE_BACKTRACE
H
hrothgar 已提交
44 45
#include <execinfo.h>
#include <ucontext.h>
A
antirez 已提交
46 47
#endif /* HAVE_BACKTRACE */

A
antirez 已提交
48 49 50 51 52 53 54 55 56 57 58
#include <sys/wait.h>
#include <errno.h>
#include <assert.h>
#include <ctype.h>
#include <stdarg.h>
#include <inttypes.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>
59
#include <sys/uio.h>
60
#include <limits.h>
61
#include <math.h>
62
#include <pthread.h>
A
antirez 已提交
63 64

#if defined(__sun)
A
antirez 已提交
65 66
#include "solarisfixes.h"
#endif
A
antirez 已提交
67

H
hrothgar 已提交
68
#include "redis.h"
A
antirez 已提交
69 70 71 72 73 74
#include "ae.h"     /* Event driven programming library */
#include "sds.h"    /* Dynamic safe strings */
#include "anet.h"   /* Networking the easy way */
#include "dict.h"   /* Hash tables */
#include "adlist.h" /* Linked lists */
#include "zmalloc.h" /* total memory usage aware version of malloc/free */
75 76
#include "lzf.h"    /* LZF compression library */
#include "pqsort.h" /* Partial qsort for SORT+LIMIT */
A
antirez 已提交
77 78 79 80 81 82 83 84

/* Error codes */
#define REDIS_OK                0
#define REDIS_ERR               -1

/* Static server configuration */
#define REDIS_SERVERPORT        6379    /* TCP port */
#define REDIS_MAXIDLETIME       (60*5)  /* default client timeout */
85
#define REDIS_IOBUF_LEN         1024
A
antirez 已提交
86
#define REDIS_LOADBUF_LEN       1024
87
#define REDIS_STATIC_ARGS       4
A
antirez 已提交
88 89 90 91
#define REDIS_DEFAULT_DBNUM     16
#define REDIS_CONFIGLINE_MAX    1024
#define REDIS_OBJFREELIST_MAX   1000000 /* Max number of objects to cache */
#define REDIS_MAX_SYNC_TIME     60      /* Slave can't take more to sync */
92
#define REDIS_EXPIRELOOKUPS_PER_CRON    100 /* try to expire 100 keys/second */
93
#define REDIS_MAX_WRITE_PER_EVENT (1024*64)
94 95 96 97 98 99
#define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */

/* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
#define REDIS_WRITEV_THRESHOLD      3
/* Max number of iovecs used for each writev call */
#define REDIS_WRITEV_IOVEC_COUNT    256
A
antirez 已提交
100 101 102 103 104

/* Hash table parameters */
#define REDIS_HT_MINFILL        10      /* Minimal hash table fill 10% */

/* Command flags */
A
antirez 已提交
105 106 107 108 109 110 111
#define REDIS_CMD_BULK          1       /* Bulk write command */
#define REDIS_CMD_INLINE        2       /* Inline command */
/* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
   this flags will return an error when the 'maxmemory' option is set in the
   config file and the server is using more than maxmemory bytes of memory.
   In short this commands are denied on low memory conditions. */
#define REDIS_CMD_DENYOOM       4
A
antirez 已提交
112 113 114 115 116

/* Object types */
#define REDIS_STRING 0
#define REDIS_LIST 1
#define REDIS_SET 2
117 118
#define REDIS_ZSET 3
#define REDIS_HASH 4
119

120 121 122 123
/* Objects encoding */
#define REDIS_ENCODING_RAW 0    /* Raw representation */
#define REDIS_ENCODING_INT 1    /* Encoded as integer */

124
/* Object types only used for dumping to disk */
A
antirez 已提交
125
#define REDIS_EXPIRETIME 253
A
antirez 已提交
126 127 128
#define REDIS_SELECTDB 254
#define REDIS_EOF 255

129 130 131 132 133 134 135
/* Defines related to the dump file format. To store 32 bits lengths for short
 * keys requires a lot of space, so we check the most significant 2 bits of
 * the first byte to interpreter the length:
 *
 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
 * 01|000000 00000000 =>  01, the len is 14 byes, 6 bits + 8 bits of next byte
 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
A
antirez 已提交
136 137 138
 * 11|000000 this means: specially encoded object will follow. The six bits
 *           number specify the kind of object that follows.
 *           See the REDIS_RDB_ENC_* defines.
139
 *
140 141
 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
 * values, will fit inside. */
142 143 144
#define REDIS_RDB_6BITLEN 0
#define REDIS_RDB_14BITLEN 1
#define REDIS_RDB_32BITLEN 2
145
#define REDIS_RDB_ENCVAL 3
146 147
#define REDIS_RDB_LENERR UINT_MAX

A
antirez 已提交
148 149 150 151 152 153
/* When a length of a string object stored on disk has the first two bits
 * set, the remaining two bits specify a special encoding for the object
 * accordingly to the following defines: */
#define REDIS_RDB_ENC_INT8 0        /* 8 bit signed integer */
#define REDIS_RDB_ENC_INT16 1       /* 16 bit signed integer */
#define REDIS_RDB_ENC_INT32 2       /* 32 bit signed integer */
A
antirez 已提交
154
#define REDIS_RDB_ENC_LZF 3         /* string compressed with FASTLZ */
A
antirez 已提交
155

156 157 158 159 160 161
/* Virtual memory object->where field. */
#define REDIS_VM_MEMORY 0       /* The object is on memory */
#define REDIS_VM_SWAPPED 1      /* The object is on disk */
#define REDIS_VM_SWAPPING 2     /* Redis is swapping this object on disk */
#define REDIS_VM_LOADING 3      /* Redis is loading this object from disk */

A
antirez 已提交
162 163 164 165
/* Virtual memory static configuration stuff.
 * Check vmFindContiguousPages() to know more about this magic numbers. */
#define REDIS_VM_MAX_NEAR_PAGES 65536
#define REDIS_VM_MAX_RANDOM_JUMP 4096
166
#define REDIS_VM_MAX_THREADS 32
167
#define REDIS_THREAD_STACK_SIZE (1024*1024*4)
168 169 170 171
/* The following is the *percentage* of completed I/O jobs to process when the
 * handelr is called. While Virtual Memory I/O operations are performed by
 * threads, this operations must be processed by the main thread when completed
 * in order to take effect. */
172
#define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
A
antirez 已提交
173

A
antirez 已提交
174
/* Client flags */
A
antirez 已提交
175 176 177 178 179 180
#define REDIS_SLAVE 1       /* This client is a slave server */
#define REDIS_MASTER 2      /* This client is a master server */
#define REDIS_MONITOR 4     /* This client is a slave monitor, see MONITOR */
#define REDIS_MULTI 8       /* This client is in a MULTI context */
#define REDIS_BLOCKED 16    /* The client is waiting in a blocking operation */
#define REDIS_IO_WAIT 32    /* The client is waiting for Virtual Memory I/O */
A
antirez 已提交
181

182
/* Slave replication state - slave side */
A
antirez 已提交
183 184 185 186
#define REDIS_REPL_NONE 0   /* No active replication */
#define REDIS_REPL_CONNECT 1    /* Must connect to master */
#define REDIS_REPL_CONNECTED 2  /* Connected to master */

187 188 189 190 191 192 193 194 195
/* Slave replication state - from the point of view of master
 * Note that in SEND_BULK and ONLINE state the slave receives new updates
 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
 * to start the next background saving in order to send updates to it. */
#define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
#define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
#define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
#define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */

A
antirez 已提交
196 197 198 199 200 201
/* List related stuff */
#define REDIS_HEAD 0
#define REDIS_TAIL 1

/* Sort operations */
#define REDIS_SORT_GET 0
A
antirez 已提交
202 203
#define REDIS_SORT_ASC 1
#define REDIS_SORT_DESC 2
A
antirez 已提交
204 205 206 207
#define REDIS_SORTKEY_MAX 1024

/* Log levels */
#define REDIS_DEBUG 0
208 209 210
#define REDIS_VERBOSE 1
#define REDIS_NOTICE 2
#define REDIS_WARNING 3
A
antirez 已提交
211 212 213 214

/* Anti-warning macro... */
#define REDIS_NOTUSED(V) ((void) V)

215 216
#define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
#define ZSKIPLIST_P 0.25      /* Skiplist P = 1/4 */
A
antirez 已提交
217

218 219 220 221 222
/* Append only defines */
#define APPENDFSYNC_NO 0
#define APPENDFSYNC_ALWAYS 1
#define APPENDFSYNC_EVERYSEC 2

223
/* We can print the stacktrace, so our assert is defined this way: */
224
#define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
225
static void _redisAssert(char *estr, char *file, int line);
226

A
antirez 已提交
227 228 229
/*================================= Data types ============================== */

/* A redis object, that is a type able to hold a string / list / set */
230 231 232

/* The VM object structure */
struct redisObjectVM {
A
antirez 已提交
233 234 235
    off_t page;         /* the page at witch the object is stored on disk */
    off_t usedpages;    /* number of pages used on disk */
    time_t atime;       /* Last access time */
236 237 238
} vm;

/* The actual Redis Object */
A
antirez 已提交
239 240
typedef struct redisObject {
    void *ptr;
241 242
    unsigned char type;
    unsigned char encoding;
243 244 245 246
    unsigned char storage;  /* If this object is a key, where is the value?
                             * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
    unsigned char vtype; /* If this object is a key, and value is swapped out,
                          * this is the type of the swapped out object. */
A
antirez 已提交
247
    int refcount;
248 249 250 251 252
    /* VM fields, this are only allocated if VM is active, otherwise the
     * object allocation function will just allocate
     * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
     * Redis without VM active will not have any overhead. */
    struct redisObjectVM vm;
A
antirez 已提交
253 254
} robj;

255 256 257 258 259 260 261 262 263
/* Macro used to initalize a Redis object allocated on the stack.
 * Note that this macro is taken near the structure definition to make sure
 * we'll update it when the structure is changed, to avoid bugs like
 * bug #85 introduced exactly in this way. */
#define initStaticStringObject(_var,_ptr) do { \
    _var.refcount = 1; \
    _var.type = REDIS_STRING; \
    _var.encoding = REDIS_ENCODING_RAW; \
    _var.ptr = _ptr; \
A
antirez 已提交
264
    if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
265 266
} while(0);

A
antirez 已提交
267
typedef struct redisDb {
A
antirez 已提交
268 269 270
    dict *dict;                 /* The keyspace for this DB */
    dict *expires;              /* Timeout of keys with a timeout set */
    dict *blockingkeys;         /* Keys with clients waiting for data (BLPOP) */
A
antirez 已提交
271
    dict *io_keys;              /* Keys with clients waiting for VM I/O */
A
antirez 已提交
272 273 274
    int id;
} redisDb;

A
antirez 已提交
275 276 277 278 279 280 281 282 283 284 285 286
/* Client MULTI/EXEC state */
typedef struct multiCmd {
    robj **argv;
    int argc;
    struct redisCommand *cmd;
} multiCmd;

typedef struct multiState {
    multiCmd *commands;     /* Array of MULTI commands */
    int count;              /* Total number of MULTI commands */
} multiState;

A
antirez 已提交
287 288 289 290
/* With multiplexing we need to take per-clinet state.
 * Clients are taken in a liked list. */
typedef struct redisClient {
    int fd;
A
antirez 已提交
291
    redisDb *db;
A
antirez 已提交
292 293
    int dictid;
    sds querybuf;
294 295
    robj **argv, **mbargv;
    int argc, mbargc;
296
    int bulklen;            /* bulk read len. -1 if not in bulk read mode */
297
    int multibulk;          /* multi bulk command format active */
A
antirez 已提交
298 299 300
    list *reply;
    int sentlen;
    time_t lastinteraction; /* time of the last interaction, used for timeout */
A
antirez 已提交
301
    int flags;              /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
302 303 304 305
    int slaveseldb;         /* slave selected db, if this client is a slave */
    int authenticated;      /* when requirepass is non-NULL */
    int replstate;          /* replication state if this is a slave */
    int repldbfd;           /* replication DB file descriptor */
A
antirez 已提交
306
    long repldboff;         /* replication DB file offset */
307
    off_t repldbsize;       /* replication DB file size */
A
antirez 已提交
308
    multiState mstate;      /* MULTI/EXEC state */
A
antirez 已提交
309
    robj **blockingkeys;    /* The key we are waiting to terminate a blocking
A
antirez 已提交
310
                             * operation such as BLPOP. Otherwise NULL. */
311
    int blockingkeysnum;    /* Number of blocking keys */
A
antirez 已提交
312 313
    time_t blockingto;      /* Blocking operation timeout. If UNIX current time
                             * is >= blockingto then the operation timed out. */
314 315
    list *io_keys;          /* Keys this client is waiting to be loaded from the
                             * swap file in order to continue. */
A
antirez 已提交
316 317 318 319 320 321 322 323 324 325 326
} redisClient;

struct saveparam {
    time_t seconds;
    int changes;
};

/* Global server state structure */
struct redisServer {
    int port;
    int fd;
A
antirez 已提交
327
    redisDb *db;
A
antirez 已提交
328
    dict *sharingpool;          /* Poll used for object sharing */
329
    unsigned int sharingpoolsize;
A
antirez 已提交
330 331
    long long dirty;            /* changes to DB from the last save */
    list *clients;
A
antirez 已提交
332
    list *slaves, *monitors;
A
antirez 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    char neterr[ANET_ERR_LEN];
    aeEventLoop *el;
    int cronloops;              /* number of times the cron function run */
    list *objfreelist;          /* A list of freed objects to avoid malloc() */
    time_t lastsave;            /* Unix time of last save succeeede */
    /* Fields used only for stats */
    time_t stat_starttime;         /* server start time */
    long long stat_numcommands;    /* number of processed commands */
    long long stat_numconnections; /* number of connections received */
    /* Configuration */
    int verbosity;
    int glueoutputbuf;
    int maxidletime;
    int dbnum;
    int daemonize;
348
    int appendonly;
349 350
    int appendfsync;
    time_t lastfsync;
351 352
    int appendfd;
    int appendseldb;
353
    char *pidfile;
354
    pid_t bgsavechildpid;
355 356
    pid_t bgrewritechildpid;
    sds bgrewritebuf; /* buffer taken by parent during oppend only rewrite */
A
antirez 已提交
357 358 359 360 361
    struct saveparam *saveparams;
    int saveparamslen;
    char *logfile;
    char *bindaddr;
    char *dbfilename;
362
    char *appendfilename;
B
Brian Hammond 已提交
363
    char *requirepass;
364
    int shareobjects;
365
    int rdbcompression;
A
antirez 已提交
366 367
    /* Replication related */
    int isslave;
368
    char *masterauth;
A
antirez 已提交
369 370
    char *masterhost;
    int masterport;
371
    redisClient *master;    /* client that is master for this slave */
A
antirez 已提交
372
    int replstate;
373
    unsigned int maxclients;
A
antirez 已提交
374
    unsigned long long maxmemory;
A
antirez 已提交
375 376
    unsigned int blpop_blocked_clients;
    unsigned int vm_blocked_clients;
A
antirez 已提交
377 378 379 380 381
    /* Sort parameters - qsort_r() is only available under BSD so we
     * have to take this state global, in order to pass it to sortCompare() */
    int sort_desc;
    int sort_alpha;
    int sort_bypattern;
382 383
    /* Virtual memory configuration */
    int vm_enabled;
384
    char *vm_swap_file;
385 386
    off_t vm_page_size;
    off_t vm_pages;
A
antirez 已提交
387
    unsigned long long vm_max_memory;
388 389 390 391 392
    /* Virtual memory state */
    FILE *vm_fp;
    int vm_fd;
    off_t vm_next_page; /* Next probably empty page */
    off_t vm_near_pages; /* Number of pages allocated sequentially */
A
antirez 已提交
393
    unsigned char *vm_bitmap; /* Bitmap of free/used pages */
A
antirez 已提交
394
    time_t unixtime;    /* Unix time sampled every second. */
395 396
    /* Virtual memory I/O threads stuff */
    /* An I/O thread process an element taken from the io_jobs queue and
397 398 399 400 401
     * put the result of the operation in the io_done list. While the
     * job is being processed, it's put on io_processing queue. */
    list *io_newjobs; /* List of VM I/O jobs yet to be processed */
    list *io_processing; /* List of VM I/O jobs being processed */
    list *io_processed; /* List of VM I/O jobs already processed */
A
antirez 已提交
402
    list *io_ready_clients; /* Clients ready to be unblocked. All keys loaded */
403
    pthread_mutex_t io_mutex; /* lock to access io_jobs/io_done/io_thread_job */
404 405
    pthread_mutex_t obj_freelist_mutex; /* safe redis objects creation/free */
    pthread_mutex_t io_swapfile_mutex; /* So we can lseek + write */
406
    pthread_attr_t io_threads_attr; /* attributes for threads creation */
407 408
    int io_active_threads; /* Number of running I/O threads */
    int vm_max_threads; /* Max number of I/O threads running at the same time */
409 410 411 412 413 414
    /* Our main thread is blocked on the event loop, locking for sockets ready
     * to be read or written, so when a threaded I/O operation is ready to be
     * processed by the main thread, the I/O thread will use a unix pipe to
     * awake the main thread. The followings are the two pipe FDs. */
    int io_ready_pipe_read;
    int io_ready_pipe_write;
A
antirez 已提交
415 416 417 418 419
    /* Virtual memory stats */
    unsigned long long vm_stats_used_pages;
    unsigned long long vm_stats_swapped_objects;
    unsigned long long vm_stats_swapouts;
    unsigned long long vm_stats_swapins;
420
    FILE *devnull;
A
antirez 已提交
421 422 423 424 425 426 427 428
};

typedef void redisCommandProc(redisClient *c);
struct redisCommand {
    char *name;
    redisCommandProc *proc;
    int arity;
    int flags;
429 430 431 432
    /* What keys should be loaded in background when calling this command? */
    int vm_firstkey; /* The first argument that's a key (0 = no keys) */
    int vm_lastkey;  /* THe last argument that's a key */
    int vm_keystep;  /* The step between first and last key */
A
antirez 已提交
433 434
};

435 436
struct redisFunctionSym {
    char *name;
437
    unsigned long pointer;
438 439
};

A
antirez 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452
typedef struct _redisSortObject {
    robj *obj;
    union {
        double score;
        robj *cmpobj;
    } u;
} redisSortObject;

typedef struct _redisSortOperation {
    int type;
    robj *pattern;
} redisSortOperation;

453 454 455 456
/* ZSETs use a specialized version of Skiplists */

typedef struct zskiplistNode {
    struct zskiplistNode **forward;
457
    struct zskiplistNode *backward;
458 459 460 461 462
    double score;
    robj *obj;
} zskiplistNode;

typedef struct zskiplist {
463
    struct zskiplistNode *header, *tail;
464
    unsigned long length;
465 466 467
    int level;
} zskiplist;

468 469
typedef struct zset {
    dict *dict;
470
    zskiplist *zsl;
471 472
} zset;

473 474
/* Our shared "common" objects */

A
antirez 已提交
475
struct sharedObjectsStruct {
476
    robj *crlf, *ok, *err, *emptybulk, *czero, *cone, *pong, *space,
A
antirez 已提交
477
    *colon, *nullbulk, *nullmultibulk, *queued,
478 479
    *emptymultibulk, *wrongtypeerr, *nokeyerr, *syntaxerr, *sameobjecterr,
    *outofrangeerr, *plus,
A
antirez 已提交
480 481 482 483
    *select0, *select1, *select2, *select3, *select4,
    *select5, *select6, *select7, *select8, *select9;
} shared;

484 485 486 487 488 489
/* Global vars that are actally used as constants. The following double
 * values are used for double on-disk serialization, and are initialized
 * at runtime to avoid strange compiler optimizations. */

static double R_Zero, R_PosInf, R_NegInf, R_Nan;

490
/* VM threaded I/O request message */
491 492 493
#define REDIS_IOJOB_LOAD 0          /* Load from disk to memory */
#define REDIS_IOJOB_PREPARE_SWAP 1  /* Compute needed pages */
#define REDIS_IOJOB_DO_SWAP 2       /* Swap from memory to disk */
A
antirez 已提交
494
typedef struct iojob {
495
    int type;   /* Request type, REDIS_IOJOB_* */
496
    redisDb *db;/* Redis database */
497
    robj *key;  /* This I/O request is about swapping this key */
498
    robj *val;  /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
499 500
                 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
    off_t page; /* Swap page where to read/write the object */
501
    off_t pages; /* Swap pages needed to safe object. PREPARE_SWAP return val */
502 503 504
    int canceled; /* True if this command was canceled by blocking side of VM */
    pthread_t thread; /* ID of the thread processing this entry */
} iojob;
505

A
antirez 已提交
506 507 508 509 510 511 512 513
/*================================ Prototypes =============================== */

static void freeStringObject(robj *o);
static void freeListObject(robj *o);
static void freeSetObject(robj *o);
static void decrRefCount(void *o);
static robj *createObject(int type, void *ptr);
static void freeClient(redisClient *c);
514
static int rdbLoad(char *filename);
A
antirez 已提交
515 516 517
static void addReply(redisClient *c, robj *obj);
static void addReplySds(redisClient *c, sds s);
static void incrRefCount(robj *o);
518
static int rdbSaveBackground(char *filename);
A
antirez 已提交
519
static robj *createStringObject(char *ptr, size_t len);
A
antirez 已提交
520
static robj *dupStringObject(robj *o);
A
antirez 已提交
521
static void replicationFeedSlaves(list *slaves, struct redisCommand *cmd, int dictid, robj **argv, int argc);
522
static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc);
A
antirez 已提交
523
static int syncWithMaster(void);
524
static robj *tryObjectSharing(robj *o);
525
static int tryObjectEncoding(robj *o);
526
static robj *getDecodedObject(robj *o);
A
antirez 已提交
527 528 529
static int removeExpire(redisDb *db, robj *key);
static int expireIfNeeded(redisDb *db, robj *key);
static int deleteIfVolatile(redisDb *db, robj *key);
A
antirez 已提交
530
static int deleteIfSwapped(redisDb *db, robj *key);
531
static int deleteKey(redisDb *db, robj *key);
A
antirez 已提交
532 533
static time_t getExpire(redisDb *db, robj *key);
static int setExpire(redisDb *db, robj *key, time_t when);
534
static void updateSlavesWaitingBgsave(int bgsaveerr);
A
antirez 已提交
535
static void freeMemoryIfNeeded(void);
536
static int processCommand(redisClient *c);
537
static void setupSigSegvAction(void);
538
static void rdbRemoveTempFile(pid_t childpid);
539
static void aofRemoveTempFile(pid_t childpid);
540
static size_t stringObjectLen(robj *o);
A
antirez 已提交
541
static void processInputBuffer(redisClient *c);
542
static zskiplist *zslCreate(void);
543
static void zslFree(zskiplist *zsl);
544
static void zslInsert(zskiplist *zsl, double score, robj *obj);
545
static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask);
A
antirez 已提交
546 547 548
static void initClientMultiState(redisClient *c);
static void freeClientMultiState(redisClient *c);
static void queueMultiCommand(redisClient *c, struct redisCommand *cmd);
549
static void unblockClientWaitingData(redisClient *c);
A
antirez 已提交
550
static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele);
551
static void vmInit(void);
A
antirez 已提交
552
static void vmMarkPagesFree(off_t page, off_t count);
A
antirez 已提交
553
static robj *vmLoadObject(robj *key);
A
antirez 已提交
554
static robj *vmPreviewObject(robj *key);
555 556
static int vmSwapOneObjectBlocking(void);
static int vmSwapOneObjectThreaded(void);
A
antirez 已提交
557
static int vmCanSwapOut(void);
558
static int tryFreeOneObjectFromFreelist(void);
559 560 561
static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata, int mask);
static void vmCancelThreadedIOJob(robj *o);
562 563 564 565 566
static void lockThreadedIO(void);
static void unlockThreadedIO(void);
static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db);
static void freeIOJob(iojob *j);
static void queueIOJob(iojob *j);
567 568
static int vmWriteObjectOnSwap(robj *o, off_t page);
static robj *vmReadObjectFromSwap(off_t page, int type);
569 570
static void waitEmptyIOJobsQueue(void);
static void vmReopenSwapFile(void);
571
static int vmFreePage(off_t page);
A
antirez 已提交
572 573 574 575 576 577 578
static int blockClientOnSwappedKeys(struct redisCommand *cmd, redisClient *c);
static int dontWaitForSwappedKey(redisClient *c, robj *key);
static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key);
static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
static struct redisCommand *lookupCommand(char *name);
static void call(redisClient *c, struct redisCommand *cmd);
static void resetClient(redisClient *c);
A
antirez 已提交
579

B
Brian Hammond 已提交
580
static void authCommand(redisClient *c);
A
antirez 已提交
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
static void pingCommand(redisClient *c);
static void echoCommand(redisClient *c);
static void setCommand(redisClient *c);
static void setnxCommand(redisClient *c);
static void getCommand(redisClient *c);
static void delCommand(redisClient *c);
static void existsCommand(redisClient *c);
static void incrCommand(redisClient *c);
static void decrCommand(redisClient *c);
static void incrbyCommand(redisClient *c);
static void decrbyCommand(redisClient *c);
static void selectCommand(redisClient *c);
static void randomkeyCommand(redisClient *c);
static void keysCommand(redisClient *c);
static void dbsizeCommand(redisClient *c);
static void lastsaveCommand(redisClient *c);
static void saveCommand(redisClient *c);
static void bgsaveCommand(redisClient *c);
599
static void bgrewriteaofCommand(redisClient *c);
A
antirez 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
static void shutdownCommand(redisClient *c);
static void moveCommand(redisClient *c);
static void renameCommand(redisClient *c);
static void renamenxCommand(redisClient *c);
static void lpushCommand(redisClient *c);
static void rpushCommand(redisClient *c);
static void lpopCommand(redisClient *c);
static void rpopCommand(redisClient *c);
static void llenCommand(redisClient *c);
static void lindexCommand(redisClient *c);
static void lrangeCommand(redisClient *c);
static void ltrimCommand(redisClient *c);
static void typeCommand(redisClient *c);
static void lsetCommand(redisClient *c);
static void saddCommand(redisClient *c);
static void sremCommand(redisClient *c);
A
antirez 已提交
616
static void smoveCommand(redisClient *c);
A
antirez 已提交
617 618
static void sismemberCommand(redisClient *c);
static void scardCommand(redisClient *c);
619
static void spopCommand(redisClient *c);
A
antirez 已提交
620
static void srandmemberCommand(redisClient *c);
A
antirez 已提交
621 622
static void sinterCommand(redisClient *c);
static void sinterstoreCommand(redisClient *c);
623 624
static void sunionCommand(redisClient *c);
static void sunionstoreCommand(redisClient *c);
625 626
static void sdiffCommand(redisClient *c);
static void sdiffstoreCommand(redisClient *c);
A
antirez 已提交
627 628 629 630 631
static void syncCommand(redisClient *c);
static void flushdbCommand(redisClient *c);
static void flushallCommand(redisClient *c);
static void sortCommand(redisClient *c);
static void lremCommand(redisClient *c);
A
antirez 已提交
632
static void rpoplpushcommand(redisClient *c);
A
antirez 已提交
633
static void infoCommand(redisClient *c);
634
static void mgetCommand(redisClient *c);
A
antirez 已提交
635
static void monitorCommand(redisClient *c);
A
antirez 已提交
636
static void expireCommand(redisClient *c);
637
static void expireatCommand(redisClient *c);
A
antirez 已提交
638
static void getsetCommand(redisClient *c);
A
antirez 已提交
639
static void ttlCommand(redisClient *c);
640
static void slaveofCommand(redisClient *c);
641
static void debugCommand(redisClient *c);
A
antirez 已提交
642 643
static void msetCommand(redisClient *c);
static void msetnxCommand(redisClient *c);
644
static void zaddCommand(redisClient *c);
A
antirez 已提交
645
static void zincrbyCommand(redisClient *c);
646
static void zrangeCommand(redisClient *c);
647
static void zrangebyscoreCommand(redisClient *c);
648
static void zcountCommand(redisClient *c);
649
static void zrevrangeCommand(redisClient *c);
650
static void zcardCommand(redisClient *c);
A
antirez 已提交
651
static void zremCommand(redisClient *c);
A
antirez 已提交
652
static void zscoreCommand(redisClient *c);
653
static void zremrangebyscoreCommand(redisClient *c);
A
antirez 已提交
654 655
static void multiCommand(redisClient *c);
static void execCommand(redisClient *c);
656
static void discardCommand(redisClient *c);
A
antirez 已提交
657 658
static void blpopCommand(redisClient *c);
static void brpopCommand(redisClient *c);
A
antirez 已提交
659
static void appendCommand(redisClient *c);
A
antirez 已提交
660

A
antirez 已提交
661 662 663 664 665
/*================================= Globals ================================= */

/* Global vars */
static struct redisServer server; /* server global state */
static struct redisCommand cmdTable[] = {
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
    {"get",getCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"set",setCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,0,0,0},
    {"setnx",setnxCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,0,0,0},
    {"append",appendCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,1,1},
    {"del",delCommand,-2,REDIS_CMD_INLINE,0,0,0},
    {"exists",existsCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"incr",incrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,1,1,1},
    {"decr",decrCommand,2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,1,1,1},
    {"mget",mgetCommand,-2,REDIS_CMD_INLINE,1,-1,1},
    {"rpush",rpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,1,1},
    {"lpush",lpushCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,1,1},
    {"rpop",rpopCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"lpop",lpopCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"brpop",brpopCommand,-3,REDIS_CMD_INLINE,1,1,1},
    {"blpop",blpopCommand,-3,REDIS_CMD_INLINE,1,1,1},
    {"llen",llenCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"lindex",lindexCommand,3,REDIS_CMD_INLINE,1,1,1},
    {"lset",lsetCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,1,1},
    {"lrange",lrangeCommand,4,REDIS_CMD_INLINE,1,1,1},
    {"ltrim",ltrimCommand,4,REDIS_CMD_INLINE,1,1,1},
    {"lrem",lremCommand,4,REDIS_CMD_BULK,1,1,1},
    {"rpoplpush",rpoplpushcommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,1,2,1},
    {"sadd",saddCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,1,1},
    {"srem",sremCommand,3,REDIS_CMD_BULK,1,1,1},
    {"smove",smoveCommand,4,REDIS_CMD_BULK,1,2,1},
    {"sismember",sismemberCommand,3,REDIS_CMD_BULK,1,1,1},
    {"scard",scardCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"spop",spopCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"srandmember",srandmemberCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"sinter",sinterCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,1,-1,1},
    {"sinterstore",sinterstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,2,-1,1},
    {"sunion",sunionCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,1,-1,1},
    {"sunionstore",sunionstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,2,-1,1},
    {"sdiff",sdiffCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,1,-1,1},
    {"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,2,-1,1},
    {"smembers",sinterCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"zadd",zaddCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,1,1},
    {"zincrby",zincrbyCommand,4,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,1,1},
    {"zrem",zremCommand,3,REDIS_CMD_BULK,1,1,1},
    {"zremrangebyscore",zremrangebyscoreCommand,4,REDIS_CMD_INLINE,1,1,1},
    {"zrange",zrangeCommand,-4,REDIS_CMD_INLINE,1,1,1},
    {"zrangebyscore",zrangebyscoreCommand,-4,REDIS_CMD_INLINE,1,1,1},
    {"zcount",zcountCommand,4,REDIS_CMD_INLINE,1,1,1},
    {"zrevrange",zrevrangeCommand,-4,REDIS_CMD_INLINE,1,1,1},
    {"zcard",zcardCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"zscore",zscoreCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,1,1},
    {"incrby",incrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,1,1,1},
    {"decrby",decrbyCommand,3,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,1,1,1},
    {"getset",getsetCommand,3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,1,1},
    {"mset",msetCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,-1,2},
    {"msetnx",msetnxCommand,-3,REDIS_CMD_BULK|REDIS_CMD_DENYOOM,1,-1,2},
    {"randomkey",randomkeyCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"select",selectCommand,2,REDIS_CMD_INLINE,0,0,0},
    {"move",moveCommand,3,REDIS_CMD_INLINE,1,1,1},
    {"rename",renameCommand,3,REDIS_CMD_INLINE,1,1,1},
    {"renamenx",renamenxCommand,3,REDIS_CMD_INLINE,1,1,1},
    {"expire",expireCommand,3,REDIS_CMD_INLINE,0,0,0},
    {"expireat",expireatCommand,3,REDIS_CMD_INLINE,0,0,0},
    {"keys",keysCommand,2,REDIS_CMD_INLINE,0,0,0},
    {"dbsize",dbsizeCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"auth",authCommand,2,REDIS_CMD_INLINE,0,0,0},
    {"ping",pingCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"echo",echoCommand,2,REDIS_CMD_BULK,0,0,0},
    {"save",saveCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"bgsave",bgsaveCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"bgrewriteaof",bgrewriteaofCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"shutdown",shutdownCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"lastsave",lastsaveCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"type",typeCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"multi",multiCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"exec",execCommand,1,REDIS_CMD_INLINE,0,0,0},
737
    {"discard",discardCommand,1,REDIS_CMD_INLINE,0,0,0},
738 739 740 741 742 743 744 745 746 747
    {"sync",syncCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"flushdb",flushdbCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"flushall",flushallCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"sort",sortCommand,-2,REDIS_CMD_INLINE|REDIS_CMD_DENYOOM,1,1,1},
    {"info",infoCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"monitor",monitorCommand,1,REDIS_CMD_INLINE,0,0,0},
    {"ttl",ttlCommand,2,REDIS_CMD_INLINE,1,1,1},
    {"slaveof",slaveofCommand,3,REDIS_CMD_INLINE,0,0,0},
    {"debug",debugCommand,-2,REDIS_CMD_INLINE,0,0,0},
    {NULL,NULL,0,0,0,0,0}
A
antirez 已提交
748
};
749

A
antirez 已提交
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
/*============================ Utility functions ============================ */

/* Glob-style pattern matching. */
int stringmatchlen(const char *pattern, int patternLen,
        const char *string, int stringLen, int nocase)
{
    while(patternLen) {
        switch(pattern[0]) {
        case '*':
            while (pattern[1] == '*') {
                pattern++;
                patternLen--;
            }
            if (patternLen == 1)
                return 1; /* match */
            while(stringLen) {
                if (stringmatchlen(pattern+1, patternLen-1,
                            string, stringLen, nocase))
                    return 1; /* match */
                string++;
                stringLen--;
            }
            return 0; /* no match */
            break;
        case '?':
            if (stringLen == 0)
                return 0; /* no match */
            string++;
            stringLen--;
            break;
        case '[':
        {
            int not, match;

            pattern++;
            patternLen--;
            not = pattern[0] == '^';
            if (not) {
                pattern++;
                patternLen--;
            }
            match = 0;
            while(1) {
                if (pattern[0] == '\\') {
                    pattern++;
                    patternLen--;
                    if (pattern[0] == string[0])
                        match = 1;
                } else if (pattern[0] == ']') {
                    break;
                } else if (patternLen == 0) {
                    pattern--;
                    patternLen++;
                    break;
                } else if (pattern[1] == '-' && patternLen >= 3) {
                    int start = pattern[0];
                    int end = pattern[2];
                    int c = string[0];
                    if (start > end) {
                        int t = start;
                        start = end;
                        end = t;
                    }
                    if (nocase) {
                        start = tolower(start);
                        end = tolower(end);
                        c = tolower(c);
                    }
                    pattern += 2;
                    patternLen -= 2;
                    if (c >= start && c <= end)
                        match = 1;
                } else {
                    if (!nocase) {
                        if (pattern[0] == string[0])
                            match = 1;
                    } else {
                        if (tolower((int)pattern[0]) == tolower((int)string[0]))
                            match = 1;
                    }
                }
                pattern++;
                patternLen--;
            }
            if (not)
                match = !match;
            if (!match)
                return 0; /* no match */
            string++;
            stringLen--;
            break;
        }
        case '\\':
            if (patternLen >= 2) {
                pattern++;
                patternLen--;
            }
            /* fall through */
        default:
            if (!nocase) {
                if (pattern[0] != string[0])
                    return 0; /* no match */
            } else {
                if (tolower((int)pattern[0]) != tolower((int)string[0]))
                    return 0; /* no match */
            }
            string++;
            stringLen--;
            break;
        }
        pattern++;
        patternLen--;
        if (stringLen == 0) {
            while(*pattern == '*') {
                pattern++;
                patternLen--;
            }
            break;
        }
    }
    if (patternLen == 0 && stringLen == 0)
        return 1;
    return 0;
}

875
static void redisLog(int level, const char *fmt, ...) {
A
antirez 已提交
876 877 878 879 880 881 882 883
    va_list ap;
    FILE *fp;

    fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
    if (!fp) return;

    va_start(ap, fmt);
    if (level >= server.verbosity) {
884
        char *c = ".-*#";
A
antirez 已提交
885 886 887 888
        char buf[64];
        time_t now;

        now = time(NULL);
889
        strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
890
        fprintf(fp,"[%d] %s %c ",(int)getpid(),buf,c[level]);
A
antirez 已提交
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
        vfprintf(fp, fmt, ap);
        fprintf(fp,"\n");
        fflush(fp);
    }
    va_end(ap);

    if (server.logfile) fclose(fp);
}

/*====================== Hash table type implementation  ==================== */

/* This is an hash table type that uses the SDS dynamic strings libary as
 * keys and radis objects as values (objects can hold SDS strings,
 * lists, sets). */

906 907 908 909 910 911
static void dictVanillaFree(void *privdata, void *val)
{
    DICT_NOTUSED(privdata);
    zfree(val);
}

A
antirez 已提交
912 913 914 915 916 917
static void dictListDestructor(void *privdata, void *val)
{
    DICT_NOTUSED(privdata);
    listRelease((list*)val);
}

A
antirez 已提交
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
static int sdsDictKeyCompare(void *privdata, const void *key1,
        const void *key2)
{
    int l1,l2;
    DICT_NOTUSED(privdata);

    l1 = sdslen((sds)key1);
    l2 = sdslen((sds)key2);
    if (l1 != l2) return 0;
    return memcmp(key1, key2, l1) == 0;
}

static void dictRedisObjectDestructor(void *privdata, void *val)
{
    DICT_NOTUSED(privdata);

A
antirez 已提交
934
    if (val == NULL) return; /* Values of swapped out keys as set to NULL */
A
antirez 已提交
935 936 937
    decrRefCount(val);
}

938
static int dictObjKeyCompare(void *privdata, const void *key1,
A
antirez 已提交
939 940 941 942 943 944
        const void *key2)
{
    const robj *o1 = key1, *o2 = key2;
    return sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
}

945
static unsigned int dictObjHash(const void *key) {
A
antirez 已提交
946 947 948 949
    const robj *o = key;
    return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
}

950 951 952
static int dictEncObjKeyCompare(void *privdata, const void *key1,
        const void *key2)
{
953 954
    robj *o1 = (robj*) key1, *o2 = (robj*) key2;
    int cmp;
955

956 957 958 959 960 961
    o1 = getDecodedObject(o1);
    o2 = getDecodedObject(o2);
    cmp = sdsDictKeyCompare(privdata,o1->ptr,o2->ptr);
    decrRefCount(o1);
    decrRefCount(o2);
    return cmp;
962 963 964
}

static unsigned int dictEncObjHash(const void *key) {
965
    robj *o = (robj*) key;
966

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    if (o->encoding == REDIS_ENCODING_RAW) {
        return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
    } else {
        if (o->encoding == REDIS_ENCODING_INT) {
            char buf[32];
            int len;

            len = snprintf(buf,32,"%ld",(long)o->ptr);
            return dictGenHashFunction((unsigned char*)buf, len);
        } else {
            unsigned int hash;

            o = getDecodedObject(o);
            hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
            decrRefCount(o);
            return hash;
        }
    }
985 986
}

A
antirez 已提交
987
/* Sets type and expires */
A
antirez 已提交
988
static dictType setDictType = {
989
    dictEncObjHash,            /* hash function */
A
antirez 已提交
990 991
    NULL,                      /* key dup */
    NULL,                      /* val dup */
992
    dictEncObjKeyCompare,      /* key compare */
A
antirez 已提交
993 994 995 996
    dictRedisObjectDestructor, /* key destructor */
    NULL                       /* val destructor */
};

A
antirez 已提交
997
/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
998 999 1000 1001 1002 1003
static dictType zsetDictType = {
    dictEncObjHash,            /* hash function */
    NULL,                      /* key dup */
    NULL,                      /* val dup */
    dictEncObjKeyCompare,      /* key compare */
    dictRedisObjectDestructor, /* key destructor */
1004
    dictVanillaFree            /* val destructor of malloc(sizeof(double)) */
1005 1006
};

A
antirez 已提交
1007
/* Db->dict */
A
antirez 已提交
1008
static dictType hashDictType = {
1009
    dictObjHash,                /* hash function */
A
antirez 已提交
1010 1011
    NULL,                       /* key dup */
    NULL,                       /* val dup */
1012
    dictObjKeyCompare,          /* key compare */
A
antirez 已提交
1013 1014 1015 1016
    dictRedisObjectDestructor,  /* key destructor */
    dictRedisObjectDestructor   /* val destructor */
};

A
antirez 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
/* Db->expires */
static dictType keyptrDictType = {
    dictObjHash,               /* hash function */
    NULL,                      /* key dup */
    NULL,                      /* val dup */
    dictObjKeyCompare,         /* key compare */
    dictRedisObjectDestructor, /* key destructor */
    NULL                       /* val destructor */
};

A
antirez 已提交
1027
/* Keylist hash table type has unencoded redis objects as keys and
A
antirez 已提交
1028 1029
 * lists as values. It's used for blocking operations (BLPOP) and to
 * map swapped keys to a list of clients waiting for this keys to be loaded. */
A
antirez 已提交
1030 1031 1032 1033 1034 1035 1036 1037 1038
static dictType keylistDictType = {
    dictObjHash,                /* hash function */
    NULL,                       /* key dup */
    NULL,                       /* val dup */
    dictObjKeyCompare,          /* key compare */
    dictRedisObjectDestructor,  /* key destructor */
    dictListDestructor          /* val destructor */
};

A
antirez 已提交
1039 1040 1041 1042 1043 1044 1045 1046
/* ========================= Random utility functions ======================= */

/* Redis generally does not try to recover from out of memory conditions
 * when allocating objects or strings, it is not clear if it will be possible
 * to report this condition to the client since the networking layer itself
 * is based on heap allocation for send buffers, so we simply abort.
 * At least the code will be simpler to read... */
static void oom(const char *msg) {
1047
    redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
A
antirez 已提交
1048 1049 1050 1051 1052
    sleep(1);
    abort();
}

/* ====================== Redis server networking stuff ===================== */
1053
static void closeTimedoutClients(void) {
A
antirez 已提交
1054 1055 1056
    redisClient *c;
    listNode *ln;
    time_t now = time(NULL);
A
antirez 已提交
1057
    listIter li;
A
antirez 已提交
1058

A
antirez 已提交
1059 1060
    listRewind(server.clients,&li);
    while ((ln = listNext(&li)) != NULL) {
A
antirez 已提交
1061
        c = listNodeValue(ln);
A
antirez 已提交
1062 1063
        if (server.maxidletime &&
            !(c->flags & REDIS_SLAVE) &&    /* no timeout for slaves */
1064
            !(c->flags & REDIS_MASTER) &&   /* no timeout for masters */
A
antirez 已提交
1065 1066
             (now - c->lastinteraction > server.maxidletime))
        {
1067
            redisLog(REDIS_VERBOSE,"Closing idle client");
A
antirez 已提交
1068
            freeClient(c);
A
antirez 已提交
1069
        } else if (c->flags & REDIS_BLOCKED) {
1070
            if (c->blockingto != 0 && c->blockingto < now) {
1071
                addReply(c,shared.nullmultibulk);
1072
                unblockClientWaitingData(c);
A
antirez 已提交
1073
            }
A
antirez 已提交
1074 1075 1076 1077
        }
    }
}

1078 1079 1080 1081 1082 1083 1084 1085 1086
static int htNeedsResize(dict *dict) {
    long long size, used;

    size = dictSlots(dict);
    used = dictSize(dict);
    return (size && used && size > DICT_HT_INITIAL_SIZE &&
            (used*100/size < REDIS_HT_MINFILL));
}

1087 1088
/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
 * we resize the hash table to save memory */
1089
static void tryResizeHashTables(void) {
1090 1091 1092
    int j;

    for (j = 0; j < server.dbnum; j++) {
1093
        if (htNeedsResize(server.db[j].dict)) {
1094
            redisLog(REDIS_VERBOSE,"The hash table %d is too sparse, resize it...",j);
1095
            dictResize(server.db[j].dict);
1096
            redisLog(REDIS_VERBOSE,"Hash table %d resized.",j);
1097
        }
1098 1099
        if (htNeedsResize(server.db[j].expires))
            dictResize(server.db[j].expires);
1100 1101 1102
    }
}

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
/* A background saving child (BGSAVE) terminated its work. Handle this. */
void backgroundSaveDoneHandler(int statloc) {
    int exitcode = WEXITSTATUS(statloc);
    int bysignal = WIFSIGNALED(statloc);

    if (!bysignal && exitcode == 0) {
        redisLog(REDIS_NOTICE,
            "Background saving terminated with success");
        server.dirty = 0;
        server.lastsave = time(NULL);
    } else if (!bysignal && exitcode != 0) {
        redisLog(REDIS_WARNING, "Background saving error");
    } else {
        redisLog(REDIS_WARNING,
            "Background saving terminated by signal");
        rdbRemoveTempFile(server.bgsavechildpid);
    }
    server.bgsavechildpid = -1;
    /* Possibly there are slaves waiting for a BGSAVE in order to be served
     * (the first stage of SYNC is a bulk transfer of dump.rdb) */
    updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
}

/* A background append only file rewriting (BGREWRITEAOF) terminated its work.
 * Handle this. */
void backgroundRewriteDoneHandler(int statloc) {
    int exitcode = WEXITSTATUS(statloc);
    int bysignal = WIFSIGNALED(statloc);

    if (!bysignal && exitcode == 0) {
        int fd;
        char tmpfile[256];

        redisLog(REDIS_NOTICE,
            "Background append only file rewriting terminated with success");
        /* Now it's time to flush the differences accumulated by the parent */
        snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) server.bgrewritechildpid);
        fd = open(tmpfile,O_WRONLY|O_APPEND);
        if (fd == -1) {
            redisLog(REDIS_WARNING, "Not able to open the temp append only file produced by the child: %s", strerror(errno));
            goto cleanup;
        }
        /* Flush our data... */
        if (write(fd,server.bgrewritebuf,sdslen(server.bgrewritebuf)) !=
                (signed) sdslen(server.bgrewritebuf)) {
            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));
            close(fd);
            goto cleanup;
        }
1152
        redisLog(REDIS_NOTICE,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server.bgrewritebuf));
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
        /* Now our work is to rename the temp file into the stable file. And
         * switch the file descriptor used by the server for append only. */
        if (rename(tmpfile,server.appendfilename) == -1) {
            redisLog(REDIS_WARNING,"Can't rename the temp append only file into the stable one: %s", strerror(errno));
            close(fd);
            goto cleanup;
        }
        /* Mission completed... almost */
        redisLog(REDIS_NOTICE,"Append only file successfully rewritten.");
        if (server.appendfd != -1) {
            /* If append only is actually enabled... */
            close(server.appendfd);
            server.appendfd = fd;
            fsync(fd);
A
antirez 已提交
1167
            server.appendseldb = -1; /* Make sure it will issue SELECT */
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
            redisLog(REDIS_NOTICE,"The new append only file was selected for future appends.");
        } else {
            /* If append only is disabled we just generate a dump in this
             * format. Why not? */
            close(fd);
        }
    } else if (!bysignal && exitcode != 0) {
        redisLog(REDIS_WARNING, "Background append only file rewriting error");
    } else {
        redisLog(REDIS_WARNING,
            "Background append only file rewriting terminated by signal");
    }
cleanup:
    sdsfree(server.bgrewritebuf);
    server.bgrewritebuf = sdsempty();
    aofRemoveTempFile(server.bgrewritechildpid);
    server.bgrewritechildpid = -1;
}

1187
static int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
1188
    int j, loops = server.cronloops++;
A
antirez 已提交
1189 1190 1191 1192
    REDIS_NOTUSED(eventLoop);
    REDIS_NOTUSED(id);
    REDIS_NOTUSED(clientData);

A
antirez 已提交
1193 1194 1195 1196 1197 1198
    /* We take a cached value of the unix time in the global state because
     * with virtual memory and aging there is to store the current time
     * in objects at every object access, and accuracy is not needed.
     * To access a global var is faster than calling time(NULL) */
    server.unixtime = time(NULL);

1199
    /* Show some info about non-empty databases */
A
antirez 已提交
1200
    for (j = 0; j < server.dbnum; j++) {
1201
        long long size, used, vkeys;
1202

A
antirez 已提交
1203 1204
        size = dictSlots(server.db[j].dict);
        used = dictSize(server.db[j].dict);
1205
        vkeys = dictSize(server.db[j].expires);
1206
        if (!(loops % 5) && (used || vkeys)) {
1207
            redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
A
antirez 已提交
1208
            /* dictPrintStats(server.dict); */
A
antirez 已提交
1209 1210 1211
        }
    }

1212 1213 1214 1215 1216 1217
    /* We don't want to resize the hash tables while a bacground saving
     * is in progress: the saving child is created using fork() that is
     * implemented with a copy-on-write semantic in most modern systems, so
     * if we resize the HT while there is the saving child at work actually
     * a lot of memory movements in the parent will cause a lot of pages
     * copied. */
1218
    if (server.bgsavechildpid == -1) tryResizeHashTables();
1219

A
antirez 已提交
1220 1221
    /* Show information about connected clients */
    if (!(loops % 5)) {
1222
        redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
A
antirez 已提交
1223 1224
            listLength(server.clients)-listLength(server.slaves),
            listLength(server.slaves),
1225
            zmalloc_used_memory(),
A
antirez 已提交
1226
            dictSize(server.sharingpool));
A
antirez 已提交
1227 1228 1229
    }

    /* Close connections of timedout clients */
A
antirez 已提交
1230
    if ((server.maxidletime && !(loops % 10)) || server.blpop_blocked_clients)
A
antirez 已提交
1231 1232
        closeTimedoutClients();

1233 1234
    /* Check if a background saving or AOF rewrite in progress terminated */
    if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
A
antirez 已提交
1235
        int statloc;
1236 1237 1238 1239 1240
        pid_t pid;

        if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
            if (pid == server.bgsavechildpid) {
                backgroundSaveDoneHandler(statloc);
A
antirez 已提交
1241
            } else {
1242
                backgroundRewriteDoneHandler(statloc);
A
antirez 已提交
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
            }
        }
    } else {
        /* If there is not a background saving in progress check if
         * we have to save now */
         time_t now = time(NULL);
         for (j = 0; j < server.saveparamslen; j++) {
            struct saveparam *sp = server.saveparams+j;

            if (server.dirty >= sp->changes &&
                now-server.lastsave > sp->seconds) {
                redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
                    sp->changes, sp->seconds);
1256
                rdbSaveBackground(server.dbfilename);
A
antirez 已提交
1257 1258 1259 1260
                break;
            }
         }
    }
1261

1262 1263 1264 1265
    /* Try to expire a few timed out keys. The algorithm used is adaptive and
     * will use few CPU cycles if there are few expiring keys, otherwise
     * it will get more aggressive to avoid that too much memory is used by
     * keys that can be removed from the keyspace. */
1266
    for (j = 0; j < server.dbnum; j++) {
1267
        int expired;
1268 1269
        redisDb *db = server.db+j;

1270 1271 1272
        /* Continue to expire if at the end of the cycle more than 25%
         * of the keys were expired. */
        do {
A
antirez 已提交
1273
            long num = dictSize(db->expires);
1274 1275
            time_t now = time(NULL);

1276
            expired = 0;
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
            if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
                num = REDIS_EXPIRELOOKUPS_PER_CRON;
            while (num--) {
                dictEntry *de;
                time_t t;

                if ((de = dictGetRandomKey(db->expires)) == NULL) break;
                t = (time_t) dictGetEntryVal(de);
                if (now > t) {
                    deleteKey(db,dictGetEntryKey(de));
1287
                    expired++;
1288 1289
                }
            }
1290
        } while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
1291 1292
    }

A
antirez 已提交
1293
    /* Swap a few keys on disk if we are over the memory limit and VM
1294
     * is enbled. Try to free objects from the free list first. */
A
antirez 已提交
1295 1296
    if (vmCanSwapOut()) {
        while (server.vm_enabled && zmalloc_used_memory() >
1297 1298
                server.vm_max_memory)
        {
A
antirez 已提交
1299 1300
            int retval;

1301
            if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
A
antirez 已提交
1302 1303 1304 1305 1306 1307 1308 1309
            retval = (server.vm_max_threads == 0) ?
                        vmSwapOneObjectBlocking() :
                        vmSwapOneObjectThreaded();
            if (retval == REDIS_ERR && (loops % 30) == 0 &&
                zmalloc_used_memory() >
                (server.vm_max_memory+server.vm_max_memory/10))
            {
                redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
A
antirez 已提交
1310
            }
A
antirez 已提交
1311 1312 1313 1314 1315
            /* Note that when using threade I/O we free just one object,
             * because anyway when the I/O thread in charge to swap this
             * object out will finish, the handler of completed jobs
             * will try to swap more objects if we are still out of memory. */
            if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
A
antirez 已提交
1316 1317 1318
        }
    }

A
antirez 已提交
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
    /* Check if we should connect to a MASTER */
    if (server.replstate == REDIS_REPL_CONNECT) {
        redisLog(REDIS_NOTICE,"Connecting to MASTER...");
        if (syncWithMaster() == REDIS_OK) {
            redisLog(REDIS_NOTICE,"MASTER <-> SLAVE sync succeeded");
        }
    }
    return 1000;
}

A
antirez 已提交
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
/* This function gets called every time Redis is entering the
 * main loop of the event driven library, that is, before to sleep
 * for ready file descriptors. */
static void beforeSleep(struct aeEventLoop *eventLoop) {
    REDIS_NOTUSED(eventLoop);

    if (server.vm_enabled && listLength(server.io_ready_clients)) {
        listIter li;
        listNode *ln;

        listRewind(server.io_ready_clients,&li);
        while((ln = listNext(&li))) {
            redisClient *c = ln->value;
            struct redisCommand *cmd;

            /* Resume the client. */
            listDelNode(server.io_ready_clients,ln);
            c->flags &= (~REDIS_IO_WAIT);
            server.vm_blocked_clients--;
            aeCreateFileEvent(server.el, c->fd, AE_READABLE,
                readQueryFromClient, c);
            cmd = lookupCommand(c->argv[0]->ptr);
            assert(cmd != NULL);
            call(c,cmd);
            resetClient(c);
            /* There may be more data to process in the input buffer. */
            if (c->querybuf && sdslen(c->querybuf) > 0)
                processInputBuffer(c);
        }
    }
}

A
antirez 已提交
1361 1362 1363 1364
static void createSharedObjects(void) {
    shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
    shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
    shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
1365 1366 1367 1368 1369 1370
    shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
    shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
    shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
    shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
    shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
    shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
A
antirez 已提交
1371
    shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
A
antirez 已提交
1372
    shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
A
antirez 已提交
1373 1374 1375 1376 1377 1378
    shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
        "-ERR Operation against a key holding the wrong kind of value\r\n"));
    shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
        "-ERR no such key\r\n"));
    shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
        "-ERR syntax error\r\n"));
1379 1380 1381 1382
    shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
        "-ERR source and destination objects are the same\r\n"));
    shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
        "-ERR index out of range\r\n"));
A
antirez 已提交
1383
    shared.space = createObject(REDIS_STRING,sdsnew(" "));
1384 1385
    shared.colon = createObject(REDIS_STRING,sdsnew(":"));
    shared.plus = createObject(REDIS_STRING,sdsnew("+"));
A
antirez 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    shared.select0 = createStringObject("select 0\r\n",10);
    shared.select1 = createStringObject("select 1\r\n",10);
    shared.select2 = createStringObject("select 2\r\n",10);
    shared.select3 = createStringObject("select 3\r\n",10);
    shared.select4 = createStringObject("select 4\r\n",10);
    shared.select5 = createStringObject("select 5\r\n",10);
    shared.select6 = createStringObject("select 6\r\n",10);
    shared.select7 = createStringObject("select 7\r\n",10);
    shared.select8 = createStringObject("select 8\r\n",10);
    shared.select9 = createStringObject("select 9\r\n",10);
}

static void appendServerSaveParams(time_t seconds, int changes) {
    server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1));
    server.saveparams[server.saveparamslen].seconds = seconds;
    server.saveparams[server.saveparamslen].changes = changes;
    server.saveparamslen++;
}

1405
static void resetServerSaveParams() {
A
antirez 已提交
1406 1407 1408 1409 1410 1411 1412 1413
    zfree(server.saveparams);
    server.saveparams = NULL;
    server.saveparamslen = 0;
}

static void initServerConfig() {
    server.dbnum = REDIS_DEFAULT_DBNUM;
    server.port = REDIS_SERVERPORT;
1414
    server.verbosity = REDIS_VERBOSE;
A
antirez 已提交
1415 1416 1417 1418 1419 1420
    server.maxidletime = REDIS_MAXIDLETIME;
    server.saveparams = NULL;
    server.logfile = NULL; /* NULL = log on standard output */
    server.bindaddr = NULL;
    server.glueoutputbuf = 1;
    server.daemonize = 0;
1421
    server.appendonly = 0;
1422
    server.appendfsync = APPENDFSYNC_ALWAYS;
1423
    server.lastfsync = time(NULL);
1424 1425
    server.appendfd = -1;
    server.appendseldb = -1; /* Make sure the first time will not match */
1426
    server.pidfile = "/var/run/redis.pid";
A
antirez 已提交
1427
    server.dbfilename = "dump.rdb";
1428
    server.appendfilename = "appendonly.aof";
B
Brian Hammond 已提交
1429
    server.requirepass = NULL;
1430
    server.shareobjects = 0;
1431
    server.rdbcompression = 1;
1432
    server.sharingpoolsize = 1024;
1433
    server.maxclients = 0;
A
antirez 已提交
1434
    server.blpop_blocked_clients = 0;
A
antirez 已提交
1435
    server.maxmemory = 0;
1436
    server.vm_enabled = 0;
1437
    server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
1438 1439 1440
    server.vm_page_size = 256;          /* 256 bytes per page */
    server.vm_pages = 1024*1024*100;    /* 104 millions of pages */
    server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
1441
    server.vm_max_threads = 4;
A
antirez 已提交
1442
    server.vm_blocked_clients = 0;
1443

1444
    resetServerSaveParams();
A
antirez 已提交
1445 1446 1447 1448 1449 1450

    appendServerSaveParams(60*60,1);  /* save after 1 hour and 1 change */
    appendServerSaveParams(300,100);  /* save after 5 minutes and 100 changes */
    appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
    /* Replication related */
    server.isslave = 0;
1451
    server.masterauth = NULL;
A
antirez 已提交
1452 1453 1454 1455
    server.masterhost = NULL;
    server.masterport = 6379;
    server.master = NULL;
    server.replstate = REDIS_REPL_NONE;
1456 1457 1458 1459 1460 1461

    /* Double constants initialization */
    R_Zero = 0.0;
    R_PosInf = 1.0/R_Zero;
    R_NegInf = -1.0/R_Zero;
    R_Nan = R_Zero/R_Zero;
A
antirez 已提交
1462 1463 1464 1465 1466 1467 1468
}

static void initServer() {
    int j;

    signal(SIGHUP, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
H
hrothgar 已提交
1469
    setupSigSegvAction();
A
antirez 已提交
1470

1471 1472 1473 1474 1475
    server.devnull = fopen("/dev/null","w");
    if (server.devnull == NULL) {
        redisLog(REDIS_WARNING, "Can't open /dev/null: %s", server.neterr);
        exit(1);
    }
A
antirez 已提交
1476 1477
    server.clients = listCreate();
    server.slaves = listCreate();
A
antirez 已提交
1478
    server.monitors = listCreate();
A
antirez 已提交
1479 1480 1481
    server.objfreelist = listCreate();
    createSharedObjects();
    server.el = aeCreateEventLoop();
A
antirez 已提交
1482
    server.db = zmalloc(sizeof(redisDb)*server.dbnum);
1483
    server.sharingpool = dictCreate(&setDictType,NULL);
A
antirez 已提交
1484 1485 1486 1487 1488
    server.fd = anetTcpServer(server.neterr, server.port, server.bindaddr);
    if (server.fd == -1) {
        redisLog(REDIS_WARNING, "Opening TCP port: %s", server.neterr);
        exit(1);
    }
A
antirez 已提交
1489 1490
    for (j = 0; j < server.dbnum; j++) {
        server.db[j].dict = dictCreate(&hashDictType,NULL);
A
antirez 已提交
1491
        server.db[j].expires = dictCreate(&keyptrDictType,NULL);
A
antirez 已提交
1492
        server.db[j].blockingkeys = dictCreate(&keylistDictType,NULL);
A
antirez 已提交
1493 1494
        if (server.vm_enabled)
            server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
A
antirez 已提交
1495 1496
        server.db[j].id = j;
    }
A
antirez 已提交
1497
    server.cronloops = 0;
1498
    server.bgsavechildpid = -1;
1499 1500
    server.bgrewritechildpid = -1;
    server.bgrewritebuf = sdsempty();
A
antirez 已提交
1501 1502 1503 1504 1505
    server.lastsave = time(NULL);
    server.dirty = 0;
    server.stat_numcommands = 0;
    server.stat_numconnections = 0;
    server.stat_starttime = time(NULL);
A
antirez 已提交
1506
    server.unixtime = time(NULL);
1507
    aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
1508 1509
    if (aeCreateFileEvent(server.el, server.fd, AE_READABLE,
        acceptHandler, NULL) == AE_ERR) oom("creating file event");
1510 1511

    if (server.appendonly) {
A
antirez 已提交
1512
        server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
1513 1514 1515 1516 1517 1518
        if (server.appendfd == -1) {
            redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
                strerror(errno));
            exit(1);
        }
    }
1519 1520

    if (server.vm_enabled) vmInit();
A
antirez 已提交
1521 1522 1523
}

/* Empty the whole database */
1524
static long long emptyDb() {
A
antirez 已提交
1525
    int j;
1526
    long long removed = 0;
A
antirez 已提交
1527

A
antirez 已提交
1528
    for (j = 0; j < server.dbnum; j++) {
1529
        removed += dictSize(server.db[j].dict);
A
antirez 已提交
1530 1531 1532
        dictEmpty(server.db[j].dict);
        dictEmpty(server.db[j].expires);
    }
1533
    return removed;
A
antirez 已提交
1534 1535
}

A
antirez 已提交
1536 1537 1538 1539 1540 1541
static int yesnotoi(char *s) {
    if (!strcasecmp(s,"yes")) return 1;
    else if (!strcasecmp(s,"no")) return 0;
    else return -1;
}

A
antirez 已提交
1542 1543 1544
/* I agree, this is a very rudimental way to load a configuration...
   will improve later if the config gets more complex */
static void loadServerConfig(char *filename) {
1545
    FILE *fp;
A
antirez 已提交
1546 1547 1548
    char buf[REDIS_CONFIGLINE_MAX+1], *err = NULL;
    int linenum = 0;
    sds line = NULL;
1549 1550 1551 1552 1553 1554 1555 1556

    if (filename[0] == '-' && filename[1] == '\0')
        fp = stdin;
    else {
        if ((fp = fopen(filename,"r")) == NULL) {
            redisLog(REDIS_WARNING,"Fatal error, can't open config file");
            exit(1);
        }
A
antirez 已提交
1557
    }
1558

A
antirez 已提交
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
    while(fgets(buf,REDIS_CONFIGLINE_MAX+1,fp) != NULL) {
        sds *argv;
        int argc, j;

        linenum++;
        line = sdsnew(buf);
        line = sdstrim(line," \t\r\n");

        /* Skip comments and blank lines*/
        if (line[0] == '#' || line[0] == '\0') {
            sdsfree(line);
            continue;
        }

        /* Split into arguments */
        argv = sdssplitlen(line,sdslen(line)," ",1,&argc);
        sdstolower(argv[0]);

        /* Execute config directives */
1578
        if (!strcasecmp(argv[0],"timeout") && argc == 2) {
A
antirez 已提交
1579
            server.maxidletime = atoi(argv[1]);
1580
            if (server.maxidletime < 0) {
A
antirez 已提交
1581 1582
                err = "Invalid timeout value"; goto loaderr;
            }
1583
        } else if (!strcasecmp(argv[0],"port") && argc == 2) {
A
antirez 已提交
1584 1585 1586 1587
            server.port = atoi(argv[1]);
            if (server.port < 1 || server.port > 65535) {
                err = "Invalid port"; goto loaderr;
            }
1588
        } else if (!strcasecmp(argv[0],"bind") && argc == 2) {
A
antirez 已提交
1589
            server.bindaddr = zstrdup(argv[1]);
1590
        } else if (!strcasecmp(argv[0],"save") && argc == 3) {
A
antirez 已提交
1591 1592 1593 1594 1595 1596
            int seconds = atoi(argv[1]);
            int changes = atoi(argv[2]);
            if (seconds < 1 || changes < 0) {
                err = "Invalid save parameters"; goto loaderr;
            }
            appendServerSaveParams(seconds,changes);
1597
        } else if (!strcasecmp(argv[0],"dir") && argc == 2) {
A
antirez 已提交
1598 1599 1600 1601 1602
            if (chdir(argv[1]) == -1) {
                redisLog(REDIS_WARNING,"Can't chdir to '%s': %s",
                    argv[1], strerror(errno));
                exit(1);
            }
1603 1604
        } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
            if (!strcasecmp(argv[1],"debug")) server.verbosity = REDIS_DEBUG;
1605
            else if (!strcasecmp(argv[1],"verbose")) server.verbosity = REDIS_VERBOSE;
1606 1607
            else if (!strcasecmp(argv[1],"notice")) server.verbosity = REDIS_NOTICE;
            else if (!strcasecmp(argv[1],"warning")) server.verbosity = REDIS_WARNING;
A
antirez 已提交
1608 1609 1610 1611
            else {
                err = "Invalid log level. Must be one of debug, notice, warning";
                goto loaderr;
            }
1612
        } else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
1613
            FILE *logfp;
A
antirez 已提交
1614 1615

            server.logfile = zstrdup(argv[1]);
1616
            if (!strcasecmp(server.logfile,"stdout")) {
A
antirez 已提交
1617 1618 1619 1620 1621 1622
                zfree(server.logfile);
                server.logfile = NULL;
            }
            if (server.logfile) {
                /* Test if we are able to open the file. The server will not
                 * be able to abort just for this problem later... */
1623 1624
                logfp = fopen(server.logfile,"a");
                if (logfp == NULL) {
A
antirez 已提交
1625 1626 1627 1628
                    err = sdscatprintf(sdsempty(),
                        "Can't open the log file: %s", strerror(errno));
                    goto loaderr;
                }
1629
                fclose(logfp);
A
antirez 已提交
1630
            }
1631
        } else if (!strcasecmp(argv[0],"databases") && argc == 2) {
A
antirez 已提交
1632 1633 1634 1635
            server.dbnum = atoi(argv[1]);
            if (server.dbnum < 1) {
                err = "Invalid number of databases"; goto loaderr;
            }
1636 1637
        } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
            server.maxclients = atoi(argv[1]);
A
antirez 已提交
1638
        } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
1639
            server.maxmemory = strtoll(argv[1], NULL, 10);
1640
        } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
A
antirez 已提交
1641 1642 1643
            server.masterhost = sdsnew(argv[1]);
            server.masterport = atoi(argv[2]);
            server.replstate = REDIS_REPL_CONNECT;
1644 1645
        } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
        	server.masterauth = zstrdup(argv[1]);
1646
        } else if (!strcasecmp(argv[0],"glueoutputbuf") && argc == 2) {
A
antirez 已提交
1647
            if ((server.glueoutputbuf = yesnotoi(argv[1])) == -1) {
A
antirez 已提交
1648 1649
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
1650
        } else if (!strcasecmp(argv[0],"shareobjects") && argc == 2) {
A
antirez 已提交
1651
            if ((server.shareobjects = yesnotoi(argv[1])) == -1) {
1652 1653
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
1654 1655 1656 1657
        } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
            if ((server.rdbcompression = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
1658 1659 1660 1661 1662
        } else if (!strcasecmp(argv[0],"shareobjectspoolsize") && argc == 2) {
            server.sharingpoolsize = atoi(argv[1]);
            if (server.sharingpoolsize < 1) {
                err = "invalid object sharing pool size"; goto loaderr;
            }
1663
        } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
A
antirez 已提交
1664
            if ((server.daemonize = yesnotoi(argv[1])) == -1) {
A
antirez 已提交
1665 1666
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
1667 1668 1669 1670
        } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
            if ((server.appendonly = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
1671
        } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
1672
            if (!strcasecmp(argv[1],"no")) {
1673
                server.appendfsync = APPENDFSYNC_NO;
1674
            } else if (!strcasecmp(argv[1],"always")) {
1675
                server.appendfsync = APPENDFSYNC_ALWAYS;
1676
            } else if (!strcasecmp(argv[1],"everysec")) {
1677 1678 1679 1680 1681
                server.appendfsync = APPENDFSYNC_EVERYSEC;
            } else {
                err = "argument must be 'no', 'always' or 'everysec'";
                goto loaderr;
            }
1682
        } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
1683
            server.requirepass = zstrdup(argv[1]);
1684
        } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
1685
            server.pidfile = zstrdup(argv[1]);
1686
        } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
1687
            server.dbfilename = zstrdup(argv[1]);
1688 1689 1690 1691
        } else if (!strcasecmp(argv[0],"vm-enabled") && argc == 2) {
            if ((server.vm_enabled = yesnotoi(argv[1])) == -1) {
                err = "argument must be 'yes' or 'no'"; goto loaderr;
            }
1692
        } else if (!strcasecmp(argv[0],"vm-swap-file") && argc == 2) {
1693
            zfree(server.vm_swap_file);
1694
            server.vm_swap_file = zstrdup(argv[1]);
A
antirez 已提交
1695 1696 1697 1698 1699 1700
        } else if (!strcasecmp(argv[0],"vm-max-memory") && argc == 2) {
            server.vm_max_memory = strtoll(argv[1], NULL, 10);
        } else if (!strcasecmp(argv[0],"vm-page-size") && argc == 2) {
            server.vm_page_size = strtoll(argv[1], NULL, 10);
        } else if (!strcasecmp(argv[0],"vm-pages") && argc == 2) {
            server.vm_pages = strtoll(argv[1], NULL, 10);
1701 1702
        } else if (!strcasecmp(argv[0],"vm-max-threads") && argc == 2) {
            server.vm_max_threads = strtoll(argv[1], NULL, 10);
A
antirez 已提交
1703 1704 1705 1706 1707 1708 1709 1710
        } else {
            err = "Bad directive or wrong number of arguments"; goto loaderr;
        }
        for (j = 0; j < argc; j++)
            sdsfree(argv[j]);
        zfree(argv);
        sdsfree(line);
    }
1711
    if (fp != stdin) fclose(fp);
A
antirez 已提交
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
    return;

loaderr:
    fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
    fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
    fprintf(stderr, ">>> '%s'\n", line);
    fprintf(stderr, "%s\n", err);
    exit(1);
}

static void freeClientArgv(redisClient *c) {
    int j;

    for (j = 0; j < c->argc; j++)
        decrRefCount(c->argv[j]);
1727 1728
    for (j = 0; j < c->mbargc; j++)
        decrRefCount(c->mbargv[j]);
A
antirez 已提交
1729
    c->argc = 0;
1730
    c->mbargc = 0;
A
antirez 已提交
1731 1732 1733 1734 1735
}

static void freeClient(redisClient *c) {
    listNode *ln;

A
antirez 已提交
1736
    /* Note that if the client we are freeing is blocked into a blocking
1737 1738 1739 1740
     * call, we have to set querybuf to NULL *before* to call
     * unblockClientWaitingData() to avoid processInputBuffer() will get
     * called. Also it is important to remove the file events after
     * this, because this call adds the READABLE event. */
A
antirez 已提交
1741 1742 1743
    sdsfree(c->querybuf);
    c->querybuf = NULL;
    if (c->flags & REDIS_BLOCKED)
1744
        unblockClientWaitingData(c);
A
antirez 已提交
1745

A
antirez 已提交
1746 1747 1748 1749 1750
    aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
    aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
    listRelease(c->reply);
    freeClientArgv(c);
    close(c->fd);
1751
    /* Remove from the list of clients */
A
antirez 已提交
1752
    ln = listSearchKey(server.clients,c);
1753
    redisAssert(ln != NULL);
A
antirez 已提交
1754
    listDelNode(server.clients,ln);
A
antirez 已提交
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
    /* Remove from the list of clients waiting for swapped keys */
    if (c->flags & REDIS_IO_WAIT && listLength(c->io_keys) == 0) {
        ln = listSearchKey(server.io_ready_clients,c);
        if (ln) {
            listDelNode(server.io_ready_clients,ln);
            server.vm_blocked_clients--;
        }
    }
    while (server.vm_enabled && listLength(c->io_keys)) {
        ln = listFirst(c->io_keys);
        dontWaitForSwappedKey(c,ln->value);
1766
    }
1767
    listRelease(c->io_keys);
1768
    /* Other cleanup */
A
antirez 已提交
1769
    if (c->flags & REDIS_SLAVE) {
1770 1771
        if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
            close(c->repldbfd);
A
antirez 已提交
1772 1773
        list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
        ln = listSearchKey(l,c);
1774
        redisAssert(ln != NULL);
A
antirez 已提交
1775
        listDelNode(l,ln);
A
antirez 已提交
1776 1777 1778 1779 1780
    }
    if (c->flags & REDIS_MASTER) {
        server.master = NULL;
        server.replstate = REDIS_REPL_CONNECT;
    }
1781
    zfree(c->argv);
1782
    zfree(c->mbargv);
A
antirez 已提交
1783
    freeClientMultiState(c);
A
antirez 已提交
1784 1785 1786
    zfree(c);
}

1787
#define GLUEREPLY_UP_TO (1024)
A
antirez 已提交
1788
static void glueReplyBuffersIfNeeded(redisClient *c) {
1789 1790
    int copylen = 0;
    char buf[GLUEREPLY_UP_TO];
1791
    listNode *ln;
A
antirez 已提交
1792
    listIter li;
A
antirez 已提交
1793 1794
    robj *o;

A
antirez 已提交
1795 1796
    listRewind(c->reply,&li);
    while((ln = listNext(&li))) {
1797 1798
        int objlen;

A
antirez 已提交
1799
        o = ln->value;
1800 1801 1802 1803
        objlen = sdslen(o->ptr);
        if (copylen + objlen <= GLUEREPLY_UP_TO) {
            memcpy(buf+copylen,o->ptr,objlen);
            copylen += objlen;
A
antirez 已提交
1804
            listDelNode(c->reply,ln);
1805 1806 1807
        } else {
            if (copylen == 0) return;
            break;
A
antirez 已提交
1808 1809
        }
    }
1810 1811 1812
    /* Now the output buffer is empty, add the new single element */
    o = createObject(REDIS_STRING,sdsnewlen(buf,copylen));
    listAddNodeHead(c->reply,o);
A
antirez 已提交
1813 1814 1815 1816 1817 1818 1819 1820 1821
}

static void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
    redisClient *c = privdata;
    int nwritten = 0, totwritten = 0, objlen;
    robj *o;
    REDIS_NOTUSED(el);
    REDIS_NOTUSED(mask);

1822
    /* Use writev() if we have enough buffers to send */
1823 1824 1825
    if (!server.glueoutputbuf &&
        listLength(c->reply) > REDIS_WRITEV_THRESHOLD && 
        !(c->flags & REDIS_MASTER))
1826 1827 1828 1829 1830
    {
        sendReplyToClientWritev(el, fd, privdata, mask);
        return;
    }

A
antirez 已提交
1831
    while(listLength(c->reply)) {
1832 1833 1834
        if (server.glueoutputbuf && listLength(c->reply) > 1)
            glueReplyBuffersIfNeeded(c);

A
antirez 已提交
1835 1836 1837 1838 1839 1840 1841 1842 1843
        o = listNodeValue(listFirst(c->reply));
        objlen = sdslen(o->ptr);

        if (objlen == 0) {
            listDelNode(c->reply,listFirst(c->reply));
            continue;
        }

        if (c->flags & REDIS_MASTER) {
1844
            /* Don't reply to a master */
A
antirez 已提交
1845 1846
            nwritten = objlen - c->sentlen;
        } else {
A
antirez 已提交
1847
            nwritten = write(fd, ((char*)o->ptr)+c->sentlen, objlen - c->sentlen);
A
antirez 已提交
1848 1849 1850 1851 1852 1853 1854 1855 1856
            if (nwritten <= 0) break;
        }
        c->sentlen += nwritten;
        totwritten += nwritten;
        /* If we fully sent the object on head go to the next one */
        if (c->sentlen == objlen) {
            listDelNode(c->reply,listFirst(c->reply));
            c->sentlen = 0;
        }
1857
        /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
A
antirez 已提交
1858
         * bytes, in a single threaded server it's a good idea to serve
1859 1860
         * other clients as well, even if a very large request comes from
         * super fast link that is always able to accept data (in real world
A
antirez 已提交
1861
         * scenario think about 'KEYS *' against the loopback interfae) */
1862
        if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
A
antirez 已提交
1863 1864 1865 1866 1867
    }
    if (nwritten == -1) {
        if (errno == EAGAIN) {
            nwritten = 0;
        } else {
1868
            redisLog(REDIS_VERBOSE,
A
antirez 已提交
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
                "Error writing to client: %s", strerror(errno));
            freeClient(c);
            return;
        }
    }
    if (totwritten > 0) c->lastinteraction = time(NULL);
    if (listLength(c->reply) == 0) {
        c->sentlen = 0;
        aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
    }
}

1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
static void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
{
    redisClient *c = privdata;
    int nwritten = 0, totwritten = 0, objlen, willwrite;
    robj *o;
    struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
    int offset, ion = 0;
    REDIS_NOTUSED(el);
    REDIS_NOTUSED(mask);

    listNode *node;
    while (listLength(c->reply)) {
        offset = c->sentlen;
        ion = 0;
        willwrite = 0;

        /* fill-in the iov[] array */
        for(node = listFirst(c->reply); node; node = listNextNode(node)) {
            o = listNodeValue(node);
            objlen = sdslen(o->ptr);

            if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT) 
                break;

            if(ion == REDIS_WRITEV_IOVEC_COUNT)
                break; /* no more iovecs */

            iov[ion].iov_base = ((char*)o->ptr) + offset;
            iov[ion].iov_len = objlen - offset;
            willwrite += objlen - offset;
            offset = 0; /* just for the first item */
            ion++;
        }

        if(willwrite == 0)
            break;

        /* write all collected blocks at once */
        if((nwritten = writev(fd, iov, ion)) < 0) {
            if (errno != EAGAIN) {
1921
                redisLog(REDIS_VERBOSE,
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
                         "Error writing to client: %s", strerror(errno));
                freeClient(c);
                return;
            }
            break;
        }

        totwritten += nwritten;
        offset = c->sentlen;

        /* remove written robjs from c->reply */
        while (nwritten && listLength(c->reply)) {
            o = listNodeValue(listFirst(c->reply));
            objlen = sdslen(o->ptr);

            if(nwritten >= objlen - offset) {
                listDelNode(c->reply, listFirst(c->reply));
                nwritten -= objlen - offset;
                c->sentlen = 0;
            } else {
                /* partial write */
                c->sentlen += nwritten;
                break;
            }
            offset = 0;
        }
    }

    if (totwritten > 0) 
        c->lastinteraction = time(NULL);

    if (listLength(c->reply) == 0) {
        c->sentlen = 0;
        aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
    }
}

A
antirez 已提交
1959 1960 1961
static struct redisCommand *lookupCommand(char *name) {
    int j = 0;
    while(cmdTable[j].name != NULL) {
1962
        if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];
A
antirez 已提交
1963 1964 1965 1966 1967 1968 1969 1970 1971
        j++;
    }
    return NULL;
}

/* resetClient prepare the client to process the next command */
static void resetClient(redisClient *c) {
    freeClientArgv(c);
    c->bulklen = -1;
1972
    c->multibulk = 0;
A
antirez 已提交
1973 1974
}

A
antirez 已提交
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
/* Call() is the core of Redis execution of a command */
static void call(redisClient *c, struct redisCommand *cmd) {
    long long dirty;

    dirty = server.dirty;
    cmd->proc(c);
    if (server.appendonly && server.dirty-dirty)
        feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
    if (server.dirty-dirty && listLength(server.slaves))
        replicationFeedSlaves(server.slaves,cmd,c->db->id,c->argv,c->argc);
    if (listLength(server.monitors))
        replicationFeedSlaves(server.monitors,cmd,c->db->id,c->argv,c->argc);
    server.stat_numcommands++;
}

A
antirez 已提交
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
/* If this function gets called we already read a whole
 * command, argments are in the client argv/argc fields.
 * processCommand() execute the command or prepare the
 * server for a bulk read from the client.
 *
 * If 1 is returned the client is still alive and valid and
 * and other operations can be performed by the caller. Otherwise
 * if 0 is returned the client was destroied (i.e. after QUIT). */
static int processCommand(redisClient *c) {
    struct redisCommand *cmd;

A
antirez 已提交
2001 2002 2003
    /* Free some memory if needed (maxmemory setting) */
    if (server.maxmemory) freeMemoryIfNeeded();

2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
    /* Handle the multi bulk command type. This is an alternative protocol
     * supported by Redis in order to receive commands that are composed of
     * multiple binary-safe "bulk" arguments. The latency of processing is
     * a bit higher but this allows things like multi-sets, so if this
     * protocol is used only for MSET and similar commands this is a big win. */
    if (c->multibulk == 0 && c->argc == 1 && ((char*)(c->argv[0]->ptr))[0] == '*') {
        c->multibulk = atoi(((char*)c->argv[0]->ptr)+1);
        if (c->multibulk <= 0) {
            resetClient(c);
            return 1;
        } else {
            decrRefCount(c->argv[c->argc-1]);
            c->argc--;
            return 1;
        }
    } else if (c->multibulk) {
        if (c->bulklen == -1) {
            if (((char*)c->argv[0]->ptr)[0] != '$') {
                addReplySds(c,sdsnew("-ERR multi bulk protocol error\r\n"));
                resetClient(c);
                return 1;
            } else {
                int bulklen = atoi(((char*)c->argv[0]->ptr)+1);
                decrRefCount(c->argv[0]);
                if (bulklen < 0 || bulklen > 1024*1024*1024) {
                    c->argc--;
                    addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
                    resetClient(c);
                    return 1;
                }
                c->argc--;
                c->bulklen = bulklen+2; /* add two bytes for CR+LF */
                return 1;
            }
        } else {
            c->mbargv = zrealloc(c->mbargv,(sizeof(robj*))*(c->mbargc+1));
            c->mbargv[c->mbargc] = c->argv[0];
            c->mbargc++;
            c->argc--;
            c->multibulk--;
            if (c->multibulk == 0) {
                robj **auxargv;
                int auxargc;

                /* Here we need to swap the multi-bulk argc/argv with the
                 * normal argc/argv of the client structure. */
                auxargv = c->argv;
                c->argv = c->mbargv;
                c->mbargv = auxargv;

                auxargc = c->argc;
                c->argc = c->mbargc;
                c->mbargc = auxargc;

                /* We need to set bulklen to something different than -1
                 * in order for the code below to process the command without
                 * to try to read the last argument of a bulk command as
                 * a special argument. */
                c->bulklen = 0;
                /* continue below and process the command */
            } else {
                c->bulklen = -1;
                return 1;
            }
        }
    }
    /* -- end of multi bulk commands processing -- */

A
antirez 已提交
2072 2073
    /* The QUIT command is handled as a special case. Normal command
     * procs are unable to close the client connection safely */
2074
    if (!strcasecmp(c->argv[0]->ptr,"quit")) {
A
antirez 已提交
2075 2076 2077
        freeClient(c);
        return 0;
    }
A
antirez 已提交
2078 2079 2080

    /* Now lookup the command and check ASAP about trivial error conditions
     * such wrong arity, bad command name and so forth. */
A
antirez 已提交
2081 2082
    cmd = lookupCommand(c->argv[0]->ptr);
    if (!cmd) {
2083 2084 2085
        addReplySds(c,
            sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
                (char*)c->argv[0]->ptr));
A
antirez 已提交
2086 2087 2088 2089
        resetClient(c);
        return 1;
    } else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
               (c->argc < -cmd->arity)) {
2090 2091 2092 2093
        addReplySds(c,
            sdscatprintf(sdsempty(),
                "-ERR wrong number of arguments for '%s' command\r\n",
                cmd->name));
A
antirez 已提交
2094 2095
        resetClient(c);
        return 1;
A
antirez 已提交
2096 2097 2098 2099
    } else if (server.maxmemory && cmd->flags & REDIS_CMD_DENYOOM && zmalloc_used_memory() > server.maxmemory) {
        addReplySds(c,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
        resetClient(c);
        return 1;
A
antirez 已提交
2100
    } else if (cmd->flags & REDIS_CMD_BULK && c->bulklen == -1) {
A
antirez 已提交
2101
        /* This is a bulk command, we have to read the last argument yet. */
A
antirez 已提交
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
        int bulklen = atoi(c->argv[c->argc-1]->ptr);

        decrRefCount(c->argv[c->argc-1]);
        if (bulklen < 0 || bulklen > 1024*1024*1024) {
            c->argc--;
            addReplySds(c,sdsnew("-ERR invalid bulk write count\r\n"));
            resetClient(c);
            return 1;
        }
        c->argc--;
        c->bulklen = bulklen+2; /* add two bytes for CR+LF */
        /* It is possible that the bulk read is already in the
A
antirez 已提交
2114 2115 2116 2117
         * buffer. Check this condition and handle it accordingly.
         * This is just a fast path, alternative to call processInputBuffer().
         * It's a good idea since the code is small and this condition
         * happens most of the times. */
A
antirez 已提交
2118 2119 2120 2121 2122
        if ((signed)sdslen(c->querybuf) >= c->bulklen) {
            c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
            c->argc++;
            c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
        } else {
A
antirez 已提交
2123 2124
            /* Otherwise return... there is to read the last argument
             * from the socket. */
A
antirez 已提交
2125 2126 2127
            return 1;
        }
    }
2128 2129 2130 2131 2132 2133
    /* Let's try to share objects on the command arguments vector */
    if (server.shareobjects) {
        int j;
        for(j = 1; j < c->argc; j++)
            c->argv[j] = tryObjectSharing(c->argv[j]);
    }
2134 2135 2136 2137
    /* Let's try to encode the bulk object to save space. */
    if (cmd->flags & REDIS_CMD_BULK)
        tryObjectEncoding(c->argv[c->argc-1]);

2138 2139 2140 2141 2142 2143 2144
    /* Check if the user is authenticated */
    if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
        addReplySds(c,sdsnew("-ERR operation not permitted\r\n"));
        resetClient(c);
        return 1;
    }

A
antirez 已提交
2145
    /* Exec the command */
2146
    if (c->flags & REDIS_MULTI && cmd->proc != execCommand && cmd->proc != discardCommand) {
A
antirez 已提交
2147 2148 2149
        queueMultiCommand(c,cmd);
        addReply(c,shared.queued);
    } else {
A
antirez 已提交
2150 2151
        if (server.vm_enabled && server.vm_max_threads > 0 &&
            blockClientOnSwappedKeys(cmd,c)) return 1;
A
antirez 已提交
2152 2153
        call(c,cmd);
    }
A
antirez 已提交
2154 2155 2156 2157 2158 2159

    /* Prepare the client for the next command */
    resetClient(c);
    return 1;
}

A
antirez 已提交
2160
static void replicationFeedSlaves(list *slaves, struct redisCommand *cmd, int dictid, robj **argv, int argc) {
2161
    listNode *ln;
A
antirez 已提交
2162
    listIter li;
A
antirez 已提交
2163
    int outc = 0, j;
2164 2165 2166 2167 2168 2169 2170 2171 2172
    robj **outv;
    /* (args*2)+1 is enough room for args, spaces, newlines */
    robj *static_outv[REDIS_STATIC_ARGS*2+1];

    if (argc <= REDIS_STATIC_ARGS) {
        outv = static_outv;
    } else {
        outv = zmalloc(sizeof(robj*)*(argc*2+1));
    }
A
antirez 已提交
2173 2174 2175 2176 2177 2178 2179
    
    for (j = 0; j < argc; j++) {
        if (j != 0) outv[outc++] = shared.space;
        if ((cmd->flags & REDIS_CMD_BULK) && j == argc-1) {
            robj *lenobj;

            lenobj = createObject(REDIS_STRING,
2180
                sdscatprintf(sdsempty(),"%lu\r\n",
A
antirez 已提交
2181
                    (unsigned long) stringObjectLen(argv[j])));
A
antirez 已提交
2182 2183 2184 2185 2186 2187 2188
            lenobj->refcount = 0;
            outv[outc++] = lenobj;
        }
        outv[outc++] = argv[j];
    }
    outv[outc++] = shared.crlf;

2189 2190 2191 2192
    /* Increment all the refcounts at start and decrement at end in order to
     * be sure to free objects if there is no slave in a replication state
     * able to be feed with commands */
    for (j = 0; j < outc; j++) incrRefCount(outv[j]);
A
antirez 已提交
2193 2194
    listRewind(slaves,&li);
    while((ln = listNext(&li))) {
A
antirez 已提交
2195
        redisClient *slave = ln->value;
2196 2197

        /* Don't feed slaves that are still waiting for BGSAVE to start */
2198
        if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) continue;
2199 2200

        /* Feed all the other slaves, MONITORs and so on */
A
antirez 已提交
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
        if (slave->slaveseldb != dictid) {
            robj *selectcmd;

            switch(dictid) {
            case 0: selectcmd = shared.select0; break;
            case 1: selectcmd = shared.select1; break;
            case 2: selectcmd = shared.select2; break;
            case 3: selectcmd = shared.select3; break;
            case 4: selectcmd = shared.select4; break;
            case 5: selectcmd = shared.select5; break;
            case 6: selectcmd = shared.select6; break;
            case 7: selectcmd = shared.select7; break;
            case 8: selectcmd = shared.select8; break;
            case 9: selectcmd = shared.select9; break;
            default:
                selectcmd = createObject(REDIS_STRING,
                    sdscatprintf(sdsempty(),"select %d\r\n",dictid));
                selectcmd->refcount = 0;
                break;
            }
            addReply(slave,selectcmd);
            slave->slaveseldb = dictid;
        }
        for (j = 0; j < outc; j++) addReply(slave,outv[j]);
    }
2226
    for (j = 0; j < outc; j++) decrRefCount(outv[j]);
2227
    if (outv != static_outv) zfree(outv);
A
antirez 已提交
2228 2229
}

A
antirez 已提交
2230
static void processInputBuffer(redisClient *c) {
A
antirez 已提交
2231
again:
A
antirez 已提交
2232 2233 2234 2235 2236 2237
    /* Before to process the input buffer, make sure the client is not
     * waitig for a blocking operation such as BLPOP. Note that the first
     * iteration the client is never blocked, otherwise the processInputBuffer
     * would not be called at all, but after the execution of the first commands
     * in the input buffer the client may be blocked, and the "goto again"
     * will try to reiterate. The following line will make it return asap. */
2238
    if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
A
antirez 已提交
2239 2240 2241 2242
    if (c->bulklen == -1) {
        /* Read the first line of the query */
        char *p = strchr(c->querybuf,'\n');
        size_t querylen;
2243

A
antirez 已提交
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
        if (p) {
            sds query, *argv;
            int argc, j;
            
            query = c->querybuf;
            c->querybuf = sdsempty();
            querylen = 1+(p-(query));
            if (sdslen(query) > querylen) {
                /* leave data after the first line of the query in the buffer */
                c->querybuf = sdscatlen(c->querybuf,query+querylen,sdslen(query)-querylen);
            }
            *p = '\0'; /* remove "\n" */
            if (*(p-1) == '\r') *(p-1) = '\0'; /* and "\r" if any */
            sdsupdatelen(query);

            /* Now we can split the query in arguments */
            argv = sdssplitlen(query,sdslen(query)," ",1,&argc);
2261 2262 2263 2264 2265 2266
            sdsfree(query);

            if (c->argv) zfree(c->argv);
            c->argv = zmalloc(sizeof(robj*)*argc);

            for (j = 0; j < argc; j++) {
A
antirez 已提交
2267 2268 2269 2270 2271 2272 2273 2274
                if (sdslen(argv[j])) {
                    c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
                    c->argc++;
                } else {
                    sdsfree(argv[j]);
                }
            }
            zfree(argv);
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
            if (c->argc) {
                /* Execute the command. If the client is still valid
                 * after processCommand() return and there is something
                 * on the query buffer try to process the next command. */
                if (processCommand(c) && sdslen(c->querybuf)) goto again;
            } else {
                /* Nothing to process, argc == 0. Just process the query
                 * buffer if it's not empty or return to the caller */
                if (sdslen(c->querybuf)) goto again;
            }
A
antirez 已提交
2285
            return;
2286
        } else if (sdslen(c->querybuf) >= REDIS_REQUEST_MAX_SIZE) {
2287
            redisLog(REDIS_VERBOSE, "Client protocol error");
A
antirez 已提交
2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
            freeClient(c);
            return;
        }
    } else {
        /* Bulk read handling. Note that if we are at this point
           the client already sent a command terminated with a newline,
           we are reading the bulk data that is actually the last
           argument of the command. */
        int qbl = sdslen(c->querybuf);

        if (c->bulklen <= qbl) {
            /* Copy everything but the final CRLF as final argument */
            c->argv[c->argc] = createStringObject(c->querybuf,c->bulklen-2);
            c->argc++;
            c->querybuf = sdsrange(c->querybuf,c->bulklen,-1);
A
antirez 已提交
2303 2304 2305 2306
            /* Process the command. If the client is still valid after
             * the processing and there is more data in the buffer
             * try to parse it. */
            if (processCommand(c) && sdslen(c->querybuf)) goto again;
A
antirez 已提交
2307 2308 2309 2310 2311
            return;
        }
    }
}

A
antirez 已提交
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
static void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
    redisClient *c = (redisClient*) privdata;
    char buf[REDIS_IOBUF_LEN];
    int nread;
    REDIS_NOTUSED(el);
    REDIS_NOTUSED(mask);

    nread = read(fd, buf, REDIS_IOBUF_LEN);
    if (nread == -1) {
        if (errno == EAGAIN) {
            nread = 0;
        } else {
2324
            redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
A
antirez 已提交
2325 2326 2327 2328
            freeClient(c);
            return;
        }
    } else if (nread == 0) {
2329
        redisLog(REDIS_VERBOSE, "Client closed connection");
A
antirez 已提交
2330 2331 2332 2333 2334 2335 2336 2337 2338
        freeClient(c);
        return;
    }
    if (nread) {
        c->querybuf = sdscatlen(c->querybuf, buf, nread);
        c->lastinteraction = time(NULL);
    } else {
        return;
    }
2339 2340
    if (!(c->flags & REDIS_BLOCKED))
        processInputBuffer(c);
A
antirez 已提交
2341 2342
}

A
antirez 已提交
2343 2344 2345
static int selectDb(redisClient *c, int id) {
    if (id < 0 || id >= server.dbnum)
        return REDIS_ERR;
A
antirez 已提交
2346
    c->db = &server.db[id];
A
antirez 已提交
2347 2348 2349
    return REDIS_OK;
}

2350 2351
static void *dupClientReplyValue(void *o) {
    incrRefCount((robj*)o);
2352
    return o;
2353 2354
}

A
antirez 已提交
2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
static redisClient *createClient(int fd) {
    redisClient *c = zmalloc(sizeof(*c));

    anetNonBlock(NULL,fd);
    anetTcpNoDelay(NULL,fd);
    if (!c) return NULL;
    selectDb(c,0);
    c->fd = fd;
    c->querybuf = sdsempty();
    c->argc = 0;
2365
    c->argv = NULL;
A
antirez 已提交
2366
    c->bulklen = -1;
2367 2368 2369
    c->multibulk = 0;
    c->mbargc = 0;
    c->mbargv = NULL;
A
antirez 已提交
2370 2371 2372
    c->sentlen = 0;
    c->flags = 0;
    c->lastinteraction = time(NULL);
B
Brian Hammond 已提交
2373
    c->authenticated = 0;
2374
    c->replstate = REDIS_REPL_NONE;
2375
    c->reply = listCreate();
A
antirez 已提交
2376
    listSetFreeMethod(c->reply,decrRefCount);
2377
    listSetDupMethod(c->reply,dupClientReplyValue);
2378 2379 2380 2381
    c->blockingkeys = NULL;
    c->blockingkeysnum = 0;
    c->io_keys = listCreate();
    listSetFreeMethod(c->io_keys,decrRefCount);
A
antirez 已提交
2382
    if (aeCreateFileEvent(server.el, c->fd, AE_READABLE,
2383
        readQueryFromClient, c) == AE_ERR) {
A
antirez 已提交
2384 2385 2386
        freeClient(c);
        return NULL;
    }
2387
    listAddNodeTail(server.clients,c);
A
antirez 已提交
2388
    initClientMultiState(c);
A
antirez 已提交
2389 2390 2391 2392 2393
    return c;
}

static void addReply(redisClient *c, robj *obj) {
    if (listLength(c->reply) == 0 &&
2394 2395
        (c->replstate == REDIS_REPL_NONE ||
         c->replstate == REDIS_REPL_ONLINE) &&
A
antirez 已提交
2396
        aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
2397
        sendReplyToClient, c) == AE_ERR) return;
2398 2399 2400 2401 2402

    if (server.vm_enabled && obj->storage != REDIS_VM_MEMORY) {
        obj = dupStringObject(obj);
        obj->refcount = 0; /* getDecodedObject() will increment the refcount */
    }
2403
    listAddNodeTail(c->reply,getDecodedObject(obj));
A
antirez 已提交
2404 2405 2406 2407 2408 2409 2410 2411
}

static void addReplySds(redisClient *c, sds s) {
    robj *o = createObject(REDIS_STRING,s);
    addReply(c,o);
    decrRefCount(o);
}

A
antirez 已提交
2412 2413 2414 2415
static void addReplyDouble(redisClient *c, double d) {
    char buf[128];

    snprintf(buf,sizeof(buf),"%.17g",d);
2416
    addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
A
antirez 已提交
2417
        (unsigned long) strlen(buf),buf));
A
antirez 已提交
2418 2419
}

2420 2421 2422 2423 2424 2425 2426 2427
static void addReplyLong(redisClient *c, long l) {
    char buf[128];
    size_t len;

    len = snprintf(buf,sizeof(buf),":%ld\r\n",l);
    addReplySds(c,sdsnewlen(buf,len));
}

2428 2429 2430 2431 2432 2433 2434 2435
static void addReplyBulkLen(redisClient *c, robj *obj) {
    size_t len;

    if (obj->encoding == REDIS_ENCODING_RAW) {
        len = sdslen(obj->ptr);
    } else {
        long n = (long)obj->ptr;

2436
        /* Compute how many bytes will take this integer as a radix 10 string */
2437 2438 2439 2440 2441 2442 2443 2444 2445
        len = 1;
        if (n < 0) {
            len++;
            n = -n;
        }
        while((n = n/10) != 0) {
            len++;
        }
    }
A
antirez 已提交
2446
    addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len));
2447 2448
}

A
antirez 已提交
2449 2450 2451
static void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
    int cport, cfd;
    char cip[128];
2452
    redisClient *c;
A
antirez 已提交
2453 2454 2455 2456 2457 2458
    REDIS_NOTUSED(el);
    REDIS_NOTUSED(mask);
    REDIS_NOTUSED(privdata);

    cfd = anetAccept(server.neterr, fd, cip, &cport);
    if (cfd == AE_ERR) {
2459
        redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
A
antirez 已提交
2460 2461
        return;
    }
2462
    redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
2463
    if ((c = createClient(cfd)) == NULL) {
A
antirez 已提交
2464 2465 2466 2467
        redisLog(REDIS_WARNING,"Error allocating resoures for the client");
        close(cfd); /* May be already closed, just ingore errors */
        return;
    }
2468 2469 2470 2471 2472 2473 2474 2475
    /* If maxclient directive is set and this is one client more... close the
     * connection. Note that we create the client instead to check before
     * for this condition, since now the socket is already set in nonblocking
     * mode and we can send an error for free using the Kernel I/O */
    if (server.maxclients && listLength(server.clients) > server.maxclients) {
        char *err = "-ERR max number of clients reached\r\n";

        /* That's a best effort error message, don't check write errors */
2476 2477 2478
        if (write(c->fd,err,strlen(err)) == -1) {
            /* Nothing to do, Just to avoid the warning... */
        }
2479 2480 2481
        freeClient(c);
        return;
    }
A
antirez 已提交
2482 2483 2484 2485 2486 2487 2488 2489
    server.stat_numconnections++;
}

/* ======================= Redis objects implementation ===================== */

static robj *createObject(int type, void *ptr) {
    robj *o;

2490
    if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
A
antirez 已提交
2491 2492 2493 2494
    if (listLength(server.objfreelist)) {
        listNode *head = listFirst(server.objfreelist);
        o = listNodeValue(head);
        listDelNode(server.objfreelist,head);
2495
        if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
A
antirez 已提交
2496
    } else {
2497
        if (server.vm_enabled) {
2498
            pthread_mutex_unlock(&server.obj_freelist_mutex);
2499 2500 2501 2502
            o = zmalloc(sizeof(*o));
        } else {
            o = zmalloc(sizeof(*o)-sizeof(struct redisObjectVM));
        }
A
antirez 已提交
2503 2504
    }
    o->type = type;
2505
    o->encoding = REDIS_ENCODING_RAW;
A
antirez 已提交
2506 2507
    o->ptr = ptr;
    o->refcount = 1;
A
antirez 已提交
2508
    if (server.vm_enabled) {
A
antirez 已提交
2509 2510 2511 2512
        /* Note that this code may run in the context of an I/O thread
         * and accessing to server.unixtime in theory is an error
         * (no locks). But in practice this is safe, and even if we read
         * garbage Redis will not fail, as it's just a statistical info */
A
antirez 已提交
2513 2514 2515
        o->vm.atime = server.unixtime;
        o->storage = REDIS_VM_MEMORY;
    }
A
antirez 已提交
2516 2517 2518 2519 2520 2521 2522
    return o;
}

static robj *createStringObject(char *ptr, size_t len) {
    return createObject(REDIS_STRING,sdsnewlen(ptr,len));
}

A
antirez 已提交
2523
static robj *dupStringObject(robj *o) {
2524
    assert(o->encoding == REDIS_ENCODING_RAW);
A
antirez 已提交
2525 2526 2527
    return createStringObject(o->ptr,sdslen(o->ptr));
}

A
antirez 已提交
2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
static robj *createListObject(void) {
    list *l = listCreate();

    listSetFreeMethod(l,decrRefCount);
    return createObject(REDIS_LIST,l);
}

static robj *createSetObject(void) {
    dict *d = dictCreate(&setDictType,NULL);
    return createObject(REDIS_SET,d);
}

2540
static robj *createZsetObject(void) {
2541 2542 2543 2544 2545
    zset *zs = zmalloc(sizeof(*zs));

    zs->dict = dictCreate(&zsetDictType,NULL);
    zs->zsl = zslCreate();
    return createObject(REDIS_ZSET,zs);
2546 2547
}

A
antirez 已提交
2548
static void freeStringObject(robj *o) {
2549 2550 2551
    if (o->encoding == REDIS_ENCODING_RAW) {
        sdsfree(o->ptr);
    }
A
antirez 已提交
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
}

static void freeListObject(robj *o) {
    listRelease((list*) o->ptr);
}

static void freeSetObject(robj *o) {
    dictRelease((dict*) o->ptr);
}

2562 2563 2564 2565 2566 2567 2568 2569
static void freeZsetObject(robj *o) {
    zset *zs = o->ptr;

    dictRelease(zs->dict);
    zslFree(zs->zsl);
    zfree(zs);
}

A
antirez 已提交
2570 2571 2572 2573 2574
static void freeHashObject(robj *o) {
    dictRelease((dict*) o->ptr);
}

static void incrRefCount(robj *o) {
2575
    redisAssert(!server.vm_enabled || o->storage == REDIS_VM_MEMORY);
A
antirez 已提交
2576 2577 2578 2579 2580
    o->refcount++;
}

static void decrRefCount(void *obj) {
    robj *o = obj;
2581

2582 2583
    /* Object is a key of a swapped out value, or in the process of being
     * loaded. */
2584 2585 2586 2587 2588 2589 2590
    if (server.vm_enabled &&
        (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING))
    {
        if (o->storage == REDIS_VM_SWAPPED || o->storage == REDIS_VM_LOADING) {
            redisAssert(o->refcount == 1);
        }
        if (o->storage == REDIS_VM_LOADING) vmCancelThreadedIOJob(obj);
2591
        redisAssert(o->type == REDIS_STRING);
A
antirez 已提交
2592 2593
        freeStringObject(o);
        vmMarkPagesFree(o->vm.page,o->vm.usedpages);
2594
        pthread_mutex_lock(&server.obj_freelist_mutex);
A
antirez 已提交
2595 2596 2597
        if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
            !listAddNodeHead(server.objfreelist,o))
            zfree(o);
2598
        pthread_mutex_unlock(&server.obj_freelist_mutex);
A
antirez 已提交
2599
        server.vm_stats_swapped_objects--;
A
antirez 已提交
2600 2601
        return;
    }
2602
    /* Object is in memory, or in the process of being swapped out. */
A
antirez 已提交
2603
    if (--(o->refcount) == 0) {
2604 2605
        if (server.vm_enabled && o->storage == REDIS_VM_SWAPPING)
            vmCancelThreadedIOJob(obj);
A
antirez 已提交
2606 2607 2608 2609
        switch(o->type) {
        case REDIS_STRING: freeStringObject(o); break;
        case REDIS_LIST: freeListObject(o); break;
        case REDIS_SET: freeSetObject(o); break;
2610
        case REDIS_ZSET: freeZsetObject(o); break;
A
antirez 已提交
2611
        case REDIS_HASH: freeHashObject(o); break;
2612
        default: redisAssert(0 != 0); break;
A
antirez 已提交
2613
        }
2614
        if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
A
antirez 已提交
2615 2616 2617
        if (listLength(server.objfreelist) > REDIS_OBJFREELIST_MAX ||
            !listAddNodeHead(server.objfreelist,o))
            zfree(o);
2618
        if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
A
antirez 已提交
2619 2620 2621
    }
}

2622 2623
static robj *lookupKey(redisDb *db, robj *key) {
    dictEntry *de = dictFind(db->dict,key);
A
antirez 已提交
2624
    if (de) {
A
antirez 已提交
2625 2626
        robj *key = dictGetEntryKey(de);
        robj *val = dictGetEntryVal(de);
A
antirez 已提交
2627

A
antirez 已提交
2628
        if (server.vm_enabled) {
2629 2630 2631 2632 2633 2634 2635
            if (key->storage == REDIS_VM_MEMORY ||
                key->storage == REDIS_VM_SWAPPING)
            {
                /* If we were swapping the object out, stop it, this key
                 * was requested. */
                if (key->storage == REDIS_VM_SWAPPING)
                    vmCancelThreadedIOJob(key);
A
antirez 已提交
2636 2637 2638
                /* Update the access time of the key for the aging algorithm. */
                key->vm.atime = server.unixtime;
            } else {
A
antirez 已提交
2639 2640
                int notify = (key->storage == REDIS_VM_LOADING);

A
antirez 已提交
2641
                /* Our value was swapped on disk. Bring it at home. */
2642
                redisAssert(val == NULL);
A
antirez 已提交
2643 2644
                val = vmLoadObject(key);
                dictGetEntryVal(de) = val;
A
antirez 已提交
2645 2646 2647 2648

                /* Clients blocked by the VM subsystem may be waiting for
                 * this key... */
                if (notify) handleClientsBlockedOnSwappedKey(db,key);
A
antirez 已提交
2649 2650 2651
            }
        }
        return val;
A
antirez 已提交
2652 2653 2654
    } else {
        return NULL;
    }
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
}

static robj *lookupKeyRead(redisDb *db, robj *key) {
    expireIfNeeded(db,key);
    return lookupKey(db,key);
}

static robj *lookupKeyWrite(redisDb *db, robj *key) {
    deleteIfVolatile(db,key);
    return lookupKey(db,key);
}

static int deleteKey(redisDb *db, robj *key) {
    int retval;

    /* We need to protect key from destruction: after the first dictDelete()
     * it may happen that 'key' is no longer valid if we don't increment
     * it's count. This may happen when we get the object reference directly
     * from the hash table with dictRandomKey() or dict iterators */
    incrRefCount(key);
    if (dictSize(db->expires)) dictDelete(db->expires,key);
    retval = dictDelete(db->dict,key);
    decrRefCount(key);

    return retval == DICT_OK;
}

2682 2683 2684 2685 2686
/* Try to share an object against the shared objects pool */
static robj *tryObjectSharing(robj *o) {
    struct dictEntry *de;
    unsigned long c;

A
antirez 已提交
2687
    if (o == NULL || server.shareobjects == 0) return o;
2688

2689
    redisAssert(o->type == REDIS_STRING);
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
    de = dictFind(server.sharingpool,o);
    if (de) {
        robj *shared = dictGetEntryKey(de);

        c = ((unsigned long) dictGetEntryVal(de))+1;
        dictGetEntryVal(de) = (void*) c;
        incrRefCount(shared);
        decrRefCount(o);
        return shared;
    } else {
        /* Here we are using a stream algorihtm: Every time an object is
         * shared we increment its count, everytime there is a miss we
         * recrement the counter of a random object. If this object reaches
         * zero we remove the object and put the current object instead. */
A
antirez 已提交
2704
        if (dictSize(server.sharingpool) >=
2705 2706
                server.sharingpoolsize) {
            de = dictGetRandomKey(server.sharingpool);
2707
            redisAssert(de != NULL);
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
            c = ((unsigned long) dictGetEntryVal(de))-1;
            dictGetEntryVal(de) = (void*) c;
            if (c == 0) {
                dictDelete(server.sharingpool,de->key);
            }
        } else {
            c = 0; /* If the pool is empty we want to add this object */
        }
        if (c == 0) {
            int retval;

            retval = dictAdd(server.sharingpool,o,(void*)1);
2720
            redisAssert(retval == DICT_OK);
2721 2722 2723 2724 2725 2726
            incrRefCount(o);
        }
        return o;
    }
}

2727 2728 2729 2730 2731 2732
/* Check if the nul-terminated string 's' can be represented by a long
 * (that is, is a number that fits into long without any other space or
 * character before or after the digits).
 *
 * If so, the function returns REDIS_OK and *longval is set to the value
 * of the number. Otherwise REDIS_ERR is returned */
2733
static int isStringRepresentableAsLong(sds s, long *longval) {
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
    char buf[32], *endptr;
    long value;
    int slen;
    
    value = strtol(s, &endptr, 10);
    if (endptr[0] != '\0') return REDIS_ERR;
    slen = snprintf(buf,32,"%ld",value);

    /* If the number converted back into a string is not identical
     * then it's not possible to encode the string as integer */
2744
    if (sdslen(s) != (unsigned)slen || memcmp(buf,s,slen)) return REDIS_ERR;
2745 2746 2747 2748
    if (longval) *longval = value;
    return REDIS_OK;
}

2749 2750 2751 2752
/* Try to encode a string object in order to save space */
static int tryObjectEncoding(robj *o) {
    long value;
    sds s = o->ptr;
A
antirez 已提交
2753

2754 2755
    if (o->encoding != REDIS_ENCODING_RAW)
        return REDIS_ERR; /* Already encoded */
A
antirez 已提交
2756

2757 2758 2759 2760
    /* It's not save to encode shared objects: shared objects can be shared
     * everywhere in the "object space" of Redis. Encoded objects can only
     * appear as "values" (and not, for instance, as keys) */
     if (o->refcount > 1) return REDIS_ERR;
A
antirez 已提交
2761

2762
    /* Currently we try to encode only strings */
2763
    redisAssert(o->type == REDIS_STRING);
2764

2765 2766
    /* Check if we can represent this string as a long integer */
    if (isStringRepresentableAsLong(s,&value) == REDIS_ERR) return REDIS_ERR;
2767 2768 2769 2770 2771 2772 2773 2774

    /* Ok, this object can be encoded */
    o->encoding = REDIS_ENCODING_INT;
    sdsfree(o->ptr);
    o->ptr = (void*) value;
    return REDIS_OK;
}

2775 2776 2777
/* Get a decoded version of an encoded object (returned as a new object).
 * If the object is already raw-encoded just increment the ref count. */
static robj *getDecodedObject(robj *o) {
2778 2779
    robj *dec;
    
2780 2781 2782 2783
    if (o->encoding == REDIS_ENCODING_RAW) {
        incrRefCount(o);
        return o;
    }
2784 2785 2786 2787 2788 2789 2790
    if (o->type == REDIS_STRING && o->encoding == REDIS_ENCODING_INT) {
        char buf[32];

        snprintf(buf,32,"%ld",(long)o->ptr);
        dec = createStringObject(buf,strlen(buf));
        return dec;
    } else {
2791
        redisAssert(1 != 1);
2792
    }
A
antirez 已提交
2793 2794
}

2795 2796 2797
/* Compare two string objects via strcmp() or alike.
 * Note that the objects may be integer-encoded. In such a case we
 * use snprintf() to get a string representation of the numbers on the stack
2798 2799 2800 2801 2802
 * and compare the strings, it's much faster than calling getDecodedObject().
 *
 * Important note: if objects are not integer encoded, but binary-safe strings,
 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
 * binary safe. */
2803
static int compareStringObjects(robj *a, robj *b) {
2804
    redisAssert(a->type == REDIS_STRING && b->type == REDIS_STRING);
2805 2806
    char bufa[128], bufb[128], *astr, *bstr;
    int bothsds = 1;
2807

2808
    if (a == b) return 0;
2809 2810 2811 2812
    if (a->encoding != REDIS_ENCODING_RAW) {
        snprintf(bufa,sizeof(bufa),"%ld",(long) a->ptr);
        astr = bufa;
        bothsds = 0;
2813
    } else {
2814
        astr = a->ptr;
2815
    }
2816 2817 2818 2819 2820 2821 2822 2823
    if (b->encoding != REDIS_ENCODING_RAW) {
        snprintf(bufb,sizeof(bufb),"%ld",(long) b->ptr);
        bstr = bufb;
        bothsds = 0;
    } else {
        bstr = b->ptr;
    }
    return bothsds ? sdscmp(astr,bstr) : strcmp(astr,bstr);
2824 2825
}

2826
static size_t stringObjectLen(robj *o) {
2827
    redisAssert(o->type == REDIS_STRING);
2828 2829 2830 2831 2832 2833 2834 2835 2836
    if (o->encoding == REDIS_ENCODING_RAW) {
        return sdslen(o->ptr);
    } else {
        char buf[32];

        return snprintf(buf,32,"%ld",(long)o->ptr);
    }
}

2837
/*============================ RDB saving/loading =========================== */
A
antirez 已提交
2838

2839 2840 2841 2842 2843
static int rdbSaveType(FILE *fp, unsigned char type) {
    if (fwrite(&type,1,1,fp) == 0) return -1;
    return 0;
}

A
antirez 已提交
2844 2845 2846 2847 2848 2849
static int rdbSaveTime(FILE *fp, time_t t) {
    int32_t t32 = (int32_t) t;
    if (fwrite(&t32,4,1,fp) == 0) return -1;
    return 0;
}

2850
/* check rdbLoadLen() comments for more info */
2851 2852 2853 2854 2855
static int rdbSaveLen(FILE *fp, uint32_t len) {
    unsigned char buf[2];

    if (len < (1<<6)) {
        /* Save a 6 bit len */
2856
        buf[0] = (len&0xFF)|(REDIS_RDB_6BITLEN<<6);
2857 2858 2859
        if (fwrite(buf,1,1,fp) == 0) return -1;
    } else if (len < (1<<14)) {
        /* Save a 14 bit len */
2860
        buf[0] = ((len>>8)&0xFF)|(REDIS_RDB_14BITLEN<<6);
2861
        buf[1] = len&0xFF;
2862
        if (fwrite(buf,2,1,fp) == 0) return -1;
2863 2864
    } else {
        /* Save a 32 bit len */
2865
        buf[0] = (REDIS_RDB_32BITLEN<<6);
2866 2867 2868 2869 2870 2871 2872
        if (fwrite(buf,1,1,fp) == 0) return -1;
        len = htonl(len);
        if (fwrite(&len,4,1,fp) == 0) return -1;
    }
    return 0;
}

2873 2874 2875
/* String objects in the form "2391" "-100" without any space and with a
 * range of values that can fit in an 8, 16 or 32 bit signed value can be
 * encoded as integers to save space */
2876
static int rdbTryIntegerEncoding(sds s, unsigned char *enc) {
2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910
    long long value;
    char *endptr, buf[32];

    /* Check if it's possible to encode this value as a number */
    value = strtoll(s, &endptr, 10);
    if (endptr[0] != '\0') return 0;
    snprintf(buf,32,"%lld",value);

    /* If the number converted back into a string is not identical
     * then it's not possible to encode the string as integer */
    if (strlen(buf) != sdslen(s) || memcmp(buf,s,sdslen(s))) return 0;

    /* Finally check if it fits in our ranges */
    if (value >= -(1<<7) && value <= (1<<7)-1) {
        enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT8;
        enc[1] = value&0xFF;
        return 2;
    } else if (value >= -(1<<15) && value <= (1<<15)-1) {
        enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT16;
        enc[1] = value&0xFF;
        enc[2] = (value>>8)&0xFF;
        return 3;
    } else if (value >= -((long long)1<<31) && value <= ((long long)1<<31)-1) {
        enc[0] = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_INT32;
        enc[1] = value&0xFF;
        enc[2] = (value>>8)&0xFF;
        enc[3] = (value>>16)&0xFF;
        enc[4] = (value>>24)&0xFF;
        return 5;
    } else {
        return 0;
    }
}

A
antirez 已提交
2911 2912 2913 2914 2915 2916 2917 2918
static int rdbSaveLzfStringObject(FILE *fp, robj *obj) {
    unsigned int comprlen, outlen;
    unsigned char byte;
    void *out;

    /* We require at least four bytes compression for this to be worth it */
    outlen = sdslen(obj->ptr)-4;
    if (outlen <= 0) return 0;
A
antirez 已提交
2919
    if ((out = zmalloc(outlen+1)) == NULL) return 0;
A
antirez 已提交
2920 2921
    comprlen = lzf_compress(obj->ptr, sdslen(obj->ptr), out, outlen);
    if (comprlen == 0) {
2922
        zfree(out);
A
antirez 已提交
2923 2924 2925 2926 2927 2928 2929 2930
        return 0;
    }
    /* Data compressed! Let's save it on disk */
    byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
    if (fwrite(&byte,1,1,fp) == 0) goto writeerr;
    if (rdbSaveLen(fp,comprlen) == -1) goto writeerr;
    if (rdbSaveLen(fp,sdslen(obj->ptr)) == -1) goto writeerr;
    if (fwrite(out,comprlen,1,fp) == 0) goto writeerr;
2931
    zfree(out);
A
antirez 已提交
2932 2933 2934
    return comprlen;

writeerr:
2935
    zfree(out);
A
antirez 已提交
2936 2937 2938
    return -1;
}

2939 2940
/* Save a string objet as [len][data] on disk. If the object is a string
 * representation of an integer value we try to safe it in a special form */
2941 2942
static int rdbSaveStringObjectRaw(FILE *fp, robj *obj) {
    size_t len;
2943
    int enclen;
2944

2945 2946
    len = sdslen(obj->ptr);

A
antirez 已提交
2947
    /* Try integer encoding */
2948 2949 2950 2951 2952 2953 2954
    if (len <= 11) {
        unsigned char buf[5];
        if ((enclen = rdbTryIntegerEncoding(obj->ptr,buf)) > 0) {
            if (fwrite(buf,enclen,1,fp) == 0) return -1;
            return 0;
        }
    }
A
antirez 已提交
2955 2956

    /* Try LZF compression - under 20 bytes it's unable to compress even
2957
     * aaaaaaaaaaaaaaaaaa so skip it */
2958
    if (server.rdbcompression && len > 20) {
A
antirez 已提交
2959 2960 2961 2962 2963 2964 2965 2966 2967
        int retval;

        retval = rdbSaveLzfStringObject(fp,obj);
        if (retval == -1) return -1;
        if (retval > 0) return 0;
        /* retval == 0 means data can't be compressed, save the old way */
    }

    /* Store verbatim */
2968 2969 2970 2971 2972
    if (rdbSaveLen(fp,len) == -1) return -1;
    if (len && fwrite(obj->ptr,len,1,fp) == 0) return -1;
    return 0;
}

2973 2974 2975 2976
/* Like rdbSaveStringObjectRaw() but handle encoded objects */
static int rdbSaveStringObject(FILE *fp, robj *obj) {
    int retval;

A
antirez 已提交
2977 2978 2979 2980 2981 2982
    /* Avoid incr/decr ref count business when possible.
     * This plays well with copy-on-write given that we are probably
     * in a child process (BGSAVE). Also this makes sure key objects
     * of swapped objects are not incRefCount-ed (an assert does not allow
     * this in order to avoid bugs) */
    if (obj->encoding != REDIS_ENCODING_RAW) {
2983 2984 2985 2986 2987 2988
        obj = getDecodedObject(obj);
        retval = rdbSaveStringObjectRaw(fp,obj);
        decrRefCount(obj);
    } else {
        retval = rdbSaveStringObjectRaw(fp,obj);
    }
2989
    return retval;
2990 2991
}

2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010
/* Save a double value. Doubles are saved as strings prefixed by an unsigned
 * 8 bit integer specifing the length of the representation.
 * This 8 bit integer has special values in order to specify the following
 * conditions:
 * 253: not a number
 * 254: + inf
 * 255: - inf
 */
static int rdbSaveDoubleValue(FILE *fp, double val) {
    unsigned char buf[128];
    int len;

    if (isnan(val)) {
        buf[0] = 253;
        len = 1;
    } else if (!isfinite(val)) {
        len = 1;
        buf[0] = (val < 0) ? 255 : 254;
    } else {
3011
        snprintf((char*)buf+1,sizeof(buf)-1,"%.17g",val);
A
antirez 已提交
3012
        buf[0] = strlen((char*)buf+1);
3013 3014 3015 3016 3017 3018
        len = buf[0]+1;
    }
    if (fwrite(buf,len,1,fp) == 0) return -1;
    return 0;
}

3019 3020 3021 3022 3023 3024 3025 3026
/* Save a Redis object. */
static int rdbSaveObject(FILE *fp, robj *o) {
    if (o->type == REDIS_STRING) {
        /* Save a string value */
        if (rdbSaveStringObject(fp,o) == -1) return -1;
    } else if (o->type == REDIS_LIST) {
        /* Save a list value */
        list *list = o->ptr;
A
antirez 已提交
3027
        listIter li;
3028 3029 3030
        listNode *ln;

        if (rdbSaveLen(fp,listLength(list)) == -1) return -1;
A
antirez 已提交
3031 3032
        listRewind(list,&li);
        while((ln = listNext(&li))) {
3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074
            robj *eleobj = listNodeValue(ln);

            if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
        }
    } else if (o->type == REDIS_SET) {
        /* Save a set value */
        dict *set = o->ptr;
        dictIterator *di = dictGetIterator(set);
        dictEntry *de;

        if (rdbSaveLen(fp,dictSize(set)) == -1) return -1;
        while((de = dictNext(di)) != NULL) {
            robj *eleobj = dictGetEntryKey(de);

            if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
        }
        dictReleaseIterator(di);
    } else if (o->type == REDIS_ZSET) {
        /* Save a set value */
        zset *zs = o->ptr;
        dictIterator *di = dictGetIterator(zs->dict);
        dictEntry *de;

        if (rdbSaveLen(fp,dictSize(zs->dict)) == -1) return -1;
        while((de = dictNext(di)) != NULL) {
            robj *eleobj = dictGetEntryKey(de);
            double *score = dictGetEntryVal(de);

            if (rdbSaveStringObject(fp,eleobj) == -1) return -1;
            if (rdbSaveDoubleValue(fp,*score) == -1) return -1;
        }
        dictReleaseIterator(di);
    } else {
        redisAssert(0 != 0);
    }
    return 0;
}

/* Return the length the object will have on disk if saved with
 * the rdbSaveObject() function. Currently we use a trick to get
 * this length with very little changes to the code. In the future
 * we could switch to a faster solution. */
3075 3076
static off_t rdbSavedObjectLen(robj *o, FILE *fp) {
    if (fp == NULL) fp = server.devnull;
3077 3078 3079 3080 3081
    rewind(fp);
    assert(rdbSaveObject(fp,o) != 1);
    return ftello(fp);
}

A
antirez 已提交
3082
/* Return the number of pages required to save this object in the swap file */
3083 3084
static off_t rdbSavedObjectPages(robj *o, FILE *fp) {
    off_t bytes = rdbSavedObjectLen(o,fp);
A
antirez 已提交
3085 3086 3087 3088
    
    return (bytes+(server.vm_page_size-1))/server.vm_page_size;
}

A
antirez 已提交
3089
/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3090
static int rdbSave(char *filename) {
A
antirez 已提交
3091 3092 3093 3094 3095
    dictIterator *di = NULL;
    dictEntry *de;
    FILE *fp;
    char tmpfile[256];
    int j;
A
antirez 已提交
3096
    time_t now = time(NULL);
A
antirez 已提交
3097

A
antirez 已提交
3098 3099 3100 3101 3102 3103
    /* Wait for I/O therads to terminate, just in case this is a
     * foreground-saving, to avoid seeking the swap file descriptor at the
     * same time. */
    if (server.vm_enabled)
        waitEmptyIOJobsQueue();

3104
    snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
A
antirez 已提交
3105 3106 3107 3108 3109
    fp = fopen(tmpfile,"w");
    if (!fp) {
        redisLog(REDIS_WARNING, "Failed saving the DB: %s", strerror(errno));
        return REDIS_ERR;
    }
3110
    if (fwrite("REDIS0001",9,1,fp) == 0) goto werr;
A
antirez 已提交
3111
    for (j = 0; j < server.dbnum; j++) {
A
antirez 已提交
3112 3113
        redisDb *db = server.db+j;
        dict *d = db->dict;
A
antirez 已提交
3114
        if (dictSize(d) == 0) continue;
A
antirez 已提交
3115 3116 3117 3118 3119 3120 3121
        di = dictGetIterator(d);
        if (!di) {
            fclose(fp);
            return REDIS_ERR;
        }

        /* Write the SELECT DB opcode */
3122 3123
        if (rdbSaveType(fp,REDIS_SELECTDB) == -1) goto werr;
        if (rdbSaveLen(fp,j) == -1) goto werr;
A
antirez 已提交
3124 3125 3126 3127 3128

        /* Iterate this DB writing every entry */
        while((de = dictNext(di)) != NULL) {
            robj *key = dictGetEntryKey(de);
            robj *o = dictGetEntryVal(de);
A
antirez 已提交
3129 3130 3131 3132 3133 3134 3135 3136 3137
            time_t expiretime = getExpire(db,key);

            /* Save the expire time */
            if (expiretime != -1) {
                /* If this key is already expired skip it */
                if (expiretime < now) continue;
                if (rdbSaveType(fp,REDIS_EXPIRETIME) == -1) goto werr;
                if (rdbSaveTime(fp,expiretime) == -1) goto werr;
            }
A
antirez 已提交
3138 3139
            /* Save the key and associated value. This requires special
             * handling if the value is swapped out. */
3140 3141
            if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
                                      key->storage == REDIS_VM_SWAPPING) {
A
antirez 已提交
3142 3143 3144 3145 3146
                /* Save type, key, value */
                if (rdbSaveType(fp,o->type) == -1) goto werr;
                if (rdbSaveStringObject(fp,key) == -1) goto werr;
                if (rdbSaveObject(fp,o) == -1) goto werr;
            } else {
3147
                /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3148
                robj *po;
A
antirez 已提交
3149 3150 3151 3152
                /* Get a preview of the object in memory */
                po = vmPreviewObject(key);
                /* Save type, key, value */
                if (rdbSaveType(fp,key->vtype) == -1) goto werr;
3153
                if (rdbSaveStringObject(fp,key) == -1) goto werr;
A
antirez 已提交
3154 3155 3156 3157
                if (rdbSaveObject(fp,po) == -1) goto werr;
                /* Remove the loaded object from memory */
                decrRefCount(po);
            }
A
antirez 已提交
3158 3159 3160 3161
        }
        dictReleaseIterator(di);
    }
    /* EOF opcode */
3162 3163 3164
    if (rdbSaveType(fp,REDIS_EOF) == -1) goto werr;

    /* Make sure data will not remain on the OS's output buffers */
A
antirez 已提交
3165 3166 3167 3168 3169 3170 3171
    fflush(fp);
    fsync(fileno(fp));
    fclose(fp);
    
    /* Use RENAME to make sure the DB file is changed atomically only
     * if the generate DB file is ok. */
    if (rename(tmpfile,filename) == -1) {
3172
        redisLog(REDIS_WARNING,"Error moving temp DB file on the final destination: %s", strerror(errno));
A
antirez 已提交
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188
        unlink(tmpfile);
        return REDIS_ERR;
    }
    redisLog(REDIS_NOTICE,"DB saved on disk");
    server.dirty = 0;
    server.lastsave = time(NULL);
    return REDIS_OK;

werr:
    fclose(fp);
    unlink(tmpfile);
    redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
    if (di) dictReleaseIterator(di);
    return REDIS_ERR;
}

3189
static int rdbSaveBackground(char *filename) {
A
antirez 已提交
3190 3191
    pid_t childpid;

3192
    if (server.bgsavechildpid != -1) return REDIS_ERR;
3193
    if (server.vm_enabled) waitEmptyIOJobsQueue();
A
antirez 已提交
3194 3195
    if ((childpid = fork()) == 0) {
        /* Child */
3196
        if (server.vm_enabled) vmReopenSwapFile();
A
antirez 已提交
3197
        close(server.fd);
3198
        if (rdbSave(filename) == REDIS_OK) {
3199
            _exit(0);
A
antirez 已提交
3200
        } else {
3201
            _exit(1);
A
antirez 已提交
3202 3203 3204
        }
    } else {
        /* Parent */
3205 3206 3207 3208 3209
        if (childpid == -1) {
            redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
                strerror(errno));
            return REDIS_ERR;
        }
A
antirez 已提交
3210
        redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
3211
        server.bgsavechildpid = childpid;
A
antirez 已提交
3212 3213 3214 3215 3216
        return REDIS_OK;
    }
    return REDIS_OK; /* unreached */
}

3217 3218 3219 3220 3221 3222 3223
static void rdbRemoveTempFile(pid_t childpid) {
    char tmpfile[256];

    snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
    unlink(tmpfile);
}

3224 3225
static int rdbLoadType(FILE *fp) {
    unsigned char type;
A
antirez 已提交
3226 3227 3228 3229
    if (fread(&type,1,1,fp) == 0) return -1;
    return type;
}

A
antirez 已提交
3230 3231 3232 3233 3234 3235
static time_t rdbLoadTime(FILE *fp) {
    int32_t t32;
    if (fread(&t32,4,1,fp) == 0) return -1;
    return (time_t) t32;
}

3236 3237 3238 3239 3240
/* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
 * of this file for a description of how this are stored on disk.
 *
 * isencoded is set to 1 if the readed length is not actually a length but
 * an "encoding type", check the above comments for more info */
3241
static uint32_t rdbLoadLen(FILE *fp, int *isencoded) {
3242 3243
    unsigned char buf[2];
    uint32_t len;
3244
    int type;
3245

3246
    if (isencoded) *isencoded = 0;
3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
    if (fread(buf,1,1,fp) == 0) return REDIS_RDB_LENERR;
    type = (buf[0]&0xC0)>>6;
    if (type == REDIS_RDB_6BITLEN) {
        /* Read a 6 bit len */
        return buf[0]&0x3F;
    } else if (type == REDIS_RDB_ENCVAL) {
        /* Read a 6 bit len encoding type */
        if (isencoded) *isencoded = 1;
        return buf[0]&0x3F;
    } else if (type == REDIS_RDB_14BITLEN) {
        /* Read a 14 bit len */
        if (fread(buf+1,1,1,fp) == 0) return REDIS_RDB_LENERR;
        return ((buf[0]&0x3F)<<8)|buf[1];
    } else {
        /* Read a 32 bit len */
3262 3263 3264 3265 3266
        if (fread(&len,4,1,fp) == 0) return REDIS_RDB_LENERR;
        return ntohl(len);
    }
}

3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285
static robj *rdbLoadIntegerObject(FILE *fp, int enctype) {
    unsigned char enc[4];
    long long val;

    if (enctype == REDIS_RDB_ENC_INT8) {
        if (fread(enc,1,1,fp) == 0) return NULL;
        val = (signed char)enc[0];
    } else if (enctype == REDIS_RDB_ENC_INT16) {
        uint16_t v;
        if (fread(enc,2,1,fp) == 0) return NULL;
        v = enc[0]|(enc[1]<<8);
        val = (int16_t)v;
    } else if (enctype == REDIS_RDB_ENC_INT32) {
        uint32_t v;
        if (fread(enc,4,1,fp) == 0) return NULL;
        v = enc[0]|(enc[1]<<8)|(enc[2]<<16)|(enc[3]<<24);
        val = (int32_t)v;
    } else {
        val = 0; /* anti-warning */
3286
        redisAssert(0!=0);
3287 3288 3289 3290
    }
    return createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",val));
}

3291
static robj *rdbLoadLzfStringObject(FILE*fp) {
3292 3293 3294 3295
    unsigned int len, clen;
    unsigned char *c = NULL;
    sds val = NULL;

3296 3297
    if ((clen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
    if ((len = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
3298 3299 3300 3301
    if ((c = zmalloc(clen)) == NULL) goto err;
    if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
    if (fread(c,clen,1,fp) == 0) goto err;
    if (lzf_decompress(c,clen,val,len) == 0) goto err;
3302
    zfree(c);
3303 3304 3305 3306 3307 3308 3309
    return createObject(REDIS_STRING,val);
err:
    zfree(c);
    sdsfree(val);
    return NULL;
}

3310
static robj *rdbLoadStringObject(FILE*fp) {
3311 3312
    int isencoded;
    uint32_t len;
3313 3314
    sds val;

3315
    len = rdbLoadLen(fp,&isencoded);
3316 3317 3318 3319 3320
    if (isencoded) {
        switch(len) {
        case REDIS_RDB_ENC_INT8:
        case REDIS_RDB_ENC_INT16:
        case REDIS_RDB_ENC_INT32:
A
antirez 已提交
3321
            return tryObjectSharing(rdbLoadIntegerObject(fp,len));
3322
        case REDIS_RDB_ENC_LZF:
3323
            return tryObjectSharing(rdbLoadLzfStringObject(fp));
3324
        default:
3325
            redisAssert(0!=0);
3326 3327 3328
        }
    }

3329 3330 3331 3332 3333 3334
    if (len == REDIS_RDB_LENERR) return NULL;
    val = sdsnewlen(NULL,len);
    if (len && fread(val,len,1,fp) == 0) {
        sdsfree(val);
        return NULL;
    }
3335
    return tryObjectSharing(createObject(REDIS_STRING,val));
3336 3337
}

3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349
/* For information about double serialization check rdbSaveDoubleValue() */
static int rdbLoadDoubleValue(FILE *fp, double *val) {
    char buf[128];
    unsigned char len;

    if (fread(&len,1,1,fp) == 0) return -1;
    switch(len) {
    case 255: *val = R_NegInf; return 0;
    case 254: *val = R_PosInf; return 0;
    case 253: *val = R_Nan; return 0;
    default:
        if (fread(buf,len,1,fp) == 0) return -1;
3350
        buf[len] = '\0';
3351 3352 3353 3354 3355
        sscanf(buf, "%lg", val);
        return 0;
    }
}

3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370
/* Load a Redis object of the specified type from the specified file.
 * On success a newly allocated object is returned, otherwise NULL. */
static robj *rdbLoadObject(int type, FILE *fp) {
    robj *o;

    if (type == REDIS_STRING) {
        /* Read string value */
        if ((o = rdbLoadStringObject(fp)) == NULL) return NULL;
        tryObjectEncoding(o);
    } else if (type == REDIS_LIST || type == REDIS_SET) {
        /* Read list/set value */
        uint32_t listlen;

        if ((listlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
        o = (type == REDIS_LIST) ? createListObject() : createSetObject();
3371 3372 3373 3374
        /* It's faster to expand the dict to the right size asap in order
         * to avoid rehashing */
        if (type == REDIS_SET && listlen > DICT_HT_INITIAL_SIZE)
            dictExpand(o->ptr,listlen);
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412
        /* Load every single element of the list/set */
        while(listlen--) {
            robj *ele;

            if ((ele = rdbLoadStringObject(fp)) == NULL) return NULL;
            tryObjectEncoding(ele);
            if (type == REDIS_LIST) {
                listAddNodeTail((list*)o->ptr,ele);
            } else {
                dictAdd((dict*)o->ptr,ele,NULL);
            }
        }
    } else if (type == REDIS_ZSET) {
        /* Read list/set value */
        uint32_t zsetlen;
        zset *zs;

        if ((zsetlen = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR) return NULL;
        o = createZsetObject();
        zs = o->ptr;
        /* Load every single element of the list/set */
        while(zsetlen--) {
            robj *ele;
            double *score = zmalloc(sizeof(double));

            if ((ele = rdbLoadStringObject(fp)) == NULL) return NULL;
            tryObjectEncoding(ele);
            if (rdbLoadDoubleValue(fp,score) == -1) return NULL;
            dictAdd(zs->dict,ele,score);
            zslInsert(zs->zsl,*score,ele);
            incrRefCount(ele); /* added to skiplist */
        }
    } else {
        redisAssert(0 != 0);
    }
    return o;
}

3413
static int rdbLoad(char *filename) {
A
antirez 已提交
3414
    FILE *fp;
3415 3416
    robj *keyobj = NULL;
    uint32_t dbid;
A
antirez 已提交
3417
    int type, retval, rdbver;
A
antirez 已提交
3418
    dict *d = server.db[0].dict;
A
antirez 已提交
3419
    redisDb *db = server.db+0;
3420
    char buf[1024];
A
antirez 已提交
3421
    time_t expiretime = -1, now = time(NULL);
3422
    long long loadedkeys = 0;
A
antirez 已提交
3423

A
antirez 已提交
3424 3425 3426
    fp = fopen(filename,"r");
    if (!fp) return REDIS_ERR;
    if (fread(buf,9,1,fp) == 0) goto eoferr;
3427 3428
    buf[9] = '\0';
    if (memcmp(buf,"REDIS",5) != 0) {
A
antirez 已提交
3429 3430 3431 3432
        fclose(fp);
        redisLog(REDIS_WARNING,"Wrong signature trying to load DB from file");
        return REDIS_ERR;
    }
3433
    rdbver = atoi(buf+5);
3434
    if (rdbver != 1) {
3435 3436 3437 3438
        fclose(fp);
        redisLog(REDIS_WARNING,"Can't handle RDB format version %d",rdbver);
        return REDIS_ERR;
    }
A
antirez 已提交
3439 3440 3441 3442
    while(1) {
        robj *o;

        /* Read type. */
3443
        if ((type = rdbLoadType(fp)) == -1) goto eoferr;
A
antirez 已提交
3444 3445 3446 3447 3448
        if (type == REDIS_EXPIRETIME) {
            if ((expiretime = rdbLoadTime(fp)) == -1) goto eoferr;
            /* We read the time so we need to read the object type again */
            if ((type = rdbLoadType(fp)) == -1) goto eoferr;
        }
A
antirez 已提交
3449 3450 3451
        if (type == REDIS_EOF) break;
        /* Handle SELECT DB opcode as a special case */
        if (type == REDIS_SELECTDB) {
3452
            if ((dbid = rdbLoadLen(fp,NULL)) == REDIS_RDB_LENERR)
3453
                goto eoferr;
A
antirez 已提交
3454
            if (dbid >= (unsigned)server.dbnum) {
3455
                redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
A
antirez 已提交
3456 3457
                exit(1);
            }
A
antirez 已提交
3458 3459
            db = server.db+dbid;
            d = db->dict;
A
antirez 已提交
3460 3461 3462
            continue;
        }
        /* Read key */
3463 3464 3465
        if ((keyobj = rdbLoadStringObject(fp)) == NULL) goto eoferr;
        /* Read value */
        if ((o = rdbLoadObject(type,fp)) == NULL) goto eoferr;
A
antirez 已提交
3466
        /* Add the new object in the hash table */
3467
        retval = dictAdd(d,keyobj,o);
A
antirez 已提交
3468
        if (retval == DICT_ERR) {
3469
            redisLog(REDIS_WARNING,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj->ptr);
A
antirez 已提交
3470 3471
            exit(1);
        }
A
antirez 已提交
3472 3473 3474 3475 3476 3477 3478
        /* Set the expire time if needed */
        if (expiretime != -1) {
            setExpire(db,keyobj,expiretime);
            /* Delete this key if already expired */
            if (expiretime < now) deleteKey(db,keyobj);
            expiretime = -1;
        }
3479
        keyobj = o = NULL;
3480 3481 3482 3483
        /* Handle swapping while loading big datasets when VM is on */
        loadedkeys++;
        if (server.vm_enabled && (loadedkeys % 5000) == 0) {
            while (zmalloc_used_memory() > server.vm_max_memory) {
3484
                if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
3485 3486
            }
        }
A
antirez 已提交
3487 3488 3489 3490 3491
    }
    fclose(fp);
    return REDIS_OK;

eoferr: /* unexpected end of file is handled here with a fatal exit */
3492
    if (keyobj) decrRefCount(keyobj);
3493
    redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
A
antirez 已提交
3494 3495 3496 3497 3498 3499
    exit(1);
    return REDIS_ERR; /* Just to avoid warning */
}

/*================================== Commands =============================== */

B
Brian Hammond 已提交
3500
static void authCommand(redisClient *c) {
A
antirez 已提交
3501
    if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
B
Brian Hammond 已提交
3502 3503 3504 3505
      c->authenticated = 1;
      addReply(c,shared.ok);
    } else {
      c->authenticated = 0;
3506
      addReplySds(c,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
B
Brian Hammond 已提交
3507 3508 3509
    }
}

A
antirez 已提交
3510 3511 3512 3513 3514
static void pingCommand(redisClient *c) {
    addReply(c,shared.pong);
}

static void echoCommand(redisClient *c) {
3515
    addReplyBulkLen(c,c->argv[1]);
A
antirez 已提交
3516 3517 3518 3519 3520 3521 3522 3523 3524
    addReply(c,c->argv[1]);
    addReply(c,shared.crlf);
}

/*=================================== Strings =============================== */

static void setGenericCommand(redisClient *c, int nx) {
    int retval;

A
antirez 已提交
3525
    if (nx) deleteIfVolatile(c->db,c->argv[1]);
A
antirez 已提交
3526
    retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
A
antirez 已提交
3527 3528
    if (retval == DICT_ERR) {
        if (!nx) {
A
antirez 已提交
3529 3530 3531 3532 3533 3534
            /* If the key is about a swapped value, we want a new key object
             * to overwrite the old. So we delete the old key in the database.
             * This will also make sure that swap pages about the old object
             * will be marked as free. */
            if (deleteIfSwapped(c->db,c->argv[1]))
                incrRefCount(c->argv[1]);
A
antirez 已提交
3535
            dictReplace(c->db->dict,c->argv[1],c->argv[2]);
A
antirez 已提交
3536 3537
            incrRefCount(c->argv[2]);
        } else {
3538
            addReply(c,shared.czero);
A
antirez 已提交
3539 3540 3541 3542 3543 3544 3545
            return;
        }
    } else {
        incrRefCount(c->argv[1]);
        incrRefCount(c->argv[2]);
    }
    server.dirty++;
A
antirez 已提交
3546
    removeExpire(c->db,c->argv[1]);
3547
    addReply(c, nx ? shared.cone : shared.ok);
A
antirez 已提交
3548 3549 3550
}

static void setCommand(redisClient *c) {
A
antirez 已提交
3551
    setGenericCommand(c,0);
A
antirez 已提交
3552 3553 3554
}

static void setnxCommand(redisClient *c) {
A
antirez 已提交
3555
    setGenericCommand(c,1);
A
antirez 已提交
3556 3557
}

3558
static int getGenericCommand(redisClient *c) {
A
antirez 已提交
3559 3560 3561
    robj *o = lookupKeyRead(c->db,c->argv[1]);

    if (o == NULL) {
3562
        addReply(c,shared.nullbulk);
3563
        return REDIS_OK;
A
antirez 已提交
3564 3565
    } else {
        if (o->type != REDIS_STRING) {
3566
            addReply(c,shared.wrongtypeerr);
3567
            return REDIS_ERR;
A
antirez 已提交
3568
        } else {
3569
            addReplyBulkLen(c,o);
A
antirez 已提交
3570 3571
            addReply(c,o);
            addReply(c,shared.crlf);
3572
            return REDIS_OK;
A
antirez 已提交
3573 3574 3575 3576
        }
    }
}

3577 3578 3579 3580
static void getCommand(redisClient *c) {
    getGenericCommand(c);
}

A
antirez 已提交
3581
static void getsetCommand(redisClient *c) {
3582
    if (getGenericCommand(c) == REDIS_ERR) return;
A
antirez 已提交
3583 3584 3585 3586 3587 3588 3589 3590 3591 3592
    if (dictAdd(c->db->dict,c->argv[1],c->argv[2]) == DICT_ERR) {
        dictReplace(c->db->dict,c->argv[1],c->argv[2]);
    } else {
        incrRefCount(c->argv[1]);
    }
    incrRefCount(c->argv[2]);
    server.dirty++;
    removeExpire(c->db,c->argv[1]);
}

3593 3594 3595
static void mgetCommand(redisClient *c) {
    int j;
  
3596
    addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->argc-1));
3597
    for (j = 1; j < c->argc; j++) {
A
antirez 已提交
3598 3599
        robj *o = lookupKeyRead(c->db,c->argv[j]);
        if (o == NULL) {
3600
            addReply(c,shared.nullbulk);
3601 3602
        } else {
            if (o->type != REDIS_STRING) {
3603
                addReply(c,shared.nullbulk);
3604
            } else {
3605
                addReplyBulkLen(c,o);
3606 3607 3608 3609 3610 3611 3612
                addReply(c,o);
                addReply(c,shared.crlf);
            }
        }
    }
}

A
antirez 已提交
3613
static void msetGenericCommand(redisClient *c, int nx) {
3614
    int j, busykeys = 0;
A
antirez 已提交
3615 3616

    if ((c->argc % 2) == 0) {
3617
        addReplySds(c,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
A
antirez 已提交
3618 3619 3620 3621 3622 3623
        return;
    }
    /* Handle the NX flag. The MSETNX semantic is to return zero and don't
     * set nothing at all if at least one already key exists. */
    if (nx) {
        for (j = 1; j < c->argc; j += 2) {
3624 3625
            if (lookupKeyWrite(c->db,c->argv[j]) != NULL) {
                busykeys++;
A
antirez 已提交
3626 3627 3628
            }
        }
    }
3629 3630 3631 3632
    if (busykeys) {
        addReply(c, shared.czero);
        return;
    }
A
antirez 已提交
3633 3634 3635 3636

    for (j = 1; j < c->argc; j += 2) {
        int retval;

3637
        tryObjectEncoding(c->argv[j+1]);
A
antirez 已提交
3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659
        retval = dictAdd(c->db->dict,c->argv[j],c->argv[j+1]);
        if (retval == DICT_ERR) {
            dictReplace(c->db->dict,c->argv[j],c->argv[j+1]);
            incrRefCount(c->argv[j+1]);
        } else {
            incrRefCount(c->argv[j]);
            incrRefCount(c->argv[j+1]);
        }
        removeExpire(c->db,c->argv[j]);
    }
    server.dirty += (c->argc-1)/2;
    addReply(c, nx ? shared.cone : shared.ok);
}

static void msetCommand(redisClient *c) {
    msetGenericCommand(c,0);
}

static void msetnxCommand(redisClient *c) {
    msetGenericCommand(c,1);
}

3660
static void incrDecrCommand(redisClient *c, long long incr) {
A
antirez 已提交
3661 3662 3663 3664
    long long value;
    int retval;
    robj *o;
    
A
antirez 已提交
3665 3666
    o = lookupKeyWrite(c->db,c->argv[1]);
    if (o == NULL) {
A
antirez 已提交
3667 3668 3669 3670 3671 3672 3673
        value = 0;
    } else {
        if (o->type != REDIS_STRING) {
            value = 0;
        } else {
            char *eptr;

3674 3675 3676 3677 3678
            if (o->encoding == REDIS_ENCODING_RAW)
                value = strtoll(o->ptr, &eptr, 10);
            else if (o->encoding == REDIS_ENCODING_INT)
                value = (long)o->ptr;
            else
3679
                redisAssert(1 != 1);
A
antirez 已提交
3680 3681 3682 3683 3684
        }
    }

    value += incr;
    o = createObject(REDIS_STRING,sdscatprintf(sdsempty(),"%lld",value));
3685
    tryObjectEncoding(o);
A
antirez 已提交
3686
    retval = dictAdd(c->db->dict,c->argv[1],o);
A
antirez 已提交
3687
    if (retval == DICT_ERR) {
A
antirez 已提交
3688 3689
        dictReplace(c->db->dict,c->argv[1],o);
        removeExpire(c->db,c->argv[1]);
A
antirez 已提交
3690 3691 3692 3693
    } else {
        incrRefCount(c->argv[1]);
    }
    server.dirty++;
3694
    addReply(c,shared.colon);
A
antirez 已提交
3695 3696 3697 3698 3699
    addReply(c,o);
    addReply(c,shared.crlf);
}

static void incrCommand(redisClient *c) {
A
antirez 已提交
3700
    incrDecrCommand(c,1);
A
antirez 已提交
3701 3702 3703
}

static void decrCommand(redisClient *c) {
A
antirez 已提交
3704
    incrDecrCommand(c,-1);
A
antirez 已提交
3705 3706 3707
}

static void incrbyCommand(redisClient *c) {
3708
    long long incr = strtoll(c->argv[2]->ptr, NULL, 10);
A
antirez 已提交
3709
    incrDecrCommand(c,incr);
A
antirez 已提交
3710 3711 3712
}

static void decrbyCommand(redisClient *c) {
3713
    long long incr = strtoll(c->argv[2]->ptr, NULL, 10);
A
antirez 已提交
3714
    incrDecrCommand(c,-incr);
A
antirez 已提交
3715 3716
}

A
antirez 已提交
3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762
static void appendCommand(redisClient *c) {
    int retval;
    size_t totlen;
    robj *o;

    o = lookupKeyWrite(c->db,c->argv[1]);
    if (o == NULL) {
        /* Create the key */
        retval = dictAdd(c->db->dict,c->argv[1],c->argv[2]);
        incrRefCount(c->argv[1]);
        incrRefCount(c->argv[2]);
        totlen = stringObjectLen(c->argv[2]);
    } else {
        dictEntry *de;
       
        de = dictFind(c->db->dict,c->argv[1]);
        assert(de != NULL);

        o = dictGetEntryVal(de);
        if (o->type != REDIS_STRING) {
            addReply(c,shared.wrongtypeerr);
            return;
        }
        /* If the object is specially encoded or shared we have to make
         * a copy */
        if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
            robj *decoded = getDecodedObject(o);

            o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
            decrRefCount(decoded);
            dictReplace(c->db->dict,c->argv[1],o);
        }
        /* APPEND! */
        if (c->argv[2]->encoding == REDIS_ENCODING_RAW) {
            o->ptr = sdscatlen(o->ptr,
                c->argv[2]->ptr, sdslen(c->argv[2]->ptr));
        } else {
            o->ptr = sdscatprintf(o->ptr, "%ld",
                (unsigned long) c->argv[2]->ptr);
        }
        totlen = sdslen(o->ptr);
    }
    server.dirty++;
    addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen));
}

A
antirez 已提交
3763 3764 3765
/* ========================= Type agnostic commands ========================= */

static void delCommand(redisClient *c) {
3766 3767 3768 3769 3770 3771 3772 3773 3774 3775
    int deleted = 0, j;

    for (j = 1; j < c->argc; j++) {
        if (deleteKey(c->db,c->argv[j])) {
            server.dirty++;
            deleted++;
        }
    }
    switch(deleted) {
    case 0:
3776
        addReply(c,shared.czero);
3777 3778 3779 3780 3781 3782 3783
        break;
    case 1:
        addReply(c,shared.cone);
        break;
    default:
        addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",deleted));
        break;
A
antirez 已提交
3784 3785 3786 3787
    }
}

static void existsCommand(redisClient *c) {
A
antirez 已提交
3788
    addReply(c,lookupKeyRead(c->db,c->argv[1]) ? shared.cone : shared.czero);
A
antirez 已提交
3789 3790 3791 3792 3793 3794
}

static void selectCommand(redisClient *c) {
    int id = atoi(c->argv[1]->ptr);
    
    if (selectDb(c,id) == REDIS_ERR) {
A
antirez 已提交
3795
        addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
A
antirez 已提交
3796 3797 3798 3799 3800 3801 3802
    } else {
        addReply(c,shared.ok);
    }
}

static void randomkeyCommand(redisClient *c) {
    dictEntry *de;
A
antirez 已提交
3803 3804 3805
   
    while(1) {
        de = dictGetRandomKey(c->db->dict);
3806
        if (!de || expireIfNeeded(c->db,dictGetEntryKey(de)) == 0) break;
A
antirez 已提交
3807
    }
A
antirez 已提交
3808
    if (de == NULL) {
3809
        addReply(c,shared.plus);
A
antirez 已提交
3810 3811
        addReply(c,shared.crlf);
    } else {
3812
        addReply(c,shared.plus);
A
antirez 已提交
3813 3814 3815 3816 3817 3818 3819 3820 3821 3822
        addReply(c,dictGetEntryKey(de));
        addReply(c,shared.crlf);
    }
}

static void keysCommand(redisClient *c) {
    dictIterator *di;
    dictEntry *de;
    sds pattern = c->argv[1]->ptr;
    int plen = sdslen(pattern);
A
antirez 已提交
3823
    unsigned long numkeys = 0;
A
antirez 已提交
3824 3825
    robj *lenobj = createObject(REDIS_STRING,NULL);

A
antirez 已提交
3826
    di = dictGetIterator(c->db->dict);
A
antirez 已提交
3827 3828 3829 3830
    addReply(c,lenobj);
    decrRefCount(lenobj);
    while((de = dictNext(di)) != NULL) {
        robj *keyobj = dictGetEntryKey(de);
A
antirez 已提交
3831

A
antirez 已提交
3832 3833 3834
        sds key = keyobj->ptr;
        if ((pattern[0] == '*' && pattern[1] == '\0') ||
            stringmatchlen(pattern,plen,key,sdslen(key),0)) {
A
antirez 已提交
3835
            if (expireIfNeeded(c->db,keyobj) == 0) {
A
antirez 已提交
3836
                addReplyBulkLen(c,keyobj);
A
antirez 已提交
3837
                addReply(c,keyobj);
A
antirez 已提交
3838
                addReply(c,shared.crlf);
A
antirez 已提交
3839 3840
                numkeys++;
            }
A
antirez 已提交
3841 3842 3843
        }
    }
    dictReleaseIterator(di);
A
antirez 已提交
3844
    lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
A
antirez 已提交
3845 3846 3847 3848
}

static void dbsizeCommand(redisClient *c) {
    addReplySds(c,
A
antirez 已提交
3849
        sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
A
antirez 已提交
3850 3851 3852 3853
}

static void lastsaveCommand(redisClient *c) {
    addReplySds(c,
3854
        sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
A
antirez 已提交
3855 3856 3857
}

static void typeCommand(redisClient *c) {
A
antirez 已提交
3858
    robj *o;
A
antirez 已提交
3859
    char *type;
A
antirez 已提交
3860 3861 3862

    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
3863
        type = "+none";
A
antirez 已提交
3864 3865
    } else {
        switch(o->type) {
3866 3867 3868
        case REDIS_STRING: type = "+string"; break;
        case REDIS_LIST: type = "+list"; break;
        case REDIS_SET: type = "+set"; break;
3869
        case REDIS_ZSET: type = "+zset"; break;
A
antirez 已提交
3870 3871 3872 3873 3874 3875 3876 3877
        default: type = "unknown"; break;
        }
    }
    addReplySds(c,sdsnew(type));
    addReply(c,shared.crlf);
}

static void saveCommand(redisClient *c) {
3878
    if (server.bgsavechildpid != -1) {
3879 3880 3881
        addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
        return;
    }
3882
    if (rdbSave(server.dbfilename) == REDIS_OK) {
A
antirez 已提交
3883 3884 3885 3886 3887 3888 3889
        addReply(c,shared.ok);
    } else {
        addReply(c,shared.err);
    }
}

static void bgsaveCommand(redisClient *c) {
3890
    if (server.bgsavechildpid != -1) {
A
antirez 已提交
3891 3892 3893
        addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
        return;
    }
3894
    if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
3895 3896
        char *status = "+Background saving started\r\n";
        addReplySds(c,sdsnew(status));
A
antirez 已提交
3897 3898 3899 3900 3901 3902 3903
    } else {
        addReply(c,shared.err);
    }
}

static void shutdownCommand(redisClient *c) {
    redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
3904 3905 3906
    /* Kill the saving child if there is a background saving in progress.
       We want to avoid race conditions, for instance our saving child may
       overwrite the synchronous saving did by SHUTDOWN. */
3907
    if (server.bgsavechildpid != -1) {
3908 3909
        redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
        kill(server.bgsavechildpid,SIGKILL);
3910
        rdbRemoveTempFile(server.bgsavechildpid);
3911
    }
3912 3913 3914
    if (server.appendonly) {
        /* Append only file: fsync() the AOF and exit */
        fsync(server.appendfd);
3915
        if (server.vm_enabled) unlink(server.vm_swap_file);
3916
        exit(0);
A
antirez 已提交
3917
    } else {
3918 3919 3920 3921 3922 3923
        /* Snapshotting. Perform a SYNC SAVE and exit */
        if (rdbSave(server.dbfilename) == REDIS_OK) {
            if (server.daemonize)
                unlink(server.pidfile);
            redisLog(REDIS_WARNING,"%zu bytes used at exit",zmalloc_used_memory());
            redisLog(REDIS_WARNING,"Server exit now, bye bye...");
3924
            if (server.vm_enabled) unlink(server.vm_swap_file);
3925 3926 3927 3928 3929 3930 3931 3932 3933
            exit(0);
        } else {
            /* Ooops.. error saving! The best we can do is to continue operating.
             * Note that if there was a background saving process, in the next
             * cron() Redis will be notified that the background saving aborted,
             * handling special stuff like slaves pending for synchronization... */
            redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit"); 
            addReplySds(c,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
        }
A
antirez 已提交
3934 3935 3936 3937 3938 3939 3940 3941
    }
}

static void renameGenericCommand(redisClient *c, int nx) {
    robj *o;

    /* To use the same key as src and dst is probably an error */
    if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
3942
        addReply(c,shared.sameobjecterr);
A
antirez 已提交
3943 3944 3945
        return;
    }

A
antirez 已提交
3946 3947
    o = lookupKeyWrite(c->db,c->argv[1]);
    if (o == NULL) {
3948
        addReply(c,shared.nokeyerr);
A
antirez 已提交
3949 3950 3951
        return;
    }
    incrRefCount(o);
A
antirez 已提交
3952 3953
    deleteIfVolatile(c->db,c->argv[2]);
    if (dictAdd(c->db->dict,c->argv[2],o) == DICT_ERR) {
A
antirez 已提交
3954 3955
        if (nx) {
            decrRefCount(o);
3956
            addReply(c,shared.czero);
A
antirez 已提交
3957 3958
            return;
        }
A
antirez 已提交
3959
        dictReplace(c->db->dict,c->argv[2],o);
A
antirez 已提交
3960 3961 3962
    } else {
        incrRefCount(c->argv[2]);
    }
A
antirez 已提交
3963
    deleteKey(c->db,c->argv[1]);
A
antirez 已提交
3964
    server.dirty++;
3965
    addReply(c,nx ? shared.cone : shared.ok);
A
antirez 已提交
3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976
}

static void renameCommand(redisClient *c) {
    renameGenericCommand(c,0);
}

static void renamenxCommand(redisClient *c) {
    renameGenericCommand(c,1);
}

static void moveCommand(redisClient *c) {
A
antirez 已提交
3977 3978
    robj *o;
    redisDb *src, *dst;
A
antirez 已提交
3979 3980 3981
    int srcid;

    /* Obtain source and target DB pointers */
A
antirez 已提交
3982 3983
    src = c->db;
    srcid = c->db->id;
A
antirez 已提交
3984
    if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
3985
        addReply(c,shared.outofrangeerr);
A
antirez 已提交
3986 3987
        return;
    }
A
antirez 已提交
3988 3989
    dst = c->db;
    selectDb(c,srcid); /* Back to the source DB */
A
antirez 已提交
3990 3991 3992 3993

    /* If the user is moving using as target the same
     * DB as the source DB it is probably an error. */
    if (src == dst) {
3994
        addReply(c,shared.sameobjecterr);
A
antirez 已提交
3995 3996 3997 3998
        return;
    }

    /* Check if the element exists and get a reference */
A
antirez 已提交
3999 4000
    o = lookupKeyWrite(c->db,c->argv[1]);
    if (!o) {
4001
        addReply(c,shared.czero);
A
antirez 已提交
4002 4003 4004 4005
        return;
    }

    /* Try to add the element to the target DB */
A
antirez 已提交
4006 4007
    deleteIfVolatile(dst,c->argv[1]);
    if (dictAdd(dst->dict,c->argv[1],o) == DICT_ERR) {
4008
        addReply(c,shared.czero);
A
antirez 已提交
4009 4010
        return;
    }
A
antirez 已提交
4011
    incrRefCount(c->argv[1]);
A
antirez 已提交
4012 4013 4014
    incrRefCount(o);

    /* OK! key moved, free the entry in the source DB */
A
antirez 已提交
4015
    deleteKey(src,c->argv[1]);
A
antirez 已提交
4016
    server.dirty++;
4017
    addReply(c,shared.cone);
A
antirez 已提交
4018 4019 4020 4021 4022 4023
}

/* =================================== Lists ================================ */
static void pushGenericCommand(redisClient *c, int where) {
    robj *lobj;
    list *list;
A
antirez 已提交
4024 4025 4026

    lobj = lookupKeyWrite(c->db,c->argv[1]);
    if (lobj == NULL) {
4027 4028 4029 4030
        if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
            addReply(c,shared.ok);
            return;
        }
A
antirez 已提交
4031 4032 4033
        lobj = createListObject();
        list = lobj->ptr;
        if (where == REDIS_HEAD) {
4034
            listAddNodeHead(list,c->argv[2]);
A
antirez 已提交
4035
        } else {
4036
            listAddNodeTail(list,c->argv[2]);
A
antirez 已提交
4037
        }
A
antirez 已提交
4038
        dictAdd(c->db->dict,c->argv[1],lobj);
A
antirez 已提交
4039 4040 4041 4042 4043 4044 4045
        incrRefCount(c->argv[1]);
        incrRefCount(c->argv[2]);
    } else {
        if (lobj->type != REDIS_LIST) {
            addReply(c,shared.wrongtypeerr);
            return;
        }
4046 4047 4048 4049
        if (handleClientsWaitingListPush(c,c->argv[1],c->argv[2])) {
            addReply(c,shared.ok);
            return;
        }
A
antirez 已提交
4050 4051
        list = lobj->ptr;
        if (where == REDIS_HEAD) {
4052
            listAddNodeHead(list,c->argv[2]);
A
antirez 已提交
4053
        } else {
4054
            listAddNodeTail(list,c->argv[2]);
A
antirez 已提交
4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
        }
        incrRefCount(c->argv[2]);
    }
    server.dirty++;
    addReply(c,shared.ok);
}

static void lpushCommand(redisClient *c) {
    pushGenericCommand(c,REDIS_HEAD);
}

static void rpushCommand(redisClient *c) {
    pushGenericCommand(c,REDIS_TAIL);
}

static void llenCommand(redisClient *c) {
A
antirez 已提交
4071
    robj *o;
A
antirez 已提交
4072 4073
    list *l;
    
A
antirez 已提交
4074 4075
    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
4076
        addReply(c,shared.czero);
A
antirez 已提交
4077 4078 4079
        return;
    } else {
        if (o->type != REDIS_LIST) {
4080
            addReply(c,shared.wrongtypeerr);
A
antirez 已提交
4081 4082
        } else {
            l = o->ptr;
4083
            addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",listLength(l)));
A
antirez 已提交
4084 4085 4086 4087 4088
        }
    }
}

static void lindexCommand(redisClient *c) {
A
antirez 已提交
4089
    robj *o;
A
antirez 已提交
4090 4091
    int index = atoi(c->argv[2]->ptr);
    
A
antirez 已提交
4092 4093
    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
4094
        addReply(c,shared.nullbulk);
A
antirez 已提交
4095 4096
    } else {
        if (o->type != REDIS_LIST) {
4097
            addReply(c,shared.wrongtypeerr);
A
antirez 已提交
4098 4099 4100 4101 4102 4103
        } else {
            list *list = o->ptr;
            listNode *ln;
            
            ln = listIndex(list, index);
            if (ln == NULL) {
4104
                addReply(c,shared.nullbulk);
A
antirez 已提交
4105 4106
            } else {
                robj *ele = listNodeValue(ln);
4107
                addReplyBulkLen(c,ele);
A
antirez 已提交
4108 4109 4110 4111 4112 4113 4114 4115
                addReply(c,ele);
                addReply(c,shared.crlf);
            }
        }
    }
}

static void lsetCommand(redisClient *c) {
A
antirez 已提交
4116
    robj *o;
A
antirez 已提交
4117 4118
    int index = atoi(c->argv[2]->ptr);
    
A
antirez 已提交
4119 4120
    o = lookupKeyWrite(c->db,c->argv[1]);
    if (o == NULL) {
A
antirez 已提交
4121 4122 4123 4124 4125 4126 4127 4128 4129 4130
        addReply(c,shared.nokeyerr);
    } else {
        if (o->type != REDIS_LIST) {
            addReply(c,shared.wrongtypeerr);
        } else {
            list *list = o->ptr;
            listNode *ln;
            
            ln = listIndex(list, index);
            if (ln == NULL) {
4131
                addReply(c,shared.outofrangeerr);
A
antirez 已提交
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145
            } else {
                robj *ele = listNodeValue(ln);

                decrRefCount(ele);
                listNodeValue(ln) = c->argv[3];
                incrRefCount(c->argv[3]);
                addReply(c,shared.ok);
                server.dirty++;
            }
        }
    }
}

static void popGenericCommand(redisClient *c, int where) {
A
antirez 已提交
4146 4147 4148 4149
    robj *o;

    o = lookupKeyWrite(c->db,c->argv[1]);
    if (o == NULL) {
4150
        addReply(c,shared.nullbulk);
A
antirez 已提交
4151 4152
    } else {
        if (o->type != REDIS_LIST) {
4153
            addReply(c,shared.wrongtypeerr);
A
antirez 已提交
4154 4155 4156 4157 4158 4159 4160 4161 4162 4163
        } else {
            list *list = o->ptr;
            listNode *ln;

            if (where == REDIS_HEAD)
                ln = listFirst(list);
            else
                ln = listLast(list);

            if (ln == NULL) {
4164
                addReply(c,shared.nullbulk);
A
antirez 已提交
4165 4166
            } else {
                robj *ele = listNodeValue(ln);
4167
                addReplyBulkLen(c,ele);
A
antirez 已提交
4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185
                addReply(c,ele);
                addReply(c,shared.crlf);
                listDelNode(list,ln);
                server.dirty++;
            }
        }
    }
}

static void lpopCommand(redisClient *c) {
    popGenericCommand(c,REDIS_HEAD);
}

static void rpopCommand(redisClient *c) {
    popGenericCommand(c,REDIS_TAIL);
}

static void lrangeCommand(redisClient *c) {
A
antirez 已提交
4186
    robj *o;
A
antirez 已提交
4187 4188
    int start = atoi(c->argv[2]->ptr);
    int end = atoi(c->argv[3]->ptr);
A
antirez 已提交
4189 4190 4191

    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
4192
        addReply(c,shared.nullmultibulk);
A
antirez 已提交
4193 4194
    } else {
        if (o->type != REDIS_LIST) {
4195
            addReply(c,shared.wrongtypeerr);
A
antirez 已提交
4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211
        } else {
            list *list = o->ptr;
            listNode *ln;
            int llen = listLength(list);
            int rangelen, j;
            robj *ele;

            /* convert negative indexes */
            if (start < 0) start = llen+start;
            if (end < 0) end = llen+end;
            if (start < 0) start = 0;
            if (end < 0) end = 0;

            /* indexes sanity checks */
            if (start > end || start >= llen) {
                /* Out of range start or start > end result in empty list */
4212
                addReply(c,shared.emptymultibulk);
A
antirez 已提交
4213 4214 4215 4216 4217 4218 4219
                return;
            }
            if (end >= llen) end = llen-1;
            rangelen = (end-start)+1;

            /* Return the result in form of a multi-bulk reply */
            ln = listIndex(list, start);
4220
            addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",rangelen));
A
antirez 已提交
4221 4222
            for (j = 0; j < rangelen; j++) {
                ele = listNodeValue(ln);
4223
                addReplyBulkLen(c,ele);
A
antirez 已提交
4224 4225 4226 4227 4228 4229 4230 4231 4232
                addReply(c,ele);
                addReply(c,shared.crlf);
                ln = ln->next;
            }
        }
    }
}

static void ltrimCommand(redisClient *c) {
A
antirez 已提交
4233
    robj *o;
A
antirez 已提交
4234 4235 4236
    int start = atoi(c->argv[2]->ptr);
    int end = atoi(c->argv[3]->ptr);
    
A
antirez 已提交
4237 4238
    o = lookupKeyWrite(c->db,c->argv[1]);
    if (o == NULL) {
4239
        addReply(c,shared.ok);
A
antirez 已提交
4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275
    } else {
        if (o->type != REDIS_LIST) {
            addReply(c,shared.wrongtypeerr);
        } else {
            list *list = o->ptr;
            listNode *ln;
            int llen = listLength(list);
            int j, ltrim, rtrim;

            /* convert negative indexes */
            if (start < 0) start = llen+start;
            if (end < 0) end = llen+end;
            if (start < 0) start = 0;
            if (end < 0) end = 0;

            /* indexes sanity checks */
            if (start > end || start >= llen) {
                /* Out of range start or start > end result in empty list */
                ltrim = llen;
                rtrim = 0;
            } else {
                if (end >= llen) end = llen-1;
                ltrim = start;
                rtrim = llen-end-1;
            }

            /* Remove list elements to perform the trim */
            for (j = 0; j < ltrim; j++) {
                ln = listFirst(list);
                listDelNode(list,ln);
            }
            for (j = 0; j < rtrim; j++) {
                ln = listLast(list);
                listDelNode(list,ln);
            }
            server.dirty++;
4276
            addReply(c,shared.ok);
A
antirez 已提交
4277 4278 4279 4280 4281
        }
    }
}

static void lremCommand(redisClient *c) {
A
antirez 已提交
4282
    robj *o;
A
antirez 已提交
4283
    
A
antirez 已提交
4284 4285
    o = lookupKeyWrite(c->db,c->argv[1]);
    if (o == NULL) {
4286
        addReply(c,shared.czero);
A
antirez 已提交
4287 4288
    } else {
        if (o->type != REDIS_LIST) {
4289
            addReply(c,shared.wrongtypeerr);
A
antirez 已提交
4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303
        } else {
            list *list = o->ptr;
            listNode *ln, *next;
            int toremove = atoi(c->argv[2]->ptr);
            int removed = 0;
            int fromtail = 0;

            if (toremove < 0) {
                toremove = -toremove;
                fromtail = 1;
            }
            ln = fromtail ? list->tail : list->head;
            while (ln) {
                robj *ele = listNodeValue(ln);
A
antirez 已提交
4304 4305

                next = fromtail ? ln->prev : ln->next;
4306
                if (compareStringObjects(ele,c->argv[3]) == 0) {
A
antirez 已提交
4307 4308 4309 4310 4311 4312 4313
                    listDelNode(list,ln);
                    server.dirty++;
                    removed++;
                    if (toremove && removed == toremove) break;
                }
                ln = next;
            }
4314
            addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",removed));
A
antirez 已提交
4315 4316 4317 4318
        }
    }
}

A
antirez 已提交
4319
/* This is the semantic of this command:
A
antirez 已提交
4320
 *  RPOPLPUSH srclist dstlist:
A
antirez 已提交
4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333
 *   IF LLEN(srclist) > 0
 *     element = RPOP srclist
 *     LPUSH dstlist element
 *     RETURN element
 *   ELSE
 *     RETURN nil
 *   END
 *  END
 *
 * The idea is to be able to get an element from a list in a reliable way
 * since the element is not just returned but pushed against another list
 * as well. This command was originally proposed by Ezra Zygmuntowicz.
 */
A
antirez 已提交
4334
static void rpoplpushcommand(redisClient *c) {
A
antirez 已提交
4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353
    robj *sobj;

    sobj = lookupKeyWrite(c->db,c->argv[1]);
    if (sobj == NULL) {
        addReply(c,shared.nullbulk);
    } else {
        if (sobj->type != REDIS_LIST) {
            addReply(c,shared.wrongtypeerr);
        } else {
            list *srclist = sobj->ptr;
            listNode *ln = listLast(srclist);

            if (ln == NULL) {
                addReply(c,shared.nullbulk);
            } else {
                robj *dobj = lookupKeyWrite(c->db,c->argv[2]);
                robj *ele = listNodeValue(ln);
                list *dstlist;

4354
                if (dobj && dobj->type != REDIS_LIST) {
A
antirez 已提交
4355 4356 4357
                    addReply(c,shared.wrongtypeerr);
                    return;
                }
4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371

                /* Add the element to the target list (unless it's directly
                 * passed to some BLPOP-ing client */
                if (!handleClientsWaitingListPush(c,c->argv[2],ele)) {
                    if (dobj == NULL) {
                        /* Create the list if the key does not exist */
                        dobj = createListObject();
                        dictAdd(c->db->dict,c->argv[2],dobj);
                        incrRefCount(c->argv[2]);
                    }
                    dstlist = dobj->ptr;
                    listAddNodeHead(dstlist,ele);
                    incrRefCount(ele);
                }
A
antirez 已提交
4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386

                /* Send the element to the client as reply as well */
                addReplyBulkLen(c,ele);
                addReply(c,ele);
                addReply(c,shared.crlf);

                /* Finally remove the element from the source list */
                listDelNode(srclist,ln);
                server.dirty++;
            }
        }
    }
}


A
antirez 已提交
4387 4388 4389 4390 4391
/* ==================================== Sets ================================ */

static void saddCommand(redisClient *c) {
    robj *set;

A
antirez 已提交
4392 4393
    set = lookupKeyWrite(c->db,c->argv[1]);
    if (set == NULL) {
A
antirez 已提交
4394
        set = createSetObject();
A
antirez 已提交
4395
        dictAdd(c->db->dict,c->argv[1],set);
A
antirez 已提交
4396 4397 4398
        incrRefCount(c->argv[1]);
    } else {
        if (set->type != REDIS_SET) {
4399
            addReply(c,shared.wrongtypeerr);
A
antirez 已提交
4400 4401 4402 4403 4404 4405
            return;
        }
    }
    if (dictAdd(set->ptr,c->argv[2],NULL) == DICT_OK) {
        incrRefCount(c->argv[2]);
        server.dirty++;
4406
        addReply(c,shared.cone);
A
antirez 已提交
4407
    } else {
4408
        addReply(c,shared.czero);
A
antirez 已提交
4409 4410 4411 4412
    }
}

static void sremCommand(redisClient *c) {
A
antirez 已提交
4413
    robj *set;
A
antirez 已提交
4414

A
antirez 已提交
4415 4416
    set = lookupKeyWrite(c->db,c->argv[1]);
    if (set == NULL) {
4417
        addReply(c,shared.czero);
A
antirez 已提交
4418 4419
    } else {
        if (set->type != REDIS_SET) {
4420
            addReply(c,shared.wrongtypeerr);
A
antirez 已提交
4421 4422 4423 4424
            return;
        }
        if (dictDelete(set->ptr,c->argv[2]) == DICT_OK) {
            server.dirty++;
4425
            if (htNeedsResize(set->ptr)) dictResize(set->ptr);
4426
            addReply(c,shared.cone);
A
antirez 已提交
4427
        } else {
4428
            addReply(c,shared.czero);
A
antirez 已提交
4429 4430 4431 4432
        }
    }
}

A
antirez 已提交
4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467
static void smoveCommand(redisClient *c) {
    robj *srcset, *dstset;

    srcset = lookupKeyWrite(c->db,c->argv[1]);
    dstset = lookupKeyWrite(c->db,c->argv[2]);

    /* If the source key does not exist return 0, if it's of the wrong type
     * raise an error */
    if (srcset == NULL || srcset->type != REDIS_SET) {
        addReply(c, srcset ? shared.wrongtypeerr : shared.czero);
        return;
    }
    /* Error if the destination key is not a set as well */
    if (dstset && dstset->type != REDIS_SET) {
        addReply(c,shared.wrongtypeerr);
        return;
    }
    /* Remove the element from the source set */
    if (dictDelete(srcset->ptr,c->argv[3]) == DICT_ERR) {
        /* Key not found in the src set! return zero */
        addReply(c,shared.czero);
        return;
    }
    server.dirty++;
    /* Add the element to the destination set */
    if (!dstset) {
        dstset = createSetObject();
        dictAdd(c->db->dict,c->argv[2],dstset);
        incrRefCount(c->argv[2]);
    }
    if (dictAdd(dstset->ptr,c->argv[3],NULL) == DICT_OK)
        incrRefCount(c->argv[3]);
    addReply(c,shared.cone);
}

A
antirez 已提交
4468
static void sismemberCommand(redisClient *c) {
A
antirez 已提交
4469
    robj *set;
A
antirez 已提交
4470

A
antirez 已提交
4471 4472
    set = lookupKeyRead(c->db,c->argv[1]);
    if (set == NULL) {
4473
        addReply(c,shared.czero);
A
antirez 已提交
4474 4475
    } else {
        if (set->type != REDIS_SET) {
4476
            addReply(c,shared.wrongtypeerr);
A
antirez 已提交
4477 4478 4479
            return;
        }
        if (dictFind(set->ptr,c->argv[2]))
4480
            addReply(c,shared.cone);
A
antirez 已提交
4481
        else
4482
            addReply(c,shared.czero);
A
antirez 已提交
4483 4484 4485 4486
    }
}

static void scardCommand(redisClient *c) {
A
antirez 已提交
4487
    robj *o;
A
antirez 已提交
4488 4489
    dict *s;
    
A
antirez 已提交
4490 4491
    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
4492
        addReply(c,shared.czero);
A
antirez 已提交
4493 4494 4495
        return;
    } else {
        if (o->type != REDIS_SET) {
4496
            addReply(c,shared.wrongtypeerr);
A
antirez 已提交
4497 4498
        } else {
            s = o->ptr;
4499
            addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",
A
antirez 已提交
4500
                dictSize(s)));
A
antirez 已提交
4501 4502 4503 4504
        }
    }
}

4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522
static void spopCommand(redisClient *c) {
    robj *set;
    dictEntry *de;

    set = lookupKeyWrite(c->db,c->argv[1]);
    if (set == NULL) {
        addReply(c,shared.nullbulk);
    } else {
        if (set->type != REDIS_SET) {
            addReply(c,shared.wrongtypeerr);
            return;
        }
        de = dictGetRandomKey(set->ptr);
        if (de == NULL) {
            addReply(c,shared.nullbulk);
        } else {
            robj *ele = dictGetEntryKey(de);

4523
            addReplyBulkLen(c,ele);
4524 4525 4526 4527 4528 4529 4530 4531 4532
            addReply(c,ele);
            addReply(c,shared.crlf);
            dictDelete(set->ptr,ele);
            if (htNeedsResize(set->ptr)) dictResize(set->ptr);
            server.dirty++;
        }
    }
}

A
antirez 已提交
4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557
static void srandmemberCommand(redisClient *c) {
    robj *set;
    dictEntry *de;

    set = lookupKeyRead(c->db,c->argv[1]);
    if (set == NULL) {
        addReply(c,shared.nullbulk);
    } else {
        if (set->type != REDIS_SET) {
            addReply(c,shared.wrongtypeerr);
            return;
        }
        de = dictGetRandomKey(set->ptr);
        if (de == NULL) {
            addReply(c,shared.nullbulk);
        } else {
            robj *ele = dictGetEntryKey(de);

            addReplyBulkLen(c,ele);
            addReply(c,ele);
            addReply(c,shared.crlf);
        }
    }
}

A
antirez 已提交
4558 4559 4560
static int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
    dict **d1 = (void*) s1, **d2 = (void*) s2;

A
antirez 已提交
4561
    return dictSize(*d1)-dictSize(*d2);
A
antirez 已提交
4562 4563
}

4564
static void sinterGenericCommand(redisClient *c, robj **setskeys, unsigned long setsnum, robj *dstkey) {
A
antirez 已提交
4565 4566 4567 4568
    dict **dv = zmalloc(sizeof(dict*)*setsnum);
    dictIterator *di;
    dictEntry *de;
    robj *lenobj = NULL, *dstset = NULL;
4569
    unsigned long j, cardinality = 0;
A
antirez 已提交
4570 4571 4572

    for (j = 0; j < setsnum; j++) {
        robj *setobj;
A
antirez 已提交
4573 4574 4575 4576 4577

        setobj = dstkey ?
                    lookupKeyWrite(c->db,setskeys[j]) :
                    lookupKeyRead(c->db,setskeys[j]);
        if (!setobj) {
A
antirez 已提交
4578
            zfree(dv);
4579
            if (dstkey) {
4580 4581
                if (deleteKey(c->db,dstkey))
                    server.dirty++;
A
antirez 已提交
4582
                addReply(c,shared.czero);
4583 4584 4585
            } else {
                addReply(c,shared.nullmultibulk);
            }
A
antirez 已提交
4586 4587 4588 4589
            return;
        }
        if (setobj->type != REDIS_SET) {
            zfree(dv);
4590
            addReply(c,shared.wrongtypeerr);
A
antirez 已提交
4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627
            return;
        }
        dv[j] = setobj->ptr;
    }
    /* Sort sets from the smallest to largest, this will improve our
     * algorithm's performace */
    qsort(dv,setsnum,sizeof(dict*),qsortCompareSetsByCardinality);

    /* The first thing we should output is the total number of elements...
     * since this is a multi-bulk write, but at this stage we don't know
     * the intersection set size, so we use a trick, append an empty object
     * to the output list and save the pointer to later modify it with the
     * right length */
    if (!dstkey) {
        lenobj = createObject(REDIS_STRING,NULL);
        addReply(c,lenobj);
        decrRefCount(lenobj);
    } else {
        /* If we have a target key where to store the resulting set
         * create this key with an empty set inside */
        dstset = createSetObject();
    }

    /* Iterate all the elements of the first (smallest) set, and test
     * the element against all the other sets, if at least one set does
     * not include the element it is discarded */
    di = dictGetIterator(dv[0]);

    while((de = dictNext(di)) != NULL) {
        robj *ele;

        for (j = 1; j < setsnum; j++)
            if (dictFind(dv[j],dictGetEntryKey(de)) == NULL) break;
        if (j != setsnum)
            continue; /* at least one set does not contain the member */
        ele = dictGetEntryKey(de);
        if (!dstkey) {
4628
            addReplyBulkLen(c,ele);
A
antirez 已提交
4629 4630 4631 4632 4633 4634 4635 4636 4637 4638
            addReply(c,ele);
            addReply(c,shared.crlf);
            cardinality++;
        } else {
            dictAdd(dstset->ptr,ele,NULL);
            incrRefCount(ele);
        }
    }
    dictReleaseIterator(di);

4639 4640 4641 4642 4643 4644 4645
    if (dstkey) {
        /* Store the resulting set into the target */
        deleteKey(c->db,dstkey);
        dictAdd(c->db->dict,dstkey,dstset);
        incrRefCount(dstkey);
    }

4646
    if (!dstkey) {
4647
        lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
4648
    } else {
4649
        addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",
4650
            dictSize((dict*)dstset->ptr)));
4651 4652
        server.dirty++;
    }
A
antirez 已提交
4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663
    zfree(dv);
}

static void sinterCommand(redisClient *c) {
    sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
}

static void sinterstoreCommand(redisClient *c) {
    sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
}

4664 4665 4666 4667
#define REDIS_OP_UNION 0
#define REDIS_OP_DIFF 1

static void sunionDiffGenericCommand(redisClient *c, robj **setskeys, int setsnum, robj *dstkey, int op) {
4668 4669 4670
    dict **dv = zmalloc(sizeof(dict*)*setsnum);
    dictIterator *di;
    dictEntry *de;
4671
    robj *dstset = NULL;
4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699
    int j, cardinality = 0;

    for (j = 0; j < setsnum; j++) {
        robj *setobj;

        setobj = dstkey ?
                    lookupKeyWrite(c->db,setskeys[j]) :
                    lookupKeyRead(c->db,setskeys[j]);
        if (!setobj) {
            dv[j] = NULL;
            continue;
        }
        if (setobj->type != REDIS_SET) {
            zfree(dv);
            addReply(c,shared.wrongtypeerr);
            return;
        }
        dv[j] = setobj->ptr;
    }

    /* We need a temp set object to store our union. If the dstkey
     * is not NULL (that is, we are inside an SUNIONSTORE operation) then
     * this set object will be the resulting object to set into the target key*/
    dstset = createSetObject();

    /* Iterate all the elements of all the sets, add every element a single
     * time to the result set */
    for (j = 0; j < setsnum; j++) {
4700
        if (op == REDIS_OP_DIFF && j == 0 && !dv[j]) break; /* result set is empty */
4701 4702 4703 4704 4705 4706 4707 4708 4709
        if (!dv[j]) continue; /* non existing keys are like empty sets */

        di = dictGetIterator(dv[j]);

        while((de = dictNext(di)) != NULL) {
            robj *ele;

            /* dictAdd will not add the same element multiple times */
            ele = dictGetEntryKey(de);
4710 4711 4712
            if (op == REDIS_OP_UNION || j == 0) {
                if (dictAdd(dstset->ptr,ele,NULL) == DICT_OK) {
                    incrRefCount(ele);
4713 4714
                    cardinality++;
                }
4715 4716 4717 4718
            } else if (op == REDIS_OP_DIFF) {
                if (dictDelete(dstset->ptr,ele) == DICT_OK) {
                    cardinality--;
                }
4719 4720 4721
            }
        }
        dictReleaseIterator(di);
4722 4723

        if (op == REDIS_OP_DIFF && cardinality == 0) break; /* result set is empty */
4724 4725
    }

4726 4727 4728 4729 4730 4731 4732 4733
    /* Output the content of the resulting set, if not in STORE mode */
    if (!dstkey) {
        addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
        di = dictGetIterator(dstset->ptr);
        while((de = dictNext(di)) != NULL) {
            robj *ele;

            ele = dictGetEntryKey(de);
4734
            addReplyBulkLen(c,ele);
4735 4736 4737 4738
            addReply(c,ele);
            addReply(c,shared.crlf);
        }
        dictReleaseIterator(di);
4739 4740 4741 4742 4743 4744
    } else {
        /* If we have a target key where to store the resulting set
         * create this key with the result set inside */
        deleteKey(c->db,dstkey);
        dictAdd(c->db->dict,dstkey,dstset);
        incrRefCount(dstkey);
4745 4746 4747
    }

    /* Cleanup */
4748 4749 4750
    if (!dstkey) {
        decrRefCount(dstset);
    } else {
4751
        addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",
4752
            dictSize((dict*)dstset->ptr)));
4753 4754 4755 4756 4757 4758
        server.dirty++;
    }
    zfree(dv);
}

static void sunionCommand(redisClient *c) {
4759
    sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
4760 4761 4762
}

static void sunionstoreCommand(redisClient *c) {
4763 4764 4765 4766 4767 4768 4769 4770 4771
    sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
}

static void sdiffCommand(redisClient *c) {
    sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
}

static void sdiffstoreCommand(redisClient *c) {
    sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
4772 4773
}

4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807
/* ==================================== ZSets =============================== */

/* ZSETs are ordered sets using two data structures to hold the same elements
 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
 * data structure.
 *
 * The elements are added to an hash table mapping Redis objects to scores.
 * At the same time the elements are added to a skip list mapping scores
 * to Redis objects (so objects are sorted by scores in this "view"). */

/* This skiplist implementation is almost a C translation of the original
 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
 * Alternative to Balanced Trees", modified in three ways:
 * a) this implementation allows for repeated values.
 * b) the comparison is not just by key (our 'score') but by satellite data.
 * c) there is a back pointer, so it's a doubly linked list with the back
 * pointers being only at "level 1". This allows to traverse the list
 * from tail to head, useful for ZREVRANGE. */

static zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
    zskiplistNode *zn = zmalloc(sizeof(*zn));

    zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
    zn->score = score;
    zn->obj = obj;
    return zn;
}

static zskiplist *zslCreate(void) {
    int j;
    zskiplist *zsl;
    
    zsl = zmalloc(sizeof(*zsl));
    zsl->level = 1;
4808
    zsl->length = 0;
4809 4810 4811
    zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
    for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++)
        zsl->header->forward[j] = NULL;
4812 4813
    zsl->header->backward = NULL;
    zsl->tail = NULL;
4814 4815 4816
    return zsl;
}

4817 4818
static void zslFreeNode(zskiplistNode *node) {
    decrRefCount(node->obj);
4819
    zfree(node->forward);
4820 4821 4822 4823
    zfree(node);
}

static void zslFree(zskiplist *zsl) {
4824
    zskiplistNode *node = zsl->header->forward[0], *next;
4825

4826 4827
    zfree(zsl->header->forward);
    zfree(zsl->header);
4828
    while(node) {
4829
        next = node->forward[0];
4830 4831 4832
        zslFreeNode(node);
        node = next;
    }
4833
    zfree(zsl);
4834 4835
}

4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848
static int zslRandomLevel(void) {
    int level = 1;
    while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
        level += 1;
    return level;
}

static void zslInsert(zskiplist *zsl, double score, robj *obj) {
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    int i, level;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
4849 4850 4851 4852
        while (x->forward[i] &&
            (x->forward[i]->score < score ||
                (x->forward[i]->score == score &&
                compareStringObjects(x->forward[i]->obj,obj) < 0)))
4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870
            x = x->forward[i];
        update[i] = x;
    }
    /* we assume the key is not already inside, since we allow duplicated
     * scores, and the re-insertion of score and redis object should never
     * happpen since the caller of zslInsert() should test in the hash table
     * if the element is already inside or not. */
    level = zslRandomLevel();
    if (level > zsl->level) {
        for (i = zsl->level; i < level; i++)
            update[i] = zsl->header;
        zsl->level = level;
    }
    x = zslCreateNode(level,score,obj);
    for (i = 0; i < level; i++) {
        x->forward[i] = update[i]->forward[i];
        update[i]->forward[i] = x;
    }
A
antirez 已提交
4871
    x->backward = (update[0] == zsl->header) ? NULL : update[0];
4872 4873 4874 4875
    if (x->forward[0])
        x->forward[0]->backward = x;
    else
        zsl->tail = x;
4876
    zsl->length++;
4877 4878
}

4879
/* Delete an element with matching score/object from the skiplist. */
4880
static int zslDelete(zskiplist *zsl, double score, robj *obj) {
4881 4882 4883 4884 4885
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
4886 4887 4888 4889
        while (x->forward[i] &&
            (x->forward[i]->score < score ||
                (x->forward[i]->score == score &&
                compareStringObjects(x->forward[i]->obj,obj) < 0)))
4890 4891 4892 4893 4894 4895
            x = x->forward[i];
        update[i] = x;
    }
    /* We may have multiple elements with the same score, what we need
     * is to find the element with both the right score and object. */
    x = x->forward[0];
4896
    if (x && score == x->score && compareStringObjects(x->obj,obj) == 0) {
4897 4898 4899 4900 4901 4902 4903
        for (i = 0; i < zsl->level; i++) {
            if (update[i]->forward[i] != x) break;
            update[i]->forward[i] = x->forward[i];
        }
        if (x->forward[0]) {
            x->forward[0]->backward = (x->backward == zsl->header) ?
                                        NULL : x->backward;
4904
        } else {
4905
            zsl->tail = x->backward;
4906
        }
4907 4908 4909 4910 4911 4912 4913
        zslFreeNode(x);
        while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
            zsl->level--;
        zsl->length--;
        return 1;
    } else {
        return 0; /* not found */
4914 4915
    }
    return 0; /* not found */
4916 4917
}

4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960
/* Delete all the elements with score between min and max from the skiplist.
 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
 * Note that this function takes the reference to the hash table view of the
 * sorted set, in order to remove the elements from the hash table too. */
static unsigned long zslDeleteRange(zskiplist *zsl, double min, double max, dict *dict) {
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    unsigned long removed = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        while (x->forward[i] && x->forward[i]->score < min)
            x = x->forward[i];
        update[i] = x;
    }
    /* We may have multiple elements with the same score, what we need
     * is to find the element with both the right score and object. */
    x = x->forward[0];
    while (x && x->score <= max) {
        zskiplistNode *next;

        for (i = 0; i < zsl->level; i++) {
            if (update[i]->forward[i] != x) break;
            update[i]->forward[i] = x->forward[i];
        }
        if (x->forward[0]) {
            x->forward[0]->backward = (x->backward == zsl->header) ?
                                        NULL : x->backward;
        } else {
            zsl->tail = x->backward;
        }
        next = x->forward[0];
        dictDelete(dict,x->obj);
        zslFreeNode(x);
        while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
            zsl->level--;
        zsl->length--;
        removed++;
        x = next;
    }
    return removed; /* not found */
}

4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976
/* Find the first node having a score equal or greater than the specified one.
 * Returns NULL if there is no match. */
static zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
    zskiplistNode *x;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        while (x->forward[i] && x->forward[i]->score < score)
            x = x->forward[i];
    }
    /* We may have multiple elements with the same score, what we need
     * is to find the element with both the right score and object. */
    return x->forward[0];
}

4977 4978
/* The actual Z-commands implementations */

A
antirez 已提交
4979
/* This generic command implements both ZADD and ZINCRBY.
A
antirez 已提交
4980
 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
A
antirez 已提交
4981
 * the increment if the operation is a ZINCRBY (doincrement == 1). */
A
antirez 已提交
4982
static void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
4983 4984 4985 4986
    robj *zsetobj;
    zset *zs;
    double *score;

A
antirez 已提交
4987
    zsetobj = lookupKeyWrite(c->db,key);
4988 4989
    if (zsetobj == NULL) {
        zsetobj = createZsetObject();
A
antirez 已提交
4990 4991
        dictAdd(c->db->dict,key,zsetobj);
        incrRefCount(key);
4992 4993 4994 4995 4996 4997 4998
    } else {
        if (zsetobj->type != REDIS_ZSET) {
            addReply(c,shared.wrongtypeerr);
            return;
        }
    }
    zs = zsetobj->ptr;
A
antirez 已提交
4999

A
antirez 已提交
5000
    /* Ok now since we implement both ZADD and ZINCRBY here the code
A
antirez 已提交
5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019
     * needs to handle the two different conditions. It's all about setting
     * '*score', that is, the new score to set, to the right value. */
    score = zmalloc(sizeof(double));
    if (doincrement) {
        dictEntry *de;

        /* Read the old score. If the element was not present starts from 0 */
        de = dictFind(zs->dict,ele);
        if (de) {
            double *oldscore = dictGetEntryVal(de);
            *score = *oldscore + scoreval;
        } else {
            *score = scoreval;
        }
    } else {
        *score = scoreval;
    }

    /* What follows is a simple remove and re-insert operation that is common
A
antirez 已提交
5020
     * to both ZADD and ZINCRBY... */
A
antirez 已提交
5021
    if (dictAdd(zs->dict,ele,score) == DICT_OK) {
5022
        /* case 1: New element */
A
antirez 已提交
5023 5024 5025
        incrRefCount(ele); /* added to hash */
        zslInsert(zs->zsl,*score,ele);
        incrRefCount(ele); /* added to skiplist */
5026
        server.dirty++;
A
antirez 已提交
5027 5028
        if (doincrement)
            addReplyDouble(c,*score);
A
antirez 已提交
5029 5030
        else
            addReply(c,shared.cone);
5031 5032 5033 5034 5035
    } else {
        dictEntry *de;
        double *oldscore;
        
        /* case 2: Score update operation */
A
antirez 已提交
5036
        de = dictFind(zs->dict,ele);
5037
        redisAssert(de != NULL);
5038 5039 5040 5041
        oldscore = dictGetEntryVal(de);
        if (*score != *oldscore) {
            int deleted;

A
antirez 已提交
5042 5043
            /* Remove and insert the element in the skip list with new score */
            deleted = zslDelete(zs->zsl,*oldscore,ele);
5044
            redisAssert(deleted != 0);
A
antirez 已提交
5045 5046 5047 5048
            zslInsert(zs->zsl,*score,ele);
            incrRefCount(ele);
            /* Update the score in the hash table */
            dictReplace(zs->dict,ele,score);
5049
            server.dirty++;
5050 5051
        } else {
            zfree(score);
5052
        }
A
antirez 已提交
5053 5054 5055 5056
        if (doincrement)
            addReplyDouble(c,*score);
        else
            addReply(c,shared.czero);
5057 5058 5059
    }
}

A
antirez 已提交
5060 5061 5062 5063 5064 5065 5066
static void zaddCommand(redisClient *c) {
    double scoreval;

    scoreval = strtod(c->argv[2]->ptr,NULL);
    zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
}

A
antirez 已提交
5067
static void zincrbyCommand(redisClient *c) {
A
antirez 已提交
5068 5069 5070 5071 5072 5073
    double scoreval;

    scoreval = strtod(c->argv[2]->ptr,NULL);
    zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
}

A
antirez 已提交
5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098
static void zremCommand(redisClient *c) {
    robj *zsetobj;
    zset *zs;

    zsetobj = lookupKeyWrite(c->db,c->argv[1]);
    if (zsetobj == NULL) {
        addReply(c,shared.czero);
    } else {
        dictEntry *de;
        double *oldscore;
        int deleted;

        if (zsetobj->type != REDIS_ZSET) {
            addReply(c,shared.wrongtypeerr);
            return;
        }
        zs = zsetobj->ptr;
        de = dictFind(zs->dict,c->argv[2]);
        if (de == NULL) {
            addReply(c,shared.czero);
            return;
        }
        /* Delete from the skiplist */
        oldscore = dictGetEntryVal(de);
        deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
5099
        redisAssert(deleted != 0);
A
antirez 已提交
5100 5101 5102 5103 5104 5105 5106 5107 5108

        /* Delete from the hash table */
        dictDelete(zs->dict,c->argv[2]);
        if (htNeedsResize(zs->dict)) dictResize(zs->dict);
        server.dirty++;
        addReply(c,shared.cone);
    }
}

5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132
static void zremrangebyscoreCommand(redisClient *c) {
    double min = strtod(c->argv[2]->ptr,NULL);
    double max = strtod(c->argv[3]->ptr,NULL);
    robj *zsetobj;
    zset *zs;

    zsetobj = lookupKeyWrite(c->db,c->argv[1]);
    if (zsetobj == NULL) {
        addReply(c,shared.czero);
    } else {
        long deleted;

        if (zsetobj->type != REDIS_ZSET) {
            addReply(c,shared.wrongtypeerr);
            return;
        }
        zs = zsetobj->ptr;
        deleted = zslDeleteRange(zs->zsl,min,max,zs->dict);
        if (htNeedsResize(zs->dict)) dictResize(zs->dict);
        server.dirty += deleted;
        addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",deleted));
    }
}

5133
static void zrangeGenericCommand(redisClient *c, int reverse) {
5134 5135 5136
    robj *o;
    int start = atoi(c->argv[2]->ptr);
    int end = atoi(c->argv[3]->ptr);
5137 5138 5139 5140 5141 5142 5143 5144
    int withscores = 0;

    if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
        withscores = 1;
    } else if (c->argc >= 5) {
        addReply(c,shared.syntaxerr);
        return;
    }
5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176

    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
        addReply(c,shared.nullmultibulk);
    } else {
        if (o->type != REDIS_ZSET) {
            addReply(c,shared.wrongtypeerr);
        } else {
            zset *zsetobj = o->ptr;
            zskiplist *zsl = zsetobj->zsl;
            zskiplistNode *ln;

            int llen = zsl->length;
            int rangelen, j;
            robj *ele;

            /* convert negative indexes */
            if (start < 0) start = llen+start;
            if (end < 0) end = llen+end;
            if (start < 0) start = 0;
            if (end < 0) end = 0;

            /* indexes sanity checks */
            if (start > end || start >= llen) {
                /* Out of range start or start > end result in empty list */
                addReply(c,shared.emptymultibulk);
                return;
            }
            if (end >= llen) end = llen-1;
            rangelen = (end-start)+1;

            /* Return the result in form of a multi-bulk reply */
5177 5178 5179 5180 5181 5182 5183 5184 5185
            if (reverse) {
                ln = zsl->tail;
                while (start--)
                    ln = ln->backward;
            } else {
                ln = zsl->header->forward[0];
                while (start--)
                    ln = ln->forward[0];
            }
5186

5187 5188
            addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
                withscores ? (rangelen*2) : rangelen));
5189
            for (j = 0; j < rangelen; j++) {
5190
                ele = ln->obj;
5191 5192 5193
                addReplyBulkLen(c,ele);
                addReply(c,ele);
                addReply(c,shared.crlf);
5194 5195
                if (withscores)
                    addReplyDouble(c,ln->score);
5196
                ln = reverse ? ln->backward : ln->forward[0];
5197 5198 5199 5200 5201
            }
        }
    }
}

5202 5203 5204 5205 5206 5207 5208 5209
static void zrangeCommand(redisClient *c) {
    zrangeGenericCommand(c,0);
}

static void zrevrangeCommand(redisClient *c) {
    zrangeGenericCommand(c,1);
}

5210 5211 5212
/* This command implements both ZRANGEBYSCORE and ZCOUNT.
 * If justcount is non-zero, just the count is returned. */
static void genericZrangebyscoreCommand(redisClient *c, int justcount) {
5213
    robj *o;
5214 5215
    double min, max;
    int minex = 0, maxex = 0; /* are min or max exclusive? */
5216
    int offset = 0, limit = -1;
5217 5218 5219
    int withscores = 0;
    int badsyntax = 0;

5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239
    /* Parse the min-max interval. If one of the values is prefixed
     * by the "(" character, it's considered "open". For instance
     * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
     * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
    if (((char*)c->argv[2]->ptr)[0] == '(') {
        min = strtod((char*)c->argv[2]->ptr+1,NULL);
        minex = 1;
    } else {
        min = strtod(c->argv[2]->ptr,NULL);
    }
    if (((char*)c->argv[3]->ptr)[0] == '(') {
        max = strtod((char*)c->argv[3]->ptr+1,NULL);
        maxex = 1;
    } else {
        max = strtod(c->argv[3]->ptr,NULL);
    }

    /* Parse "WITHSCORES": note that if the command was called with
     * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
     * enter the following paths to parse WITHSCORES and LIMIT. */
5240
    if (c->argc == 5 || c->argc == 8) {
5241 5242 5243 5244
        if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
            withscores = 1;
        else
            badsyntax = 1;
5245
    }
5246
    if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
5247 5248
        badsyntax = 1;
    if (badsyntax) {
5249 5250
        addReplySds(c,
            sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5251
        return;
5252 5253
    }

5254
    /* Parse "LIMIT" */
5255
    if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
5256 5257
        addReply(c,shared.syntaxerr);
        return;
5258
    } else if (c->argc == (7 + withscores)) {
5259 5260
        offset = atoi(c->argv[5]->ptr);
        limit = atoi(c->argv[6]->ptr);
5261
        if (offset < 0) offset = 0;
5262
    }
5263

5264
    /* Ok, lookup the key and get the range */
5265 5266
    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
5267
        addReply(c,justcount ? shared.czero : shared.nullmultibulk);
5268 5269 5270 5271 5272 5273 5274
    } else {
        if (o->type != REDIS_ZSET) {
            addReply(c,shared.wrongtypeerr);
        } else {
            zset *zsetobj = o->ptr;
            zskiplist *zsl = zsetobj->zsl;
            zskiplistNode *ln;
5275 5276
            robj *ele, *lenobj = NULL;
            unsigned long rangelen = 0;
5277

5278 5279
            /* Get the first node with the score >= min, or with
             * score > min if 'minex' is true. */
5280
            ln = zslFirstWithScore(zsl,min);
5281 5282
            while (minex && ln && ln->score == min) ln = ln->forward[0];

5283 5284
            if (ln == NULL) {
                /* No element matching the speciifed interval */
5285
                addReply(c,justcount ? shared.czero : shared.emptymultibulk);
5286 5287 5288 5289 5290 5291 5292
                return;
            }

            /* We don't know in advance how many matching elements there
             * are in the list, so we push this object that will represent
             * the multi-bulk length in the output buffer, and will "fix"
             * it later */
5293 5294 5295 5296 5297
            if (!justcount) {
                lenobj = createObject(REDIS_STRING,NULL);
                addReply(c,lenobj);
                decrRefCount(lenobj);
            }
5298

5299
            while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
5300 5301 5302 5303 5304 5305
                if (offset) {
                    offset--;
                    ln = ln->forward[0];
                    continue;
                }
                if (limit == 0) break;
5306 5307 5308 5309 5310 5311 5312 5313
                if (!justcount) {
                    ele = ln->obj;
                    addReplyBulkLen(c,ele);
                    addReply(c,ele);
                    addReply(c,shared.crlf);
                    if (withscores)
                        addReplyDouble(c,ln->score);
                }
5314 5315
                ln = ln->forward[0];
                rangelen++;
5316
                if (limit > 0) limit--;
5317
            }
5318 5319 5320 5321 5322 5323
            if (justcount) {
                addReplyLong(c,(long)rangelen);
            } else {
                lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
                     withscores ? (rangelen*2) : rangelen);
            }
5324 5325 5326 5327
        }
    }
}

5328 5329 5330 5331 5332 5333 5334 5335
static void zrangebyscoreCommand(redisClient *c) {
    genericZrangebyscoreCommand(c,0);
}

static void zcountCommand(redisClient *c) {
    genericZrangebyscoreCommand(c,1);
}

5336
static void zcardCommand(redisClient *c) {
5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348
    robj *o;
    zset *zs;
    
    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
        addReply(c,shared.czero);
        return;
    } else {
        if (o->type != REDIS_ZSET) {
            addReply(c,shared.wrongtypeerr);
        } else {
            zs = o->ptr;
5349
            addReplySds(c,sdscatprintf(sdsempty(),":%lu\r\n",zs->zsl->length));
5350 5351 5352 5353
        }
    }
}

A
antirez 已提交
5354 5355 5356 5357 5358 5359
static void zscoreCommand(redisClient *c) {
    robj *o;
    zset *zs;
    
    o = lookupKeyRead(c->db,c->argv[1]);
    if (o == NULL) {
5360
        addReply(c,shared.nullbulk);
A
antirez 已提交
5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374
        return;
    } else {
        if (o->type != REDIS_ZSET) {
            addReply(c,shared.wrongtypeerr);
        } else {
            dictEntry *de;

            zs = o->ptr;
            de = dictFind(zs->dict,c->argv[2]);
            if (!de) {
                addReply(c,shared.nullbulk);
            } else {
                double *score = dictGetEntryVal(de);

A
antirez 已提交
5375
                addReplyDouble(c,*score);
A
antirez 已提交
5376 5377 5378 5379 5380
            }
        }
    }
}

5381 5382
/* ========================= Non type-specific commands  ==================== */

A
antirez 已提交
5383
static void flushdbCommand(redisClient *c) {
5384
    server.dirty += dictSize(c->db->dict);
A
antirez 已提交
5385 5386
    dictEmpty(c->db->dict);
    dictEmpty(c->db->expires);
A
antirez 已提交
5387 5388 5389 5390
    addReply(c,shared.ok);
}

static void flushallCommand(redisClient *c) {
5391
    server.dirty += emptyDb();
A
antirez 已提交
5392
    addReply(c,shared.ok);
5393
    rdbSave(server.dbfilename);
5394
    server.dirty++;
A
antirez 已提交
5395 5396
}

5397
static redisSortOperation *createSortOperation(int type, robj *pattern) {
A
antirez 已提交
5398 5399 5400 5401 5402 5403 5404 5405
    redisSortOperation *so = zmalloc(sizeof(*so));
    so->type = type;
    so->pattern = pattern;
    return so;
}

/* Return the value associated to the key with a name obtained
 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5406
static robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst) {
A
antirez 已提交
5407 5408 5409 5410 5411 5412
    char *p;
    sds spat, ssub;
    robj keyobj;
    int prefixlen, sublen, postfixlen;
    /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
    struct {
5413 5414
        long len;
        long free;
A
antirez 已提交
5415 5416 5417
        char buf[REDIS_SORTKEY_MAX+1];
    } keyname;

A
antirez 已提交
5418 5419 5420 5421 5422 5423 5424 5425
    /* If the pattern is "#" return the substitution object itself in order
     * to implement the "SORT ... GET #" feature. */
    spat = pattern->ptr;
    if (spat[0] == '#' && spat[1] == '\0') {
        return subst;
    }

    /* The substitution object may be specially encoded. If so we create
5426 5427 5428
     * a decoded object on the fly. Otherwise getDecodedObject will just
     * increment the ref count, that we'll decrement later. */
    subst = getDecodedObject(subst);
5429

A
antirez 已提交
5430 5431 5432
    ssub = subst->ptr;
    if (sdslen(spat)+sdslen(ssub)-1 > REDIS_SORTKEY_MAX) return NULL;
    p = strchr(spat,'*');
5433 5434 5435 5436
    if (!p) {
        decrRefCount(subst);
        return NULL;
    }
A
antirez 已提交
5437 5438 5439 5440 5441 5442 5443 5444 5445 5446

    prefixlen = p-spat;
    sublen = sdslen(ssub);
    postfixlen = sdslen(spat)-(prefixlen+1);
    memcpy(keyname.buf,spat,prefixlen);
    memcpy(keyname.buf+prefixlen,ssub,sublen);
    memcpy(keyname.buf+prefixlen+sublen,p+1,postfixlen);
    keyname.buf[prefixlen+sublen+postfixlen] = '\0';
    keyname.len = prefixlen+sublen+postfixlen;

5447
    initStaticStringObject(keyobj,((char*)&keyname)+(sizeof(long)*2))
5448 5449
    decrRefCount(subst);

A
antirez 已提交
5450
    /* printf("lookup '%s' => %p\n", keyname.buf,de); */
A
antirez 已提交
5451
    return lookupKeyRead(db,&keyobj);
A
antirez 已提交
5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486
}

/* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
 * the additional parameter is not standard but a BSD-specific we have to
 * pass sorting parameters via the global 'server' structure */
static int sortCompare(const void *s1, const void *s2) {
    const redisSortObject *so1 = s1, *so2 = s2;
    int cmp;

    if (!server.sort_alpha) {
        /* Numeric sorting. Here it's trivial as we precomputed scores */
        if (so1->u.score > so2->u.score) {
            cmp = 1;
        } else if (so1->u.score < so2->u.score) {
            cmp = -1;
        } else {
            cmp = 0;
        }
    } else {
        /* Alphanumeric sorting */
        if (server.sort_bypattern) {
            if (!so1->u.cmpobj || !so2->u.cmpobj) {
                /* At least one compare object is NULL */
                if (so1->u.cmpobj == so2->u.cmpobj)
                    cmp = 0;
                else if (so1->u.cmpobj == NULL)
                    cmp = -1;
                else
                    cmp = 1;
            } else {
                /* We have both the objects, use strcoll */
                cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr);
            }
        } else {
            /* Compare elements directly */
5487 5488 5489 5490 5491 5492 5493
            robj *dec1, *dec2;

            dec1 = getDecodedObject(so1->obj);
            dec2 = getDecodedObject(so2->obj);
            cmp = strcoll(dec1->ptr,dec2->ptr);
            decrRefCount(dec1);
            decrRefCount(dec2);
A
antirez 已提交
5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507
        }
    }
    return server.sort_desc ? -cmp : cmp;
}

/* The SORT command is the most complex command in Redis. Warning: this code
 * is optimized for speed and a bit less for readability */
static void sortCommand(redisClient *c) {
    list *operations;
    int outputlen = 0;
    int desc = 0, alpha = 0;
    int limit_start = 0, limit_count = -1, start, end;
    int j, dontsort = 0, vectorlen;
    int getop = 0; /* GET operation counter */
A
antirez 已提交
5508
    robj *sortval, *sortby = NULL, *storekey = NULL;
A
antirez 已提交
5509 5510 5511
    redisSortObject *vector; /* Resulting vector to sort */

    /* Lookup the key to sort. It must be of the right types */
A
antirez 已提交
5512 5513
    sortval = lookupKeyRead(c->db,c->argv[1]);
    if (sortval == NULL) {
5514
        addReply(c,shared.nullmultibulk);
A
antirez 已提交
5515 5516
        return;
    }
A
antirez 已提交
5517 5518 5519
    if (sortval->type != REDIS_SET && sortval->type != REDIS_LIST &&
        sortval->type != REDIS_ZSET)
    {
5520
        addReply(c,shared.wrongtypeerr);
A
antirez 已提交
5521 5522 5523 5524 5525 5526
        return;
    }

    /* Create a list of operations to perform for every sorted element.
     * Operations can be GET/DEL/INCR/DECR */
    operations = listCreate();
5527
    listSetFreeMethod(operations,zfree);
A
antirez 已提交
5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547
    j = 2;

    /* Now we need to protect sortval incrementing its count, in the future
     * SORT may have options able to overwrite/delete keys during the sorting
     * and the sorted key itself may get destroied */
    incrRefCount(sortval);

    /* The SORT command has an SQL-alike syntax, parse it */
    while(j < c->argc) {
        int leftargs = c->argc-j-1;
        if (!strcasecmp(c->argv[j]->ptr,"asc")) {
            desc = 0;
        } else if (!strcasecmp(c->argv[j]->ptr,"desc")) {
            desc = 1;
        } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) {
            alpha = 1;
        } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) {
            limit_start = atoi(c->argv[j+1]->ptr);
            limit_count = atoi(c->argv[j+2]->ptr);
            j+=2;
A
antirez 已提交
5548 5549 5550
        } else if (!strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) {
            storekey = c->argv[j+1];
            j++;
A
antirez 已提交
5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564
        } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) {
            sortby = c->argv[j+1];
            /* If the BY pattern does not contain '*', i.e. it is constant,
             * we don't need to sort nor to lookup the weight keys. */
            if (strchr(c->argv[j+1]->ptr,'*') == NULL) dontsort = 1;
            j++;
        } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) {
            listAddNodeTail(operations,createSortOperation(
                REDIS_SORT_GET,c->argv[j+1]));
            getop++;
            j++;
        } else {
            decrRefCount(sortval);
            listRelease(operations);
5565
            addReply(c,shared.syntaxerr);
A
antirez 已提交
5566 5567 5568 5569 5570 5571
            return;
        }
        j++;
    }

    /* Load the sorting vector with all the objects to sort */
A
antirez 已提交
5572 5573 5574 5575
    switch(sortval->type) {
    case REDIS_LIST: vectorlen = listLength((list*)sortval->ptr); break;
    case REDIS_SET: vectorlen =  dictSize((dict*)sortval->ptr); break;
    case REDIS_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break;
5576
    default: vectorlen = 0; redisAssert(0); /* Avoid GCC warning */
A
antirez 已提交
5577
    }
A
antirez 已提交
5578 5579
    vector = zmalloc(sizeof(redisSortObject)*vectorlen);
    j = 0;
A
antirez 已提交
5580

A
antirez 已提交
5581 5582
    if (sortval->type == REDIS_LIST) {
        list *list = sortval->ptr;
5583
        listNode *ln;
A
antirez 已提交
5584
        listIter li;
5585

A
antirez 已提交
5586 5587
        listRewind(list,&li);
        while((ln = listNext(&li))) {
A
antirez 已提交
5588 5589 5590 5591 5592 5593 5594
            robj *ele = ln->value;
            vector[j].obj = ele;
            vector[j].u.score = 0;
            vector[j].u.cmpobj = NULL;
            j++;
        }
    } else {
A
antirez 已提交
5595
        dict *set;
A
antirez 已提交
5596 5597 5598
        dictIterator *di;
        dictEntry *setele;

A
antirez 已提交
5599 5600 5601 5602 5603 5604 5605
        if (sortval->type == REDIS_SET) {
            set = sortval->ptr;
        } else {
            zset *zs = sortval->ptr;
            set = zs->dict;
        }

A
antirez 已提交
5606 5607 5608 5609 5610 5611 5612 5613 5614
        di = dictGetIterator(set);
        while((setele = dictNext(di)) != NULL) {
            vector[j].obj = dictGetEntryKey(setele);
            vector[j].u.score = 0;
            vector[j].u.cmpobj = NULL;
            j++;
        }
        dictReleaseIterator(di);
    }
5615
    redisAssert(j == vectorlen);
A
antirez 已提交
5616 5617 5618 5619 5620 5621 5622

    /* Now it's time to load the right scores in the sorting vector */
    if (dontsort == 0) {
        for (j = 0; j < vectorlen; j++) {
            if (sortby) {
                robj *byval;

A
antirez 已提交
5623
                byval = lookupKeyByPattern(c->db,sortby,vector[j].obj);
A
antirez 已提交
5624 5625
                if (!byval || byval->type != REDIS_STRING) continue;
                if (alpha) {
5626
                    vector[j].u.cmpobj = getDecodedObject(byval);
A
antirez 已提交
5627
                } else {
5628 5629 5630
                    if (byval->encoding == REDIS_ENCODING_RAW) {
                        vector[j].u.score = strtod(byval->ptr,NULL);
                    } else {
5631 5632 5633
                        /* Don't need to decode the object if it's
                         * integer-encoded (the only encoding supported) so
                         * far. We can just cast it */
5634
                        if (byval->encoding == REDIS_ENCODING_INT) {
5635
                            vector[j].u.score = (long)byval->ptr;
5636
                        } else
5637
                            redisAssert(1 != 1);
5638
                    }
A
antirez 已提交
5639 5640
                }
            } else {
5641 5642 5643 5644 5645 5646 5647
                if (!alpha) {
                    if (vector[j].obj->encoding == REDIS_ENCODING_RAW)
                        vector[j].u.score = strtod(vector[j].obj->ptr,NULL);
                    else {
                        if (vector[j].obj->encoding == REDIS_ENCODING_INT)
                            vector[j].u.score = (long) vector[j].obj->ptr;
                        else
5648
                            redisAssert(1 != 1);
5649 5650
                    }
                }
A
antirez 已提交
5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668
            }
        }
    }

    /* We are ready to sort the vector... perform a bit of sanity check
     * on the LIMIT option too. We'll use a partial version of quicksort. */
    start = (limit_start < 0) ? 0 : limit_start;
    end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1;
    if (start >= vectorlen) {
        start = vectorlen-1;
        end = vectorlen-2;
    }
    if (end >= vectorlen) end = vectorlen-1;

    if (dontsort == 0) {
        server.sort_desc = desc;
        server.sort_alpha = alpha;
        server.sort_bypattern = sortby ? 1 : 0;
5669 5670 5671 5672
        if (sortby && (start != 0 || end != vectorlen-1))
            pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
        else
            qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare);
A
antirez 已提交
5673 5674 5675 5676 5677
    }

    /* Send command output to the output buffer, performing the specified
     * GET/DEL/INCR/DECR operations if any. */
    outputlen = getop ? getop*(end-start+1) : end-start+1;
A
antirez 已提交
5678 5679 5680 5681 5682
    if (storekey == NULL) {
        /* STORE option not specified, sent the sorting result to client */
        addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",outputlen));
        for (j = start; j <= end; j++) {
            listNode *ln;
A
antirez 已提交
5683 5684
            listIter li;

A
antirez 已提交
5685 5686 5687 5688 5689
            if (!getop) {
                addReplyBulkLen(c,vector[j].obj);
                addReply(c,vector[j].obj);
                addReply(c,shared.crlf);
            }
A
antirez 已提交
5690 5691
            listRewind(operations,&li);
            while((ln = listNext(&li))) {
A
antirez 已提交
5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704
                redisSortOperation *sop = ln->value;
                robj *val = lookupKeyByPattern(c->db,sop->pattern,
                    vector[j].obj);

                if (sop->type == REDIS_SORT_GET) {
                    if (!val || val->type != REDIS_STRING) {
                        addReply(c,shared.nullbulk);
                    } else {
                        addReplyBulkLen(c,val);
                        addReply(c,val);
                        addReply(c,shared.crlf);
                    }
                } else {
5705
                    redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
A
antirez 已提交
5706 5707
                }
            }
A
antirez 已提交
5708
        }
A
antirez 已提交
5709 5710 5711 5712 5713 5714 5715
    } else {
        robj *listObject = createListObject();
        list *listPtr = (list*) listObject->ptr;

        /* STORE option specified, set the sorting result as a List object */
        for (j = start; j <= end; j++) {
            listNode *ln;
A
antirez 已提交
5716 5717
            listIter li;

A
antirez 已提交
5718 5719 5720 5721
            if (!getop) {
                listAddNodeTail(listPtr,vector[j].obj);
                incrRefCount(vector[j].obj);
            }
A
antirez 已提交
5722 5723
            listRewind(operations,&li);
            while((ln = listNext(&li))) {
A
antirez 已提交
5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734
                redisSortOperation *sop = ln->value;
                robj *val = lookupKeyByPattern(c->db,sop->pattern,
                    vector[j].obj);

                if (sop->type == REDIS_SORT_GET) {
                    if (!val || val->type != REDIS_STRING) {
                        listAddNodeTail(listPtr,createStringObject("",0));
                    } else {
                        listAddNodeTail(listPtr,val);
                        incrRefCount(val);
                    }
A
antirez 已提交
5735
                } else {
5736
                    redisAssert(sop->type == REDIS_SORT_GET); /* always fails */
A
antirez 已提交
5737 5738 5739
                }
            }
        }
5740 5741 5742
        if (dictReplace(c->db->dict,storekey,listObject)) {
            incrRefCount(storekey);
        }
A
antirez 已提交
5743 5744 5745 5746 5747
        /* Note: we add 1 because the DB is dirty anyway since even if the
         * SORT result is empty a new key is set and maybe the old content
         * replaced. */
        server.dirty += 1+outputlen;
        addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",outputlen));
A
antirez 已提交
5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759
    }

    /* Cleanup */
    decrRefCount(sortval);
    listRelease(operations);
    for (j = 0; j < vectorlen; j++) {
        if (sortby && alpha && vector[j].u.cmpobj)
            decrRefCount(vector[j].u.cmpobj);
    }
    zfree(vector);
}

5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776
/* Convert an amount of bytes into a human readable string in the form
 * of 100B, 2G, 100M, 4K, and so forth. */
static void bytesToHuman(char *s, unsigned long long n) {
    double d;

    if (n < 1024) {
        /* Bytes */
        sprintf(s,"%lluB",n);
        return;
    } else if (n < (1024*1024)) {
        d = (double)n/(1024);
        sprintf(s,"%.2fK",d);
    } else if (n < (1024LL*1024*1024)) {
        d = (double)n/(1024*1024);
        sprintf(s,"%.2fM",d);
    } else if (n < (1024LL*1024*1024*1024)) {
        d = (double)n/(1024LL*1024*1024);
5777
        sprintf(s,"%.2fG",d);
5778 5779 5780
    }
}

5781 5782 5783 5784
/* Create the string returned by the INFO command. This is decoupled
 * by the INFO command itself as we need to report the same information
 * on memory corruption problems. */
static sds genRedisInfoString(void) {
A
antirez 已提交
5785 5786
    sds info;
    time_t uptime = time(NULL)-server.stat_starttime;
5787
    int j;
5788 5789
    char hmem[64];
  
5790
    bytesToHuman(hmem,zmalloc_used_memory());
A
antirez 已提交
5791 5792
    info = sdscatprintf(sdsempty(),
        "redis_version:%s\r\n"
5793
        "arch_bits:%s\r\n"
5794
        "multiplexing_api:%s\r\n"
A
antirez 已提交
5795
        "process_id:%ld\r\n"
5796 5797
        "uptime_in_seconds:%ld\r\n"
        "uptime_in_days:%ld\r\n"
A
antirez 已提交
5798 5799
        "connected_clients:%d\r\n"
        "connected_slaves:%d\r\n"
A
antirez 已提交
5800
        "blocked_clients:%d\r\n"
B
Bob Potter 已提交
5801
        "used_memory:%zu\r\n"
5802
        "used_memory_human:%s\r\n"
A
antirez 已提交
5803
        "changes_since_last_save:%lld\r\n"
5804
        "bgsave_in_progress:%d\r\n"
5805
        "last_save_time:%ld\r\n"
A
antirez 已提交
5806
        "bgrewriteaof_in_progress:%d\r\n"
A
antirez 已提交
5807 5808
        "total_connections_received:%lld\r\n"
        "total_commands_processed:%lld\r\n"
A
antirez 已提交
5809
        "vm_enabled:%d\r\n"
5810
        "role:%s\r\n"
A
antirez 已提交
5811
        ,REDIS_VERSION,
5812
        (sizeof(long) == 8) ? "64" : "32",
5813
        aeGetApiName(),
A
antirez 已提交
5814
        (long) getpid(),
5815 5816
        uptime,
        uptime/(3600*24),
A
antirez 已提交
5817 5818
        listLength(server.clients)-listLength(server.slaves),
        listLength(server.slaves),
A
antirez 已提交
5819
        server.blpop_blocked_clients,
5820
        zmalloc_used_memory(),
5821
        hmem,
A
antirez 已提交
5822
        server.dirty,
5823
        server.bgsavechildpid != -1,
A
antirez 已提交
5824
        server.lastsave,
A
antirez 已提交
5825
        server.bgrewritechildpid != -1,
A
antirez 已提交
5826 5827
        server.stat_numconnections,
        server.stat_numcommands,
A
antirez 已提交
5828
        server.vm_enabled != 0,
5829
        server.masterhost == NULL ? "master" : "slave"
A
antirez 已提交
5830
    );
5831 5832 5833 5834 5835 5836 5837 5838 5839 5840
    if (server.masterhost) {
        info = sdscatprintf(info,
            "master_host:%s\r\n"
            "master_port:%d\r\n"
            "master_link_status:%s\r\n"
            "master_last_io_seconds_ago:%d\r\n"
            ,server.masterhost,
            server.masterport,
            (server.replstate == REDIS_REPL_CONNECTED) ?
                "up" : "down",
5841
            server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1
5842 5843
        );
    }
A
antirez 已提交
5844
    if (server.vm_enabled) {
A
antirez 已提交
5845
        lockThreadedIO();
A
antirez 已提交
5846 5847 5848 5849 5850 5851 5852 5853
        info = sdscatprintf(info,
            "vm_conf_max_memory:%llu\r\n"
            "vm_conf_page_size:%llu\r\n"
            "vm_conf_pages:%llu\r\n"
            "vm_stats_used_pages:%llu\r\n"
            "vm_stats_swapped_objects:%llu\r\n"
            "vm_stats_swappin_count:%llu\r\n"
            "vm_stats_swappout_count:%llu\r\n"
5854 5855 5856
            "vm_stats_io_newjobs_len:%lu\r\n"
            "vm_stats_io_processing_len:%lu\r\n"
            "vm_stats_io_processed_len:%lu\r\n"
5857
            "vm_stats_io_active_threads:%lu\r\n"
A
antirez 已提交
5858
            "vm_stats_blocked_clients:%lu\r\n"
A
antirez 已提交
5859 5860 5861 5862 5863 5864
            ,(unsigned long long) server.vm_max_memory,
            (unsigned long long) server.vm_page_size,
            (unsigned long long) server.vm_pages,
            (unsigned long long) server.vm_stats_used_pages,
            (unsigned long long) server.vm_stats_swapped_objects,
            (unsigned long long) server.vm_stats_swapins,
5865 5866 5867 5868
            (unsigned long long) server.vm_stats_swapouts,
            (unsigned long) listLength(server.io_newjobs),
            (unsigned long) listLength(server.io_processing),
            (unsigned long) listLength(server.io_processed),
A
antirez 已提交
5869 5870
            (unsigned long) server.io_active_threads,
            (unsigned long) server.vm_blocked_clients
A
antirez 已提交
5871
        );
A
antirez 已提交
5872
        unlockThreadedIO();
A
antirez 已提交
5873
    }
5874 5875 5876 5877 5878 5879
    for (j = 0; j < server.dbnum; j++) {
        long long keys, vkeys;

        keys = dictSize(server.db[j].dict);
        vkeys = dictSize(server.db[j].expires);
        if (keys || vkeys) {
5880
            info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
5881 5882 5883
                j, keys, vkeys);
        }
    }
5884 5885 5886 5887 5888
    return info;
}

static void infoCommand(redisClient *c) {
    sds info = genRedisInfoString();
A
antirez 已提交
5889 5890
    addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
        (unsigned long)sdslen(info)));
A
antirez 已提交
5891
    addReplySds(c,info);
5892
    addReply(c,shared.crlf);
A
antirez 已提交
5893 5894
}

A
antirez 已提交
5895 5896 5897 5898 5899 5900
static void monitorCommand(redisClient *c) {
    /* ignore MONITOR if aleady slave or in monitor mode */
    if (c->flags & REDIS_SLAVE) return;

    c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
    c->slaveseldb = 0;
5901
    listAddNodeTail(server.monitors,c);
A
antirez 已提交
5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922
    addReply(c,shared.ok);
}

/* ================================= Expire ================================= */
static int removeExpire(redisDb *db, robj *key) {
    if (dictDelete(db->expires,key) == DICT_OK) {
        return 1;
    } else {
        return 0;
    }
}

static int setExpire(redisDb *db, robj *key, time_t when) {
    if (dictAdd(db->expires,key,(void*)when) == DICT_ERR) {
        return 0;
    } else {
        incrRefCount(key);
        return 1;
    }
}

A
antirez 已提交
5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934
/* Return the expire time of the specified key, or -1 if no expire
 * is associated with this key (i.e. the key is non volatile) */
static time_t getExpire(redisDb *db, robj *key) {
    dictEntry *de;

    /* No expire? return ASAP */
    if (dictSize(db->expires) == 0 ||
       (de = dictFind(db->expires,key)) == NULL) return -1;

    return (time_t) dictGetEntryVal(de);
}

A
antirez 已提交
5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959
static int expireIfNeeded(redisDb *db, robj *key) {
    time_t when;
    dictEntry *de;

    /* No expire? return ASAP */
    if (dictSize(db->expires) == 0 ||
       (de = dictFind(db->expires,key)) == NULL) return 0;

    /* Lookup the expire */
    when = (time_t) dictGetEntryVal(de);
    if (time(NULL) <= when) return 0;

    /* Delete the key */
    dictDelete(db->expires,key);
    return dictDelete(db->dict,key) == DICT_OK;
}

static int deleteIfVolatile(redisDb *db, robj *key) {
    dictEntry *de;

    /* No expire? return ASAP */
    if (dictSize(db->expires) == 0 ||
       (de = dictFind(db->expires,key)) == NULL) return 0;

    /* Delete the key */
5960
    server.dirty++;
A
antirez 已提交
5961 5962 5963 5964
    dictDelete(db->expires,key);
    return dictDelete(db->dict,key) == DICT_OK;
}

5965
static void expireGenericCommand(redisClient *c, robj *key, time_t seconds) {
A
antirez 已提交
5966 5967
    dictEntry *de;

5968
    de = dictFind(c->db->dict,key);
A
antirez 已提交
5969 5970 5971 5972
    if (de == NULL) {
        addReply(c,shared.czero);
        return;
    }
5973 5974 5975
    if (seconds < 0) {
        if (deleteKey(c->db,key)) server.dirty++;
        addReply(c, shared.cone);
A
antirez 已提交
5976 5977 5978
        return;
    } else {
        time_t when = time(NULL)+seconds;
5979
        if (setExpire(c->db,key,when)) {
A
antirez 已提交
5980
            addReply(c,shared.cone);
5981 5982
            server.dirty++;
        } else {
A
antirez 已提交
5983
            addReply(c,shared.czero);
5984
        }
A
antirez 已提交
5985 5986 5987 5988
        return;
    }
}

5989 5990 5991 5992 5993 5994 5995 5996
static void expireCommand(redisClient *c) {
    expireGenericCommand(c,c->argv[1],strtol(c->argv[2]->ptr,NULL,10));
}

static void expireatCommand(redisClient *c) {
    expireGenericCommand(c,c->argv[1],strtol(c->argv[2]->ptr,NULL,10)-time(NULL));
}

A
antirez 已提交
5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008
static void ttlCommand(redisClient *c) {
    time_t expire;
    int ttl = -1;

    expire = getExpire(c->db,c->argv[1]);
    if (expire != -1) {
        ttl = (int) (expire-time(NULL));
        if (ttl < 0) ttl = -1;
    }
    addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
}

A
antirez 已提交
6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050
/* ================================ MULTI/EXEC ============================== */

/* Client state initialization for MULTI/EXEC */
static void initClientMultiState(redisClient *c) {
    c->mstate.commands = NULL;
    c->mstate.count = 0;
}

/* Release all the resources associated with MULTI/EXEC state */
static void freeClientMultiState(redisClient *c) {
    int j;

    for (j = 0; j < c->mstate.count; j++) {
        int i;
        multiCmd *mc = c->mstate.commands+j;

        for (i = 0; i < mc->argc; i++)
            decrRefCount(mc->argv[i]);
        zfree(mc->argv);
    }
    zfree(c->mstate.commands);
}

/* Add a new command into the MULTI commands queue */
static void queueMultiCommand(redisClient *c, struct redisCommand *cmd) {
    multiCmd *mc;
    int j;

    c->mstate.commands = zrealloc(c->mstate.commands,
            sizeof(multiCmd)*(c->mstate.count+1));
    mc = c->mstate.commands+c->mstate.count;
    mc->cmd = cmd;
    mc->argc = c->argc;
    mc->argv = zmalloc(sizeof(robj*)*c->argc);
    memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
    for (j = 0; j < c->argc; j++)
        incrRefCount(mc->argv[j]);
    c->mstate.count++;
}

static void multiCommand(redisClient *c) {
    c->flags |= REDIS_MULTI;
A
antirez 已提交
6051
    addReply(c,shared.ok);
A
antirez 已提交
6052 6053
}

6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065
static void discardCommand(redisClient *c) {
    if (!(c->flags & REDIS_MULTI)) {
        addReplySds(c,sdsnew("-ERR DISCARD without MULTI\r\n"));
        return;
    }

    freeClientMultiState(c);
    initClientMultiState(c);
    c->flags &= (~REDIS_MULTI);
    addReply(c,shared.ok);
}

A
antirez 已提交
6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090
static void execCommand(redisClient *c) {
    int j;
    robj **orig_argv;
    int orig_argc;

    if (!(c->flags & REDIS_MULTI)) {
        addReplySds(c,sdsnew("-ERR EXEC without MULTI\r\n"));
        return;
    }

    orig_argv = c->argv;
    orig_argc = c->argc;
    addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",c->mstate.count));
    for (j = 0; j < c->mstate.count; j++) {
        c->argc = c->mstate.commands[j].argc;
        c->argv = c->mstate.commands[j].argv;
        call(c,c->mstate.commands[j].cmd);
    }
    c->argv = orig_argv;
    c->argc = orig_argc;
    freeClientMultiState(c);
    initClientMultiState(c);
    c->flags &= (~REDIS_MULTI);
}

A
antirez 已提交
6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110
/* =========================== Blocking Operations  ========================= */

/* Currently Redis blocking operations support is limited to list POP ops,
 * so the current implementation is not fully generic, but it is also not
 * completely specific so it will not require a rewrite to support new
 * kind of blocking operations in the future.
 *
 * Still it's important to note that list blocking operations can be already
 * used as a notification mechanism in order to implement other blocking
 * operations at application level, so there must be a very strong evidence
 * of usefulness and generality before new blocking operations are implemented.
 *
 * This is how the current blocking POP works, we use BLPOP as example:
 * - If the user calls BLPOP and the key exists and contains a non empty list
 *   then LPOP is called instead. So BLPOP is semantically the same as LPOP
 *   if there is not to block.
 * - If instead BLPOP is called and the key does not exists or the list is
 *   empty we need to block. In order to do so we remove the notification for
 *   new data to read in the client socket (so that we'll not serve new
 *   requests if the blocking request is not served). Also we put the client
6111
 *   in a dictionary (db->blockingkeys) mapping keys to a list of clients
A
antirez 已提交
6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123
 *   blocking for this keys.
 * - If a PUSH operation against a key with blocked clients waiting is
 *   performed, we serve the first in the list: basically instead to push
 *   the new element inside the list we return it to the (first / oldest)
 *   blocking client, unblock the client, and remove it form the list.
 *
 * The above comment and the source code should be enough in order to understand
 * the implementation and modify / fix it later.
 */

/* Set a client in blocking mode for the specified key, with the specified
 * timeout */
6124
static void blockForKeys(redisClient *c, robj **keys, int numkeys, time_t timeout) {
A
antirez 已提交
6125 6126
    dictEntry *de;
    list *l;
6127
    int j;
A
antirez 已提交
6128

6129 6130
    c->blockingkeys = zmalloc(sizeof(robj*)*numkeys);
    c->blockingkeysnum = numkeys;
A
antirez 已提交
6131
    c->blockingto = timeout;
6132 6133 6134 6135
    for (j = 0; j < numkeys; j++) {
        /* Add the key in the client structure, to map clients -> keys */
        c->blockingkeys[j] = keys[j];
        incrRefCount(keys[j]);
A
antirez 已提交
6136

6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150
        /* And in the other "side", to map keys -> clients */
        de = dictFind(c->db->blockingkeys,keys[j]);
        if (de == NULL) {
            int retval;

            /* For every key we take a list of clients blocked for it */
            l = listCreate();
            retval = dictAdd(c->db->blockingkeys,keys[j],l);
            incrRefCount(keys[j]);
            assert(retval == DICT_OK);
        } else {
            l = dictGetEntryVal(de);
        }
        listAddNodeTail(l,c);
A
antirez 已提交
6151
    }
6152
    /* Mark the client as a blocked client */
A
antirez 已提交
6153
    c->flags |= REDIS_BLOCKED;
A
antirez 已提交
6154
    server.blpop_blocked_clients++;
A
antirez 已提交
6155 6156 6157
}

/* Unblock a client that's waiting in a blocking operation such as BLPOP */
6158
static void unblockClientWaitingData(redisClient *c) {
A
antirez 已提交
6159 6160
    dictEntry *de;
    list *l;
6161
    int j;
A
antirez 已提交
6162

6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178
    assert(c->blockingkeys != NULL);
    /* The client may wait for multiple keys, so unblock it for every key. */
    for (j = 0; j < c->blockingkeysnum; j++) {
        /* Remove this client from the list of clients waiting for this key. */
        de = dictFind(c->db->blockingkeys,c->blockingkeys[j]);
        assert(de != NULL);
        l = dictGetEntryVal(de);
        listDelNode(l,listSearchKey(l,c));
        /* If the list is empty we need to remove it to avoid wasting memory */
        if (listLength(l) == 0)
            dictDelete(c->db->blockingkeys,c->blockingkeys[j]);
        decrRefCount(c->blockingkeys[j]);
    }
    /* Cleanup the client structure */
    zfree(c->blockingkeys);
    c->blockingkeys = NULL;
A
antirez 已提交
6179
    c->flags &= (~REDIS_BLOCKED);
A
antirez 已提交
6180
    server.blpop_blocked_clients--;
6181
    /* We want to process data if there is some command waiting
6182 6183 6184 6185
     * in the input buffer. Note that this is safe even if
     * unblockClientWaitingData() gets called from freeClient() because
     * freeClient() will be smart enough to call this function
     * *after* c->querybuf was set to NULL. */
A
antirez 已提交
6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211
    if (c->querybuf && sdslen(c->querybuf) > 0) processInputBuffer(c);
}

/* This should be called from any function PUSHing into lists.
 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
 * 'ele' is the element pushed.
 *
 * If the function returns 0 there was no client waiting for a list push
 * against this key.
 *
 * If the function returns 1 there was a client waiting for a list push
 * against this key, the element was passed to this client thus it's not
 * needed to actually add it to the list and the caller should return asap. */
static int handleClientsWaitingListPush(redisClient *c, robj *key, robj *ele) {
    struct dictEntry *de;
    redisClient *receiver;
    list *l;
    listNode *ln;

    de = dictFind(c->db->blockingkeys,key);
    if (de == NULL) return 0;
    l = dictGetEntryVal(de);
    ln = listFirst(l);
    assert(ln != NULL);
    receiver = ln->value;

6212 6213 6214 6215
    addReplySds(receiver,sdsnew("*2\r\n"));
    addReplyBulkLen(receiver,key);
    addReply(receiver,key);
    addReply(receiver,shared.crlf);
A
antirez 已提交
6216 6217 6218
    addReplyBulkLen(receiver,ele);
    addReply(receiver,ele);
    addReply(receiver,shared.crlf);
6219
    unblockClientWaitingData(receiver);
A
antirez 已提交
6220 6221 6222 6223 6224 6225 6226
    return 1;
}

/* Blocking RPOP/LPOP */
static void blockingPopGenericCommand(redisClient *c, int where) {
    robj *o;
    time_t timeout;
6227
    int j;
A
antirez 已提交
6228

6229 6230 6231 6232 6233
    for (j = 1; j < c->argc-1; j++) {
        o = lookupKeyWrite(c->db,c->argv[j]);
        if (o != NULL) {
            if (o->type != REDIS_LIST) {
                addReply(c,shared.wrongtypeerr);
A
antirez 已提交
6234
                return;
6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266
            } else {
                list *list = o->ptr;
                if (listLength(list) != 0) {
                    /* If the list contains elements fall back to the usual
                     * non-blocking POP operation */
                    robj *argv[2], **orig_argv;
                    int orig_argc;
                   
                    /* We need to alter the command arguments before to call
                     * popGenericCommand() as the command takes a single key. */
                    orig_argv = c->argv;
                    orig_argc = c->argc;
                    argv[1] = c->argv[j];
                    c->argv = argv;
                    c->argc = 2;

                    /* Also the return value is different, we need to output
                     * the multi bulk reply header and the key name. The
                     * "real" command will add the last element (the value)
                     * for us. If this souds like an hack to you it's just
                     * because it is... */
                    addReplySds(c,sdsnew("*2\r\n"));
                    addReplyBulkLen(c,argv[1]);
                    addReply(c,argv[1]);
                    addReply(c,shared.crlf);
                    popGenericCommand(c,where);

                    /* Fix the client structure with the original stuff */
                    c->argv = orig_argv;
                    c->argc = orig_argc;
                    return;
                }
A
antirez 已提交
6267 6268 6269 6270
            }
        }
    }
    /* If the list is empty or the key does not exists we must block */
6271
    timeout = strtol(c->argv[c->argc-1]->ptr,NULL,10);
A
antirez 已提交
6272
    if (timeout > 0) timeout += time(NULL);
6273
    blockForKeys(c,c->argv+1,c->argc-2,timeout);
A
antirez 已提交
6274 6275 6276 6277 6278 6279 6280 6281 6282 6283
}

static void blpopCommand(redisClient *c) {
    blockingPopGenericCommand(c,REDIS_HEAD);
}

static void brpopCommand(redisClient *c) {
    blockingPopGenericCommand(c,REDIS_TAIL);
}

A
antirez 已提交
6284 6285
/* =============================== Replication  ============================= */

A
antirez 已提交
6286
static int syncWrite(int fd, char *ptr, ssize_t size, int timeout) {
A
antirez 已提交
6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305
    ssize_t nwritten, ret = size;
    time_t start = time(NULL);

    timeout++;
    while(size) {
        if (aeWait(fd,AE_WRITABLE,1000) & AE_WRITABLE) {
            nwritten = write(fd,ptr,size);
            if (nwritten == -1) return -1;
            ptr += nwritten;
            size -= nwritten;
        }
        if ((time(NULL)-start) > timeout) {
            errno = ETIMEDOUT;
            return -1;
        }
    }
    return ret;
}

A
antirez 已提交
6306
static int syncRead(int fd, char *ptr, ssize_t size, int timeout) {
A
antirez 已提交
6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348
    ssize_t nread, totread = 0;
    time_t start = time(NULL);

    timeout++;
    while(size) {
        if (aeWait(fd,AE_READABLE,1000) & AE_READABLE) {
            nread = read(fd,ptr,size);
            if (nread == -1) return -1;
            ptr += nread;
            size -= nread;
            totread += nread;
        }
        if ((time(NULL)-start) > timeout) {
            errno = ETIMEDOUT;
            return -1;
        }
    }
    return totread;
}

static int syncReadLine(int fd, char *ptr, ssize_t size, int timeout) {
    ssize_t nread = 0;

    size--;
    while(size) {
        char c;

        if (syncRead(fd,&c,1,timeout) == -1) return -1;
        if (c == '\n') {
            *ptr = '\0';
            if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
            return nread;
        } else {
            *ptr++ = c;
            *ptr = '\0';
            nread++;
        }
    }
    return nread;
}

static void syncCommand(redisClient *c) {
6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363
    /* ignore SYNC if aleady slave or in monitor mode */
    if (c->flags & REDIS_SLAVE) return;

    /* SYNC can't be issued when the server has pending data to send to
     * the client about already issued commands. We need a fresh reply
     * buffer registering the differences between the BGSAVE and the current
     * dataset, so that we can copy to other slaves if needed. */
    if (listLength(c->reply) != 0) {
        addReplySds(c,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
        return;
    }

    redisLog(REDIS_NOTICE,"Slave ask for synchronization");
    /* Here we need to check if there is a background saving operation
     * in progress, or if it is required to start one */
6364
    if (server.bgsavechildpid != -1) {
6365 6366 6367 6368 6369
        /* Ok a background save is in progress. Let's check if it is a good
         * one for replication, i.e. if there is another slave that is
         * registering differences since the server forked to save */
        redisClient *slave;
        listNode *ln;
A
antirez 已提交
6370
        listIter li;
6371

A
antirez 已提交
6372 6373
        listRewind(server.slaves,&li);
        while((ln = listNext(&li))) {
6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399
            slave = ln->value;
            if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) break;
        }
        if (ln) {
            /* Perfect, the server is already registering differences for
             * another slave. Set the right state, and copy the buffer. */
            listRelease(c->reply);
            c->reply = listDup(slave->reply);
            c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
            redisLog(REDIS_NOTICE,"Waiting for end of BGSAVE for SYNC");
        } else {
            /* No way, we need to wait for the next BGSAVE in order to
             * register differences */
            c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
            redisLog(REDIS_NOTICE,"Waiting for next BGSAVE for SYNC");
        }
    } else {
        /* Ok we don't have a BGSAVE in progress, let's start one */
        redisLog(REDIS_NOTICE,"Starting BGSAVE for SYNC");
        if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
            redisLog(REDIS_NOTICE,"Replication failed, can't BGSAVE");
            addReplySds(c,sdsnew("-ERR Unalbe to perform background save\r\n"));
            return;
        }
        c->replstate = REDIS_REPL_WAIT_BGSAVE_END;
    }
6400
    c->repldbfd = -1;
6401 6402
    c->flags |= REDIS_SLAVE;
    c->slaveseldb = 0;
6403
    listAddNodeTail(server.slaves,c);
6404 6405 6406
    return;
}

6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439
static void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
    redisClient *slave = privdata;
    REDIS_NOTUSED(el);
    REDIS_NOTUSED(mask);
    char buf[REDIS_IOBUF_LEN];
    ssize_t nwritten, buflen;

    if (slave->repldboff == 0) {
        /* Write the bulk write count before to transfer the DB. In theory here
         * we don't know how much room there is in the output buffer of the
         * socket, but in pratice SO_SNDLOWAT (the minimum count for output
         * operations) will never be smaller than the few bytes we need. */
        sds bulkcount;

        bulkcount = sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
            slave->repldbsize);
        if (write(fd,bulkcount,sdslen(bulkcount)) != (signed)sdslen(bulkcount))
        {
            sdsfree(bulkcount);
            freeClient(slave);
            return;
        }
        sdsfree(bulkcount);
    }
    lseek(slave->repldbfd,slave->repldboff,SEEK_SET);
    buflen = read(slave->repldbfd,buf,REDIS_IOBUF_LEN);
    if (buflen <= 0) {
        redisLog(REDIS_WARNING,"Read error sending DB to slave: %s",
            (buflen == 0) ? "premature EOF" : strerror(errno));
        freeClient(slave);
        return;
    }
    if ((nwritten = write(fd,buf,buflen)) == -1) {
6440
        redisLog(REDIS_VERBOSE,"Write error sending DB to slave: %s",
6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451
            strerror(errno));
        freeClient(slave);
        return;
    }
    slave->repldboff += nwritten;
    if (slave->repldboff == slave->repldbsize) {
        close(slave->repldbfd);
        slave->repldbfd = -1;
        aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
        slave->replstate = REDIS_REPL_ONLINE;
        if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE,
6452
            sendReplyToClient, slave) == AE_ERR) {
6453 6454 6455 6456 6457 6458 6459
            freeClient(slave);
            return;
        }
        addReplySds(slave,sdsempty());
        redisLog(REDIS_NOTICE,"Synchronization with slave succeeded");
    }
}
A
antirez 已提交
6460

6461 6462 6463 6464 6465 6466 6467
/* This function is called at the end of every backgrond saving.
 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
 * otherwise REDIS_ERR is passed to the function.
 *
 * The goal of this function is to handle slaves waiting for a successful
 * background saving in order to perform non-blocking synchronization. */
static void updateSlavesWaitingBgsave(int bgsaveerr) {
6468 6469
    listNode *ln;
    int startbgsave = 0;
A
antirez 已提交
6470
    listIter li;
A
antirez 已提交
6471

A
antirez 已提交
6472 6473
    listRewind(server.slaves,&li);
    while((ln = listNext(&li))) {
6474
        redisClient *slave = ln->value;
A
antirez 已提交
6475

6476 6477 6478 6479
        if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
            startbgsave = 1;
            slave->replstate = REDIS_REPL_WAIT_BGSAVE_END;
        } else if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
6480
            struct redis_stat buf;
6481 6482 6483 6484 6485 6486 6487
           
            if (bgsaveerr != REDIS_OK) {
                freeClient(slave);
                redisLog(REDIS_WARNING,"SYNC failed. BGSAVE child returned an error");
                continue;
            }
            if ((slave->repldbfd = open(server.dbfilename,O_RDONLY)) == -1 ||
6488
                redis_fstat(slave->repldbfd,&buf) == -1) {
6489 6490 6491 6492 6493 6494 6495 6496
                freeClient(slave);
                redisLog(REDIS_WARNING,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno));
                continue;
            }
            slave->repldboff = 0;
            slave->repldbsize = buf.st_size;
            slave->replstate = REDIS_REPL_SEND_BULK;
            aeDeleteFileEvent(server.el,slave->fd,AE_WRITABLE);
6497
            if (aeCreateFileEvent(server.el, slave->fd, AE_WRITABLE, sendBulkToSlave, slave) == AE_ERR) {
6498 6499 6500 6501
                freeClient(slave);
                continue;
            }
        }
A
antirez 已提交
6502
    }
6503 6504
    if (startbgsave) {
        if (rdbSaveBackground(server.dbfilename) != REDIS_OK) {
A
antirez 已提交
6505 6506 6507
            listIter li;

            listRewind(server.slaves,&li);
6508
            redisLog(REDIS_WARNING,"SYNC failed. BGSAVE failed");
A
antirez 已提交
6509
            while((ln = listNext(&li))) {
6510
                redisClient *slave = ln->value;
A
antirez 已提交
6511

6512 6513 6514 6515 6516
                if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START)
                    freeClient(slave);
            }
        }
    }
A
antirez 已提交
6517 6518 6519
}

static int syncWithMaster(void) {
6520
    char buf[1024], tmpfile[256], authcmd[1024];
A
antirez 已提交
6521 6522 6523 6524 6525 6526 6527 6528 6529
    int dumpsize;
    int fd = anetTcpConnect(NULL,server.masterhost,server.masterport);
    int dfd;

    if (fd == -1) {
        redisLog(REDIS_WARNING,"Unable to connect to MASTER: %s",
            strerror(errno));
        return REDIS_ERR;
    }
6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553

    /* AUTH with the master if required. */
    if(server.masterauth) {
    	snprintf(authcmd, 1024, "AUTH %s\r\n", server.masterauth);
    	if (syncWrite(fd, authcmd, strlen(server.masterauth)+7, 5) == -1) {
            close(fd);
            redisLog(REDIS_WARNING,"Unable to AUTH to MASTER: %s",
                strerror(errno));
            return REDIS_ERR;
    	}
        /* Read the AUTH result.  */
        if (syncReadLine(fd,buf,1024,3600) == -1) {
            close(fd);
            redisLog(REDIS_WARNING,"I/O error reading auth result from MASTER: %s",
                strerror(errno));
            return REDIS_ERR;
        }
        if (buf[0] != '+') {
            close(fd);
            redisLog(REDIS_WARNING,"Cannot AUTH to MASTER, is the masterauth password correct?");
            return REDIS_ERR;
        }
    }

A
antirez 已提交
6554 6555 6556 6557 6558 6559 6560 6561
    /* Issue the SYNC command */
    if (syncWrite(fd,"SYNC \r\n",7,5) == -1) {
        close(fd);
        redisLog(REDIS_WARNING,"I/O error writing to MASTER: %s",
            strerror(errno));
        return REDIS_ERR;
    }
    /* Read the bulk write count */
6562
    if (syncReadLine(fd,buf,1024,3600) == -1) {
A
antirez 已提交
6563 6564 6565 6566 6567
        close(fd);
        redisLog(REDIS_WARNING,"I/O error reading bulk count from MASTER: %s",
            strerror(errno));
        return REDIS_ERR;
    }
6568 6569 6570 6571 6572
    if (buf[0] != '$') {
        close(fd);
        redisLog(REDIS_WARNING,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
        return REDIS_ERR;
    }
6573
    dumpsize = atoi(buf+1);
A
antirez 已提交
6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610
    redisLog(REDIS_NOTICE,"Receiving %d bytes data dump from MASTER",dumpsize);
    /* Read the bulk write data on a temp file */
    snprintf(tmpfile,256,"temp-%d.%ld.rdb",(int)time(NULL),(long int)random());
    dfd = open(tmpfile,O_CREAT|O_WRONLY,0644);
    if (dfd == -1) {
        close(fd);
        redisLog(REDIS_WARNING,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno));
        return REDIS_ERR;
    }
    while(dumpsize) {
        int nread, nwritten;

        nread = read(fd,buf,(dumpsize < 1024)?dumpsize:1024);
        if (nread == -1) {
            redisLog(REDIS_WARNING,"I/O error trying to sync with MASTER: %s",
                strerror(errno));
            close(fd);
            close(dfd);
            return REDIS_ERR;
        }
        nwritten = write(dfd,buf,nread);
        if (nwritten == -1) {
            redisLog(REDIS_WARNING,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno));
            close(fd);
            close(dfd);
            return REDIS_ERR;
        }
        dumpsize -= nread;
    }
    close(dfd);
    if (rename(tmpfile,server.dbfilename) == -1) {
        redisLog(REDIS_WARNING,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno));
        unlink(tmpfile);
        close(fd);
        return REDIS_ERR;
    }
    emptyDb();
6611
    if (rdbLoad(server.dbfilename) != REDIS_OK) {
A
antirez 已提交
6612 6613 6614 6615 6616 6617
        redisLog(REDIS_WARNING,"Failed trying to load the MASTER synchronization DB from disk");
        close(fd);
        return REDIS_ERR;
    }
    server.master = createClient(fd);
    server.master->flags |= REDIS_MASTER;
6618
    server.master->authenticated = 1;
A
antirez 已提交
6619 6620 6621 6622
    server.replstate = REDIS_REPL_CONNECTED;
    return REDIS_OK;
}

6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644
static void slaveofCommand(redisClient *c) {
    if (!strcasecmp(c->argv[1]->ptr,"no") &&
        !strcasecmp(c->argv[2]->ptr,"one")) {
        if (server.masterhost) {
            sdsfree(server.masterhost);
            server.masterhost = NULL;
            if (server.master) freeClient(server.master);
            server.replstate = REDIS_REPL_NONE;
            redisLog(REDIS_NOTICE,"MASTER MODE enabled (user request)");
        }
    } else {
        sdsfree(server.masterhost);
        server.masterhost = sdsdup(c->argv[1]->ptr);
        server.masterport = atoi(c->argv[2]->ptr);
        if (server.master) freeClient(server.master);
        server.replstate = REDIS_REPL_CONNECT;
        redisLog(REDIS_NOTICE,"SLAVE OF %s:%d enabled (user request)",
            server.masterhost, server.masterport);
    }
    addReply(c,shared.ok);
}

A
antirez 已提交
6645 6646
/* ============================ Maxmemory directive  ======================== */

6647 6648 6649 6650 6651
/* Try to free one object form the pre-allocated objects free list.
 * This is useful under low mem conditions as by default we take 1 million
 * free objects allocated. On success REDIS_OK is returned, otherwise
 * REDIS_ERR. */
static int tryFreeOneObjectFromFreelist(void) {
6652 6653
    robj *o;

6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665
    if (server.vm_enabled) pthread_mutex_lock(&server.obj_freelist_mutex);
    if (listLength(server.objfreelist)) {
        listNode *head = listFirst(server.objfreelist);
        o = listNodeValue(head);
        listDelNode(server.objfreelist,head);
        if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
        zfree(o);
        return REDIS_OK;
    } else {
        if (server.vm_enabled) pthread_mutex_unlock(&server.obj_freelist_mutex);
        return REDIS_ERR;
    }
6666 6667
}

A
antirez 已提交
6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680
/* This function gets called when 'maxmemory' is set on the config file to limit
 * the max memory used by the server, and we are out of memory.
 * This function will try to, in order:
 *
 * - Free objects from the free list
 * - Try to remove keys with an EXPIRE set
 *
 * It is not possible to free enough memory to reach used-memory < maxmemory
 * the server will start refusing commands that will enlarge even more the
 * memory usage.
 */
static void freeMemoryIfNeeded(void) {
    while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700
        int j, k, freed = 0;

        if (tryFreeOneObjectFromFreelist() == REDIS_OK) continue;
        for (j = 0; j < server.dbnum; j++) {
            int minttl = -1;
            robj *minkey = NULL;
            struct dictEntry *de;

            if (dictSize(server.db[j].expires)) {
                freed = 1;
                /* From a sample of three keys drop the one nearest to
                 * the natural expire */
                for (k = 0; k < 3; k++) {
                    time_t t;

                    de = dictGetRandomKey(server.db[j].expires);
                    t = (time_t) dictGetEntryVal(de);
                    if (minttl == -1 || t < minttl) {
                        minkey = dictGetEntryKey(de);
                        minttl = t;
A
antirez 已提交
6701 6702
                    }
                }
6703
                deleteKey(server.db+j,minkey);
A
antirez 已提交
6704 6705
            }
        }
6706
        if (!freed) return; /* nothing to free... */
A
antirez 已提交
6707 6708 6709
    }
}

6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724
/* ============================== Append Only file ========================== */

static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
    sds buf = sdsempty();
    int j;
    ssize_t nwritten;
    time_t now;
    robj *tmpargv[3];

    /* The DB this command was targetting is not the same as the last command
     * we appendend. To issue a SELECT command is needed. */
    if (dictid != server.appendseldb) {
        char seldb[64];

        snprintf(seldb,sizeof(seldb),"%d",dictid);
6725
        buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
A
antirez 已提交
6726
            (unsigned long)strlen(seldb),seldb);
6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748
        server.appendseldb = dictid;
    }

    /* "Fix" the argv vector if the command is EXPIRE. We want to translate
     * EXPIREs into EXPIREATs calls */
    if (cmd->proc == expireCommand) {
        long when;

        tmpargv[0] = createStringObject("EXPIREAT",8);
        tmpargv[1] = argv[1];
        incrRefCount(argv[1]);
        when = time(NULL)+strtol(argv[2]->ptr,NULL,10);
        tmpargv[2] = createObject(REDIS_STRING,
            sdscatprintf(sdsempty(),"%ld",when));
        argv = tmpargv;
    }

    /* Append the actual command */
    buf = sdscatprintf(buf,"*%d\r\n",argc);
    for (j = 0; j < argc; j++) {
        robj *o = argv[j];

6749
        o = getDecodedObject(o);
A
antirez 已提交
6750
        buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
6751 6752
        buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
        buf = sdscatlen(buf,"\r\n",2);
6753
        decrRefCount(o);
6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778
    }

    /* Free the objects from the modified argv for EXPIREAT */
    if (cmd->proc == expireCommand) {
        for (j = 0; j < 3; j++)
            decrRefCount(argv[j]);
    }

    /* We want to perform a single write. This should be guaranteed atomic
     * at least if the filesystem we are writing is a real physical one.
     * While this will save us against the server being killed I don't think
     * there is much to do about the whole server stopping for power problems
     * or alike */
     nwritten = write(server.appendfd,buf,sdslen(buf));
     if (nwritten != (signed)sdslen(buf)) {
        /* Ooops, we are in troubles. The best thing to do for now is
         * to simply exit instead to give the illusion that everything is
         * working as expected. */
         if (nwritten == -1) {
            redisLog(REDIS_WARNING,"Exiting on error writing to the append-only file: %s",strerror(errno));
         } else {
            redisLog(REDIS_WARNING,"Exiting on short write while writing to the append-only file: %s",strerror(errno));
         }
         exit(1);
    }
A
antirez 已提交
6779 6780 6781 6782 6783 6784 6785 6786
    /* If a background append only file rewriting is in progress we want to
     * accumulate the differences between the child DB and the current one
     * in a buffer, so that when the child process will do its work we
     * can append the differences to the new append only file. */
    if (server.bgrewritechildpid != -1)
        server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));

    sdsfree(buf);
6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807
    now = time(NULL);
    if (server.appendfsync == APPENDFSYNC_ALWAYS ||
        (server.appendfsync == APPENDFSYNC_EVERYSEC &&
         now-server.lastfsync > 1))
    {
        fsync(server.appendfd); /* Let's try to get this data on the disk */
        server.lastfsync = now;
    }
}

/* In Redis commands are always executed in the context of a client, so in
 * order to load the append only file we need to create a fake client. */
static struct redisClient *createFakeClient(void) {
    struct redisClient *c = zmalloc(sizeof(*c));

    selectDb(c,0);
    c->fd = -1;
    c->querybuf = sdsempty();
    c->argc = 0;
    c->argv = NULL;
    c->flags = 0;
A
antirez 已提交
6808 6809 6810
    /* We set the fake client as a slave waiting for the synchronization
     * so that Redis will not try to send replies to this client. */
    c->replstate = REDIS_REPL_WAIT_BGSAVE_START;
6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829
    c->reply = listCreate();
    listSetFreeMethod(c->reply,decrRefCount);
    listSetDupMethod(c->reply,dupClientReplyValue);
    return c;
}

static void freeFakeClient(struct redisClient *c) {
    sdsfree(c->querybuf);
    listRelease(c->reply);
    zfree(c);
}

/* Replay the append log file. On error REDIS_OK is returned. On non fatal
 * error (the append only file is zero-length) REDIS_ERR is returned. On
 * fatal error an error message is logged and the program exists. */
int loadAppendOnlyFile(char *filename) {
    struct redisClient *fakeClient;
    FILE *fp = fopen(filename,"r");
    struct redis_stat sb;
6830
    unsigned long long loadedkeys = 0;
6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862

    if (redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0)
        return REDIS_ERR;

    if (fp == NULL) {
        redisLog(REDIS_WARNING,"Fatal error: can't open the append log file for reading: %s",strerror(errno));
        exit(1);
    }

    fakeClient = createFakeClient();
    while(1) {
        int argc, j;
        unsigned long len;
        robj **argv;
        char buf[128];
        sds argsds;
        struct redisCommand *cmd;

        if (fgets(buf,sizeof(buf),fp) == NULL) {
            if (feof(fp))
                break;
            else
                goto readerr;
        }
        if (buf[0] != '*') goto fmterr;
        argc = atoi(buf+1);
        argv = zmalloc(sizeof(robj*)*argc);
        for (j = 0; j < argc; j++) {
            if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
            if (buf[0] != '$') goto fmterr;
            len = strtol(buf+1,NULL,10);
            argsds = sdsnewlen(NULL,len);
6863
            if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891
            argv[j] = createObject(REDIS_STRING,argsds);
            if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
        }

        /* Command lookup */
        cmd = lookupCommand(argv[0]->ptr);
        if (!cmd) {
            redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", argv[0]->ptr);
            exit(1);
        }
        /* Try object sharing and encoding */
        if (server.shareobjects) {
            int j;
            for(j = 1; j < argc; j++)
                argv[j] = tryObjectSharing(argv[j]);
        }
        if (cmd->flags & REDIS_CMD_BULK)
            tryObjectEncoding(argv[argc-1]);
        /* Run the command in the context of a fake client */
        fakeClient->argc = argc;
        fakeClient->argv = argv;
        cmd->proc(fakeClient);
        /* Discard the reply objects list from the fake client */
        while(listLength(fakeClient->reply))
            listDelNode(fakeClient->reply,listFirst(fakeClient->reply));
        /* Clean up, ready for the next command */
        for (j = 0; j < argc; j++) decrRefCount(argv[j]);
        zfree(argv);
6892 6893 6894 6895
        /* Handle swapping while loading big datasets when VM is on */
        loadedkeys++;
        if (server.vm_enabled && (loadedkeys % 5000) == 0) {
            while (zmalloc_used_memory() > server.vm_max_memory) {
6896
                if (vmSwapOneObjectBlocking() == REDIS_ERR) break;
6897 6898
            }
        }
6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915
    }
    fclose(fp);
    freeFakeClient(fakeClient);
    return REDIS_OK;

readerr:
    if (feof(fp)) {
        redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
    } else {
        redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
    }
    exit(1);
fmterr:
    redisLog(REDIS_WARNING,"Bad file format reading the append only file");
    exit(1);
}

6916 6917 6918
/* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
static int fwriteBulk(FILE *fp, robj *obj) {
    char buf[128];
6919 6920
    int decrrc = 0;

A
antirez 已提交
6921 6922 6923 6924 6925 6926
    /* Avoid the incr/decr ref count business if possible to help
     * copy-on-write (we are often in a child process when this function
     * is called).
     * Also makes sure that key objects don't get incrRefCount-ed when VM
     * is enabled */
    if (obj->encoding != REDIS_ENCODING_RAW) {
6927 6928 6929
        obj = getDecodedObject(obj);
        decrrc = 1;
    }
6930 6931
    snprintf(buf,sizeof(buf),"$%ld\r\n",(long)sdslen(obj->ptr));
    if (fwrite(buf,strlen(buf),1,fp) == 0) goto err;
6932 6933
    if (sdslen(obj->ptr) && fwrite(obj->ptr,sdslen(obj->ptr),1,fp) == 0)
        goto err;
6934
    if (fwrite("\r\n",2,1,fp) == 0) goto err;
6935
    if (decrrc) decrRefCount(obj);
6936 6937
    return 1;
err:
6938
    if (decrrc) decrRefCount(obj);
6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994
    return 0;
}

/* Write a double value in bulk format $<count>\r\n<payload>\r\n */
static int fwriteBulkDouble(FILE *fp, double d) {
    char buf[128], dbuf[128];

    snprintf(dbuf,sizeof(dbuf),"%.17g\r\n",d);
    snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(dbuf)-2);
    if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
    if (fwrite(dbuf,strlen(dbuf),1,fp) == 0) return 0;
    return 1;
}

/* Write a long value in bulk format $<count>\r\n<payload>\r\n */
static int fwriteBulkLong(FILE *fp, long l) {
    char buf[128], lbuf[128];

    snprintf(lbuf,sizeof(lbuf),"%ld\r\n",l);
    snprintf(buf,sizeof(buf),"$%lu\r\n",(unsigned long)strlen(lbuf)-2);
    if (fwrite(buf,strlen(buf),1,fp) == 0) return 0;
    if (fwrite(lbuf,strlen(lbuf),1,fp) == 0) return 0;
    return 1;
}

/* Write a sequence of commands able to fully rebuild the dataset into
 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
static int rewriteAppendOnlyFile(char *filename) {
    dictIterator *di = NULL;
    dictEntry *de;
    FILE *fp;
    char tmpfile[256];
    int j;
    time_t now = time(NULL);

    /* Note that we have to use a different temp name here compared to the
     * one used by rewriteAppendOnlyFileBackground() function. */
    snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
    fp = fopen(tmpfile,"w");
    if (!fp) {
        redisLog(REDIS_WARNING, "Failed rewriting the append only file: %s", strerror(errno));
        return REDIS_ERR;
    }
    for (j = 0; j < server.dbnum; j++) {
        char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
        redisDb *db = server.db+j;
        dict *d = db->dict;
        if (dictSize(d) == 0) continue;
        di = dictGetIterator(d);
        if (!di) {
            fclose(fp);
            return REDIS_ERR;
        }

        /* SELECT the new DB */
        if (fwrite(selectcmd,sizeof(selectcmd)-1,1,fp) == 0) goto werr;
A
antirez 已提交
6995
        if (fwriteBulkLong(fp,j) == 0) goto werr;
6996 6997 6998

        /* Iterate this DB writing every entry */
        while((de = dictNext(di)) != NULL) {
6999 7000 7001 7002 7003
            robj *key, *o;
            time_t expiretime;
            int swapped;

            key = dictGetEntryKey(de);
7004 7005 7006 7007
            /* If the value for this key is swapped, load a preview in memory.
             * We use a "swapped" flag to remember if we need to free the
             * value object instead to just increment the ref count anyway
             * in order to avoid copy-on-write of pages if we are forked() */
7008 7009
            if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
                key->storage == REDIS_VM_SWAPPING) {
7010 7011 7012 7013 7014 7015 7016
                o = dictGetEntryVal(de);
                swapped = 0;
            } else {
                o = vmPreviewObject(key);
                swapped = 1;
            }
            expiretime = getExpire(db,key);
7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029

            /* Save the key and associated value */
            if (o->type == REDIS_STRING) {
                /* Emit a SET command */
                char cmd[]="*3\r\n$3\r\nSET\r\n";
                if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                /* Key and value */
                if (fwriteBulk(fp,key) == 0) goto werr;
                if (fwriteBulk(fp,o) == 0) goto werr;
            } else if (o->type == REDIS_LIST) {
                /* Emit the RPUSHes needed to rebuild the list */
                list *list = o->ptr;
                listNode *ln;
A
antirez 已提交
7030
                listIter li;
7031

A
antirez 已提交
7032 7033
                listRewind(list,&li);
                while((ln = listNext(&li))) {
7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073
                    char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
                    robj *eleobj = listNodeValue(ln);

                    if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                    if (fwriteBulk(fp,key) == 0) goto werr;
                    if (fwriteBulk(fp,eleobj) == 0) goto werr;
                }
            } else if (o->type == REDIS_SET) {
                /* Emit the SADDs needed to rebuild the set */
                dict *set = o->ptr;
                dictIterator *di = dictGetIterator(set);
                dictEntry *de;

                while((de = dictNext(di)) != NULL) {
                    char cmd[]="*3\r\n$4\r\nSADD\r\n";
                    robj *eleobj = dictGetEntryKey(de);

                    if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                    if (fwriteBulk(fp,key) == 0) goto werr;
                    if (fwriteBulk(fp,eleobj) == 0) goto werr;
                }
                dictReleaseIterator(di);
            } else if (o->type == REDIS_ZSET) {
                /* Emit the ZADDs needed to rebuild the sorted set */
                zset *zs = o->ptr;
                dictIterator *di = dictGetIterator(zs->dict);
                dictEntry *de;

                while((de = dictNext(di)) != NULL) {
                    char cmd[]="*4\r\n$4\r\nZADD\r\n";
                    robj *eleobj = dictGetEntryKey(de);
                    double *score = dictGetEntryVal(de);

                    if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                    if (fwriteBulk(fp,key) == 0) goto werr;
                    if (fwriteBulkDouble(fp,*score) == 0) goto werr;
                    if (fwriteBulk(fp,eleobj) == 0) goto werr;
                }
                dictReleaseIterator(di);
            } else {
7074
                redisAssert(0 != 0);
7075 7076 7077
            }
            /* Save the expire time */
            if (expiretime != -1) {
7078
                char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
7079 7080 7081 7082 7083 7084
                /* If this key is already expired skip it */
                if (expiretime < now) continue;
                if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                if (fwriteBulk(fp,key) == 0) goto werr;
                if (fwriteBulkLong(fp,expiretime) == 0) goto werr;
            }
7085
            if (swapped) decrRefCount(o);
7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107
        }
        dictReleaseIterator(di);
    }

    /* Make sure data will not remain on the OS's output buffers */
    fflush(fp);
    fsync(fileno(fp));
    fclose(fp);
    
    /* Use RENAME to make sure the DB file is changed atomically only
     * if the generate DB file is ok. */
    if (rename(tmpfile,filename) == -1) {
        redisLog(REDIS_WARNING,"Error moving temp append only file on the final destination: %s", strerror(errno));
        unlink(tmpfile);
        return REDIS_ERR;
    }
    redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
    return REDIS_OK;

werr:
    fclose(fp);
    unlink(tmpfile);
7108
    redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128
    if (di) dictReleaseIterator(di);
    return REDIS_ERR;
}

/* This is how rewriting of the append only file in background works:
 *
 * 1) The user calls BGREWRITEAOF
 * 2) Redis calls this function, that forks():
 *    2a) the child rewrite the append only file in a temp file.
 *    2b) the parent accumulates differences in server.bgrewritebuf.
 * 3) When the child finished '2a' exists.
 * 4) The parent will trap the exit code, if it's OK, will append the
 *    data accumulated into server.bgrewritebuf into the temp file, and
 *    finally will rename(2) the temp file in the actual file name.
 *    The the new file is reopened as the new append only file. Profit!
 */
static int rewriteAppendOnlyFileBackground(void) {
    pid_t childpid;

    if (server.bgrewritechildpid != -1) return REDIS_ERR;
7129
    if (server.vm_enabled) waitEmptyIOJobsQueue();
7130 7131 7132 7133
    if ((childpid = fork()) == 0) {
        /* Child */
        char tmpfile[256];

7134 7135
        if (server.vm_enabled) vmReopenSwapFile();
        close(server.fd);
7136 7137
        snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
        if (rewriteAppendOnlyFile(tmpfile) == REDIS_OK) {
7138
            _exit(0);
7139
        } else {
7140
            _exit(1);
7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152
        }
    } else {
        /* Parent */
        if (childpid == -1) {
            redisLog(REDIS_WARNING,
                "Can't rewrite append only file in background: fork: %s",
                strerror(errno));
            return REDIS_ERR;
        }
        redisLog(REDIS_NOTICE,
            "Background append only file rewriting started by pid %d",childpid);
        server.bgrewritechildpid = childpid;
A
antirez 已提交
7153 7154 7155 7156 7157
        /* We set appendseldb to -1 in order to force the next call to the
         * feedAppendOnlyFile() to issue a SELECT command, so the differences
         * accumulated by the parent into server.bgrewritebuf will start
         * with a SELECT statement and it will be safe to merge. */
        server.appendseldb = -1;
7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168
        return REDIS_OK;
    }
    return REDIS_OK; /* unreached */
}

static void bgrewriteaofCommand(redisClient *c) {
    if (server.bgrewritechildpid != -1) {
        addReplySds(c,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
        return;
    }
    if (rewriteAppendOnlyFileBackground() == REDIS_OK) {
7169 7170
        char *status = "+Background append only file rewriting started\r\n";
        addReplySds(c,sdsnew(status));
7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182
    } else {
        addReply(c,shared.err);
    }
}

static void aofRemoveTempFile(pid_t childpid) {
    char tmpfile[256];

    snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
    unlink(tmpfile);
}

7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204
/* Virtual Memory is composed mainly of two subsystems:
 * - Blocking Virutal Memory
 * - Threaded Virtual Memory I/O
 * The two parts are not fully decoupled, but functions are split among two
 * different sections of the source code (delimited by comments) in order to
 * make more clear what functionality is about the blocking VM and what about
 * the threaded (not blocking) VM.
 *
 * Redis VM design:
 *
 * Redis VM is a blocking VM (one that blocks reading swapped values from
 * disk into memory when a value swapped out is needed in memory) that is made
 * unblocking by trying to examine the command argument vector in order to
 * load in background values that will likely be needed in order to exec
 * the command. The command is executed only once all the relevant keys
 * are loaded into memory.
 *
 * This basically is almost as simple of a blocking VM, but almost as parallel
 * as a fully non-blocking VM.
 */

/* =================== Virtual Memory - Blocking Side  ====================== */
7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221

/* substitute the first occurrence of '%p' with the process pid in the
 * swap file name. */
static void expandVmSwapFilename(void) {
    char *p = strstr(server.vm_swap_file,"%p");
    sds new;
    
    if (!p) return;
    new = sdsempty();
    *p = '\0';
    new = sdscat(new,server.vm_swap_file);
    new = sdscatprintf(new,"%ld",(long) getpid());
    new = sdscat(new,p+2);
    zfree(server.vm_swap_file);
    server.vm_swap_file = new;
}

7222 7223
static void vmInit(void) {
    off_t totsize;
7224
    int pipefds[2];
7225
    size_t stacksize;
7226

7227 7228 7229
    if (server.vm_max_threads != 0)
        zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */

7230 7231
    expandVmSwapFilename();
    redisLog(REDIS_NOTICE,"Using '%s' as swap file",server.vm_swap_file);
A
antirez 已提交
7232 7233 7234
    if ((server.vm_fp = fopen(server.vm_swap_file,"r+b")) == NULL) {
        server.vm_fp = fopen(server.vm_swap_file,"w+b");
    }
7235
    if (server.vm_fp == NULL) {
A
antirez 已提交
7236 7237 7238
        redisLog(REDIS_WARNING,
            "Impossible to open the swap file: %s. Exiting.",
            strerror(errno));
7239 7240 7241 7242 7243
        exit(1);
    }
    server.vm_fd = fileno(server.vm_fp);
    server.vm_next_page = 0;
    server.vm_near_pages = 0;
A
antirez 已提交
7244 7245 7246 7247
    server.vm_stats_used_pages = 0;
    server.vm_stats_swapped_objects = 0;
    server.vm_stats_swapouts = 0;
    server.vm_stats_swapins = 0;
7248 7249 7250 7251 7252 7253 7254 7255 7256
    totsize = server.vm_pages*server.vm_page_size;
    redisLog(REDIS_NOTICE,"Allocating %lld bytes of swap file",totsize);
    if (ftruncate(server.vm_fd,totsize) == -1) {
        redisLog(REDIS_WARNING,"Can't ftruncate swap file: %s. Exiting.",
            strerror(errno));
        exit(1);
    } else {
        redisLog(REDIS_NOTICE,"Swap file allocated with success");
    }
A
antirez 已提交
7257
    server.vm_bitmap = zmalloc((server.vm_pages+7)/8);
7258
    redisLog(REDIS_VERBOSE,"Allocated %lld bytes page table for %lld pages",
A
antirez 已提交
7259
        (long long) (server.vm_pages+7)/8, server.vm_pages);
A
antirez 已提交
7260
    memset(server.vm_bitmap,0,(server.vm_pages+7)/8);
7261

7262 7263 7264 7265
    /* Initialize threaded I/O (used by Virtual Memory) */
    server.io_newjobs = listCreate();
    server.io_processing = listCreate();
    server.io_processed = listCreate();
A
antirez 已提交
7266
    server.io_ready_clients = listCreate();
7267
    pthread_mutex_init(&server.io_mutex,NULL);
7268 7269
    pthread_mutex_init(&server.obj_freelist_mutex,NULL);
    pthread_mutex_init(&server.io_swapfile_mutex,NULL);
7270
    server.io_active_threads = 0;
7271 7272 7273 7274 7275 7276 7277 7278
    if (pipe(pipefds) == -1) {
        redisLog(REDIS_WARNING,"Unable to intialized VM: pipe(2): %s. Exiting."
            ,strerror(errno));
        exit(1);
    }
    server.io_ready_pipe_read = pipefds[0];
    server.io_ready_pipe_write = pipefds[1];
    redisAssert(anetNonBlock(NULL,server.io_ready_pipe_read) != ANET_ERR);
7279 7280 7281 7282 7283
    /* LZF requires a lot of stack */
    pthread_attr_init(&server.io_threads_attr);
    pthread_attr_getstacksize(&server.io_threads_attr, &stacksize);
    while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
    pthread_attr_setstacksize(&server.io_threads_attr, stacksize);
7284 7285 7286 7287
    /* Listen for events in the threaded I/O pipe */
    if (aeCreateFileEvent(server.el, server.io_ready_pipe_read, AE_READABLE,
        vmThreadedIOCompletedJob, NULL) == AE_ERR)
        oom("creating file event");
7288 7289
}

A
antirez 已提交
7290 7291 7292 7293
/* Mark the page as used */
static void vmMarkPageUsed(off_t page) {
    off_t byte = page/8;
    int bit = page&7;
7294
    redisAssert(vmFreePage(page) == 1);
A
antirez 已提交
7295 7296 7297 7298 7299 7300 7301 7302
    server.vm_bitmap[byte] |= 1<<bit;
}

/* Mark N contiguous pages as used, with 'page' being the first. */
static void vmMarkPagesUsed(off_t page, off_t count) {
    off_t j;

    for (j = 0; j < count; j++)
A
antirez 已提交
7303
        vmMarkPageUsed(page+j);
A
antirez 已提交
7304
    server.vm_stats_used_pages += count;
7305 7306
    redisLog(REDIS_DEBUG,"Mark USED pages: %lld pages at %lld\n",
        (long long)count, (long long)page);
A
antirez 已提交
7307 7308 7309 7310 7311 7312
}

/* Mark the page as free */
static void vmMarkPageFree(off_t page) {
    off_t byte = page/8;
    int bit = page&7;
7313
    redisAssert(vmFreePage(page) == 0);
A
antirez 已提交
7314 7315 7316 7317 7318 7319 7320 7321
    server.vm_bitmap[byte] &= ~(1<<bit);
}

/* Mark N contiguous pages as free, with 'page' being the first. */
static void vmMarkPagesFree(off_t page, off_t count) {
    off_t j;

    for (j = 0; j < count; j++)
A
antirez 已提交
7322
        vmMarkPageFree(page+j);
A
antirez 已提交
7323
    server.vm_stats_used_pages -= count;
7324 7325
    redisLog(REDIS_DEBUG,"Mark FREE pages: %lld pages at %lld\n",
        (long long)count, (long long)page);
A
antirez 已提交
7326 7327 7328 7329 7330 7331
}

/* Test if the page is free */
static int vmFreePage(off_t page) {
    off_t byte = page/8;
    int bit = page&7;
A
antirez 已提交
7332
    return (server.vm_bitmap[byte] & (1<<bit)) == 0;
A
antirez 已提交
7333 7334 7335
}

/* Find N contiguous free pages storing the first page of the cluster in *first.
A
antirez 已提交
7336 7337
 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise 
 * REDIS_ERR is returned.
A
antirez 已提交
7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353
 *
 * This function uses a simple algorithm: we try to allocate
 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
 * again from the start of the swap file searching for free spaces.
 *
 * If it looks pretty clear that there are no free pages near our offset
 * we try to find less populated places doing a forward jump of
 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
 * without hurry, and then we jump again and so forth...
 * 
 * This function can be improved using a free list to avoid to guess
 * too much, since we could collect data about freed pages.
 *
 * note: I implemented this function just after watching an episode of
 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
 */
A
antirez 已提交
7354
static int vmFindContiguousPages(off_t *first, off_t n) {
A
antirez 已提交
7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380
    off_t base, offset = 0, since_jump = 0, numfree = 0;

    if (server.vm_near_pages == REDIS_VM_MAX_NEAR_PAGES) {
        server.vm_near_pages = 0;
        server.vm_next_page = 0;
    }
    server.vm_near_pages++; /* Yet another try for pages near to the old ones */
    base = server.vm_next_page;

    while(offset < server.vm_pages) {
        off_t this = base+offset;

        /* If we overflow, restart from page zero */
        if (this >= server.vm_pages) {
            this -= server.vm_pages;
            if (this == 0) {
                /* Just overflowed, what we found on tail is no longer
                 * interesting, as it's no longer contiguous. */
                numfree = 0;
            }
        }
        if (vmFreePage(this)) {
            /* This is a free page */
            numfree++;
            /* Already got N free pages? Return to the caller, with success */
            if (numfree == n) {
A
antirez 已提交
7381 7382
                *first = this-(n-1);
                server.vm_next_page = this+1;
7383
                redisLog(REDIS_DEBUG, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n, (long long) *first);
A
antirez 已提交
7384
                return REDIS_OK;
A
antirez 已提交
7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404
            }
        } else {
            /* The current one is not a free page */
            numfree = 0;
        }

        /* Fast-forward if the current page is not free and we already
         * searched enough near this place. */
        since_jump++;
        if (!numfree && since_jump >= REDIS_VM_MAX_RANDOM_JUMP/4) {
            offset += random() % REDIS_VM_MAX_RANDOM_JUMP;
            since_jump = 0;
            /* Note that even if we rewind after the jump, we are don't need
             * to make sure numfree is set to zero as we only jump *if* it
             * is set to zero. */
        } else {
            /* Otherwise just check the next page */
            offset++;
        }
    }
A
antirez 已提交
7405 7406 7407
    return REDIS_ERR;
}

7408 7409 7410 7411 7412 7413
/* Write the specified object at the specified page of the swap file */
static int vmWriteObjectOnSwap(robj *o, off_t page) {
    if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
    if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
        if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
        redisLog(REDIS_WARNING,
7414
            "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
7415 7416 7417 7418 7419 7420 7421 7422
            strerror(errno));
        return REDIS_ERR;
    }
    rdbSaveObject(server.vm_fp,o);
    if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
    return REDIS_OK;
}

A
antirez 已提交
7423 7424 7425 7426
/* Swap the 'val' object relative to 'key' into disk. Store all the information
 * needed to later retrieve the object into the key object.
 * If we can't find enough contiguous empty pages to swap the object on disk
 * REDIS_ERR is returned. */
7427
static int vmSwapObjectBlocking(robj *key, robj *val) {
7428
    off_t pages = rdbSavedObjectPages(val,NULL);
A
antirez 已提交
7429 7430 7431
    off_t page;

    assert(key->storage == REDIS_VM_MEMORY);
A
antirez 已提交
7432
    assert(key->refcount == 1);
A
antirez 已提交
7433
    if (vmFindContiguousPages(&page,pages) == REDIS_ERR) return REDIS_ERR;
7434
    if (vmWriteObjectOnSwap(val,page) == REDIS_ERR) return REDIS_ERR;
A
antirez 已提交
7435 7436 7437
    key->vm.page = page;
    key->vm.usedpages = pages;
    key->storage = REDIS_VM_SWAPPED;
7438
    key->vtype = val->type;
A
antirez 已提交
7439 7440
    decrRefCount(val); /* Deallocate the object from memory. */
    vmMarkPagesUsed(page,pages);
A
antirez 已提交
7441 7442 7443
    redisLog(REDIS_DEBUG,"VM: object %s swapped out at %lld (%lld pages)",
        (unsigned char*) key->ptr,
        (unsigned long long) page, (unsigned long long) pages);
A
antirez 已提交
7444 7445
    server.vm_stats_swapped_objects++;
    server.vm_stats_swapouts++;
7446
    fflush(server.vm_fp);
A
antirez 已提交
7447 7448 7449
    return REDIS_OK;
}

7450 7451
static robj *vmReadObjectFromSwap(off_t page, int type) {
    robj *o;
A
antirez 已提交
7452

7453 7454
    if (server.vm_enabled) pthread_mutex_lock(&server.io_swapfile_mutex);
    if (fseeko(server.vm_fp,page*server.vm_page_size,SEEK_SET) == -1) {
A
antirez 已提交
7455
        redisLog(REDIS_WARNING,
A
antirez 已提交
7456
            "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
A
antirez 已提交
7457
            strerror(errno));
7458
        _exit(1);
A
antirez 已提交
7459
    }
7460 7461
    o = rdbLoadObject(type,server.vm_fp);
    if (o == NULL) {
A
antirez 已提交
7462
        redisLog(REDIS_WARNING, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno));
7463
        _exit(1);
A
antirez 已提交
7464
    }
7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476
    if (server.vm_enabled) pthread_mutex_unlock(&server.io_swapfile_mutex);
    return o;
}

/* Load the value object relative to the 'key' object from swap to memory.
 * The newly allocated object is returned.
 *
 * If preview is true the unserialized object is returned to the caller but
 * no changes are made to the key object, nor the pages are marked as freed */
static robj *vmGenericLoadObject(robj *key, int preview) {
    robj *val;

A
antirez 已提交
7477
    redisAssert(key->storage == REDIS_VM_SWAPPED || key->storage == REDIS_VM_LOADING);
7478
    val = vmReadObjectFromSwap(key->vm.page,key->vtype);
A
antirez 已提交
7479 7480 7481 7482 7483 7484
    if (!preview) {
        key->storage = REDIS_VM_MEMORY;
        key->vm.atime = server.unixtime;
        vmMarkPagesFree(key->vm.page,key->vm.usedpages);
        redisLog(REDIS_DEBUG, "VM: object %s loaded from disk",
            (unsigned char*) key->ptr);
A
antirez 已提交
7485
        server.vm_stats_swapped_objects--;
A
antirez 已提交
7486 7487 7488
    } else {
        redisLog(REDIS_DEBUG, "VM: object %s previewed from disk",
            (unsigned char*) key->ptr);
A
antirez 已提交
7489
    }
A
antirez 已提交
7490
    server.vm_stats_swapins++;
A
antirez 已提交
7491
    return val;
A
antirez 已提交
7492 7493
}

A
antirez 已提交
7494 7495
/* Plain object loading, from swap to memory */
static robj *vmLoadObject(robj *key) {
7496 7497 7498 7499
    /* If we are loading the object in background, stop it, we
     * need to load this object synchronously ASAP. */
    if (key->storage == REDIS_VM_LOADING)
        vmCancelThreadedIOJob(key);
A
antirez 已提交
7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510
    return vmGenericLoadObject(key,0);
}

/* Just load the value on disk, without to modify the key.
 * This is useful when we want to perform some operation on the value
 * without to really bring it from swap to memory, like while saving the
 * dataset or rewriting the append only log. */
static robj *vmPreviewObject(robj *key) {
    return vmGenericLoadObject(key,1);
}

A
antirez 已提交
7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574
/* How a good candidate is this object for swapping?
 * The better candidate it is, the greater the returned value.
 *
 * Currently we try to perform a fast estimation of the object size in
 * memory, and combine it with aging informations.
 *
 * Basically swappability = idle-time * log(estimated size)
 *
 * Bigger objects are preferred over smaller objects, but not
 * proportionally, this is why we use the logarithm. This algorithm is
 * just a first try and will probably be tuned later. */
static double computeObjectSwappability(robj *o) {
    time_t age = server.unixtime - o->vm.atime;
    long asize = 0;
    list *l;
    dict *d;
    struct dictEntry *de;
    int z;

    if (age <= 0) return 0;
    switch(o->type) {
    case REDIS_STRING:
        if (o->encoding != REDIS_ENCODING_RAW) {
            asize = sizeof(*o);
        } else {
            asize = sdslen(o->ptr)+sizeof(*o)+sizeof(long)*2;
        }
        break;
    case REDIS_LIST:
        l = o->ptr;
        listNode *ln = listFirst(l);

        asize = sizeof(list);
        if (ln) {
            robj *ele = ln->value;
            long elesize;

            elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
                            (sizeof(*o)+sdslen(ele->ptr)) :
                            sizeof(*o);
            asize += (sizeof(listNode)+elesize)*listLength(l);
        }
        break;
    case REDIS_SET:
    case REDIS_ZSET:
        z = (o->type == REDIS_ZSET);
        d = z ? ((zset*)o->ptr)->dict : o->ptr;

        asize = sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
        if (z) asize += sizeof(zset)-sizeof(dict);
        if (dictSize(d)) {
            long elesize;
            robj *ele;

            de = dictGetRandomKey(d);
            ele = dictGetEntryKey(de);
            elesize = (ele->encoding == REDIS_ENCODING_RAW) ?
                            (sizeof(*o)+sdslen(ele->ptr)) :
                            sizeof(*o);
            asize += (sizeof(struct dictEntry)+elesize)*dictSize(d);
            if (z) asize += sizeof(zskiplistNode)*dictSize(d);
        }
        break;
    }
7575
    return (double)age*log(1+asize);
A
antirez 已提交
7576 7577 7578 7579
}

/* Try to swap an object that's a good candidate for swapping.
 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
7580 7581 7582 7583 7584
 * to swap any object at all.
 *
 * If 'usethreaded' is true, Redis will try to swap the object in background
 * using I/O threads. */
static int vmSwapOneObject(int usethreads) {
A
antirez 已提交
7585 7586 7587
    int j, i;
    struct dictEntry *best = NULL;
    double best_swappability = 0;
7588
    redisDb *best_db = NULL;
A
antirez 已提交
7589 7590 7591 7592
    robj *key, *val;

    for (j = 0; j < server.dbnum; j++) {
        redisDb *db = server.db+j;
7593 7594 7595
        /* Why maxtries is set to 100?
         * Because this way (usually) we'll find 1 object even if just 1% - 2%
         * are swappable objects */
7596
        int maxtries = 100;
A
antirez 已提交
7597 7598 7599 7600 7601 7602

        if (dictSize(db->dict) == 0) continue;
        for (i = 0; i < 5; i++) {
            dictEntry *de;
            double swappability;

7603
            if (maxtries) maxtries--;
A
antirez 已提交
7604 7605 7606
            de = dictGetRandomKey(db->dict);
            key = dictGetEntryKey(de);
            val = dictGetEntryVal(de);
A
antirez 已提交
7607 7608 7609 7610 7611 7612 7613 7614
            /* Only swap objects that are currently in memory.
             *
             * Also don't swap shared objects if threaded VM is on, as we
             * try to ensure that the main thread does not touch the
             * object while the I/O thread is using it, but we can't
             * control other keys without adding additional mutex. */
            if (key->storage != REDIS_VM_MEMORY ||
                (server.vm_max_threads != 0 && val->refcount != 1)) {
7615 7616 7617
                if (maxtries) i--; /* don't count this try */
                continue;
            }
A
antirez 已提交
7618 7619 7620 7621
            swappability = computeObjectSwappability(val);
            if (!best || swappability > best_swappability) {
                best = de;
                best_swappability = swappability;
7622
                best_db = db;
A
antirez 已提交
7623 7624 7625
            }
        }
    }
7626
    if (best == NULL) return REDIS_ERR;
A
antirez 已提交
7627 7628 7629
    key = dictGetEntryKey(best);
    val = dictGetEntryVal(best);

7630
    redisLog(REDIS_DEBUG,"Key with best swappability: %s, %f",
A
antirez 已提交
7631 7632 7633 7634 7635 7636 7637 7638 7639
        key->ptr, best_swappability);

    /* Unshare the key if needed */
    if (key->refcount > 1) {
        robj *newkey = dupStringObject(key);
        decrRefCount(key);
        key = dictGetEntryKey(best) = newkey;
    }
    /* Swap it */
7640
    if (usethreads) {
7641
        vmSwapObjectThreaded(key,val,best_db);
A
antirez 已提交
7642 7643
        return REDIS_OK;
    } else {
7644 7645 7646 7647 7648 7649
        if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
            dictGetEntryVal(best) = NULL;
            return REDIS_OK;
        } else {
            return REDIS_ERR;
        }
A
antirez 已提交
7650 7651 7652
    }
}

7653 7654 7655 7656 7657 7658 7659 7660
static int vmSwapOneObjectBlocking() {
    return vmSwapOneObject(0);
}

static int vmSwapOneObjectThreaded() {
    return vmSwapOneObject(1);
}

A
antirez 已提交
7661 7662 7663 7664 7665 7666 7667
/* Return true if it's safe to swap out objects in a given moment.
 * Basically we don't want to swap objects out while there is a BGSAVE
 * or a BGAEOREWRITE running in backgroud. */
static int vmCanSwapOut(void) {
    return (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1);
}

A
antirez 已提交
7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680
/* Delete a key if swapped. Returns 1 if the key was found, was swapped
 * and was deleted. Otherwise 0 is returned. */
static int deleteIfSwapped(redisDb *db, robj *key) {
    dictEntry *de;
    robj *foundkey;

    if ((de = dictFind(db->dict,key)) == NULL) return 0;
    foundkey = dictGetEntryKey(de);
    if (foundkey->storage == REDIS_VM_MEMORY) return 0;
    deleteKey(db,key);
    return 1;
}

7681 7682
/* =================== Virtual Memory - Threaded I/O  ======================= */

7683
static void freeIOJob(iojob *j) {
A
antirez 已提交
7684 7685 7686
    if ((j->type == REDIS_IOJOB_PREPARE_SWAP ||
        j->type == REDIS_IOJOB_DO_SWAP ||
        j->type == REDIS_IOJOB_LOAD) && j->val != NULL)
7687 7688 7689 7690 7691
        decrRefCount(j->val);
    decrRefCount(j->key);
    zfree(j);
}

7692 7693 7694 7695 7696 7697 7698
/* Every time a thread finished a Job, it writes a byte into the write side
 * of an unix pipe in order to "awake" the main thread, and this function
 * is called. */
static void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
            int mask)
{
    char buf[1];
7699
    int retval, processed = 0, toprocess = -1, trytoswap = 1;
7700 7701 7702 7703 7704 7705 7706
    REDIS_NOTUSED(el);
    REDIS_NOTUSED(mask);
    REDIS_NOTUSED(privdata);

    /* For every byte we read in the read side of the pipe, there is one
     * I/O job completed to process. */
    while((retval = read(fd,buf,1)) == 1) {
7707 7708 7709 7710 7711
        iojob *j;
        listNode *ln;
        robj *key;
        struct dictEntry *de;

7712
        redisLog(REDIS_DEBUG,"Processing I/O completed job");
7713 7714 7715

        /* Get the processed element (the oldest one) */
        lockThreadedIO();
A
antirez 已提交
7716
        assert(listLength(server.io_processed) != 0);
7717 7718 7719 7720
        if (toprocess == -1) {
            toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
            if (toprocess <= 0) toprocess = 1;
        }
7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731
        ln = listFirst(server.io_processed);
        j = ln->value;
        listDelNode(server.io_processed,ln);
        unlockThreadedIO();
        /* If this job is marked as canceled, just ignore it */
        if (j->canceled) {
            freeIOJob(j);
            continue;
        }
        /* Post process it in the main thread, as there are things we
         * can do just here to avoid race conditions and/or invasive locks */
7732
        redisLog(REDIS_DEBUG,"Job %p type: %d, key at %p (%s) refcount: %d\n", (void*) j, j->type, (void*)j->key, (char*)j->key->ptr, j->key->refcount);
7733 7734 7735 7736
        de = dictFind(j->db->dict,j->key);
        assert(de != NULL);
        key = dictGetEntryKey(de);
        if (j->type == REDIS_IOJOB_LOAD) {
A
antirez 已提交
7737 7738
            redisDb *db;

7739 7740 7741 7742 7743 7744 7745 7746
            /* Key loaded, bring it at home */
            key->storage = REDIS_VM_MEMORY;
            key->vm.atime = server.unixtime;
            vmMarkPagesFree(key->vm.page,key->vm.usedpages);
            redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
                (unsigned char*) key->ptr);
            server.vm_stats_swapped_objects--;
            server.vm_stats_swapins++;
A
antirez 已提交
7747 7748 7749
            dictGetEntryVal(de) = j->val;
            incrRefCount(j->val);
            db = j->db;
7750
            freeIOJob(j);
A
antirez 已提交
7751 7752
            /* Handle clients waiting for this key to be loaded. */
            handleClientsBlockedOnSwappedKey(db,key);
7753 7754 7755 7756
        } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
            /* Now we know the amount of pages required to swap this object.
             * Let's find some space for it, and queue this task again
             * rebranded as REDIS_IOJOB_DO_SWAP. */
7757 7758 7759 7760 7761
            if (!vmCanSwapOut() ||
                vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
            {
                /* Ooops... no space or we can't swap as there is
                 * a fork()ed Redis trying to save stuff on disk. */
7762
                freeIOJob(j);
7763
                key->storage = REDIS_VM_MEMORY; /* undo operation */
7764
            } else {
A
antirez 已提交
7765 7766 7767 7768
                /* Note that we need to mark this pages as used now,
                 * if the job will be canceled, we'll mark them as freed
                 * again. */
                vmMarkPagesUsed(j->page,j->pages);
7769 7770 7771 7772 7773 7774 7775 7776 7777
                j->type = REDIS_IOJOB_DO_SWAP;
                lockThreadedIO();
                queueIOJob(j);
                unlockThreadedIO();
            }
        } else if (j->type == REDIS_IOJOB_DO_SWAP) {
            robj *val;

            /* Key swapped. We can finally free some memory. */
7778 7779 7780 7781 7782 7783 7784 7785 7786
            if (key->storage != REDIS_VM_SWAPPING) {
                printf("key->storage: %d\n",key->storage);
                printf("key->name: %s\n",(char*)key->ptr);
                printf("key->refcount: %d\n",key->refcount);
                printf("val: %p\n",(void*)j->val);
                printf("val->type: %d\n",j->val->type);
                printf("val->ptr: %s\n",(char*)j->val->ptr);
            }
            redisAssert(key->storage == REDIS_VM_SWAPPING);
7787 7788 7789 7790 7791 7792
            val = dictGetEntryVal(de);
            key->vm.page = j->page;
            key->vm.usedpages = j->pages;
            key->storage = REDIS_VM_SWAPPED;
            key->vtype = j->val->type;
            decrRefCount(val); /* Deallocate the object from memory. */
A
antirez 已提交
7793
            dictGetEntryVal(de) = NULL;
7794 7795 7796 7797 7798 7799 7800
            redisLog(REDIS_DEBUG,
                "VM: object %s swapped out at %lld (%lld pages) (threaded)",
                (unsigned char*) key->ptr,
                (unsigned long long) j->page, (unsigned long long) j->pages);
            server.vm_stats_swapped_objects++;
            server.vm_stats_swapouts++;
            freeIOJob(j);
A
antirez 已提交
7801 7802
            /* Put a few more swap requests in queue if we are still
             * out of memory */
7803 7804 7805
            if (trytoswap && vmCanSwapOut() &&
                zmalloc_used_memory() > server.vm_max_memory)
            {
A
antirez 已提交
7806 7807 7808 7809 7810 7811 7812
                int more = 1;
                while(more) {
                    lockThreadedIO();
                    more = listLength(server.io_newjobs) <
                            (unsigned) server.vm_max_threads;
                    unlockThreadedIO();
                    /* Don't waste CPU time if swappable objects are rare. */
7813 7814 7815 7816
                    if (vmSwapOneObjectThreaded() == REDIS_ERR) {
                        trytoswap = 0;
                        break;
                    }
A
antirez 已提交
7817 7818
                }
            }
7819
        }
7820
        processed++;
7821
        if (processed == toprocess) return;
7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841
    }
    if (retval < 0 && errno != EAGAIN) {
        redisLog(REDIS_WARNING,
            "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
            strerror(errno));
    }
}

static void lockThreadedIO(void) {
    pthread_mutex_lock(&server.io_mutex);
}

static void unlockThreadedIO(void) {
    pthread_mutex_unlock(&server.io_mutex);
}

/* Remove the specified object from the threaded I/O queue if still not
 * processed, otherwise make sure to flag it as canceled. */
static void vmCancelThreadedIOJob(robj *o) {
    list *lists[3] = {
7842 7843 7844
        server.io_newjobs,      /* 0 */
        server.io_processing,   /* 1 */
        server.io_processed     /* 2 */
7845 7846 7847 7848
    };
    int i;

    assert(o->storage == REDIS_VM_LOADING || o->storage == REDIS_VM_SWAPPING);
7849
again:
7850 7851 7852 7853
    lockThreadedIO();
    /* Search for a matching key in one of the queues */
    for (i = 0; i < 3; i++) {
        listNode *ln;
A
antirez 已提交
7854
        listIter li;
7855

A
antirez 已提交
7856 7857
        listRewind(lists[i],&li);
        while ((ln = listNext(&li)) != NULL) {
7858 7859
            iojob *job = ln->value;

7860
            if (job->canceled) continue; /* Skip this, already canceled. */
7861
            if (compareStringObjects(job->key,o) == 0) {
7862 7863
                redisLog(REDIS_DEBUG,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
                    (void*)job, (char*)o->ptr, job->type, i);
7864 7865
                /* Mark the pages as free since the swap didn't happened
                 * or happened but is now discarded. */
7866
                if (i != 1 && job->type == REDIS_IOJOB_DO_SWAP)
7867 7868 7869
                    vmMarkPagesFree(job->page,job->pages);
                /* Cancel the job. It depends on the list the job is
                 * living in. */
7870 7871
                switch(i) {
                case 0: /* io_newjobs */
7872
                    /* If the job was yet not processed the best thing to do
7873
                     * is to remove it from the queue at all */
7874
                    freeIOJob(job);
7875 7876 7877
                    listDelNode(lists[i],ln);
                    break;
                case 1: /* io_processing */
A
antirez 已提交
7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896
                    /* Oh Shi- the thread is messing with the Job:
                     *
                     * Probably it's accessing the object if this is a
                     * PREPARE_SWAP or DO_SWAP job.
                     * If it's a LOAD job it may be reading from disk and
                     * if we don't wait for the job to terminate before to
                     * cancel it, maybe in a few microseconds data can be
                     * corrupted in this pages. So the short story is:
                     *
                     * Better to wait for the job to move into the
                     * next queue (processed)... */

                    /* We try again and again until the job is completed. */
                    unlockThreadedIO();
                    /* But let's wait some time for the I/O thread
                     * to finish with this job. After all this condition
                     * should be very rare. */
                    usleep(1);
                    goto again;
7897
                case 2: /* io_processed */
7898 7899 7900
                    /* The job was already processed, that's easy...
                     * just mark it as canceled so that we'll ignore it
                     * when processing completed jobs. */
7901 7902 7903
                    job->canceled = 1;
                    break;
                }
A
antirez 已提交
7904 7905
                /* Finally we have to adjust the storage type of the object
                 * in order to "UNDO" the operaiton. */
7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918
                if (o->storage == REDIS_VM_LOADING)
                    o->storage = REDIS_VM_SWAPPED;
                else if (o->storage == REDIS_VM_SWAPPING)
                    o->storage = REDIS_VM_MEMORY;
                unlockThreadedIO();
                return;
            }
        }
    }
    unlockThreadedIO();
    assert(1 != 1); /* We should never reach this */
}

7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929
static void *IOThreadEntryPoint(void *arg) {
    iojob *j;
    listNode *ln;
    REDIS_NOTUSED(arg);

    pthread_detach(pthread_self());
    while(1) {
        /* Get a new job to process */
        lockThreadedIO();
        if (listLength(server.io_newjobs) == 0) {
            /* No new jobs in queue, exit. */
7930 7931
            redisLog(REDIS_DEBUG,"Thread %ld exiting, nothing to do",
                (long) pthread_self());
7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943
            server.io_active_threads--;
            unlockThreadedIO();
            return NULL;
        }
        ln = listFirst(server.io_newjobs);
        j = ln->value;
        listDelNode(server.io_newjobs,ln);
        /* Add the job in the processing queue */
        j->thread = pthread_self();
        listAddNodeTail(server.io_processing,j);
        ln = listLast(server.io_processing); /* We use ln later to remove it */
        unlockThreadedIO();
7944 7945
        redisLog(REDIS_DEBUG,"Thread %ld got a new job (type %d): %p about key '%s'",
            (long) pthread_self(), j->type, (void*)j, (char*)j->key->ptr);
7946 7947 7948

        /* Process the Job */
        if (j->type == REDIS_IOJOB_LOAD) {
A
antirez 已提交
7949
            j->val = vmReadObjectFromSwap(j->page,j->key->vtype);
7950 7951 7952 7953 7954
        } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
            FILE *fp = fopen("/dev/null","w+");
            j->pages = rdbSavedObjectPages(j->val,fp);
            fclose(fp);
        } else if (j->type == REDIS_IOJOB_DO_SWAP) {
7955 7956
            if (vmWriteObjectOnSwap(j->val,j->page) == REDIS_ERR)
                j->canceled = 1;
7957 7958 7959
        }

        /* Done: insert the job into the processed queue */
7960 7961
        redisLog(REDIS_DEBUG,"Thread %ld completed the job: %p (key %s)",
            (long) pthread_self(), (void*)j, (char*)j->key->ptr);
7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974
        lockThreadedIO();
        listDelNode(server.io_processing,ln);
        listAddNodeTail(server.io_processed,j);
        unlockThreadedIO();
        
        /* Signal the main thread there is new stuff to process */
        assert(write(server.io_ready_pipe_write,"x",1) == 1);
    }
    return NULL; /* never reached */
}

static void spawnIOThread(void) {
    pthread_t thread;
7975
    sigset_t mask, omask;
7976

7977 7978 7979 7980 7981
    sigemptyset(&mask);
    sigaddset(&mask,SIGCHLD);
    sigaddset(&mask,SIGHUP);
    sigaddset(&mask,SIGPIPE);
    pthread_sigmask(SIG_SETMASK, &mask, &omask);
7982
    pthread_create(&thread,&server.io_threads_attr,IOThreadEntryPoint,NULL);
7983
    pthread_sigmask(SIG_SETMASK, &omask, NULL);
7984 7985 7986
    server.io_active_threads++;
}

7987 7988
/* We need to wait for the last thread to exit before we are able to
 * fork() in order to BGSAVE or BGREWRITEAOF. */
7989
static void waitEmptyIOJobsQueue(void) {
7990
    while(1) {
7991 7992
        int io_processed_len;

7993
        lockThreadedIO();
7994 7995 7996 7997
        if (listLength(server.io_newjobs) == 0 &&
            listLength(server.io_processing) == 0 &&
            server.io_active_threads == 0)
        {
7998 7999 8000
            unlockThreadedIO();
            return;
        }
8001 8002 8003 8004 8005
        /* While waiting for empty jobs queue condition we post-process some
         * finshed job, as I/O threads may be hanging trying to write against
         * the io_ready_pipe_write FD but there are so much pending jobs that
         * it's blocking. */
        io_processed_len = listLength(server.io_processed);
8006
        unlockThreadedIO();
8007 8008 8009 8010 8011 8012
        if (io_processed_len) {
            vmThreadedIOCompletedJob(NULL,server.io_ready_pipe_read,NULL,0);
            usleep(1000); /* 1 millisecond */
        } else {
            usleep(10000); /* 10 milliseconds */
        }
8013 8014 8015
    }
}

8016
static void vmReopenSwapFile(void) {
8017 8018
    /* Note: we don't close the old one as we are in the child process
     * and don't want to mess at all with the original file object. */
8019 8020 8021 8022
    server.vm_fp = fopen(server.vm_swap_file,"r+b");
    if (server.vm_fp == NULL) {
        redisLog(REDIS_WARNING,"Can't re-open the VM swap file: %s. Exiting.",
            server.vm_swap_file);
8023
        _exit(1);
8024 8025 8026 8027
    }
    server.vm_fd = fileno(server.vm_fp);
}

8028 8029
/* This function must be called while with threaded IO locked */
static void queueIOJob(iojob *j) {
8030 8031
    redisLog(REDIS_DEBUG,"Queued IO Job %p type %d about key '%s'\n",
        (void*)j, j->type, (char*)j->key->ptr);
8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050
    listAddNodeTail(server.io_newjobs,j);
    if (server.io_active_threads < server.vm_max_threads)
        spawnIOThread();
}

static int vmSwapObjectThreaded(robj *key, robj *val, redisDb *db) {
    iojob *j;
    
    assert(key->storage == REDIS_VM_MEMORY);
    assert(key->refcount == 1);

    j = zmalloc(sizeof(*j));
    j->type = REDIS_IOJOB_PREPARE_SWAP;
    j->db = db;
    j->key = dupStringObject(key);
    j->val = val;
    incrRefCount(val);
    j->canceled = 0;
    j->thread = (pthread_t) -1;
A
antirez 已提交
8051
    key->storage = REDIS_VM_SWAPPING;
8052 8053 8054 8055 8056 8057 8058

    lockThreadedIO();
    queueIOJob(j);
    unlockThreadedIO();
    return REDIS_OK;
}

8059 8060
/* ============ Virtual Memory - Blocking clients on missing keys =========== */

A
antirez 已提交
8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126
/* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
 * If there is not already a job loading the key, it is craeted.
 * The key is added to the io_keys list in the client structure, and also
 * in the hash table mapping swapped keys to waiting clients, that is,
 * server.io_waited_keys. */
static int waitForSwappedKey(redisClient *c, robj *key) {
    struct dictEntry *de;
    robj *o;
    list *l;

    /* If the key does not exist or is already in RAM we don't need to
     * block the client at all. */
    de = dictFind(c->db->dict,key);
    if (de == NULL) return 0;
    o = dictGetEntryKey(de);
    if (o->storage == REDIS_VM_MEMORY) {
        return 0;
    } else if (o->storage == REDIS_VM_SWAPPING) {
        /* We were swapping the key, undo it! */
        vmCancelThreadedIOJob(o);
        return 0;
    }
    
    /* OK: the key is either swapped, or being loaded just now. */

    /* Add the key to the list of keys this client is waiting for.
     * This maps clients to keys they are waiting for. */
    listAddNodeTail(c->io_keys,key);
    incrRefCount(key);

    /* Add the client to the swapped keys => clients waiting map. */
    de = dictFind(c->db->io_keys,key);
    if (de == NULL) {
        int retval;

        /* For every key we take a list of clients blocked for it */
        l = listCreate();
        retval = dictAdd(c->db->io_keys,key,l);
        incrRefCount(key);
        assert(retval == DICT_OK);
    } else {
        l = dictGetEntryVal(de);
    }
    listAddNodeTail(l,c);

    /* Are we already loading the key from disk? If not create a job */
    if (o->storage == REDIS_VM_SWAPPED) {
        iojob *j;

        o->storage = REDIS_VM_LOADING;
        j = zmalloc(sizeof(*j));
        j->type = REDIS_IOJOB_LOAD;
        j->db = c->db;
        j->key = dupStringObject(key);
        j->key->vtype = o->vtype;
        j->page = o->vm.page;
        j->val = NULL;
        j->canceled = 0;
        j->thread = (pthread_t) -1;
        lockThreadedIO();
        queueIOJob(j);
        unlockThreadedIO();
    }
    return 1;
}

8127
/* Is this client attempting to run a command against swapped keys?
A
antirez 已提交
8128
 * If so, block it ASAP, load the keys in background, then resume it.
8129
 *
A
antirez 已提交
8130 8131 8132 8133 8134 8135 8136 8137
 * The important idea about this function is that it can fail! If keys will
 * still be swapped when the client is resumed, this key lookups will
 * just block loading keys from disk. In practical terms this should only
 * happen with SORT BY command or if there is a bug in this function.
 *
 * Return 1 if the client is marked as blocked, 0 if the client can
 * continue as the keys it is going to access appear to be in memory. */
static int blockClientOnSwappedKeys(struct redisCommand *cmd, redisClient *c) {
8138 8139 8140 8141 8142 8143 8144
    int j, last;

    if (cmd->vm_firstkey == 0) return 0;
    last = cmd->vm_lastkey;
    if (last < 0) last = c->argc+last;
    for (j = cmd->vm_firstkey; j <= last; j += cmd->vm_keystep)
        waitForSwappedKey(c,c->argv[j]);
A
antirez 已提交
8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211
    /* If the client was blocked for at least one key, mark it as blocked. */
    if (listLength(c->io_keys)) {
        c->flags |= REDIS_IO_WAIT;
        aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
        server.vm_blocked_clients++;
        return 1;
    } else {
        return 0;
    }
}

/* Remove the 'key' from the list of blocked keys for a given client.
 *
 * The function returns 1 when there are no longer blocking keys after
 * the current one was removed (and the client can be unblocked). */
static int dontWaitForSwappedKey(redisClient *c, robj *key) {
    list *l;
    listNode *ln;
    listIter li;
    struct dictEntry *de;

    /* Remove the key from the list of keys this client is waiting for. */
    listRewind(c->io_keys,&li);
    while ((ln = listNext(&li)) != NULL) {
        if (compareStringObjects(ln->value,key) == 0) {
            listDelNode(c->io_keys,ln);
            break;
        }
    }
    assert(ln != NULL);

    /* Remove the client form the key => waiting clients map. */
    de = dictFind(c->db->io_keys,key);
    assert(de != NULL);
    l = dictGetEntryVal(de);
    ln = listSearchKey(l,c);
    assert(ln != NULL);
    listDelNode(l,ln);
    if (listLength(l) == 0)
        dictDelete(c->db->io_keys,key);

    return listLength(c->io_keys) == 0;
}

static void handleClientsBlockedOnSwappedKey(redisDb *db, robj *key) {
    struct dictEntry *de;
    list *l;
    listNode *ln;
    int len;

    de = dictFind(db->io_keys,key);
    if (!de) return;

    l = dictGetEntryVal(de);
    len = listLength(l);
    /* Note: we can't use something like while(listLength(l)) as the list
     * can be freed by the calling function when we remove the last element. */
    while (len--) {
        ln = listFirst(l);
        redisClient *c = ln->value;

        if (dontWaitForSwappedKey(c,key)) {
            /* Put the client in the list of clients ready to go as we
             * loaded all the keys about it. */
            listAddNodeTail(server.io_ready_clients,c);
        }
    }
8212 8213
}

8214 8215 8216 8217 8218
/* ================================= Debugging ============================== */

static void debugCommand(redisClient *c) {
    if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
        *((char*)-1) = 'x';
8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230
    } else if (!strcasecmp(c->argv[1]->ptr,"reload")) {
        if (rdbSave(server.dbfilename) != REDIS_OK) {
            addReply(c,shared.err);
            return;
        }
        emptyDb();
        if (rdbLoad(server.dbfilename) != REDIS_OK) {
            addReply(c,shared.err);
            return;
        }
        redisLog(REDIS_WARNING,"DB reloaded by DEBUG RELOAD");
        addReply(c,shared.ok);
8231 8232 8233 8234 8235 8236 8237 8238
    } else if (!strcasecmp(c->argv[1]->ptr,"loadaof")) {
        emptyDb();
        if (loadAppendOnlyFile(server.appendfilename) != REDIS_OK) {
            addReply(c,shared.err);
            return;
        }
        redisLog(REDIS_WARNING,"Append Only File loaded by DEBUG LOADAOF");
        addReply(c,shared.ok);
A
antirez 已提交
8239 8240 8241 8242 8243 8244 8245 8246 8247 8248
    } else if (!strcasecmp(c->argv[1]->ptr,"object") && c->argc == 3) {
        dictEntry *de = dictFind(c->db->dict,c->argv[2]);
        robj *key, *val;

        if (!de) {
            addReply(c,shared.nokeyerr);
            return;
        }
        key = dictGetEntryKey(de);
        val = dictGetEntryVal(de);
8249 8250
        if (!server.vm_enabled || (key->storage == REDIS_VM_MEMORY ||
                                   key->storage == REDIS_VM_SWAPPING)) {
8251 8252 8253
            addReplySds(c,sdscatprintf(sdsempty(),
                "+Key at:%p refcount:%d, value at:%p refcount:%d "
                "encoding:%d serializedlength:%lld\r\n",
8254
                (void*)key, key->refcount, (void*)val, val->refcount,
A
antirez 已提交
8255
                val->encoding, (long long) rdbSavedObjectLen(val,NULL)));
8256 8257 8258 8259 8260 8261 8262
        } else {
            addReplySds(c,sdscatprintf(sdsempty(),
                "+Key at:%p refcount:%d, value swapped at: page %llu "
                "using %llu pages\r\n",
                (void*)key, key->refcount, (unsigned long long) key->vm.page,
                (unsigned long long) key->vm.usedpages));
        }
A
antirez 已提交
8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276
    } else if (!strcasecmp(c->argv[1]->ptr,"swapout") && c->argc == 3) {
        dictEntry *de = dictFind(c->db->dict,c->argv[2]);
        robj *key, *val;

        if (!server.vm_enabled) {
            addReplySds(c,sdsnew("-ERR Virtual Memory is disabled\r\n"));
            return;
        }
        if (!de) {
            addReply(c,shared.nokeyerr);
            return;
        }
        key = dictGetEntryKey(de);
        val = dictGetEntryVal(de);
A
antirez 已提交
8277 8278 8279 8280 8281 8282 8283
        /* If the key is shared we want to create a copy */
        if (key->refcount > 1) {
            robj *newkey = dupStringObject(key);
            decrRefCount(key);
            key = dictGetEntryKey(de) = newkey;
        }
        /* Swap it */
A
antirez 已提交
8284 8285
        if (key->storage != REDIS_VM_MEMORY) {
            addReplySds(c,sdsnew("-ERR This key is not in memory\r\n"));
8286
        } else if (vmSwapObjectBlocking(key,val) == REDIS_OK) {
A
antirez 已提交
8287 8288 8289 8290 8291
            dictGetEntryVal(de) = NULL;
            addReply(c,shared.ok);
        } else {
            addReply(c,shared.err);
        }
8292
    } else {
A
antirez 已提交
8293
        addReplySds(c,sdsnew(
A
antirez 已提交
8294
            "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
8295 8296
    }
}
8297

8298
static void _redisAssert(char *estr, char *file, int line) {
8299
    redisLog(REDIS_WARNING,"=== ASSERTION FAILED ===");
8300
    redisLog(REDIS_WARNING,"==> %s:%d '%s' is not true\n",file,line,estr);
8301 8302 8303 8304 8305 8306
#ifdef HAVE_BACKTRACE
    redisLog(REDIS_WARNING,"(forcing SIGSEGV in order to print the stack trace)");
    *((char*)-1) = 'x';
#endif
}

8307
/* =================================== Main! ================================ */
8308

8309 8310 8311 8312
#ifdef __linux__
int linuxOvercommitMemoryValue(void) {
    FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
    char buf[64];
8313

8314 8315 8316 8317 8318 8319
    if (!fp) return -1;
    if (fgets(buf,64,fp) == NULL) {
        fclose(fp);
        return -1;
    }
    fclose(fp);
8320

8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351
    return atoi(buf);
}

void linuxOvercommitMemoryWarning(void) {
    if (linuxOvercommitMemoryValue() == 0) {
        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.");
    }
}
#endif /* __linux__ */

static void daemonize(void) {
    int fd;
    FILE *fp;

    if (fork() != 0) exit(0); /* parent exits */
    setsid(); /* create a new session */

    /* Every output goes to /dev/null. If Redis is daemonized but
     * the 'logfile' is set to 'stdout' in the configuration file
     * it will not log at all. */
    if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
        dup2(fd, STDIN_FILENO);
        dup2(fd, STDOUT_FILENO);
        dup2(fd, STDERR_FILENO);
        if (fd > STDERR_FILENO) close(fd);
    }
    /* Try to write the pid file */
    fp = fopen(server.pidfile,"w");
    if (fp) {
        fprintf(fp,"%d\n",getpid());
        fclose(fp);
8352 8353 8354
    }
}

8355
int main(int argc, char **argv) {
8356 8357
    time_t start;

8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368
    initServerConfig();
    if (argc == 2) {
        resetServerSaveParams();
        loadServerConfig(argv[1]);
    } else if (argc > 2) {
        fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
        exit(1);
    } else {
        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'");
    }
    if (server.daemonize) daemonize();
8369
    initServer();
8370 8371 8372 8373
    redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
#ifdef __linux__
    linuxOvercommitMemoryWarning();
#endif
8374
    start = time(NULL);
8375 8376
    if (server.appendonly) {
        if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
8377
            redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
8378 8379
    } else {
        if (rdbLoad(server.dbfilename) == REDIS_OK)
8380
            redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
8381 8382
    }
    redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
A
antirez 已提交
8383
    aeSetBeforeSleepProc(server.el,beforeSleep);
8384 8385 8386 8387 8388 8389 8390 8391 8392 8393
    aeMain(server.el);
    aeDeleteEventLoop(server.el);
    return 0;
}

/* ============================= Backtrace support ========================= */

#ifdef HAVE_BACKTRACE
static char *findFuncName(void *pointer, unsigned long *offset);

8394 8395 8396 8397 8398
static void *getMcontextEip(ucontext_t *uc) {
#if defined(__FreeBSD__)
    return (void*) uc->uc_mcontext.mc_eip;
#elif defined(__dietlibc__)
    return (void*) uc->uc_mcontext.eip;
8399
#elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
8400 8401 8402
  #if __x86_64__
    return (void*) uc->uc_mcontext->__ss.__rip;
  #else
8403
    return (void*) uc->uc_mcontext->__ss.__eip;
8404
  #endif
8405
#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
8406
  #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
8407
    return (void*) uc->uc_mcontext->__ss.__rip;
8408 8409 8410
  #else
    return (void*) uc->uc_mcontext->__ss.__eip;
  #endif 
A
antirez 已提交
8411 8412
#elif defined(__i386__) || defined(__X86_64__)  || defined(__x86_64__)
    return (void*) uc->uc_mcontext.gregs[REG_EIP]; /* Linux 32/64 bit */
8413 8414 8415 8416
#elif defined(__ia64__) /* Linux IA64 */
    return (void*) uc->uc_mcontext.sc_ip;
#else
    return NULL;
8417 8418 8419 8420 8421 8422 8423 8424 8425
#endif
}

static void segvHandler(int sig, siginfo_t *info, void *secret) {
    void *trace[100];
    char **messages = NULL;
    int i, trace_size = 0;
    unsigned long offset=0;
    ucontext_t *uc = (ucontext_t*) secret;
8426
    sds infostring;
8427 8428 8429 8430
    REDIS_NOTUSED(info);

    redisLog(REDIS_WARNING,
        "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
8431 8432 8433 8434
    infostring = genRedisInfoString();
    redisLog(REDIS_WARNING, "%s",infostring);
    /* It's not safe to sdsfree() the returned string under memory
     * corruption conditions. Let it leak as we are going to abort */
8435 8436
    
    trace_size = backtrace(trace, 100);
8437
    /* overwrite sigaction with caller's address */
8438 8439 8440
    if (getMcontextEip(uc) != NULL) {
        trace[1] = getMcontextEip(uc);
    }
8441
    messages = backtrace_symbols(trace, trace_size);
H
hrothgar 已提交
8442

8443
    for (i=1; i<trace_size; ++i) {
8444 8445 8446 8447 8448 8449 8450 8451 8452
        char *fn = findFuncName(trace[i], &offset), *p;

        p = strchr(messages[i],'+');
        if (!fn || (p && ((unsigned long)strtol(p+1,NULL,10)) < offset)) {
            redisLog(REDIS_WARNING,"%s", messages[i]);
        } else {
            redisLog(REDIS_WARNING,"%d redis-server %p %s + %d", i, trace[i], fn, (unsigned int)offset);
        }
    }
8453
    /* free(messages); Don't call free() with possibly corrupted memory. */
8454
    _exit(0);
H
hrothgar 已提交
8455
}
8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466

static void setupSigSegvAction(void) {
    struct sigaction act;

    sigemptyset (&act.sa_mask);
    /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
     * is used. Otherwise, sa_handler is used */
    act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
    act.sa_sigaction = segvHandler;
    sigaction (SIGSEGV, &act, NULL);
    sigaction (SIGBUS, &act, NULL);
8467 8468 8469
    sigaction (SIGFPE, &act, NULL);
    sigaction (SIGILL, &act, NULL);
    sigaction (SIGBUS, &act, NULL);
8470
    return;
8471
}
8472

8473 8474 8475 8476 8477 8478 8479
#include "staticsymbols.h"
/* This function try to convert a pointer into a function name. It's used in
 * oreder to provide a backtrace under segmentation fault that's able to
 * display functions declared as static (otherwise the backtrace is useless). */
static char *findFuncName(void *pointer, unsigned long *offset){
    int i, ret = -1;
    unsigned long off, minoff = 0;
A
antirez 已提交
8480

8481 8482 8483
    /* Try to match against the Symbol with the smallest offset */
    for (i=0; symsTable[i].pointer; i++) {
        unsigned long lp = (unsigned long) pointer;
8484

8485 8486 8487 8488 8489 8490 8491
        if (lp != (unsigned long)-1 && lp >= symsTable[i].pointer) {
            off=lp-symsTable[i].pointer;
            if (ret < 0 || off < minoff) {
                minoff=off;
                ret=i;
            }
        }
8492
    }
8493 8494 8495
    if (ret == -1) return NULL;
    *offset = minoff;
    return symsTable[ret].name;
8496
}
8497 8498
#else /* HAVE_BACKTRACE */
static void setupSigSegvAction(void) {
8499
}
8500
#endif /* HAVE_BACKTRACE */
8501

A
antirez 已提交
8502 8503


8504 8505 8506
/* The End */


A
antirez 已提交
8507