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