2 * Copyright (c) 2006-2009, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
30 #define REDIS_VERSION "1.3.2"
40 #define __USE_POSIX199309
46 #endif /* HAVE_BACKTRACE */
54 #include <arpa/inet.h>
58 #include <sys/resource.h>
65 #include "solarisfixes.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 */
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 */
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
101 /* Hash table parameters */
102 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
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
114 #define REDIS_STRING 0
120 /* Objects encoding */
121 #define REDIS_ENCODING_RAW 0 /* Raw representation */
122 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
124 /* Object types only used for dumping to disk */
125 #define REDIS_EXPIRETIME 253
126 #define REDIS_SELECTDB 254
127 #define REDIS_EOF 255
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:
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.
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
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 */
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 */
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 number of completed I/O jobs to process when the
169 * handelr is called. 1 is the minimum, and also the default, as it allows
170 * to block as little as possible other accessing clients. While Virtual
171 * Memory I/O operations are performed by threads, this operations must
172 * be processed by the main thread when completed to take effect. */
173 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
176 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
177 #define REDIS_SLAVE 2 /* This client is a slave server */
178 #define REDIS_MASTER 4 /* This client is a master server */
179 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
180 #define REDIS_MULTI 16 /* This client is in a MULTI context */
181 #define REDIS_BLOCKED 32 /* The client is waiting in a blocking operation */
182 #define REDIS_IO_WAIT 64 /* The client is waiting for Virtual Memory I/O */
184 /* Slave replication state - slave side */
185 #define REDIS_REPL_NONE 0 /* No active replication */
186 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
187 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
189 /* Slave replication state - from the point of view of master
190 * Note that in SEND_BULK and ONLINE state the slave receives new updates
191 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
192 * to start the next background saving in order to send updates to it. */
193 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
194 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
195 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
196 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
198 /* List related stuff */
202 /* Sort operations */
203 #define REDIS_SORT_GET 0
204 #define REDIS_SORT_ASC 1
205 #define REDIS_SORT_DESC 2
206 #define REDIS_SORTKEY_MAX 1024
209 #define REDIS_DEBUG 0
210 #define REDIS_VERBOSE 1
211 #define REDIS_NOTICE 2
212 #define REDIS_WARNING 3
214 /* Anti-warning macro... */
215 #define REDIS_NOTUSED(V) ((void) V)
217 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
218 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
220 /* Append only defines */
221 #define APPENDFSYNC_NO 0
222 #define APPENDFSYNC_ALWAYS 1
223 #define APPENDFSYNC_EVERYSEC 2
225 /* We can print the stacktrace, so our assert is defined this way: */
226 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),exit(1)))
227 static void _redisAssert(char *estr
, char *file
, int line
);
229 /*================================= Data types ============================== */
231 /* A redis object, that is a type able to hold a string / list / set */
233 /* The VM object structure */
234 struct redisObjectVM
{
235 off_t page
; /* the page at witch the object is stored on disk */
236 off_t usedpages
; /* number of pages used on disk */
237 time_t atime
; /* Last access time */
240 /* The actual Redis Object */
241 typedef struct redisObject
{
244 unsigned char encoding
;
245 unsigned char storage
; /* If this object is a key, where is the value?
246 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
247 unsigned char vtype
; /* If this object is a key, and value is swapped out,
248 * this is the type of the swapped out object. */
250 /* VM fields, this are only allocated if VM is active, otherwise the
251 * object allocation function will just allocate
252 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
253 * Redis without VM active will not have any overhead. */
254 struct redisObjectVM vm
;
257 /* Macro used to initalize a Redis object allocated on the stack.
258 * Note that this macro is taken near the structure definition to make sure
259 * we'll update it when the structure is changed, to avoid bugs like
260 * bug #85 introduced exactly in this way. */
261 #define initStaticStringObject(_var,_ptr) do { \
263 _var.type = REDIS_STRING; \
264 _var.encoding = REDIS_ENCODING_RAW; \
266 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
269 typedef struct redisDb
{
270 dict
*dict
; /* The keyspace for this DB */
271 dict
*expires
; /* Timeout of keys with a timeout set */
272 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
276 /* Client MULTI/EXEC state */
277 typedef struct multiCmd
{
280 struct redisCommand
*cmd
;
283 typedef struct multiState
{
284 multiCmd
*commands
; /* Array of MULTI commands */
285 int count
; /* Total number of MULTI commands */
288 /* With multiplexing we need to take per-clinet state.
289 * Clients are taken in a liked list. */
290 typedef struct redisClient
{
295 robj
**argv
, **mbargv
;
297 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
298 int multibulk
; /* multi bulk command format active */
301 time_t lastinteraction
; /* time of the last interaction, used for timeout */
302 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
304 int slaveseldb
; /* slave selected db, if this client is a slave */
305 int authenticated
; /* when requirepass is non-NULL */
306 int replstate
; /* replication state if this is a slave */
307 int repldbfd
; /* replication DB file descriptor */
308 long repldboff
; /* replication DB file offset */
309 off_t repldbsize
; /* replication DB file size */
310 multiState mstate
; /* MULTI/EXEC state */
311 robj
**blockingkeys
; /* The key we waiting to terminate a blocking
312 * operation such as BLPOP. Otherwise NULL. */
313 int blockingkeysnum
; /* Number of blocking keys */
314 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
315 * is >= blockingto then the operation timed out. */
316 list
*io_keys
; /* Keys this client is waiting to be loaded from the
317 * swap file in order to continue. */
325 /* Global server state structure */
330 dict
*sharingpool
; /* Poll used for object sharing */
331 unsigned int sharingpoolsize
;
332 long long dirty
; /* changes to DB from the last save */
334 list
*slaves
, *monitors
;
335 char neterr
[ANET_ERR_LEN
];
337 int cronloops
; /* number of times the cron function run */
338 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
339 time_t lastsave
; /* Unix time of last save succeeede */
340 size_t usedmemory
; /* Used memory in megabytes */
341 /* Fields used only for stats */
342 time_t stat_starttime
; /* server start time */
343 long long stat_numcommands
; /* number of processed commands */
344 long long stat_numconnections
; /* number of connections received */
357 pid_t bgsavechildpid
;
358 pid_t bgrewritechildpid
;
359 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
360 struct saveparam
*saveparams
;
365 char *appendfilename
;
369 /* Replication related */
374 redisClient
*master
; /* client that is master for this slave */
376 unsigned int maxclients
;
377 unsigned long long maxmemory
;
378 unsigned int blockedclients
;
379 /* Sort parameters - qsort_r() is only available under BSD so we
380 * have to take this state global, in order to pass it to sortCompare() */
384 /* Virtual memory configuration */
389 unsigned long long vm_max_memory
;
390 /* Virtual memory state */
393 off_t vm_next_page
; /* Next probably empty page */
394 off_t vm_near_pages
; /* Number of pages allocated sequentially */
395 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
396 time_t unixtime
; /* Unix time sampled every second. */
397 /* Virtual memory I/O threads stuff */
398 /* An I/O thread process an element taken from the io_jobs queue and
399 * put the result of the operation in the io_done list. While the
400 * job is being processed, it's put on io_processing queue. */
401 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
402 list
*io_processing
; /* List of VM I/O jobs being processed */
403 list
*io_processed
; /* List of VM I/O jobs already processed */
404 list
*io_clients
; /* All the clients waiting for SWAP I/O operations */
405 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
406 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
407 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
408 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
409 int io_active_threads
; /* Number of running I/O threads */
410 int vm_max_threads
; /* Max number of I/O threads running at the same time */
411 /* Our main thread is blocked on the event loop, locking for sockets ready
412 * to be read or written, so when a threaded I/O operation is ready to be
413 * processed by the main thread, the I/O thread will use a unix pipe to
414 * awake the main thread. The followings are the two pipe FDs. */
415 int io_ready_pipe_read
;
416 int io_ready_pipe_write
;
417 /* Virtual memory stats */
418 unsigned long long vm_stats_used_pages
;
419 unsigned long long vm_stats_swapped_objects
;
420 unsigned long long vm_stats_swapouts
;
421 unsigned long long vm_stats_swapins
;
425 typedef void redisCommandProc(redisClient
*c
);
426 struct redisCommand
{
428 redisCommandProc
*proc
;
433 struct redisFunctionSym
{
435 unsigned long pointer
;
438 typedef struct _redisSortObject
{
446 typedef struct _redisSortOperation
{
449 } redisSortOperation
;
451 /* ZSETs use a specialized version of Skiplists */
453 typedef struct zskiplistNode
{
454 struct zskiplistNode
**forward
;
455 struct zskiplistNode
*backward
;
460 typedef struct zskiplist
{
461 struct zskiplistNode
*header
, *tail
;
462 unsigned long length
;
466 typedef struct zset
{
471 /* Our shared "common" objects */
473 struct sharedObjectsStruct
{
474 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
475 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
476 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
477 *outofrangeerr
, *plus
,
478 *select0
, *select1
, *select2
, *select3
, *select4
,
479 *select5
, *select6
, *select7
, *select8
, *select9
;
482 /* Global vars that are actally used as constants. The following double
483 * values are used for double on-disk serialization, and are initialized
484 * at runtime to avoid strange compiler optimizations. */
486 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
488 /* VM threaded I/O request message */
489 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
490 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
491 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
492 typedef struct iojon
{
493 int type
; /* Request type, REDIS_IOJOB_* */
494 redisDb
*db
;/* Redis database */
495 robj
*key
; /* This I/O request is about swapping this key */
496 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
497 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
498 off_t page
; /* Swap page where to read/write the object */
499 off_t pages
; /* Swap pages needed to safe object. PREPARE_SWAP return val */
500 int canceled
; /* True if this command was canceled by blocking side of VM */
501 pthread_t thread
; /* ID of the thread processing this entry */
504 /*================================ Prototypes =============================== */
506 static void freeStringObject(robj
*o
);
507 static void freeListObject(robj
*o
);
508 static void freeSetObject(robj
*o
);
509 static void decrRefCount(void *o
);
510 static robj
*createObject(int type
, void *ptr
);
511 static void freeClient(redisClient
*c
);
512 static int rdbLoad(char *filename
);
513 static void addReply(redisClient
*c
, robj
*obj
);
514 static void addReplySds(redisClient
*c
, sds s
);
515 static void incrRefCount(robj
*o
);
516 static int rdbSaveBackground(char *filename
);
517 static robj
*createStringObject(char *ptr
, size_t len
);
518 static robj
*dupStringObject(robj
*o
);
519 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
520 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
521 static int syncWithMaster(void);
522 static robj
*tryObjectSharing(robj
*o
);
523 static int tryObjectEncoding(robj
*o
);
524 static robj
*getDecodedObject(robj
*o
);
525 static int removeExpire(redisDb
*db
, robj
*key
);
526 static int expireIfNeeded(redisDb
*db
, robj
*key
);
527 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
528 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
529 static int deleteKey(redisDb
*db
, robj
*key
);
530 static time_t getExpire(redisDb
*db
, robj
*key
);
531 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
532 static void updateSlavesWaitingBgsave(int bgsaveerr
);
533 static void freeMemoryIfNeeded(void);
534 static int processCommand(redisClient
*c
);
535 static void setupSigSegvAction(void);
536 static void rdbRemoveTempFile(pid_t childpid
);
537 static void aofRemoveTempFile(pid_t childpid
);
538 static size_t stringObjectLen(robj
*o
);
539 static void processInputBuffer(redisClient
*c
);
540 static zskiplist
*zslCreate(void);
541 static void zslFree(zskiplist
*zsl
);
542 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
543 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
544 static void initClientMultiState(redisClient
*c
);
545 static void freeClientMultiState(redisClient
*c
);
546 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
547 static void unblockClient(redisClient
*c
);
548 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
549 static void vmInit(void);
550 static void vmMarkPagesFree(off_t page
, off_t count
);
551 static robj
*vmLoadObject(robj
*key
);
552 static robj
*vmPreviewObject(robj
*key
);
553 static int vmSwapOneObjectBlocking(void);
554 static int vmSwapOneObjectThreaded(void);
555 static int vmCanSwapOut(void);
556 static int tryFreeOneObjectFromFreelist(void);
557 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
558 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
559 static void vmCancelThreadedIOJob(robj
*o
);
560 static void lockThreadedIO(void);
561 static void unlockThreadedIO(void);
562 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
563 static void freeIOJob(iojob
*j
);
564 static void queueIOJob(iojob
*j
);
565 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
566 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
567 static void waitEmptyIOJobsQueue(void);
568 static void vmReopenSwapFile(void);
569 static int vmFreePage(off_t page
);
571 static void authCommand(redisClient
*c
);
572 static void pingCommand(redisClient
*c
);
573 static void echoCommand(redisClient
*c
);
574 static void setCommand(redisClient
*c
);
575 static void setnxCommand(redisClient
*c
);
576 static void getCommand(redisClient
*c
);
577 static void delCommand(redisClient
*c
);
578 static void existsCommand(redisClient
*c
);
579 static void incrCommand(redisClient
*c
);
580 static void decrCommand(redisClient
*c
);
581 static void incrbyCommand(redisClient
*c
);
582 static void decrbyCommand(redisClient
*c
);
583 static void selectCommand(redisClient
*c
);
584 static void randomkeyCommand(redisClient
*c
);
585 static void keysCommand(redisClient
*c
);
586 static void dbsizeCommand(redisClient
*c
);
587 static void lastsaveCommand(redisClient
*c
);
588 static void saveCommand(redisClient
*c
);
589 static void bgsaveCommand(redisClient
*c
);
590 static void bgrewriteaofCommand(redisClient
*c
);
591 static void shutdownCommand(redisClient
*c
);
592 static void moveCommand(redisClient
*c
);
593 static void renameCommand(redisClient
*c
);
594 static void renamenxCommand(redisClient
*c
);
595 static void lpushCommand(redisClient
*c
);
596 static void rpushCommand(redisClient
*c
);
597 static void lpopCommand(redisClient
*c
);
598 static void rpopCommand(redisClient
*c
);
599 static void llenCommand(redisClient
*c
);
600 static void lindexCommand(redisClient
*c
);
601 static void lrangeCommand(redisClient
*c
);
602 static void ltrimCommand(redisClient
*c
);
603 static void typeCommand(redisClient
*c
);
604 static void lsetCommand(redisClient
*c
);
605 static void saddCommand(redisClient
*c
);
606 static void sremCommand(redisClient
*c
);
607 static void smoveCommand(redisClient
*c
);
608 static void sismemberCommand(redisClient
*c
);
609 static void scardCommand(redisClient
*c
);
610 static void spopCommand(redisClient
*c
);
611 static void srandmemberCommand(redisClient
*c
);
612 static void sinterCommand(redisClient
*c
);
613 static void sinterstoreCommand(redisClient
*c
);
614 static void sunionCommand(redisClient
*c
);
615 static void sunionstoreCommand(redisClient
*c
);
616 static void sdiffCommand(redisClient
*c
);
617 static void sdiffstoreCommand(redisClient
*c
);
618 static void syncCommand(redisClient
*c
);
619 static void flushdbCommand(redisClient
*c
);
620 static void flushallCommand(redisClient
*c
);
621 static void sortCommand(redisClient
*c
);
622 static void lremCommand(redisClient
*c
);
623 static void rpoplpushcommand(redisClient
*c
);
624 static void infoCommand(redisClient
*c
);
625 static void mgetCommand(redisClient
*c
);
626 static void monitorCommand(redisClient
*c
);
627 static void expireCommand(redisClient
*c
);
628 static void expireatCommand(redisClient
*c
);
629 static void getsetCommand(redisClient
*c
);
630 static void ttlCommand(redisClient
*c
);
631 static void slaveofCommand(redisClient
*c
);
632 static void debugCommand(redisClient
*c
);
633 static void msetCommand(redisClient
*c
);
634 static void msetnxCommand(redisClient
*c
);
635 static void zaddCommand(redisClient
*c
);
636 static void zincrbyCommand(redisClient
*c
);
637 static void zrangeCommand(redisClient
*c
);
638 static void zrangebyscoreCommand(redisClient
*c
);
639 static void zrevrangeCommand(redisClient
*c
);
640 static void zcardCommand(redisClient
*c
);
641 static void zremCommand(redisClient
*c
);
642 static void zscoreCommand(redisClient
*c
);
643 static void zremrangebyscoreCommand(redisClient
*c
);
644 static void multiCommand(redisClient
*c
);
645 static void execCommand(redisClient
*c
);
646 static void blpopCommand(redisClient
*c
);
647 static void brpopCommand(redisClient
*c
);
649 /*================================= Globals ================================= */
652 static struct redisServer server
; /* server global state */
653 static struct redisCommand cmdTable
[] = {
654 {"get",getCommand
,2,REDIS_CMD_INLINE
},
655 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
656 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
657 {"del",delCommand
,-2,REDIS_CMD_INLINE
},
658 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
659 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
660 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
661 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
662 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
663 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
664 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
665 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
666 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
},
667 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
},
668 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
669 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
670 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
671 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
672 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
673 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
674 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
675 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
676 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
677 {"smove",smoveCommand
,4,REDIS_CMD_BULK
},
678 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
679 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
680 {"spop",spopCommand
,2,REDIS_CMD_INLINE
},
681 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
},
682 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
683 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
684 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
685 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
686 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
687 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
688 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
689 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
690 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
691 {"zrem",zremCommand
,3,REDIS_CMD_BULK
},
692 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
},
693 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
},
694 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
},
695 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
},
696 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
},
697 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
698 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
699 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
700 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
701 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
702 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
703 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
704 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
705 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
706 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
707 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
708 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
709 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
},
710 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
711 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
712 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
713 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
714 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
715 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
716 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
717 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
},
718 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
719 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
720 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
721 {"multi",multiCommand
,1,REDIS_CMD_INLINE
},
722 {"exec",execCommand
,1,REDIS_CMD_INLINE
},
723 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
724 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
725 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
726 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
727 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
728 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
729 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
},
730 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
},
731 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
},
735 /*============================ Utility functions ============================ */
737 /* Glob-style pattern matching. */
738 int stringmatchlen(const char *pattern
, int patternLen
,
739 const char *string
, int stringLen
, int nocase
)
744 while (pattern
[1] == '*') {
749 return 1; /* match */
751 if (stringmatchlen(pattern
+1, patternLen
-1,
752 string
, stringLen
, nocase
))
753 return 1; /* match */
757 return 0; /* no match */
761 return 0; /* no match */
771 not = pattern
[0] == '^';
778 if (pattern
[0] == '\\') {
781 if (pattern
[0] == string
[0])
783 } else if (pattern
[0] == ']') {
785 } else if (patternLen
== 0) {
789 } else if (pattern
[1] == '-' && patternLen
>= 3) {
790 int start
= pattern
[0];
791 int end
= pattern
[2];
799 start
= tolower(start
);
805 if (c
>= start
&& c
<= end
)
809 if (pattern
[0] == string
[0])
812 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
822 return 0; /* no match */
828 if (patternLen
>= 2) {
835 if (pattern
[0] != string
[0])
836 return 0; /* no match */
838 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
839 return 0; /* no match */
847 if (stringLen
== 0) {
848 while(*pattern
== '*') {
855 if (patternLen
== 0 && stringLen
== 0)
860 static void redisLog(int level
, const char *fmt
, ...) {
864 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
868 if (level
>= server
.verbosity
) {
874 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
875 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
876 vfprintf(fp
, fmt
, ap
);
882 if (server
.logfile
) fclose(fp
);
885 /*====================== Hash table type implementation ==================== */
887 /* This is an hash table type that uses the SDS dynamic strings libary as
888 * keys and radis objects as values (objects can hold SDS strings,
891 static void dictVanillaFree(void *privdata
, void *val
)
893 DICT_NOTUSED(privdata
);
897 static void dictListDestructor(void *privdata
, void *val
)
899 DICT_NOTUSED(privdata
);
900 listRelease((list
*)val
);
903 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
907 DICT_NOTUSED(privdata
);
909 l1
= sdslen((sds
)key1
);
910 l2
= sdslen((sds
)key2
);
911 if (l1
!= l2
) return 0;
912 return memcmp(key1
, key2
, l1
) == 0;
915 static void dictRedisObjectDestructor(void *privdata
, void *val
)
917 DICT_NOTUSED(privdata
);
919 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
923 static int dictObjKeyCompare(void *privdata
, const void *key1
,
926 const robj
*o1
= key1
, *o2
= key2
;
927 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
930 static unsigned int dictObjHash(const void *key
) {
932 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
935 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
938 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
941 o1
= getDecodedObject(o1
);
942 o2
= getDecodedObject(o2
);
943 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
949 static unsigned int dictEncObjHash(const void *key
) {
950 robj
*o
= (robj
*) key
;
952 o
= getDecodedObject(o
);
953 unsigned int hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
958 /* Sets type and expires */
959 static dictType setDictType
= {
960 dictEncObjHash
, /* hash function */
963 dictEncObjKeyCompare
, /* key compare */
964 dictRedisObjectDestructor
, /* key destructor */
965 NULL
/* val destructor */
968 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
969 static dictType zsetDictType
= {
970 dictEncObjHash
, /* hash function */
973 dictEncObjKeyCompare
, /* key compare */
974 dictRedisObjectDestructor
, /* key destructor */
975 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
979 static dictType hashDictType
= {
980 dictObjHash
, /* hash function */
983 dictObjKeyCompare
, /* key compare */
984 dictRedisObjectDestructor
, /* key destructor */
985 dictRedisObjectDestructor
/* val destructor */
989 static dictType keyptrDictType
= {
990 dictObjHash
, /* hash function */
993 dictObjKeyCompare
, /* key compare */
994 dictRedisObjectDestructor
, /* key destructor */
995 NULL
/* val destructor */
998 /* Keylist hash table type has unencoded redis objects as keys and
999 * lists as values. It's used for blocking operations (BLPOP) */
1000 static dictType keylistDictType
= {
1001 dictObjHash
, /* hash function */
1004 dictObjKeyCompare
, /* key compare */
1005 dictRedisObjectDestructor
, /* key destructor */
1006 dictListDestructor
/* val destructor */
1009 /* ========================= Random utility functions ======================= */
1011 /* Redis generally does not try to recover from out of memory conditions
1012 * when allocating objects or strings, it is not clear if it will be possible
1013 * to report this condition to the client since the networking layer itself
1014 * is based on heap allocation for send buffers, so we simply abort.
1015 * At least the code will be simpler to read... */
1016 static void oom(const char *msg
) {
1017 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1022 /* ====================== Redis server networking stuff ===================== */
1023 static void closeTimedoutClients(void) {
1026 time_t now
= time(NULL
);
1029 listRewind(server
.clients
,&li
);
1030 while ((ln
= listNext(&li
)) != NULL
) {
1031 c
= listNodeValue(ln
);
1032 if (server
.maxidletime
&&
1033 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1034 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1035 (now
- c
->lastinteraction
> server
.maxidletime
))
1037 redisLog(REDIS_VERBOSE
,"Closing idle client");
1039 } else if (c
->flags
& REDIS_BLOCKED
) {
1040 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1041 addReply(c
,shared
.nullmultibulk
);
1048 static int htNeedsResize(dict
*dict
) {
1049 long long size
, used
;
1051 size
= dictSlots(dict
);
1052 used
= dictSize(dict
);
1053 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1054 (used
*100/size
< REDIS_HT_MINFILL
));
1057 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1058 * we resize the hash table to save memory */
1059 static void tryResizeHashTables(void) {
1062 for (j
= 0; j
< server
.dbnum
; j
++) {
1063 if (htNeedsResize(server
.db
[j
].dict
)) {
1064 redisLog(REDIS_VERBOSE
,"The hash table %d is too sparse, resize it...",j
);
1065 dictResize(server
.db
[j
].dict
);
1066 redisLog(REDIS_VERBOSE
,"Hash table %d resized.",j
);
1068 if (htNeedsResize(server
.db
[j
].expires
))
1069 dictResize(server
.db
[j
].expires
);
1073 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1074 void backgroundSaveDoneHandler(int statloc
) {
1075 int exitcode
= WEXITSTATUS(statloc
);
1076 int bysignal
= WIFSIGNALED(statloc
);
1078 if (!bysignal
&& exitcode
== 0) {
1079 redisLog(REDIS_NOTICE
,
1080 "Background saving terminated with success");
1082 server
.lastsave
= time(NULL
);
1083 } else if (!bysignal
&& exitcode
!= 0) {
1084 redisLog(REDIS_WARNING
, "Background saving error");
1086 redisLog(REDIS_WARNING
,
1087 "Background saving terminated by signal");
1088 rdbRemoveTempFile(server
.bgsavechildpid
);
1090 server
.bgsavechildpid
= -1;
1091 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1092 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1093 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1096 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1098 void backgroundRewriteDoneHandler(int statloc
) {
1099 int exitcode
= WEXITSTATUS(statloc
);
1100 int bysignal
= WIFSIGNALED(statloc
);
1102 if (!bysignal
&& exitcode
== 0) {
1106 redisLog(REDIS_NOTICE
,
1107 "Background append only file rewriting terminated with success");
1108 /* Now it's time to flush the differences accumulated by the parent */
1109 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1110 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1112 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1115 /* Flush our data... */
1116 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1117 (signed) sdslen(server
.bgrewritebuf
)) {
1118 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
));
1122 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1123 /* Now our work is to rename the temp file into the stable file. And
1124 * switch the file descriptor used by the server for append only. */
1125 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1126 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1130 /* Mission completed... almost */
1131 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1132 if (server
.appendfd
!= -1) {
1133 /* If append only is actually enabled... */
1134 close(server
.appendfd
);
1135 server
.appendfd
= fd
;
1137 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1138 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1140 /* If append only is disabled we just generate a dump in this
1141 * format. Why not? */
1144 } else if (!bysignal
&& exitcode
!= 0) {
1145 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1147 redisLog(REDIS_WARNING
,
1148 "Background append only file rewriting terminated by signal");
1151 sdsfree(server
.bgrewritebuf
);
1152 server
.bgrewritebuf
= sdsempty();
1153 aofRemoveTempFile(server
.bgrewritechildpid
);
1154 server
.bgrewritechildpid
= -1;
1157 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1158 int j
, loops
= server
.cronloops
++;
1159 REDIS_NOTUSED(eventLoop
);
1161 REDIS_NOTUSED(clientData
);
1163 /* We take a cached value of the unix time in the global state because
1164 * with virtual memory and aging there is to store the current time
1165 * in objects at every object access, and accuracy is not needed.
1166 * To access a global var is faster than calling time(NULL) */
1167 server
.unixtime
= time(NULL
);
1169 /* Update the global state with the amount of used memory */
1170 server
.usedmemory
= zmalloc_used_memory();
1172 /* Show some info about non-empty databases */
1173 for (j
= 0; j
< server
.dbnum
; j
++) {
1174 long long size
, used
, vkeys
;
1176 size
= dictSlots(server
.db
[j
].dict
);
1177 used
= dictSize(server
.db
[j
].dict
);
1178 vkeys
= dictSize(server
.db
[j
].expires
);
1179 if (!(loops
% 5) && (used
|| vkeys
)) {
1180 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1181 /* dictPrintStats(server.dict); */
1185 /* We don't want to resize the hash tables while a bacground saving
1186 * is in progress: the saving child is created using fork() that is
1187 * implemented with a copy-on-write semantic in most modern systems, so
1188 * if we resize the HT while there is the saving child at work actually
1189 * a lot of memory movements in the parent will cause a lot of pages
1191 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1193 /* Show information about connected clients */
1195 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1196 listLength(server
.clients
)-listLength(server
.slaves
),
1197 listLength(server
.slaves
),
1199 dictSize(server
.sharingpool
));
1202 /* Close connections of timedout clients */
1203 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blockedclients
)
1204 closeTimedoutClients();
1206 /* Check if a background saving or AOF rewrite in progress terminated */
1207 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1211 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1212 if (pid
== server
.bgsavechildpid
) {
1213 backgroundSaveDoneHandler(statloc
);
1215 backgroundRewriteDoneHandler(statloc
);
1219 /* If there is not a background saving in progress check if
1220 * we have to save now */
1221 time_t now
= time(NULL
);
1222 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1223 struct saveparam
*sp
= server
.saveparams
+j
;
1225 if (server
.dirty
>= sp
->changes
&&
1226 now
-server
.lastsave
> sp
->seconds
) {
1227 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1228 sp
->changes
, sp
->seconds
);
1229 rdbSaveBackground(server
.dbfilename
);
1235 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1236 * will use few CPU cycles if there are few expiring keys, otherwise
1237 * it will get more aggressive to avoid that too much memory is used by
1238 * keys that can be removed from the keyspace. */
1239 for (j
= 0; j
< server
.dbnum
; j
++) {
1241 redisDb
*db
= server
.db
+j
;
1243 /* Continue to expire if at the end of the cycle more than 25%
1244 * of the keys were expired. */
1246 long num
= dictSize(db
->expires
);
1247 time_t now
= time(NULL
);
1250 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1251 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1256 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1257 t
= (time_t) dictGetEntryVal(de
);
1259 deleteKey(db
,dictGetEntryKey(de
));
1263 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1266 /* Swap a few keys on disk if we are over the memory limit and VM
1267 * is enbled. Try to free objects from the free list first. */
1268 if (vmCanSwapOut()) {
1269 while (server
.vm_enabled
&& zmalloc_used_memory() >
1270 server
.vm_max_memory
)
1274 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1275 retval
= (server
.vm_max_threads
== 0) ?
1276 vmSwapOneObjectBlocking() :
1277 vmSwapOneObjectThreaded();
1278 if (retval
== REDIS_ERR
&& (loops
% 30) == 0 &&
1279 zmalloc_used_memory() >
1280 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1282 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1284 /* Note that when using threade I/O we free just one object,
1285 * because anyway when the I/O thread in charge to swap this
1286 * object out will finish, the handler of completed jobs
1287 * will try to swap more objects if we are still out of memory. */
1288 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1292 /* Check if we should connect to a MASTER */
1293 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1294 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1295 if (syncWithMaster() == REDIS_OK
) {
1296 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1302 static void createSharedObjects(void) {
1303 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1304 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1305 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1306 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1307 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1308 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1309 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1310 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1311 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1312 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1313 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1314 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1315 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1316 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1317 "-ERR no such key\r\n"));
1318 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1319 "-ERR syntax error\r\n"));
1320 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1321 "-ERR source and destination objects are the same\r\n"));
1322 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1323 "-ERR index out of range\r\n"));
1324 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1325 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1326 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1327 shared
.select0
= createStringObject("select 0\r\n",10);
1328 shared
.select1
= createStringObject("select 1\r\n",10);
1329 shared
.select2
= createStringObject("select 2\r\n",10);
1330 shared
.select3
= createStringObject("select 3\r\n",10);
1331 shared
.select4
= createStringObject("select 4\r\n",10);
1332 shared
.select5
= createStringObject("select 5\r\n",10);
1333 shared
.select6
= createStringObject("select 6\r\n",10);
1334 shared
.select7
= createStringObject("select 7\r\n",10);
1335 shared
.select8
= createStringObject("select 8\r\n",10);
1336 shared
.select9
= createStringObject("select 9\r\n",10);
1339 static void appendServerSaveParams(time_t seconds
, int changes
) {
1340 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1341 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1342 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1343 server
.saveparamslen
++;
1346 static void resetServerSaveParams() {
1347 zfree(server
.saveparams
);
1348 server
.saveparams
= NULL
;
1349 server
.saveparamslen
= 0;
1352 static void initServerConfig() {
1353 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1354 server
.port
= REDIS_SERVERPORT
;
1355 server
.verbosity
= REDIS_VERBOSE
;
1356 server
.maxidletime
= REDIS_MAXIDLETIME
;
1357 server
.saveparams
= NULL
;
1358 server
.logfile
= NULL
; /* NULL = log on standard output */
1359 server
.bindaddr
= NULL
;
1360 server
.glueoutputbuf
= 1;
1361 server
.daemonize
= 0;
1362 server
.appendonly
= 0;
1363 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1364 server
.lastfsync
= time(NULL
);
1365 server
.appendfd
= -1;
1366 server
.appendseldb
= -1; /* Make sure the first time will not match */
1367 server
.pidfile
= "/var/run/redis.pid";
1368 server
.dbfilename
= "dump.rdb";
1369 server
.appendfilename
= "appendonly.aof";
1370 server
.requirepass
= NULL
;
1371 server
.shareobjects
= 0;
1372 server
.rdbcompression
= 1;
1373 server
.sharingpoolsize
= 1024;
1374 server
.maxclients
= 0;
1375 server
.blockedclients
= 0;
1376 server
.maxmemory
= 0;
1377 server
.vm_enabled
= 0;
1378 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
1379 server
.vm_page_size
= 256; /* 256 bytes per page */
1380 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1381 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1382 server
.vm_max_threads
= 4;
1384 resetServerSaveParams();
1386 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1387 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1388 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1389 /* Replication related */
1391 server
.masterauth
= NULL
;
1392 server
.masterhost
= NULL
;
1393 server
.masterport
= 6379;
1394 server
.master
= NULL
;
1395 server
.replstate
= REDIS_REPL_NONE
;
1397 /* Double constants initialization */
1399 R_PosInf
= 1.0/R_Zero
;
1400 R_NegInf
= -1.0/R_Zero
;
1401 R_Nan
= R_Zero
/R_Zero
;
1404 static void initServer() {
1407 signal(SIGHUP
, SIG_IGN
);
1408 signal(SIGPIPE
, SIG_IGN
);
1409 setupSigSegvAction();
1411 server
.devnull
= fopen("/dev/null","w");
1412 if (server
.devnull
== NULL
) {
1413 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1416 server
.clients
= listCreate();
1417 server
.slaves
= listCreate();
1418 server
.monitors
= listCreate();
1419 server
.objfreelist
= listCreate();
1420 createSharedObjects();
1421 server
.el
= aeCreateEventLoop();
1422 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1423 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1424 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1425 if (server
.fd
== -1) {
1426 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1429 for (j
= 0; j
< server
.dbnum
; j
++) {
1430 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
1431 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1432 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1433 server
.db
[j
].id
= j
;
1435 server
.cronloops
= 0;
1436 server
.bgsavechildpid
= -1;
1437 server
.bgrewritechildpid
= -1;
1438 server
.bgrewritebuf
= sdsempty();
1439 server
.lastsave
= time(NULL
);
1441 server
.usedmemory
= 0;
1442 server
.stat_numcommands
= 0;
1443 server
.stat_numconnections
= 0;
1444 server
.stat_starttime
= time(NULL
);
1445 server
.unixtime
= time(NULL
);
1446 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1447 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1448 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1450 if (server
.appendonly
) {
1451 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1452 if (server
.appendfd
== -1) {
1453 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1459 if (server
.vm_enabled
) vmInit();
1462 /* Empty the whole database */
1463 static long long emptyDb() {
1465 long long removed
= 0;
1467 for (j
= 0; j
< server
.dbnum
; j
++) {
1468 removed
+= dictSize(server
.db
[j
].dict
);
1469 dictEmpty(server
.db
[j
].dict
);
1470 dictEmpty(server
.db
[j
].expires
);
1475 static int yesnotoi(char *s
) {
1476 if (!strcasecmp(s
,"yes")) return 1;
1477 else if (!strcasecmp(s
,"no")) return 0;
1481 /* I agree, this is a very rudimental way to load a configuration...
1482 will improve later if the config gets more complex */
1483 static void loadServerConfig(char *filename
) {
1485 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1489 if (filename
[0] == '-' && filename
[1] == '\0')
1492 if ((fp
= fopen(filename
,"r")) == NULL
) {
1493 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1498 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1504 line
= sdstrim(line
," \t\r\n");
1506 /* Skip comments and blank lines*/
1507 if (line
[0] == '#' || line
[0] == '\0') {
1512 /* Split into arguments */
1513 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1514 sdstolower(argv
[0]);
1516 /* Execute config directives */
1517 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1518 server
.maxidletime
= atoi(argv
[1]);
1519 if (server
.maxidletime
< 0) {
1520 err
= "Invalid timeout value"; goto loaderr
;
1522 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1523 server
.port
= atoi(argv
[1]);
1524 if (server
.port
< 1 || server
.port
> 65535) {
1525 err
= "Invalid port"; goto loaderr
;
1527 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1528 server
.bindaddr
= zstrdup(argv
[1]);
1529 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1530 int seconds
= atoi(argv
[1]);
1531 int changes
= atoi(argv
[2]);
1532 if (seconds
< 1 || changes
< 0) {
1533 err
= "Invalid save parameters"; goto loaderr
;
1535 appendServerSaveParams(seconds
,changes
);
1536 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1537 if (chdir(argv
[1]) == -1) {
1538 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1539 argv
[1], strerror(errno
));
1542 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1543 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1544 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1545 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1546 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1548 err
= "Invalid log level. Must be one of debug, notice, warning";
1551 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1554 server
.logfile
= zstrdup(argv
[1]);
1555 if (!strcasecmp(server
.logfile
,"stdout")) {
1556 zfree(server
.logfile
);
1557 server
.logfile
= NULL
;
1559 if (server
.logfile
) {
1560 /* Test if we are able to open the file. The server will not
1561 * be able to abort just for this problem later... */
1562 logfp
= fopen(server
.logfile
,"a");
1563 if (logfp
== NULL
) {
1564 err
= sdscatprintf(sdsempty(),
1565 "Can't open the log file: %s", strerror(errno
));
1570 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1571 server
.dbnum
= atoi(argv
[1]);
1572 if (server
.dbnum
< 1) {
1573 err
= "Invalid number of databases"; goto loaderr
;
1575 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1576 server
.maxclients
= atoi(argv
[1]);
1577 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1578 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1579 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1580 server
.masterhost
= sdsnew(argv
[1]);
1581 server
.masterport
= atoi(argv
[2]);
1582 server
.replstate
= REDIS_REPL_CONNECT
;
1583 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1584 server
.masterauth
= zstrdup(argv
[1]);
1585 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1586 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1587 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1589 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1590 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1591 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1593 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1594 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1595 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1597 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1598 server
.sharingpoolsize
= atoi(argv
[1]);
1599 if (server
.sharingpoolsize
< 1) {
1600 err
= "invalid object sharing pool size"; goto loaderr
;
1602 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1603 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1604 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1606 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1607 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1608 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1610 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1611 if (!strcasecmp(argv
[1],"no")) {
1612 server
.appendfsync
= APPENDFSYNC_NO
;
1613 } else if (!strcasecmp(argv
[1],"always")) {
1614 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1615 } else if (!strcasecmp(argv
[1],"everysec")) {
1616 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1618 err
= "argument must be 'no', 'always' or 'everysec'";
1621 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1622 server
.requirepass
= zstrdup(argv
[1]);
1623 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1624 server
.pidfile
= zstrdup(argv
[1]);
1625 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1626 server
.dbfilename
= zstrdup(argv
[1]);
1627 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1628 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1629 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1631 } else if (!strcasecmp(argv
[0],"vm-swap-file") && argc
== 2) {
1632 zfree(server
.vm_swap_file
);
1633 server
.vm_swap_file
= zstrdup(argv
[1]);
1634 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1635 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1636 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1637 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1638 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1639 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1640 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1641 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1643 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1645 for (j
= 0; j
< argc
; j
++)
1650 if (fp
!= stdin
) fclose(fp
);
1654 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1655 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1656 fprintf(stderr
, ">>> '%s'\n", line
);
1657 fprintf(stderr
, "%s\n", err
);
1661 static void freeClientArgv(redisClient
*c
) {
1664 for (j
= 0; j
< c
->argc
; j
++)
1665 decrRefCount(c
->argv
[j
]);
1666 for (j
= 0; j
< c
->mbargc
; j
++)
1667 decrRefCount(c
->mbargv
[j
]);
1672 static void freeClient(redisClient
*c
) {
1675 /* Note that if the client we are freeing is blocked into a blocking
1676 * call, we have to set querybuf to NULL *before* to call unblockClient()
1677 * to avoid processInputBuffer() will get called. Also it is important
1678 * to remove the file events after this, because this call adds
1679 * the READABLE event. */
1680 sdsfree(c
->querybuf
);
1682 if (c
->flags
& REDIS_BLOCKED
)
1685 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1686 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1687 listRelease(c
->reply
);
1690 /* Remove from the list of clients */
1691 ln
= listSearchKey(server
.clients
,c
);
1692 redisAssert(ln
!= NULL
);
1693 listDelNode(server
.clients
,ln
);
1694 /* Remove from the list of clients waiting for VM operations */
1695 if (server
.vm_enabled
&& listLength(c
->io_keys
)) {
1696 ln
= listSearchKey(server
.io_clients
,c
);
1697 if (ln
) listDelNode(server
.io_clients
,ln
);
1698 listRelease(c
->io_keys
);
1700 listRelease(c
->io_keys
);
1702 if (c
->flags
& REDIS_SLAVE
) {
1703 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1705 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1706 ln
= listSearchKey(l
,c
);
1707 redisAssert(ln
!= NULL
);
1710 if (c
->flags
& REDIS_MASTER
) {
1711 server
.master
= NULL
;
1712 server
.replstate
= REDIS_REPL_CONNECT
;
1716 freeClientMultiState(c
);
1720 #define GLUEREPLY_UP_TO (1024)
1721 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1723 char buf
[GLUEREPLY_UP_TO
];
1728 listRewind(c
->reply
,&li
);
1729 while((ln
= listNext(&li
))) {
1733 objlen
= sdslen(o
->ptr
);
1734 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1735 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1737 listDelNode(c
->reply
,ln
);
1739 if (copylen
== 0) return;
1743 /* Now the output buffer is empty, add the new single element */
1744 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1745 listAddNodeHead(c
->reply
,o
);
1748 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1749 redisClient
*c
= privdata
;
1750 int nwritten
= 0, totwritten
= 0, objlen
;
1753 REDIS_NOTUSED(mask
);
1755 /* Use writev() if we have enough buffers to send */
1756 if (!server
.glueoutputbuf
&&
1757 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1758 !(c
->flags
& REDIS_MASTER
))
1760 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1764 while(listLength(c
->reply
)) {
1765 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1766 glueReplyBuffersIfNeeded(c
);
1768 o
= listNodeValue(listFirst(c
->reply
));
1769 objlen
= sdslen(o
->ptr
);
1772 listDelNode(c
->reply
,listFirst(c
->reply
));
1776 if (c
->flags
& REDIS_MASTER
) {
1777 /* Don't reply to a master */
1778 nwritten
= objlen
- c
->sentlen
;
1780 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1781 if (nwritten
<= 0) break;
1783 c
->sentlen
+= nwritten
;
1784 totwritten
+= nwritten
;
1785 /* If we fully sent the object on head go to the next one */
1786 if (c
->sentlen
== objlen
) {
1787 listDelNode(c
->reply
,listFirst(c
->reply
));
1790 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1791 * bytes, in a single threaded server it's a good idea to serve
1792 * other clients as well, even if a very large request comes from
1793 * super fast link that is always able to accept data (in real world
1794 * scenario think about 'KEYS *' against the loopback interfae) */
1795 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1797 if (nwritten
== -1) {
1798 if (errno
== EAGAIN
) {
1801 redisLog(REDIS_VERBOSE
,
1802 "Error writing to client: %s", strerror(errno
));
1807 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1808 if (listLength(c
->reply
) == 0) {
1810 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1814 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1816 redisClient
*c
= privdata
;
1817 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1819 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1820 int offset
, ion
= 0;
1822 REDIS_NOTUSED(mask
);
1825 while (listLength(c
->reply
)) {
1826 offset
= c
->sentlen
;
1830 /* fill-in the iov[] array */
1831 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1832 o
= listNodeValue(node
);
1833 objlen
= sdslen(o
->ptr
);
1835 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1838 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1839 break; /* no more iovecs */
1841 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1842 iov
[ion
].iov_len
= objlen
- offset
;
1843 willwrite
+= objlen
- offset
;
1844 offset
= 0; /* just for the first item */
1851 /* write all collected blocks at once */
1852 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1853 if (errno
!= EAGAIN
) {
1854 redisLog(REDIS_VERBOSE
,
1855 "Error writing to client: %s", strerror(errno
));
1862 totwritten
+= nwritten
;
1863 offset
= c
->sentlen
;
1865 /* remove written robjs from c->reply */
1866 while (nwritten
&& listLength(c
->reply
)) {
1867 o
= listNodeValue(listFirst(c
->reply
));
1868 objlen
= sdslen(o
->ptr
);
1870 if(nwritten
>= objlen
- offset
) {
1871 listDelNode(c
->reply
, listFirst(c
->reply
));
1872 nwritten
-= objlen
- offset
;
1876 c
->sentlen
+= nwritten
;
1884 c
->lastinteraction
= time(NULL
);
1886 if (listLength(c
->reply
) == 0) {
1888 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1892 static struct redisCommand
*lookupCommand(char *name
) {
1894 while(cmdTable
[j
].name
!= NULL
) {
1895 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1901 /* resetClient prepare the client to process the next command */
1902 static void resetClient(redisClient
*c
) {
1908 /* Call() is the core of Redis execution of a command */
1909 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
1912 dirty
= server
.dirty
;
1914 if (server
.appendonly
&& server
.dirty
-dirty
)
1915 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1916 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
1917 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1918 if (listLength(server
.monitors
))
1919 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1920 server
.stat_numcommands
++;
1923 /* If this function gets called we already read a whole
1924 * command, argments are in the client argv/argc fields.
1925 * processCommand() execute the command or prepare the
1926 * server for a bulk read from the client.
1928 * If 1 is returned the client is still alive and valid and
1929 * and other operations can be performed by the caller. Otherwise
1930 * if 0 is returned the client was destroied (i.e. after QUIT). */
1931 static int processCommand(redisClient
*c
) {
1932 struct redisCommand
*cmd
;
1934 /* Free some memory if needed (maxmemory setting) */
1935 if (server
.maxmemory
) freeMemoryIfNeeded();
1937 /* Handle the multi bulk command type. This is an alternative protocol
1938 * supported by Redis in order to receive commands that are composed of
1939 * multiple binary-safe "bulk" arguments. The latency of processing is
1940 * a bit higher but this allows things like multi-sets, so if this
1941 * protocol is used only for MSET and similar commands this is a big win. */
1942 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
1943 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1944 if (c
->multibulk
<= 0) {
1948 decrRefCount(c
->argv
[c
->argc
-1]);
1952 } else if (c
->multibulk
) {
1953 if (c
->bulklen
== -1) {
1954 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
1955 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
1959 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1960 decrRefCount(c
->argv
[0]);
1961 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1963 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1968 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1972 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
1973 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
1977 if (c
->multibulk
== 0) {
1981 /* Here we need to swap the multi-bulk argc/argv with the
1982 * normal argc/argv of the client structure. */
1984 c
->argv
= c
->mbargv
;
1985 c
->mbargv
= auxargv
;
1988 c
->argc
= c
->mbargc
;
1989 c
->mbargc
= auxargc
;
1991 /* We need to set bulklen to something different than -1
1992 * in order for the code below to process the command without
1993 * to try to read the last argument of a bulk command as
1994 * a special argument. */
1996 /* continue below and process the command */
2003 /* -- end of multi bulk commands processing -- */
2005 /* The QUIT command is handled as a special case. Normal command
2006 * procs are unable to close the client connection safely */
2007 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2011 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2014 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2015 (char*)c
->argv
[0]->ptr
));
2018 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2019 (c
->argc
< -cmd
->arity
)) {
2021 sdscatprintf(sdsempty(),
2022 "-ERR wrong number of arguments for '%s' command\r\n",
2026 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
2027 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2030 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2031 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2033 decrRefCount(c
->argv
[c
->argc
-1]);
2034 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2036 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2041 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2042 /* It is possible that the bulk read is already in the
2043 * buffer. Check this condition and handle it accordingly.
2044 * This is just a fast path, alternative to call processInputBuffer().
2045 * It's a good idea since the code is small and this condition
2046 * happens most of the times. */
2047 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2048 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2050 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2055 /* Let's try to share objects on the command arguments vector */
2056 if (server
.shareobjects
) {
2058 for(j
= 1; j
< c
->argc
; j
++)
2059 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
2061 /* Let's try to encode the bulk object to save space. */
2062 if (cmd
->flags
& REDIS_CMD_BULK
)
2063 tryObjectEncoding(c
->argv
[c
->argc
-1]);
2065 /* Check if the user is authenticated */
2066 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2067 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2072 /* Exec the command */
2073 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
) {
2074 queueMultiCommand(c
,cmd
);
2075 addReply(c
,shared
.queued
);
2080 /* Prepare the client for the next command */
2081 if (c
->flags
& REDIS_CLOSE
) {
2089 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
2094 /* (args*2)+1 is enough room for args, spaces, newlines */
2095 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
2097 if (argc
<= REDIS_STATIC_ARGS
) {
2100 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
2103 for (j
= 0; j
< argc
; j
++) {
2104 if (j
!= 0) outv
[outc
++] = shared
.space
;
2105 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
2108 lenobj
= createObject(REDIS_STRING
,
2109 sdscatprintf(sdsempty(),"%lu\r\n",
2110 (unsigned long) stringObjectLen(argv
[j
])));
2111 lenobj
->refcount
= 0;
2112 outv
[outc
++] = lenobj
;
2114 outv
[outc
++] = argv
[j
];
2116 outv
[outc
++] = shared
.crlf
;
2118 /* Increment all the refcounts at start and decrement at end in order to
2119 * be sure to free objects if there is no slave in a replication state
2120 * able to be feed with commands */
2121 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2122 listRewind(slaves
,&li
);
2123 while((ln
= listNext(&li
))) {
2124 redisClient
*slave
= ln
->value
;
2126 /* Don't feed slaves that are still waiting for BGSAVE to start */
2127 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2129 /* Feed all the other slaves, MONITORs and so on */
2130 if (slave
->slaveseldb
!= dictid
) {
2134 case 0: selectcmd
= shared
.select0
; break;
2135 case 1: selectcmd
= shared
.select1
; break;
2136 case 2: selectcmd
= shared
.select2
; break;
2137 case 3: selectcmd
= shared
.select3
; break;
2138 case 4: selectcmd
= shared
.select4
; break;
2139 case 5: selectcmd
= shared
.select5
; break;
2140 case 6: selectcmd
= shared
.select6
; break;
2141 case 7: selectcmd
= shared
.select7
; break;
2142 case 8: selectcmd
= shared
.select8
; break;
2143 case 9: selectcmd
= shared
.select9
; break;
2145 selectcmd
= createObject(REDIS_STRING
,
2146 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2147 selectcmd
->refcount
= 0;
2150 addReply(slave
,selectcmd
);
2151 slave
->slaveseldb
= dictid
;
2153 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2155 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2156 if (outv
!= static_outv
) zfree(outv
);
2159 static void processInputBuffer(redisClient
*c
) {
2161 /* Before to process the input buffer, make sure the client is not
2162 * waitig for a blocking operation such as BLPOP. Note that the first
2163 * iteration the client is never blocked, otherwise the processInputBuffer
2164 * would not be called at all, but after the execution of the first commands
2165 * in the input buffer the client may be blocked, and the "goto again"
2166 * will try to reiterate. The following line will make it return asap. */
2167 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2168 if (c
->bulklen
== -1) {
2169 /* Read the first line of the query */
2170 char *p
= strchr(c
->querybuf
,'\n');
2177 query
= c
->querybuf
;
2178 c
->querybuf
= sdsempty();
2179 querylen
= 1+(p
-(query
));
2180 if (sdslen(query
) > querylen
) {
2181 /* leave data after the first line of the query in the buffer */
2182 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2184 *p
= '\0'; /* remove "\n" */
2185 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2186 sdsupdatelen(query
);
2188 /* Now we can split the query in arguments */
2189 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2192 if (c
->argv
) zfree(c
->argv
);
2193 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2195 for (j
= 0; j
< argc
; j
++) {
2196 if (sdslen(argv
[j
])) {
2197 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2205 /* Execute the command. If the client is still valid
2206 * after processCommand() return and there is something
2207 * on the query buffer try to process the next command. */
2208 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2210 /* Nothing to process, argc == 0. Just process the query
2211 * buffer if it's not empty or return to the caller */
2212 if (sdslen(c
->querybuf
)) goto again
;
2215 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2216 redisLog(REDIS_VERBOSE
, "Client protocol error");
2221 /* Bulk read handling. Note that if we are at this point
2222 the client already sent a command terminated with a newline,
2223 we are reading the bulk data that is actually the last
2224 argument of the command. */
2225 int qbl
= sdslen(c
->querybuf
);
2227 if (c
->bulklen
<= qbl
) {
2228 /* Copy everything but the final CRLF as final argument */
2229 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2231 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2232 /* Process the command. If the client is still valid after
2233 * the processing and there is more data in the buffer
2234 * try to parse it. */
2235 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2241 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2242 redisClient
*c
= (redisClient
*) privdata
;
2243 char buf
[REDIS_IOBUF_LEN
];
2246 REDIS_NOTUSED(mask
);
2248 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2250 if (errno
== EAGAIN
) {
2253 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2257 } else if (nread
== 0) {
2258 redisLog(REDIS_VERBOSE
, "Client closed connection");
2263 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2264 c
->lastinteraction
= time(NULL
);
2268 processInputBuffer(c
);
2271 static int selectDb(redisClient
*c
, int id
) {
2272 if (id
< 0 || id
>= server
.dbnum
)
2274 c
->db
= &server
.db
[id
];
2278 static void *dupClientReplyValue(void *o
) {
2279 incrRefCount((robj
*)o
);
2283 static redisClient
*createClient(int fd
) {
2284 redisClient
*c
= zmalloc(sizeof(*c
));
2286 anetNonBlock(NULL
,fd
);
2287 anetTcpNoDelay(NULL
,fd
);
2288 if (!c
) return NULL
;
2291 c
->querybuf
= sdsempty();
2300 c
->lastinteraction
= time(NULL
);
2301 c
->authenticated
= 0;
2302 c
->replstate
= REDIS_REPL_NONE
;
2303 c
->reply
= listCreate();
2304 listSetFreeMethod(c
->reply
,decrRefCount
);
2305 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2306 c
->blockingkeys
= NULL
;
2307 c
->blockingkeysnum
= 0;
2308 c
->io_keys
= listCreate();
2309 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2310 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2311 readQueryFromClient
, c
) == AE_ERR
) {
2315 listAddNodeTail(server
.clients
,c
);
2316 initClientMultiState(c
);
2320 static void addReply(redisClient
*c
, robj
*obj
) {
2321 if (listLength(c
->reply
) == 0 &&
2322 (c
->replstate
== REDIS_REPL_NONE
||
2323 c
->replstate
== REDIS_REPL_ONLINE
) &&
2324 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2325 sendReplyToClient
, c
) == AE_ERR
) return;
2327 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2328 obj
= dupStringObject(obj
);
2329 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2331 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2334 static void addReplySds(redisClient
*c
, sds s
) {
2335 robj
*o
= createObject(REDIS_STRING
,s
);
2340 static void addReplyDouble(redisClient
*c
, double d
) {
2343 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2344 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2345 (unsigned long) strlen(buf
),buf
));
2348 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2351 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2352 len
= sdslen(obj
->ptr
);
2354 long n
= (long)obj
->ptr
;
2356 /* Compute how many bytes will take this integer as a radix 10 string */
2362 while((n
= n
/10) != 0) {
2366 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2369 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2374 REDIS_NOTUSED(mask
);
2375 REDIS_NOTUSED(privdata
);
2377 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2378 if (cfd
== AE_ERR
) {
2379 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2382 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2383 if ((c
= createClient(cfd
)) == NULL
) {
2384 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2385 close(cfd
); /* May be already closed, just ingore errors */
2388 /* If maxclient directive is set and this is one client more... close the
2389 * connection. Note that we create the client instead to check before
2390 * for this condition, since now the socket is already set in nonblocking
2391 * mode and we can send an error for free using the Kernel I/O */
2392 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2393 char *err
= "-ERR max number of clients reached\r\n";
2395 /* That's a best effort error message, don't check write errors */
2396 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2397 /* Nothing to do, Just to avoid the warning... */
2402 server
.stat_numconnections
++;
2405 /* ======================= Redis objects implementation ===================== */
2407 static robj
*createObject(int type
, void *ptr
) {
2410 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2411 if (listLength(server
.objfreelist
)) {
2412 listNode
*head
= listFirst(server
.objfreelist
);
2413 o
= listNodeValue(head
);
2414 listDelNode(server
.objfreelist
,head
);
2415 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2417 if (server
.vm_enabled
) {
2418 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2419 o
= zmalloc(sizeof(*o
));
2421 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2425 o
->encoding
= REDIS_ENCODING_RAW
;
2428 if (server
.vm_enabled
) {
2429 /* Note that this code may run in the context of an I/O thread
2430 * and accessing to server.unixtime in theory is an error
2431 * (no locks). But in practice this is safe, and even if we read
2432 * garbage Redis will not fail, as it's just a statistical info */
2433 o
->vm
.atime
= server
.unixtime
;
2434 o
->storage
= REDIS_VM_MEMORY
;
2439 static robj
*createStringObject(char *ptr
, size_t len
) {
2440 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2443 static robj
*dupStringObject(robj
*o
) {
2444 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2445 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2448 static robj
*createListObject(void) {
2449 list
*l
= listCreate();
2451 listSetFreeMethod(l
,decrRefCount
);
2452 return createObject(REDIS_LIST
,l
);
2455 static robj
*createSetObject(void) {
2456 dict
*d
= dictCreate(&setDictType
,NULL
);
2457 return createObject(REDIS_SET
,d
);
2460 static robj
*createZsetObject(void) {
2461 zset
*zs
= zmalloc(sizeof(*zs
));
2463 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2464 zs
->zsl
= zslCreate();
2465 return createObject(REDIS_ZSET
,zs
);
2468 static void freeStringObject(robj
*o
) {
2469 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2474 static void freeListObject(robj
*o
) {
2475 listRelease((list
*) o
->ptr
);
2478 static void freeSetObject(robj
*o
) {
2479 dictRelease((dict
*) o
->ptr
);
2482 static void freeZsetObject(robj
*o
) {
2485 dictRelease(zs
->dict
);
2490 static void freeHashObject(robj
*o
) {
2491 dictRelease((dict
*) o
->ptr
);
2494 static void incrRefCount(robj
*o
) {
2495 redisAssert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2499 static void decrRefCount(void *obj
) {
2502 /* Object is a key of a swapped out value, or in the process of being
2504 if (server
.vm_enabled
&&
2505 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
2507 if (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
) {
2508 redisAssert(o
->refcount
== 1);
2510 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
2511 redisAssert(o
->type
== REDIS_STRING
);
2512 freeStringObject(o
);
2513 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2514 pthread_mutex_lock(&server
.obj_freelist_mutex
);
2515 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2516 !listAddNodeHead(server
.objfreelist
,o
))
2518 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2519 server
.vm_stats_swapped_objects
--;
2522 /* Object is in memory, or in the process of being swapped out. */
2523 if (--(o
->refcount
) == 0) {
2524 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
2525 vmCancelThreadedIOJob(obj
);
2527 case REDIS_STRING
: freeStringObject(o
); break;
2528 case REDIS_LIST
: freeListObject(o
); break;
2529 case REDIS_SET
: freeSetObject(o
); break;
2530 case REDIS_ZSET
: freeZsetObject(o
); break;
2531 case REDIS_HASH
: freeHashObject(o
); break;
2532 default: redisAssert(0 != 0); break;
2534 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2535 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2536 !listAddNodeHead(server
.objfreelist
,o
))
2538 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2542 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2543 dictEntry
*de
= dictFind(db
->dict
,key
);
2545 robj
*key
= dictGetEntryKey(de
);
2546 robj
*val
= dictGetEntryVal(de
);
2548 if (server
.vm_enabled
) {
2549 if (key
->storage
== REDIS_VM_MEMORY
||
2550 key
->storage
== REDIS_VM_SWAPPING
)
2552 /* If we were swapping the object out, stop it, this key
2554 if (key
->storage
== REDIS_VM_SWAPPING
)
2555 vmCancelThreadedIOJob(key
);
2556 /* Update the access time of the key for the aging algorithm. */
2557 key
->vm
.atime
= server
.unixtime
;
2559 /* Our value was swapped on disk. Bring it at home. */
2560 redisAssert(val
== NULL
);
2561 val
= vmLoadObject(key
);
2562 dictGetEntryVal(de
) = val
;
2571 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2572 expireIfNeeded(db
,key
);
2573 return lookupKey(db
,key
);
2576 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2577 deleteIfVolatile(db
,key
);
2578 return lookupKey(db
,key
);
2581 static int deleteKey(redisDb
*db
, robj
*key
) {
2584 /* We need to protect key from destruction: after the first dictDelete()
2585 * it may happen that 'key' is no longer valid if we don't increment
2586 * it's count. This may happen when we get the object reference directly
2587 * from the hash table with dictRandomKey() or dict iterators */
2589 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2590 retval
= dictDelete(db
->dict
,key
);
2593 return retval
== DICT_OK
;
2596 /* Try to share an object against the shared objects pool */
2597 static robj
*tryObjectSharing(robj
*o
) {
2598 struct dictEntry
*de
;
2601 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2603 redisAssert(o
->type
== REDIS_STRING
);
2604 de
= dictFind(server
.sharingpool
,o
);
2606 robj
*shared
= dictGetEntryKey(de
);
2608 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2609 dictGetEntryVal(de
) = (void*) c
;
2610 incrRefCount(shared
);
2614 /* Here we are using a stream algorihtm: Every time an object is
2615 * shared we increment its count, everytime there is a miss we
2616 * recrement the counter of a random object. If this object reaches
2617 * zero we remove the object and put the current object instead. */
2618 if (dictSize(server
.sharingpool
) >=
2619 server
.sharingpoolsize
) {
2620 de
= dictGetRandomKey(server
.sharingpool
);
2621 redisAssert(de
!= NULL
);
2622 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2623 dictGetEntryVal(de
) = (void*) c
;
2625 dictDelete(server
.sharingpool
,de
->key
);
2628 c
= 0; /* If the pool is empty we want to add this object */
2633 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2634 redisAssert(retval
== DICT_OK
);
2641 /* Check if the nul-terminated string 's' can be represented by a long
2642 * (that is, is a number that fits into long without any other space or
2643 * character before or after the digits).
2645 * If so, the function returns REDIS_OK and *longval is set to the value
2646 * of the number. Otherwise REDIS_ERR is returned */
2647 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2648 char buf
[32], *endptr
;
2652 value
= strtol(s
, &endptr
, 10);
2653 if (endptr
[0] != '\0') return REDIS_ERR
;
2654 slen
= snprintf(buf
,32,"%ld",value
);
2656 /* If the number converted back into a string is not identical
2657 * then it's not possible to encode the string as integer */
2658 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2659 if (longval
) *longval
= value
;
2663 /* Try to encode a string object in order to save space */
2664 static int tryObjectEncoding(robj
*o
) {
2668 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2669 return REDIS_ERR
; /* Already encoded */
2671 /* It's not save to encode shared objects: shared objects can be shared
2672 * everywhere in the "object space" of Redis. Encoded objects can only
2673 * appear as "values" (and not, for instance, as keys) */
2674 if (o
->refcount
> 1) return REDIS_ERR
;
2676 /* Currently we try to encode only strings */
2677 redisAssert(o
->type
== REDIS_STRING
);
2679 /* Check if we can represent this string as a long integer */
2680 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2682 /* Ok, this object can be encoded */
2683 o
->encoding
= REDIS_ENCODING_INT
;
2685 o
->ptr
= (void*) value
;
2689 /* Get a decoded version of an encoded object (returned as a new object).
2690 * If the object is already raw-encoded just increment the ref count. */
2691 static robj
*getDecodedObject(robj
*o
) {
2694 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2698 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2701 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2702 dec
= createStringObject(buf
,strlen(buf
));
2705 redisAssert(1 != 1);
2709 /* Compare two string objects via strcmp() or alike.
2710 * Note that the objects may be integer-encoded. In such a case we
2711 * use snprintf() to get a string representation of the numbers on the stack
2712 * and compare the strings, it's much faster than calling getDecodedObject().
2714 * Important note: if objects are not integer encoded, but binary-safe strings,
2715 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2717 static int compareStringObjects(robj
*a
, robj
*b
) {
2718 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2719 char bufa
[128], bufb
[128], *astr
, *bstr
;
2722 if (a
== b
) return 0;
2723 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2724 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2730 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2731 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2737 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2740 static size_t stringObjectLen(robj
*o
) {
2741 redisAssert(o
->type
== REDIS_STRING
);
2742 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2743 return sdslen(o
->ptr
);
2747 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2751 /*============================ RDB saving/loading =========================== */
2753 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2754 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2758 static int rdbSaveTime(FILE *fp
, time_t t
) {
2759 int32_t t32
= (int32_t) t
;
2760 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2764 /* check rdbLoadLen() comments for more info */
2765 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2766 unsigned char buf
[2];
2769 /* Save a 6 bit len */
2770 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2771 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2772 } else if (len
< (1<<14)) {
2773 /* Save a 14 bit len */
2774 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2776 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2778 /* Save a 32 bit len */
2779 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2780 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2782 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2787 /* String objects in the form "2391" "-100" without any space and with a
2788 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2789 * encoded as integers to save space */
2790 static int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
2792 char *endptr
, buf
[32];
2794 /* Check if it's possible to encode this value as a number */
2795 value
= strtoll(s
, &endptr
, 10);
2796 if (endptr
[0] != '\0') return 0;
2797 snprintf(buf
,32,"%lld",value
);
2799 /* If the number converted back into a string is not identical
2800 * then it's not possible to encode the string as integer */
2801 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
2803 /* Finally check if it fits in our ranges */
2804 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2805 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2806 enc
[1] = value
&0xFF;
2808 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2809 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2810 enc
[1] = value
&0xFF;
2811 enc
[2] = (value
>>8)&0xFF;
2813 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2814 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2815 enc
[1] = value
&0xFF;
2816 enc
[2] = (value
>>8)&0xFF;
2817 enc
[3] = (value
>>16)&0xFF;
2818 enc
[4] = (value
>>24)&0xFF;
2825 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
2826 unsigned int comprlen
, outlen
;
2830 /* We require at least four bytes compression for this to be worth it */
2831 outlen
= sdslen(obj
->ptr
)-4;
2832 if (outlen
<= 0) return 0;
2833 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2834 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
2835 if (comprlen
== 0) {
2839 /* Data compressed! Let's save it on disk */
2840 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
2841 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
2842 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
2843 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
2844 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
2853 /* Save a string objet as [len][data] on disk. If the object is a string
2854 * representation of an integer value we try to safe it in a special form */
2855 static int rdbSaveStringObjectRaw(FILE *fp
, robj
*obj
) {
2859 len
= sdslen(obj
->ptr
);
2861 /* Try integer encoding */
2863 unsigned char buf
[5];
2864 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
2865 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
2870 /* Try LZF compression - under 20 bytes it's unable to compress even
2871 * aaaaaaaaaaaaaaaaaa so skip it */
2872 if (server
.rdbcompression
&& len
> 20) {
2875 retval
= rdbSaveLzfStringObject(fp
,obj
);
2876 if (retval
== -1) return -1;
2877 if (retval
> 0) return 0;
2878 /* retval == 0 means data can't be compressed, save the old way */
2881 /* Store verbatim */
2882 if (rdbSaveLen(fp
,len
) == -1) return -1;
2883 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
2887 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
2888 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
2891 /* Avoid incr/decr ref count business when possible.
2892 * This plays well with copy-on-write given that we are probably
2893 * in a child process (BGSAVE). Also this makes sure key objects
2894 * of swapped objects are not incRefCount-ed (an assert does not allow
2895 * this in order to avoid bugs) */
2896 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
2897 obj
= getDecodedObject(obj
);
2898 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2901 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2906 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
2907 * 8 bit integer specifing the length of the representation.
2908 * This 8 bit integer has special values in order to specify the following
2914 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
2915 unsigned char buf
[128];
2921 } else if (!isfinite(val
)) {
2923 buf
[0] = (val
< 0) ? 255 : 254;
2925 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
2926 buf
[0] = strlen((char*)buf
+1);
2929 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
2933 /* Save a Redis object. */
2934 static int rdbSaveObject(FILE *fp
, robj
*o
) {
2935 if (o
->type
== REDIS_STRING
) {
2936 /* Save a string value */
2937 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
2938 } else if (o
->type
== REDIS_LIST
) {
2939 /* Save a list value */
2940 list
*list
= o
->ptr
;
2944 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
2945 listRewind(list
,&li
);
2946 while((ln
= listNext(&li
))) {
2947 robj
*eleobj
= listNodeValue(ln
);
2949 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2951 } else if (o
->type
== REDIS_SET
) {
2952 /* Save a set value */
2954 dictIterator
*di
= dictGetIterator(set
);
2957 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
2958 while((de
= dictNext(di
)) != NULL
) {
2959 robj
*eleobj
= dictGetEntryKey(de
);
2961 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2963 dictReleaseIterator(di
);
2964 } else if (o
->type
== REDIS_ZSET
) {
2965 /* Save a set value */
2967 dictIterator
*di
= dictGetIterator(zs
->dict
);
2970 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
2971 while((de
= dictNext(di
)) != NULL
) {
2972 robj
*eleobj
= dictGetEntryKey(de
);
2973 double *score
= dictGetEntryVal(de
);
2975 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2976 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
2978 dictReleaseIterator(di
);
2980 redisAssert(0 != 0);
2985 /* Return the length the object will have on disk if saved with
2986 * the rdbSaveObject() function. Currently we use a trick to get
2987 * this length with very little changes to the code. In the future
2988 * we could switch to a faster solution. */
2989 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
2990 if (fp
== NULL
) fp
= server
.devnull
;
2992 assert(rdbSaveObject(fp
,o
) != 1);
2996 /* Return the number of pages required to save this object in the swap file */
2997 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
2998 off_t bytes
= rdbSavedObjectLen(o
,fp
);
3000 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
3003 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3004 static int rdbSave(char *filename
) {
3005 dictIterator
*di
= NULL
;
3010 time_t now
= time(NULL
);
3012 /* Wait for I/O therads to terminate, just in case this is a
3013 * foreground-saving, to avoid seeking the swap file descriptor at the
3015 if (server
.vm_enabled
)
3016 waitEmptyIOJobsQueue();
3018 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3019 fp
= fopen(tmpfile
,"w");
3021 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3024 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3025 for (j
= 0; j
< server
.dbnum
; j
++) {
3026 redisDb
*db
= server
.db
+j
;
3028 if (dictSize(d
) == 0) continue;
3029 di
= dictGetIterator(d
);
3035 /* Write the SELECT DB opcode */
3036 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3037 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3039 /* Iterate this DB writing every entry */
3040 while((de
= dictNext(di
)) != NULL
) {
3041 robj
*key
= dictGetEntryKey(de
);
3042 robj
*o
= dictGetEntryVal(de
);
3043 time_t expiretime
= getExpire(db
,key
);
3045 /* Save the expire time */
3046 if (expiretime
!= -1) {
3047 /* If this key is already expired skip it */
3048 if (expiretime
< now
) continue;
3049 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3050 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3052 /* Save the key and associated value. This requires special
3053 * handling if the value is swapped out. */
3054 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3055 key
->storage
== REDIS_VM_SWAPPING
) {
3056 /* Save type, key, value */
3057 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3058 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3059 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3061 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3063 /* Get a preview of the object in memory */
3064 po
= vmPreviewObject(key
);
3065 /* Save type, key, value */
3066 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3067 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3068 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3069 /* Remove the loaded object from memory */
3073 dictReleaseIterator(di
);
3076 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3078 /* Make sure data will not remain on the OS's output buffers */
3083 /* Use RENAME to make sure the DB file is changed atomically only
3084 * if the generate DB file is ok. */
3085 if (rename(tmpfile
,filename
) == -1) {
3086 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3090 redisLog(REDIS_NOTICE
,"DB saved on disk");
3092 server
.lastsave
= time(NULL
);
3098 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3099 if (di
) dictReleaseIterator(di
);
3103 static int rdbSaveBackground(char *filename
) {
3106 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3107 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
3108 if ((childpid
= fork()) == 0) {
3110 if (server
.vm_enabled
) vmReopenSwapFile();
3112 if (rdbSave(filename
) == REDIS_OK
) {
3119 if (childpid
== -1) {
3120 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3124 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3125 server
.bgsavechildpid
= childpid
;
3128 return REDIS_OK
; /* unreached */
3131 static void rdbRemoveTempFile(pid_t childpid
) {
3134 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3138 static int rdbLoadType(FILE *fp
) {
3140 if (fread(&type
,1,1,fp
) == 0) return -1;
3144 static time_t rdbLoadTime(FILE *fp
) {
3146 if (fread(&t32
,4,1,fp
) == 0) return -1;
3147 return (time_t) t32
;
3150 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3151 * of this file for a description of how this are stored on disk.
3153 * isencoded is set to 1 if the readed length is not actually a length but
3154 * an "encoding type", check the above comments for more info */
3155 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3156 unsigned char buf
[2];
3160 if (isencoded
) *isencoded
= 0;
3161 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3162 type
= (buf
[0]&0xC0)>>6;
3163 if (type
== REDIS_RDB_6BITLEN
) {
3164 /* Read a 6 bit len */
3166 } else if (type
== REDIS_RDB_ENCVAL
) {
3167 /* Read a 6 bit len encoding type */
3168 if (isencoded
) *isencoded
= 1;
3170 } else if (type
== REDIS_RDB_14BITLEN
) {
3171 /* Read a 14 bit len */
3172 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3173 return ((buf
[0]&0x3F)<<8)|buf
[1];
3175 /* Read a 32 bit len */
3176 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3181 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
3182 unsigned char enc
[4];
3185 if (enctype
== REDIS_RDB_ENC_INT8
) {
3186 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3187 val
= (signed char)enc
[0];
3188 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3190 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3191 v
= enc
[0]|(enc
[1]<<8);
3193 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3195 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3196 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3199 val
= 0; /* anti-warning */
3202 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3205 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3206 unsigned int len
, clen
;
3207 unsigned char *c
= NULL
;
3210 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3211 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3212 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3213 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3214 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3215 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3217 return createObject(REDIS_STRING
,val
);
3224 static robj
*rdbLoadStringObject(FILE*fp
) {
3229 len
= rdbLoadLen(fp
,&isencoded
);
3232 case REDIS_RDB_ENC_INT8
:
3233 case REDIS_RDB_ENC_INT16
:
3234 case REDIS_RDB_ENC_INT32
:
3235 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3236 case REDIS_RDB_ENC_LZF
:
3237 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3243 if (len
== REDIS_RDB_LENERR
) return NULL
;
3244 val
= sdsnewlen(NULL
,len
);
3245 if (len
&& fread(val
,len
,1,fp
) == 0) {
3249 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3252 /* For information about double serialization check rdbSaveDoubleValue() */
3253 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3257 if (fread(&len
,1,1,fp
) == 0) return -1;
3259 case 255: *val
= R_NegInf
; return 0;
3260 case 254: *val
= R_PosInf
; return 0;
3261 case 253: *val
= R_Nan
; return 0;
3263 if (fread(buf
,len
,1,fp
) == 0) return -1;
3265 sscanf(buf
, "%lg", val
);
3270 /* Load a Redis object of the specified type from the specified file.
3271 * On success a newly allocated object is returned, otherwise NULL. */
3272 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3275 if (type
== REDIS_STRING
) {
3276 /* Read string value */
3277 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3278 tryObjectEncoding(o
);
3279 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3280 /* Read list/set value */
3283 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3284 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3285 /* Load every single element of the list/set */
3289 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3290 tryObjectEncoding(ele
);
3291 if (type
== REDIS_LIST
) {
3292 listAddNodeTail((list
*)o
->ptr
,ele
);
3294 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3297 } else if (type
== REDIS_ZSET
) {
3298 /* Read list/set value */
3302 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3303 o
= createZsetObject();
3305 /* Load every single element of the list/set */
3308 double *score
= zmalloc(sizeof(double));
3310 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3311 tryObjectEncoding(ele
);
3312 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3313 dictAdd(zs
->dict
,ele
,score
);
3314 zslInsert(zs
->zsl
,*score
,ele
);
3315 incrRefCount(ele
); /* added to skiplist */
3318 redisAssert(0 != 0);
3323 static int rdbLoad(char *filename
) {
3325 robj
*keyobj
= NULL
;
3327 int type
, retval
, rdbver
;
3328 dict
*d
= server
.db
[0].dict
;
3329 redisDb
*db
= server
.db
+0;
3331 time_t expiretime
= -1, now
= time(NULL
);
3332 long long loadedkeys
= 0;
3334 fp
= fopen(filename
,"r");
3335 if (!fp
) return REDIS_ERR
;
3336 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3338 if (memcmp(buf
,"REDIS",5) != 0) {
3340 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3343 rdbver
= atoi(buf
+5);
3346 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3353 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3354 if (type
== REDIS_EXPIRETIME
) {
3355 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3356 /* We read the time so we need to read the object type again */
3357 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3359 if (type
== REDIS_EOF
) break;
3360 /* Handle SELECT DB opcode as a special case */
3361 if (type
== REDIS_SELECTDB
) {
3362 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3364 if (dbid
>= (unsigned)server
.dbnum
) {
3365 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3368 db
= server
.db
+dbid
;
3373 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3375 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3376 /* Add the new object in the hash table */
3377 retval
= dictAdd(d
,keyobj
,o
);
3378 if (retval
== DICT_ERR
) {
3379 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3382 /* Set the expire time if needed */
3383 if (expiretime
!= -1) {
3384 setExpire(db
,keyobj
,expiretime
);
3385 /* Delete this key if already expired */
3386 if (expiretime
< now
) deleteKey(db
,keyobj
);
3390 /* Handle swapping while loading big datasets when VM is on */
3392 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
3393 while (zmalloc_used_memory() > server
.vm_max_memory
) {
3394 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
3401 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3402 if (keyobj
) decrRefCount(keyobj
);
3403 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3405 return REDIS_ERR
; /* Just to avoid warning */
3408 /*================================== Commands =============================== */
3410 static void authCommand(redisClient
*c
) {
3411 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3412 c
->authenticated
= 1;
3413 addReply(c
,shared
.ok
);
3415 c
->authenticated
= 0;
3416 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3420 static void pingCommand(redisClient
*c
) {
3421 addReply(c
,shared
.pong
);
3424 static void echoCommand(redisClient
*c
) {
3425 addReplyBulkLen(c
,c
->argv
[1]);
3426 addReply(c
,c
->argv
[1]);
3427 addReply(c
,shared
.crlf
);
3430 /*=================================== Strings =============================== */
3432 static void setGenericCommand(redisClient
*c
, int nx
) {
3435 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3436 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3437 if (retval
== DICT_ERR
) {
3439 /* If the key is about a swapped value, we want a new key object
3440 * to overwrite the old. So we delete the old key in the database.
3441 * This will also make sure that swap pages about the old object
3442 * will be marked as free. */
3443 if (deleteIfSwapped(c
->db
,c
->argv
[1]))
3444 incrRefCount(c
->argv
[1]);
3445 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3446 incrRefCount(c
->argv
[2]);
3448 addReply(c
,shared
.czero
);
3452 incrRefCount(c
->argv
[1]);
3453 incrRefCount(c
->argv
[2]);
3456 removeExpire(c
->db
,c
->argv
[1]);
3457 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3460 static void setCommand(redisClient
*c
) {
3461 setGenericCommand(c
,0);
3464 static void setnxCommand(redisClient
*c
) {
3465 setGenericCommand(c
,1);
3468 static int getGenericCommand(redisClient
*c
) {
3469 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3472 addReply(c
,shared
.nullbulk
);
3475 if (o
->type
!= REDIS_STRING
) {
3476 addReply(c
,shared
.wrongtypeerr
);
3479 addReplyBulkLen(c
,o
);
3481 addReply(c
,shared
.crlf
);
3487 static void getCommand(redisClient
*c
) {
3488 getGenericCommand(c
);
3491 static void getsetCommand(redisClient
*c
) {
3492 if (getGenericCommand(c
) == REDIS_ERR
) return;
3493 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3494 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3496 incrRefCount(c
->argv
[1]);
3498 incrRefCount(c
->argv
[2]);
3500 removeExpire(c
->db
,c
->argv
[1]);
3503 static void mgetCommand(redisClient
*c
) {
3506 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3507 for (j
= 1; j
< c
->argc
; j
++) {
3508 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3510 addReply(c
,shared
.nullbulk
);
3512 if (o
->type
!= REDIS_STRING
) {
3513 addReply(c
,shared
.nullbulk
);
3515 addReplyBulkLen(c
,o
);
3517 addReply(c
,shared
.crlf
);
3523 static void msetGenericCommand(redisClient
*c
, int nx
) {
3524 int j
, busykeys
= 0;
3526 if ((c
->argc
% 2) == 0) {
3527 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3530 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3531 * set nothing at all if at least one already key exists. */
3533 for (j
= 1; j
< c
->argc
; j
+= 2) {
3534 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3540 addReply(c
, shared
.czero
);
3544 for (j
= 1; j
< c
->argc
; j
+= 2) {
3547 tryObjectEncoding(c
->argv
[j
+1]);
3548 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3549 if (retval
== DICT_ERR
) {
3550 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3551 incrRefCount(c
->argv
[j
+1]);
3553 incrRefCount(c
->argv
[j
]);
3554 incrRefCount(c
->argv
[j
+1]);
3556 removeExpire(c
->db
,c
->argv
[j
]);
3558 server
.dirty
+= (c
->argc
-1)/2;
3559 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3562 static void msetCommand(redisClient
*c
) {
3563 msetGenericCommand(c
,0);
3566 static void msetnxCommand(redisClient
*c
) {
3567 msetGenericCommand(c
,1);
3570 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3575 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3579 if (o
->type
!= REDIS_STRING
) {
3584 if (o
->encoding
== REDIS_ENCODING_RAW
)
3585 value
= strtoll(o
->ptr
, &eptr
, 10);
3586 else if (o
->encoding
== REDIS_ENCODING_INT
)
3587 value
= (long)o
->ptr
;
3589 redisAssert(1 != 1);
3594 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3595 tryObjectEncoding(o
);
3596 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3597 if (retval
== DICT_ERR
) {
3598 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3599 removeExpire(c
->db
,c
->argv
[1]);
3601 incrRefCount(c
->argv
[1]);
3604 addReply(c
,shared
.colon
);
3606 addReply(c
,shared
.crlf
);
3609 static void incrCommand(redisClient
*c
) {
3610 incrDecrCommand(c
,1);
3613 static void decrCommand(redisClient
*c
) {
3614 incrDecrCommand(c
,-1);
3617 static void incrbyCommand(redisClient
*c
) {
3618 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3619 incrDecrCommand(c
,incr
);
3622 static void decrbyCommand(redisClient
*c
) {
3623 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3624 incrDecrCommand(c
,-incr
);
3627 /* ========================= Type agnostic commands ========================= */
3629 static void delCommand(redisClient
*c
) {
3632 for (j
= 1; j
< c
->argc
; j
++) {
3633 if (deleteKey(c
->db
,c
->argv
[j
])) {
3640 addReply(c
,shared
.czero
);
3643 addReply(c
,shared
.cone
);
3646 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3651 static void existsCommand(redisClient
*c
) {
3652 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3655 static void selectCommand(redisClient
*c
) {
3656 int id
= atoi(c
->argv
[1]->ptr
);
3658 if (selectDb(c
,id
) == REDIS_ERR
) {
3659 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3661 addReply(c
,shared
.ok
);
3665 static void randomkeyCommand(redisClient
*c
) {
3669 de
= dictGetRandomKey(c
->db
->dict
);
3670 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3673 addReply(c
,shared
.plus
);
3674 addReply(c
,shared
.crlf
);
3676 addReply(c
,shared
.plus
);
3677 addReply(c
,dictGetEntryKey(de
));
3678 addReply(c
,shared
.crlf
);
3682 static void keysCommand(redisClient
*c
) {
3685 sds pattern
= c
->argv
[1]->ptr
;
3686 int plen
= sdslen(pattern
);
3687 unsigned long numkeys
= 0, keyslen
= 0;
3688 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
3690 di
= dictGetIterator(c
->db
->dict
);
3692 decrRefCount(lenobj
);
3693 while((de
= dictNext(di
)) != NULL
) {
3694 robj
*keyobj
= dictGetEntryKey(de
);
3696 sds key
= keyobj
->ptr
;
3697 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
3698 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
3699 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
3701 addReply(c
,shared
.space
);
3704 keyslen
+= sdslen(key
);
3708 dictReleaseIterator(di
);
3709 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
3710 addReply(c
,shared
.crlf
);
3713 static void dbsizeCommand(redisClient
*c
) {
3715 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
3718 static void lastsaveCommand(redisClient
*c
) {
3720 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
3723 static void typeCommand(redisClient
*c
) {
3727 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3732 case REDIS_STRING
: type
= "+string"; break;
3733 case REDIS_LIST
: type
= "+list"; break;
3734 case REDIS_SET
: type
= "+set"; break;
3735 case REDIS_ZSET
: type
= "+zset"; break;
3736 default: type
= "unknown"; break;
3739 addReplySds(c
,sdsnew(type
));
3740 addReply(c
,shared
.crlf
);
3743 static void saveCommand(redisClient
*c
) {
3744 if (server
.bgsavechildpid
!= -1) {
3745 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
3748 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3749 addReply(c
,shared
.ok
);
3751 addReply(c
,shared
.err
);
3755 static void bgsaveCommand(redisClient
*c
) {
3756 if (server
.bgsavechildpid
!= -1) {
3757 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
3760 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
3761 char *status
= "+Background saving started\r\n";
3762 addReplySds(c
,sdsnew(status
));
3764 addReply(c
,shared
.err
);
3768 static void shutdownCommand(redisClient
*c
) {
3769 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
3770 /* Kill the saving child if there is a background saving in progress.
3771 We want to avoid race conditions, for instance our saving child may
3772 overwrite the synchronous saving did by SHUTDOWN. */
3773 if (server
.bgsavechildpid
!= -1) {
3774 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
3775 kill(server
.bgsavechildpid
,SIGKILL
);
3776 rdbRemoveTempFile(server
.bgsavechildpid
);
3778 if (server
.appendonly
) {
3779 /* Append only file: fsync() the AOF and exit */
3780 fsync(server
.appendfd
);
3781 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
3784 /* Snapshotting. Perform a SYNC SAVE and exit */
3785 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3786 if (server
.daemonize
)
3787 unlink(server
.pidfile
);
3788 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
3789 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
3790 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
3793 /* Ooops.. error saving! The best we can do is to continue operating.
3794 * Note that if there was a background saving process, in the next
3795 * cron() Redis will be notified that the background saving aborted,
3796 * handling special stuff like slaves pending for synchronization... */
3797 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
3798 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3803 static void renameGenericCommand(redisClient
*c
, int nx
) {
3806 /* To use the same key as src and dst is probably an error */
3807 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
3808 addReply(c
,shared
.sameobjecterr
);
3812 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3814 addReply(c
,shared
.nokeyerr
);
3818 deleteIfVolatile(c
->db
,c
->argv
[2]);
3819 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
3822 addReply(c
,shared
.czero
);
3825 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
3827 incrRefCount(c
->argv
[2]);
3829 deleteKey(c
->db
,c
->argv
[1]);
3831 addReply(c
,nx
? shared
.cone
: shared
.ok
);
3834 static void renameCommand(redisClient
*c
) {
3835 renameGenericCommand(c
,0);
3838 static void renamenxCommand(redisClient
*c
) {
3839 renameGenericCommand(c
,1);
3842 static void moveCommand(redisClient
*c
) {
3847 /* Obtain source and target DB pointers */
3850 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
3851 addReply(c
,shared
.outofrangeerr
);
3855 selectDb(c
,srcid
); /* Back to the source DB */
3857 /* If the user is moving using as target the same
3858 * DB as the source DB it is probably an error. */
3860 addReply(c
,shared
.sameobjecterr
);
3864 /* Check if the element exists and get a reference */
3865 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3867 addReply(c
,shared
.czero
);
3871 /* Try to add the element to the target DB */
3872 deleteIfVolatile(dst
,c
->argv
[1]);
3873 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
3874 addReply(c
,shared
.czero
);
3877 incrRefCount(c
->argv
[1]);
3880 /* OK! key moved, free the entry in the source DB */
3881 deleteKey(src
,c
->argv
[1]);
3883 addReply(c
,shared
.cone
);
3886 /* =================================== Lists ================================ */
3887 static void pushGenericCommand(redisClient
*c
, int where
) {
3891 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3893 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3894 addReply(c
,shared
.ok
);
3897 lobj
= createListObject();
3899 if (where
== REDIS_HEAD
) {
3900 listAddNodeHead(list
,c
->argv
[2]);
3902 listAddNodeTail(list
,c
->argv
[2]);
3904 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
3905 incrRefCount(c
->argv
[1]);
3906 incrRefCount(c
->argv
[2]);
3908 if (lobj
->type
!= REDIS_LIST
) {
3909 addReply(c
,shared
.wrongtypeerr
);
3912 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3913 addReply(c
,shared
.ok
);
3917 if (where
== REDIS_HEAD
) {
3918 listAddNodeHead(list
,c
->argv
[2]);
3920 listAddNodeTail(list
,c
->argv
[2]);
3922 incrRefCount(c
->argv
[2]);
3925 addReply(c
,shared
.ok
);
3928 static void lpushCommand(redisClient
*c
) {
3929 pushGenericCommand(c
,REDIS_HEAD
);
3932 static void rpushCommand(redisClient
*c
) {
3933 pushGenericCommand(c
,REDIS_TAIL
);
3936 static void llenCommand(redisClient
*c
) {
3940 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3942 addReply(c
,shared
.czero
);
3945 if (o
->type
!= REDIS_LIST
) {
3946 addReply(c
,shared
.wrongtypeerr
);
3949 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
3954 static void lindexCommand(redisClient
*c
) {
3956 int index
= atoi(c
->argv
[2]->ptr
);
3958 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3960 addReply(c
,shared
.nullbulk
);
3962 if (o
->type
!= REDIS_LIST
) {
3963 addReply(c
,shared
.wrongtypeerr
);
3965 list
*list
= o
->ptr
;
3968 ln
= listIndex(list
, index
);
3970 addReply(c
,shared
.nullbulk
);
3972 robj
*ele
= listNodeValue(ln
);
3973 addReplyBulkLen(c
,ele
);
3975 addReply(c
,shared
.crlf
);
3981 static void lsetCommand(redisClient
*c
) {
3983 int index
= atoi(c
->argv
[2]->ptr
);
3985 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3987 addReply(c
,shared
.nokeyerr
);
3989 if (o
->type
!= REDIS_LIST
) {
3990 addReply(c
,shared
.wrongtypeerr
);
3992 list
*list
= o
->ptr
;
3995 ln
= listIndex(list
, index
);
3997 addReply(c
,shared
.outofrangeerr
);
3999 robj
*ele
= listNodeValue(ln
);
4002 listNodeValue(ln
) = c
->argv
[3];
4003 incrRefCount(c
->argv
[3]);
4004 addReply(c
,shared
.ok
);
4011 static void popGenericCommand(redisClient
*c
, int where
) {
4014 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4016 addReply(c
,shared
.nullbulk
);
4018 if (o
->type
!= REDIS_LIST
) {
4019 addReply(c
,shared
.wrongtypeerr
);
4021 list
*list
= o
->ptr
;
4024 if (where
== REDIS_HEAD
)
4025 ln
= listFirst(list
);
4027 ln
= listLast(list
);
4030 addReply(c
,shared
.nullbulk
);
4032 robj
*ele
= listNodeValue(ln
);
4033 addReplyBulkLen(c
,ele
);
4035 addReply(c
,shared
.crlf
);
4036 listDelNode(list
,ln
);
4043 static void lpopCommand(redisClient
*c
) {
4044 popGenericCommand(c
,REDIS_HEAD
);
4047 static void rpopCommand(redisClient
*c
) {
4048 popGenericCommand(c
,REDIS_TAIL
);
4051 static void lrangeCommand(redisClient
*c
) {
4053 int start
= atoi(c
->argv
[2]->ptr
);
4054 int end
= atoi(c
->argv
[3]->ptr
);
4056 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4058 addReply(c
,shared
.nullmultibulk
);
4060 if (o
->type
!= REDIS_LIST
) {
4061 addReply(c
,shared
.wrongtypeerr
);
4063 list
*list
= o
->ptr
;
4065 int llen
= listLength(list
);
4069 /* convert negative indexes */
4070 if (start
< 0) start
= llen
+start
;
4071 if (end
< 0) end
= llen
+end
;
4072 if (start
< 0) start
= 0;
4073 if (end
< 0) end
= 0;
4075 /* indexes sanity checks */
4076 if (start
> end
|| start
>= llen
) {
4077 /* Out of range start or start > end result in empty list */
4078 addReply(c
,shared
.emptymultibulk
);
4081 if (end
>= llen
) end
= llen
-1;
4082 rangelen
= (end
-start
)+1;
4084 /* Return the result in form of a multi-bulk reply */
4085 ln
= listIndex(list
, start
);
4086 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4087 for (j
= 0; j
< rangelen
; j
++) {
4088 ele
= listNodeValue(ln
);
4089 addReplyBulkLen(c
,ele
);
4091 addReply(c
,shared
.crlf
);
4098 static void ltrimCommand(redisClient
*c
) {
4100 int start
= atoi(c
->argv
[2]->ptr
);
4101 int end
= atoi(c
->argv
[3]->ptr
);
4103 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4105 addReply(c
,shared
.ok
);
4107 if (o
->type
!= REDIS_LIST
) {
4108 addReply(c
,shared
.wrongtypeerr
);
4110 list
*list
= o
->ptr
;
4112 int llen
= listLength(list
);
4113 int j
, ltrim
, rtrim
;
4115 /* convert negative indexes */
4116 if (start
< 0) start
= llen
+start
;
4117 if (end
< 0) end
= llen
+end
;
4118 if (start
< 0) start
= 0;
4119 if (end
< 0) end
= 0;
4121 /* indexes sanity checks */
4122 if (start
> end
|| start
>= llen
) {
4123 /* Out of range start or start > end result in empty list */
4127 if (end
>= llen
) end
= llen
-1;
4132 /* Remove list elements to perform the trim */
4133 for (j
= 0; j
< ltrim
; j
++) {
4134 ln
= listFirst(list
);
4135 listDelNode(list
,ln
);
4137 for (j
= 0; j
< rtrim
; j
++) {
4138 ln
= listLast(list
);
4139 listDelNode(list
,ln
);
4142 addReply(c
,shared
.ok
);
4147 static void lremCommand(redisClient
*c
) {
4150 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4152 addReply(c
,shared
.czero
);
4154 if (o
->type
!= REDIS_LIST
) {
4155 addReply(c
,shared
.wrongtypeerr
);
4157 list
*list
= o
->ptr
;
4158 listNode
*ln
, *next
;
4159 int toremove
= atoi(c
->argv
[2]->ptr
);
4164 toremove
= -toremove
;
4167 ln
= fromtail
? list
->tail
: list
->head
;
4169 robj
*ele
= listNodeValue(ln
);
4171 next
= fromtail
? ln
->prev
: ln
->next
;
4172 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
4173 listDelNode(list
,ln
);
4176 if (toremove
&& removed
== toremove
) break;
4180 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4185 /* This is the semantic of this command:
4186 * RPOPLPUSH srclist dstlist:
4187 * IF LLEN(srclist) > 0
4188 * element = RPOP srclist
4189 * LPUSH dstlist element
4196 * The idea is to be able to get an element from a list in a reliable way
4197 * since the element is not just returned but pushed against another list
4198 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4200 static void rpoplpushcommand(redisClient
*c
) {
4203 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4205 addReply(c
,shared
.nullbulk
);
4207 if (sobj
->type
!= REDIS_LIST
) {
4208 addReply(c
,shared
.wrongtypeerr
);
4210 list
*srclist
= sobj
->ptr
;
4211 listNode
*ln
= listLast(srclist
);
4214 addReply(c
,shared
.nullbulk
);
4216 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4217 robj
*ele
= listNodeValue(ln
);
4220 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4221 addReply(c
,shared
.wrongtypeerr
);
4225 /* Add the element to the target list (unless it's directly
4226 * passed to some BLPOP-ing client */
4227 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4229 /* Create the list if the key does not exist */
4230 dobj
= createListObject();
4231 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4232 incrRefCount(c
->argv
[2]);
4234 dstlist
= dobj
->ptr
;
4235 listAddNodeHead(dstlist
,ele
);
4239 /* Send the element to the client as reply as well */
4240 addReplyBulkLen(c
,ele
);
4242 addReply(c
,shared
.crlf
);
4244 /* Finally remove the element from the source list */
4245 listDelNode(srclist
,ln
);
4253 /* ==================================== Sets ================================ */
4255 static void saddCommand(redisClient
*c
) {
4258 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4260 set
= createSetObject();
4261 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4262 incrRefCount(c
->argv
[1]);
4264 if (set
->type
!= REDIS_SET
) {
4265 addReply(c
,shared
.wrongtypeerr
);
4269 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4270 incrRefCount(c
->argv
[2]);
4272 addReply(c
,shared
.cone
);
4274 addReply(c
,shared
.czero
);
4278 static void sremCommand(redisClient
*c
) {
4281 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4283 addReply(c
,shared
.czero
);
4285 if (set
->type
!= REDIS_SET
) {
4286 addReply(c
,shared
.wrongtypeerr
);
4289 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4291 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4292 addReply(c
,shared
.cone
);
4294 addReply(c
,shared
.czero
);
4299 static void smoveCommand(redisClient
*c
) {
4300 robj
*srcset
, *dstset
;
4302 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4303 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4305 /* If the source key does not exist return 0, if it's of the wrong type
4307 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4308 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4311 /* Error if the destination key is not a set as well */
4312 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4313 addReply(c
,shared
.wrongtypeerr
);
4316 /* Remove the element from the source set */
4317 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4318 /* Key not found in the src set! return zero */
4319 addReply(c
,shared
.czero
);
4323 /* Add the element to the destination set */
4325 dstset
= createSetObject();
4326 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4327 incrRefCount(c
->argv
[2]);
4329 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4330 incrRefCount(c
->argv
[3]);
4331 addReply(c
,shared
.cone
);
4334 static void sismemberCommand(redisClient
*c
) {
4337 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4339 addReply(c
,shared
.czero
);
4341 if (set
->type
!= REDIS_SET
) {
4342 addReply(c
,shared
.wrongtypeerr
);
4345 if (dictFind(set
->ptr
,c
->argv
[2]))
4346 addReply(c
,shared
.cone
);
4348 addReply(c
,shared
.czero
);
4352 static void scardCommand(redisClient
*c
) {
4356 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4358 addReply(c
,shared
.czero
);
4361 if (o
->type
!= REDIS_SET
) {
4362 addReply(c
,shared
.wrongtypeerr
);
4365 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4371 static void spopCommand(redisClient
*c
) {
4375 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4377 addReply(c
,shared
.nullbulk
);
4379 if (set
->type
!= REDIS_SET
) {
4380 addReply(c
,shared
.wrongtypeerr
);
4383 de
= dictGetRandomKey(set
->ptr
);
4385 addReply(c
,shared
.nullbulk
);
4387 robj
*ele
= dictGetEntryKey(de
);
4389 addReplyBulkLen(c
,ele
);
4391 addReply(c
,shared
.crlf
);
4392 dictDelete(set
->ptr
,ele
);
4393 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4399 static void srandmemberCommand(redisClient
*c
) {
4403 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4405 addReply(c
,shared
.nullbulk
);
4407 if (set
->type
!= REDIS_SET
) {
4408 addReply(c
,shared
.wrongtypeerr
);
4411 de
= dictGetRandomKey(set
->ptr
);
4413 addReply(c
,shared
.nullbulk
);
4415 robj
*ele
= dictGetEntryKey(de
);
4417 addReplyBulkLen(c
,ele
);
4419 addReply(c
,shared
.crlf
);
4424 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4425 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4427 return dictSize(*d1
)-dictSize(*d2
);
4430 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4431 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4434 robj
*lenobj
= NULL
, *dstset
= NULL
;
4435 unsigned long j
, cardinality
= 0;
4437 for (j
= 0; j
< setsnum
; j
++) {
4441 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4442 lookupKeyRead(c
->db
,setskeys
[j
]);
4446 if (deleteKey(c
->db
,dstkey
))
4448 addReply(c
,shared
.czero
);
4450 addReply(c
,shared
.nullmultibulk
);
4454 if (setobj
->type
!= REDIS_SET
) {
4456 addReply(c
,shared
.wrongtypeerr
);
4459 dv
[j
] = setobj
->ptr
;
4461 /* Sort sets from the smallest to largest, this will improve our
4462 * algorithm's performace */
4463 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4465 /* The first thing we should output is the total number of elements...
4466 * since this is a multi-bulk write, but at this stage we don't know
4467 * the intersection set size, so we use a trick, append an empty object
4468 * to the output list and save the pointer to later modify it with the
4471 lenobj
= createObject(REDIS_STRING
,NULL
);
4473 decrRefCount(lenobj
);
4475 /* If we have a target key where to store the resulting set
4476 * create this key with an empty set inside */
4477 dstset
= createSetObject();
4480 /* Iterate all the elements of the first (smallest) set, and test
4481 * the element against all the other sets, if at least one set does
4482 * not include the element it is discarded */
4483 di
= dictGetIterator(dv
[0]);
4485 while((de
= dictNext(di
)) != NULL
) {
4488 for (j
= 1; j
< setsnum
; j
++)
4489 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4491 continue; /* at least one set does not contain the member */
4492 ele
= dictGetEntryKey(de
);
4494 addReplyBulkLen(c
,ele
);
4496 addReply(c
,shared
.crlf
);
4499 dictAdd(dstset
->ptr
,ele
,NULL
);
4503 dictReleaseIterator(di
);
4506 /* Store the resulting set into the target */
4507 deleteKey(c
->db
,dstkey
);
4508 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4509 incrRefCount(dstkey
);
4513 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4515 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4516 dictSize((dict
*)dstset
->ptr
)));
4522 static void sinterCommand(redisClient
*c
) {
4523 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4526 static void sinterstoreCommand(redisClient
*c
) {
4527 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4530 #define REDIS_OP_UNION 0
4531 #define REDIS_OP_DIFF 1
4533 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4534 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4537 robj
*dstset
= NULL
;
4538 int j
, cardinality
= 0;
4540 for (j
= 0; j
< setsnum
; j
++) {
4544 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4545 lookupKeyRead(c
->db
,setskeys
[j
]);
4550 if (setobj
->type
!= REDIS_SET
) {
4552 addReply(c
,shared
.wrongtypeerr
);
4555 dv
[j
] = setobj
->ptr
;
4558 /* We need a temp set object to store our union. If the dstkey
4559 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4560 * this set object will be the resulting object to set into the target key*/
4561 dstset
= createSetObject();
4563 /* Iterate all the elements of all the sets, add every element a single
4564 * time to the result set */
4565 for (j
= 0; j
< setsnum
; j
++) {
4566 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4567 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4569 di
= dictGetIterator(dv
[j
]);
4571 while((de
= dictNext(di
)) != NULL
) {
4574 /* dictAdd will not add the same element multiple times */
4575 ele
= dictGetEntryKey(de
);
4576 if (op
== REDIS_OP_UNION
|| j
== 0) {
4577 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4581 } else if (op
== REDIS_OP_DIFF
) {
4582 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4587 dictReleaseIterator(di
);
4589 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4592 /* Output the content of the resulting set, if not in STORE mode */
4594 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4595 di
= dictGetIterator(dstset
->ptr
);
4596 while((de
= dictNext(di
)) != NULL
) {
4599 ele
= dictGetEntryKey(de
);
4600 addReplyBulkLen(c
,ele
);
4602 addReply(c
,shared
.crlf
);
4604 dictReleaseIterator(di
);
4606 /* If we have a target key where to store the resulting set
4607 * create this key with the result set inside */
4608 deleteKey(c
->db
,dstkey
);
4609 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4610 incrRefCount(dstkey
);
4615 decrRefCount(dstset
);
4617 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4618 dictSize((dict
*)dstset
->ptr
)));
4624 static void sunionCommand(redisClient
*c
) {
4625 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4628 static void sunionstoreCommand(redisClient
*c
) {
4629 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4632 static void sdiffCommand(redisClient
*c
) {
4633 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4636 static void sdiffstoreCommand(redisClient
*c
) {
4637 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4640 /* ==================================== ZSets =============================== */
4642 /* ZSETs are ordered sets using two data structures to hold the same elements
4643 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4646 * The elements are added to an hash table mapping Redis objects to scores.
4647 * At the same time the elements are added to a skip list mapping scores
4648 * to Redis objects (so objects are sorted by scores in this "view"). */
4650 /* This skiplist implementation is almost a C translation of the original
4651 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4652 * Alternative to Balanced Trees", modified in three ways:
4653 * a) this implementation allows for repeated values.
4654 * b) the comparison is not just by key (our 'score') but by satellite data.
4655 * c) there is a back pointer, so it's a doubly linked list with the back
4656 * pointers being only at "level 1". This allows to traverse the list
4657 * from tail to head, useful for ZREVRANGE. */
4659 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4660 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4662 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4668 static zskiplist
*zslCreate(void) {
4672 zsl
= zmalloc(sizeof(*zsl
));
4675 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4676 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++)
4677 zsl
->header
->forward
[j
] = NULL
;
4678 zsl
->header
->backward
= NULL
;
4683 static void zslFreeNode(zskiplistNode
*node
) {
4684 decrRefCount(node
->obj
);
4685 zfree(node
->forward
);
4689 static void zslFree(zskiplist
*zsl
) {
4690 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4692 zfree(zsl
->header
->forward
);
4695 next
= node
->forward
[0];
4702 static int zslRandomLevel(void) {
4704 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
4709 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
4710 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4714 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4715 while (x
->forward
[i
] &&
4716 (x
->forward
[i
]->score
< score
||
4717 (x
->forward
[i
]->score
== score
&&
4718 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4722 /* we assume the key is not already inside, since we allow duplicated
4723 * scores, and the re-insertion of score and redis object should never
4724 * happpen since the caller of zslInsert() should test in the hash table
4725 * if the element is already inside or not. */
4726 level
= zslRandomLevel();
4727 if (level
> zsl
->level
) {
4728 for (i
= zsl
->level
; i
< level
; i
++)
4729 update
[i
] = zsl
->header
;
4732 x
= zslCreateNode(level
,score
,obj
);
4733 for (i
= 0; i
< level
; i
++) {
4734 x
->forward
[i
] = update
[i
]->forward
[i
];
4735 update
[i
]->forward
[i
] = x
;
4737 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
4739 x
->forward
[0]->backward
= x
;
4745 /* Delete an element with matching score/object from the skiplist. */
4746 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
4747 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4751 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4752 while (x
->forward
[i
] &&
4753 (x
->forward
[i
]->score
< score
||
4754 (x
->forward
[i
]->score
== score
&&
4755 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4759 /* We may have multiple elements with the same score, what we need
4760 * is to find the element with both the right score and object. */
4762 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
4763 for (i
= 0; i
< zsl
->level
; i
++) {
4764 if (update
[i
]->forward
[i
] != x
) break;
4765 update
[i
]->forward
[i
] = x
->forward
[i
];
4767 if (x
->forward
[0]) {
4768 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4771 zsl
->tail
= x
->backward
;
4774 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4779 return 0; /* not found */
4781 return 0; /* not found */
4784 /* Delete all the elements with score between min and max from the skiplist.
4785 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4786 * Note that this function takes the reference to the hash table view of the
4787 * sorted set, in order to remove the elements from the hash table too. */
4788 static unsigned long zslDeleteRange(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
4789 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4790 unsigned long removed
= 0;
4794 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4795 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
4799 /* We may have multiple elements with the same score, what we need
4800 * is to find the element with both the right score and object. */
4802 while (x
&& x
->score
<= max
) {
4803 zskiplistNode
*next
;
4805 for (i
= 0; i
< zsl
->level
; i
++) {
4806 if (update
[i
]->forward
[i
] != x
) break;
4807 update
[i
]->forward
[i
] = x
->forward
[i
];
4809 if (x
->forward
[0]) {
4810 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4813 zsl
->tail
= x
->backward
;
4815 next
= x
->forward
[0];
4816 dictDelete(dict
,x
->obj
);
4818 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4824 return removed
; /* not found */
4827 /* Find the first node having a score equal or greater than the specified one.
4828 * Returns NULL if there is no match. */
4829 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
4834 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4835 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
4838 /* We may have multiple elements with the same score, what we need
4839 * is to find the element with both the right score and object. */
4840 return x
->forward
[0];
4843 /* The actual Z-commands implementations */
4845 /* This generic command implements both ZADD and ZINCRBY.
4846 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
4847 * the increment if the operation is a ZINCRBY (doincrement == 1). */
4848 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
4853 zsetobj
= lookupKeyWrite(c
->db
,key
);
4854 if (zsetobj
== NULL
) {
4855 zsetobj
= createZsetObject();
4856 dictAdd(c
->db
->dict
,key
,zsetobj
);
4859 if (zsetobj
->type
!= REDIS_ZSET
) {
4860 addReply(c
,shared
.wrongtypeerr
);
4866 /* Ok now since we implement both ZADD and ZINCRBY here the code
4867 * needs to handle the two different conditions. It's all about setting
4868 * '*score', that is, the new score to set, to the right value. */
4869 score
= zmalloc(sizeof(double));
4873 /* Read the old score. If the element was not present starts from 0 */
4874 de
= dictFind(zs
->dict
,ele
);
4876 double *oldscore
= dictGetEntryVal(de
);
4877 *score
= *oldscore
+ scoreval
;
4885 /* What follows is a simple remove and re-insert operation that is common
4886 * to both ZADD and ZINCRBY... */
4887 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
4888 /* case 1: New element */
4889 incrRefCount(ele
); /* added to hash */
4890 zslInsert(zs
->zsl
,*score
,ele
);
4891 incrRefCount(ele
); /* added to skiplist */
4894 addReplyDouble(c
,*score
);
4896 addReply(c
,shared
.cone
);
4901 /* case 2: Score update operation */
4902 de
= dictFind(zs
->dict
,ele
);
4903 redisAssert(de
!= NULL
);
4904 oldscore
= dictGetEntryVal(de
);
4905 if (*score
!= *oldscore
) {
4908 /* Remove and insert the element in the skip list with new score */
4909 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
4910 redisAssert(deleted
!= 0);
4911 zslInsert(zs
->zsl
,*score
,ele
);
4913 /* Update the score in the hash table */
4914 dictReplace(zs
->dict
,ele
,score
);
4920 addReplyDouble(c
,*score
);
4922 addReply(c
,shared
.czero
);
4926 static void zaddCommand(redisClient
*c
) {
4929 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4930 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
4933 static void zincrbyCommand(redisClient
*c
) {
4936 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4937 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
4940 static void zremCommand(redisClient
*c
) {
4944 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4945 if (zsetobj
== NULL
) {
4946 addReply(c
,shared
.czero
);
4952 if (zsetobj
->type
!= REDIS_ZSET
) {
4953 addReply(c
,shared
.wrongtypeerr
);
4957 de
= dictFind(zs
->dict
,c
->argv
[2]);
4959 addReply(c
,shared
.czero
);
4962 /* Delete from the skiplist */
4963 oldscore
= dictGetEntryVal(de
);
4964 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
4965 redisAssert(deleted
!= 0);
4967 /* Delete from the hash table */
4968 dictDelete(zs
->dict
,c
->argv
[2]);
4969 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4971 addReply(c
,shared
.cone
);
4975 static void zremrangebyscoreCommand(redisClient
*c
) {
4976 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4977 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4981 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4982 if (zsetobj
== NULL
) {
4983 addReply(c
,shared
.czero
);
4987 if (zsetobj
->type
!= REDIS_ZSET
) {
4988 addReply(c
,shared
.wrongtypeerr
);
4992 deleted
= zslDeleteRange(zs
->zsl
,min
,max
,zs
->dict
);
4993 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4994 server
.dirty
+= deleted
;
4995 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
4999 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
5001 int start
= atoi(c
->argv
[2]->ptr
);
5002 int end
= atoi(c
->argv
[3]->ptr
);
5005 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
5007 } else if (c
->argc
>= 5) {
5008 addReply(c
,shared
.syntaxerr
);
5012 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5014 addReply(c
,shared
.nullmultibulk
);
5016 if (o
->type
!= REDIS_ZSET
) {
5017 addReply(c
,shared
.wrongtypeerr
);
5019 zset
*zsetobj
= o
->ptr
;
5020 zskiplist
*zsl
= zsetobj
->zsl
;
5023 int llen
= zsl
->length
;
5027 /* convert negative indexes */
5028 if (start
< 0) start
= llen
+start
;
5029 if (end
< 0) end
= llen
+end
;
5030 if (start
< 0) start
= 0;
5031 if (end
< 0) end
= 0;
5033 /* indexes sanity checks */
5034 if (start
> end
|| start
>= llen
) {
5035 /* Out of range start or start > end result in empty list */
5036 addReply(c
,shared
.emptymultibulk
);
5039 if (end
>= llen
) end
= llen
-1;
5040 rangelen
= (end
-start
)+1;
5042 /* Return the result in form of a multi-bulk reply */
5048 ln
= zsl
->header
->forward
[0];
5050 ln
= ln
->forward
[0];
5053 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
5054 withscores
? (rangelen
*2) : rangelen
));
5055 for (j
= 0; j
< rangelen
; j
++) {
5057 addReplyBulkLen(c
,ele
);
5059 addReply(c
,shared
.crlf
);
5061 addReplyDouble(c
,ln
->score
);
5062 ln
= reverse
? ln
->backward
: ln
->forward
[0];
5068 static void zrangeCommand(redisClient
*c
) {
5069 zrangeGenericCommand(c
,0);
5072 static void zrevrangeCommand(redisClient
*c
) {
5073 zrangeGenericCommand(c
,1);
5076 static void zrangebyscoreCommand(redisClient
*c
) {
5078 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
5079 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
5080 int offset
= 0, limit
= -1;
5082 if (c
->argc
!= 4 && c
->argc
!= 7) {
5084 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5086 } else if (c
->argc
== 7 && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
5087 addReply(c
,shared
.syntaxerr
);
5089 } else if (c
->argc
== 7) {
5090 offset
= atoi(c
->argv
[5]->ptr
);
5091 limit
= atoi(c
->argv
[6]->ptr
);
5092 if (offset
< 0) offset
= 0;
5095 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5097 addReply(c
,shared
.nullmultibulk
);
5099 if (o
->type
!= REDIS_ZSET
) {
5100 addReply(c
,shared
.wrongtypeerr
);
5102 zset
*zsetobj
= o
->ptr
;
5103 zskiplist
*zsl
= zsetobj
->zsl
;
5106 unsigned int rangelen
= 0;
5108 /* Get the first node with the score >= min */
5109 ln
= zslFirstWithScore(zsl
,min
);
5111 /* No element matching the speciifed interval */
5112 addReply(c
,shared
.emptymultibulk
);
5116 /* We don't know in advance how many matching elements there
5117 * are in the list, so we push this object that will represent
5118 * the multi-bulk length in the output buffer, and will "fix"
5120 lenobj
= createObject(REDIS_STRING
,NULL
);
5122 decrRefCount(lenobj
);
5124 while(ln
&& ln
->score
<= max
) {
5127 ln
= ln
->forward
[0];
5130 if (limit
== 0) break;
5132 addReplyBulkLen(c
,ele
);
5134 addReply(c
,shared
.crlf
);
5135 ln
= ln
->forward
[0];
5137 if (limit
> 0) limit
--;
5139 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",rangelen
);
5144 static void zcardCommand(redisClient
*c
) {
5148 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5150 addReply(c
,shared
.czero
);
5153 if (o
->type
!= REDIS_ZSET
) {
5154 addReply(c
,shared
.wrongtypeerr
);
5157 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
5162 static void zscoreCommand(redisClient
*c
) {
5166 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5168 addReply(c
,shared
.nullbulk
);
5171 if (o
->type
!= REDIS_ZSET
) {
5172 addReply(c
,shared
.wrongtypeerr
);
5177 de
= dictFind(zs
->dict
,c
->argv
[2]);
5179 addReply(c
,shared
.nullbulk
);
5181 double *score
= dictGetEntryVal(de
);
5183 addReplyDouble(c
,*score
);
5189 /* ========================= Non type-specific commands ==================== */
5191 static void flushdbCommand(redisClient
*c
) {
5192 server
.dirty
+= dictSize(c
->db
->dict
);
5193 dictEmpty(c
->db
->dict
);
5194 dictEmpty(c
->db
->expires
);
5195 addReply(c
,shared
.ok
);
5198 static void flushallCommand(redisClient
*c
) {
5199 server
.dirty
+= emptyDb();
5200 addReply(c
,shared
.ok
);
5201 rdbSave(server
.dbfilename
);
5205 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
5206 redisSortOperation
*so
= zmalloc(sizeof(*so
));
5208 so
->pattern
= pattern
;
5212 /* Return the value associated to the key with a name obtained
5213 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5214 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
5218 int prefixlen
, sublen
, postfixlen
;
5219 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5223 char buf
[REDIS_SORTKEY_MAX
+1];
5226 /* If the pattern is "#" return the substitution object itself in order
5227 * to implement the "SORT ... GET #" feature. */
5228 spat
= pattern
->ptr
;
5229 if (spat
[0] == '#' && spat
[1] == '\0') {
5233 /* The substitution object may be specially encoded. If so we create
5234 * a decoded object on the fly. Otherwise getDecodedObject will just
5235 * increment the ref count, that we'll decrement later. */
5236 subst
= getDecodedObject(subst
);
5239 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
5240 p
= strchr(spat
,'*');
5242 decrRefCount(subst
);
5247 sublen
= sdslen(ssub
);
5248 postfixlen
= sdslen(spat
)-(prefixlen
+1);
5249 memcpy(keyname
.buf
,spat
,prefixlen
);
5250 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
5251 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
5252 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
5253 keyname
.len
= prefixlen
+sublen
+postfixlen
;
5255 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
5256 decrRefCount(subst
);
5258 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5259 return lookupKeyRead(db
,&keyobj
);
5262 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5263 * the additional parameter is not standard but a BSD-specific we have to
5264 * pass sorting parameters via the global 'server' structure */
5265 static int sortCompare(const void *s1
, const void *s2
) {
5266 const redisSortObject
*so1
= s1
, *so2
= s2
;
5269 if (!server
.sort_alpha
) {
5270 /* Numeric sorting. Here it's trivial as we precomputed scores */
5271 if (so1
->u
.score
> so2
->u
.score
) {
5273 } else if (so1
->u
.score
< so2
->u
.score
) {
5279 /* Alphanumeric sorting */
5280 if (server
.sort_bypattern
) {
5281 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
5282 /* At least one compare object is NULL */
5283 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
5285 else if (so1
->u
.cmpobj
== NULL
)
5290 /* We have both the objects, use strcoll */
5291 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
5294 /* Compare elements directly */
5297 dec1
= getDecodedObject(so1
->obj
);
5298 dec2
= getDecodedObject(so2
->obj
);
5299 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
5304 return server
.sort_desc
? -cmp
: cmp
;
5307 /* The SORT command is the most complex command in Redis. Warning: this code
5308 * is optimized for speed and a bit less for readability */
5309 static void sortCommand(redisClient
*c
) {
5312 int desc
= 0, alpha
= 0;
5313 int limit_start
= 0, limit_count
= -1, start
, end
;
5314 int j
, dontsort
= 0, vectorlen
;
5315 int getop
= 0; /* GET operation counter */
5316 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
5317 redisSortObject
*vector
; /* Resulting vector to sort */
5319 /* Lookup the key to sort. It must be of the right types */
5320 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
5321 if (sortval
== NULL
) {
5322 addReply(c
,shared
.nullmultibulk
);
5325 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
5326 sortval
->type
!= REDIS_ZSET
)
5328 addReply(c
,shared
.wrongtypeerr
);
5332 /* Create a list of operations to perform for every sorted element.
5333 * Operations can be GET/DEL/INCR/DECR */
5334 operations
= listCreate();
5335 listSetFreeMethod(operations
,zfree
);
5338 /* Now we need to protect sortval incrementing its count, in the future
5339 * SORT may have options able to overwrite/delete keys during the sorting
5340 * and the sorted key itself may get destroied */
5341 incrRefCount(sortval
);
5343 /* The SORT command has an SQL-alike syntax, parse it */
5344 while(j
< c
->argc
) {
5345 int leftargs
= c
->argc
-j
-1;
5346 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
5348 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
5350 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
5352 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
5353 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
5354 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
5356 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
5357 storekey
= c
->argv
[j
+1];
5359 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
5360 sortby
= c
->argv
[j
+1];
5361 /* If the BY pattern does not contain '*', i.e. it is constant,
5362 * we don't need to sort nor to lookup the weight keys. */
5363 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
5365 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
5366 listAddNodeTail(operations
,createSortOperation(
5367 REDIS_SORT_GET
,c
->argv
[j
+1]));
5371 decrRefCount(sortval
);
5372 listRelease(operations
);
5373 addReply(c
,shared
.syntaxerr
);
5379 /* Load the sorting vector with all the objects to sort */
5380 switch(sortval
->type
) {
5381 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
5382 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
5383 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
5384 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
5386 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
5389 if (sortval
->type
== REDIS_LIST
) {
5390 list
*list
= sortval
->ptr
;
5394 listRewind(list
,&li
);
5395 while((ln
= listNext(&li
))) {
5396 robj
*ele
= ln
->value
;
5397 vector
[j
].obj
= ele
;
5398 vector
[j
].u
.score
= 0;
5399 vector
[j
].u
.cmpobj
= NULL
;
5407 if (sortval
->type
== REDIS_SET
) {
5410 zset
*zs
= sortval
->ptr
;
5414 di
= dictGetIterator(set
);
5415 while((setele
= dictNext(di
)) != NULL
) {
5416 vector
[j
].obj
= dictGetEntryKey(setele
);
5417 vector
[j
].u
.score
= 0;
5418 vector
[j
].u
.cmpobj
= NULL
;
5421 dictReleaseIterator(di
);
5423 redisAssert(j
== vectorlen
);
5425 /* Now it's time to load the right scores in the sorting vector */
5426 if (dontsort
== 0) {
5427 for (j
= 0; j
< vectorlen
; j
++) {
5431 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
5432 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
5434 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
5436 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
5437 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
5439 /* Don't need to decode the object if it's
5440 * integer-encoded (the only encoding supported) so
5441 * far. We can just cast it */
5442 if (byval
->encoding
== REDIS_ENCODING_INT
) {
5443 vector
[j
].u
.score
= (long)byval
->ptr
;
5445 redisAssert(1 != 1);
5450 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
5451 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
5453 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
5454 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
5456 redisAssert(1 != 1);
5463 /* We are ready to sort the vector... perform a bit of sanity check
5464 * on the LIMIT option too. We'll use a partial version of quicksort. */
5465 start
= (limit_start
< 0) ? 0 : limit_start
;
5466 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
5467 if (start
>= vectorlen
) {
5468 start
= vectorlen
-1;
5471 if (end
>= vectorlen
) end
= vectorlen
-1;
5473 if (dontsort
== 0) {
5474 server
.sort_desc
= desc
;
5475 server
.sort_alpha
= alpha
;
5476 server
.sort_bypattern
= sortby
? 1 : 0;
5477 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
5478 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
5480 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
5483 /* Send command output to the output buffer, performing the specified
5484 * GET/DEL/INCR/DECR operations if any. */
5485 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
5486 if (storekey
== NULL
) {
5487 /* STORE option not specified, sent the sorting result to client */
5488 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
5489 for (j
= start
; j
<= end
; j
++) {
5494 addReplyBulkLen(c
,vector
[j
].obj
);
5495 addReply(c
,vector
[j
].obj
);
5496 addReply(c
,shared
.crlf
);
5498 listRewind(operations
,&li
);
5499 while((ln
= listNext(&li
))) {
5500 redisSortOperation
*sop
= ln
->value
;
5501 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5504 if (sop
->type
== REDIS_SORT_GET
) {
5505 if (!val
|| val
->type
!= REDIS_STRING
) {
5506 addReply(c
,shared
.nullbulk
);
5508 addReplyBulkLen(c
,val
);
5510 addReply(c
,shared
.crlf
);
5513 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5518 robj
*listObject
= createListObject();
5519 list
*listPtr
= (list
*) listObject
->ptr
;
5521 /* STORE option specified, set the sorting result as a List object */
5522 for (j
= start
; j
<= end
; j
++) {
5527 listAddNodeTail(listPtr
,vector
[j
].obj
);
5528 incrRefCount(vector
[j
].obj
);
5530 listRewind(operations
,&li
);
5531 while((ln
= listNext(&li
))) {
5532 redisSortOperation
*sop
= ln
->value
;
5533 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5536 if (sop
->type
== REDIS_SORT_GET
) {
5537 if (!val
|| val
->type
!= REDIS_STRING
) {
5538 listAddNodeTail(listPtr
,createStringObject("",0));
5540 listAddNodeTail(listPtr
,val
);
5544 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5548 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
5549 incrRefCount(storekey
);
5551 /* Note: we add 1 because the DB is dirty anyway since even if the
5552 * SORT result is empty a new key is set and maybe the old content
5554 server
.dirty
+= 1+outputlen
;
5555 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
5559 decrRefCount(sortval
);
5560 listRelease(operations
);
5561 for (j
= 0; j
< vectorlen
; j
++) {
5562 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
5563 decrRefCount(vector
[j
].u
.cmpobj
);
5568 /* Convert an amount of bytes into a human readable string in the form
5569 * of 100B, 2G, 100M, 4K, and so forth. */
5570 static void bytesToHuman(char *s
, unsigned long long n
) {
5575 sprintf(s
,"%lluB",n
);
5577 } else if (n
< (1024*1024)) {
5578 d
= (double)n
/(1024);
5579 sprintf(s
,"%.2fK",d
);
5580 } else if (n
< (1024LL*1024*1024)) {
5581 d
= (double)n
/(1024*1024);
5582 sprintf(s
,"%.2fM",d
);
5583 } else if (n
< (1024LL*1024*1024*1024)) {
5584 d
= (double)n
/(1024LL*1024*1024);
5585 sprintf(s
,"%.2fM",d
);
5589 /* Create the string returned by the INFO command. This is decoupled
5590 * by the INFO command itself as we need to report the same information
5591 * on memory corruption problems. */
5592 static sds
genRedisInfoString(void) {
5594 time_t uptime
= time(NULL
)-server
.stat_starttime
;
5598 bytesToHuman(hmem
,server
.usedmemory
);
5599 info
= sdscatprintf(sdsempty(),
5600 "redis_version:%s\r\n"
5602 "multiplexing_api:%s\r\n"
5603 "process_id:%ld\r\n"
5604 "uptime_in_seconds:%ld\r\n"
5605 "uptime_in_days:%ld\r\n"
5606 "connected_clients:%d\r\n"
5607 "connected_slaves:%d\r\n"
5608 "blocked_clients:%d\r\n"
5609 "used_memory:%zu\r\n"
5610 "used_memory_human:%s\r\n"
5611 "changes_since_last_save:%lld\r\n"
5612 "bgsave_in_progress:%d\r\n"
5613 "last_save_time:%ld\r\n"
5614 "bgrewriteaof_in_progress:%d\r\n"
5615 "total_connections_received:%lld\r\n"
5616 "total_commands_processed:%lld\r\n"
5620 (sizeof(long) == 8) ? "64" : "32",
5625 listLength(server
.clients
)-listLength(server
.slaves
),
5626 listLength(server
.slaves
),
5627 server
.blockedclients
,
5631 server
.bgsavechildpid
!= -1,
5633 server
.bgrewritechildpid
!= -1,
5634 server
.stat_numconnections
,
5635 server
.stat_numcommands
,
5636 server
.vm_enabled
!= 0,
5637 server
.masterhost
== NULL
? "master" : "slave"
5639 if (server
.masterhost
) {
5640 info
= sdscatprintf(info
,
5641 "master_host:%s\r\n"
5642 "master_port:%d\r\n"
5643 "master_link_status:%s\r\n"
5644 "master_last_io_seconds_ago:%d\r\n"
5647 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
5649 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
5652 if (server
.vm_enabled
) {
5654 info
= sdscatprintf(info
,
5655 "vm_conf_max_memory:%llu\r\n"
5656 "vm_conf_page_size:%llu\r\n"
5657 "vm_conf_pages:%llu\r\n"
5658 "vm_stats_used_pages:%llu\r\n"
5659 "vm_stats_swapped_objects:%llu\r\n"
5660 "vm_stats_swappin_count:%llu\r\n"
5661 "vm_stats_swappout_count:%llu\r\n"
5662 "vm_stats_io_newjobs_len:%lu\r\n"
5663 "vm_stats_io_processing_len:%lu\r\n"
5664 "vm_stats_io_processed_len:%lu\r\n"
5665 "vm_stats_io_waiting_clients:%lu\r\n"
5666 "vm_stats_io_active_threads:%lu\r\n"
5667 ,(unsigned long long) server
.vm_max_memory
,
5668 (unsigned long long) server
.vm_page_size
,
5669 (unsigned long long) server
.vm_pages
,
5670 (unsigned long long) server
.vm_stats_used_pages
,
5671 (unsigned long long) server
.vm_stats_swapped_objects
,
5672 (unsigned long long) server
.vm_stats_swapins
,
5673 (unsigned long long) server
.vm_stats_swapouts
,
5674 (unsigned long) listLength(server
.io_newjobs
),
5675 (unsigned long) listLength(server
.io_processing
),
5676 (unsigned long) listLength(server
.io_processed
),
5677 (unsigned long) listLength(server
.io_clients
),
5678 (unsigned long) server
.io_active_threads
5682 for (j
= 0; j
< server
.dbnum
; j
++) {
5683 long long keys
, vkeys
;
5685 keys
= dictSize(server
.db
[j
].dict
);
5686 vkeys
= dictSize(server
.db
[j
].expires
);
5687 if (keys
|| vkeys
) {
5688 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
5695 static void infoCommand(redisClient
*c
) {
5696 sds info
= genRedisInfoString();
5697 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
5698 (unsigned long)sdslen(info
)));
5699 addReplySds(c
,info
);
5700 addReply(c
,shared
.crlf
);
5703 static void monitorCommand(redisClient
*c
) {
5704 /* ignore MONITOR if aleady slave or in monitor mode */
5705 if (c
->flags
& REDIS_SLAVE
) return;
5707 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
5709 listAddNodeTail(server
.monitors
,c
);
5710 addReply(c
,shared
.ok
);
5713 /* ================================= Expire ================================= */
5714 static int removeExpire(redisDb
*db
, robj
*key
) {
5715 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
5722 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
5723 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
5731 /* Return the expire time of the specified key, or -1 if no expire
5732 * is associated with this key (i.e. the key is non volatile) */
5733 static time_t getExpire(redisDb
*db
, robj
*key
) {
5736 /* No expire? return ASAP */
5737 if (dictSize(db
->expires
) == 0 ||
5738 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
5740 return (time_t) dictGetEntryVal(de
);
5743 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
5747 /* No expire? return ASAP */
5748 if (dictSize(db
->expires
) == 0 ||
5749 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5751 /* Lookup the expire */
5752 when
= (time_t) dictGetEntryVal(de
);
5753 if (time(NULL
) <= when
) return 0;
5755 /* Delete the key */
5756 dictDelete(db
->expires
,key
);
5757 return dictDelete(db
->dict
,key
) == DICT_OK
;
5760 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
5763 /* No expire? return ASAP */
5764 if (dictSize(db
->expires
) == 0 ||
5765 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5767 /* Delete the key */
5769 dictDelete(db
->expires
,key
);
5770 return dictDelete(db
->dict
,key
) == DICT_OK
;
5773 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
5776 de
= dictFind(c
->db
->dict
,key
);
5778 addReply(c
,shared
.czero
);
5782 if (deleteKey(c
->db
,key
)) server
.dirty
++;
5783 addReply(c
, shared
.cone
);
5786 time_t when
= time(NULL
)+seconds
;
5787 if (setExpire(c
->db
,key
,when
)) {
5788 addReply(c
,shared
.cone
);
5791 addReply(c
,shared
.czero
);
5797 static void expireCommand(redisClient
*c
) {
5798 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
5801 static void expireatCommand(redisClient
*c
) {
5802 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
5805 static void ttlCommand(redisClient
*c
) {
5809 expire
= getExpire(c
->db
,c
->argv
[1]);
5811 ttl
= (int) (expire
-time(NULL
));
5812 if (ttl
< 0) ttl
= -1;
5814 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
5817 /* ================================ MULTI/EXEC ============================== */
5819 /* Client state initialization for MULTI/EXEC */
5820 static void initClientMultiState(redisClient
*c
) {
5821 c
->mstate
.commands
= NULL
;
5822 c
->mstate
.count
= 0;
5825 /* Release all the resources associated with MULTI/EXEC state */
5826 static void freeClientMultiState(redisClient
*c
) {
5829 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5831 multiCmd
*mc
= c
->mstate
.commands
+j
;
5833 for (i
= 0; i
< mc
->argc
; i
++)
5834 decrRefCount(mc
->argv
[i
]);
5837 zfree(c
->mstate
.commands
);
5840 /* Add a new command into the MULTI commands queue */
5841 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
5845 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
5846 sizeof(multiCmd
)*(c
->mstate
.count
+1));
5847 mc
= c
->mstate
.commands
+c
->mstate
.count
;
5850 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
5851 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
5852 for (j
= 0; j
< c
->argc
; j
++)
5853 incrRefCount(mc
->argv
[j
]);
5857 static void multiCommand(redisClient
*c
) {
5858 c
->flags
|= REDIS_MULTI
;
5859 addReply(c
,shared
.ok
);
5862 static void execCommand(redisClient
*c
) {
5867 if (!(c
->flags
& REDIS_MULTI
)) {
5868 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
5872 orig_argv
= c
->argv
;
5873 orig_argc
= c
->argc
;
5874 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
5875 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5876 c
->argc
= c
->mstate
.commands
[j
].argc
;
5877 c
->argv
= c
->mstate
.commands
[j
].argv
;
5878 call(c
,c
->mstate
.commands
[j
].cmd
);
5880 c
->argv
= orig_argv
;
5881 c
->argc
= orig_argc
;
5882 freeClientMultiState(c
);
5883 initClientMultiState(c
);
5884 c
->flags
&= (~REDIS_MULTI
);
5887 /* =========================== Blocking Operations ========================= */
5889 /* Currently Redis blocking operations support is limited to list POP ops,
5890 * so the current implementation is not fully generic, but it is also not
5891 * completely specific so it will not require a rewrite to support new
5892 * kind of blocking operations in the future.
5894 * Still it's important to note that list blocking operations can be already
5895 * used as a notification mechanism in order to implement other blocking
5896 * operations at application level, so there must be a very strong evidence
5897 * of usefulness and generality before new blocking operations are implemented.
5899 * This is how the current blocking POP works, we use BLPOP as example:
5900 * - If the user calls BLPOP and the key exists and contains a non empty list
5901 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5902 * if there is not to block.
5903 * - If instead BLPOP is called and the key does not exists or the list is
5904 * empty we need to block. In order to do so we remove the notification for
5905 * new data to read in the client socket (so that we'll not serve new
5906 * requests if the blocking request is not served). Also we put the client
5907 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
5908 * blocking for this keys.
5909 * - If a PUSH operation against a key with blocked clients waiting is
5910 * performed, we serve the first in the list: basically instead to push
5911 * the new element inside the list we return it to the (first / oldest)
5912 * blocking client, unblock the client, and remove it form the list.
5914 * The above comment and the source code should be enough in order to understand
5915 * the implementation and modify / fix it later.
5918 /* Set a client in blocking mode for the specified key, with the specified
5920 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
5925 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
5926 c
->blockingkeysnum
= numkeys
;
5927 c
->blockingto
= timeout
;
5928 for (j
= 0; j
< numkeys
; j
++) {
5929 /* Add the key in the client structure, to map clients -> keys */
5930 c
->blockingkeys
[j
] = keys
[j
];
5931 incrRefCount(keys
[j
]);
5933 /* And in the other "side", to map keys -> clients */
5934 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
5938 /* For every key we take a list of clients blocked for it */
5940 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
5941 incrRefCount(keys
[j
]);
5942 assert(retval
== DICT_OK
);
5944 l
= dictGetEntryVal(de
);
5946 listAddNodeTail(l
,c
);
5948 /* Mark the client as a blocked client */
5949 c
->flags
|= REDIS_BLOCKED
;
5950 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
5951 server
.blockedclients
++;
5954 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
5955 static void unblockClient(redisClient
*c
) {
5960 assert(c
->blockingkeys
!= NULL
);
5961 /* The client may wait for multiple keys, so unblock it for every key. */
5962 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
5963 /* Remove this client from the list of clients waiting for this key. */
5964 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5966 l
= dictGetEntryVal(de
);
5967 listDelNode(l
,listSearchKey(l
,c
));
5968 /* If the list is empty we need to remove it to avoid wasting memory */
5969 if (listLength(l
) == 0)
5970 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5971 decrRefCount(c
->blockingkeys
[j
]);
5973 /* Cleanup the client structure */
5974 zfree(c
->blockingkeys
);
5975 c
->blockingkeys
= NULL
;
5976 c
->flags
&= (~REDIS_BLOCKED
);
5977 server
.blockedclients
--;
5978 /* Ok now we are ready to get read events from socket, note that we
5979 * can't trap errors here as it's possible that unblockClients() is
5980 * called from freeClient() itself, and the only thing we can do
5981 * if we failed to register the READABLE event is to kill the client.
5982 * Still the following function should never fail in the real world as
5983 * we are sure the file descriptor is sane, and we exit on out of mem. */
5984 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, readQueryFromClient
, c
);
5985 /* As a final step we want to process data if there is some command waiting
5986 * in the input buffer. Note that this is safe even if unblockClient()
5987 * gets called from freeClient() because freeClient() will be smart
5988 * enough to call this function *after* c->querybuf was set to NULL. */
5989 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
5992 /* This should be called from any function PUSHing into lists.
5993 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5994 * 'ele' is the element pushed.
5996 * If the function returns 0 there was no client waiting for a list push
5999 * If the function returns 1 there was a client waiting for a list push
6000 * against this key, the element was passed to this client thus it's not
6001 * needed to actually add it to the list and the caller should return asap. */
6002 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
6003 struct dictEntry
*de
;
6004 redisClient
*receiver
;
6008 de
= dictFind(c
->db
->blockingkeys
,key
);
6009 if (de
== NULL
) return 0;
6010 l
= dictGetEntryVal(de
);
6013 receiver
= ln
->value
;
6015 addReplySds(receiver
,sdsnew("*2\r\n"));
6016 addReplyBulkLen(receiver
,key
);
6017 addReply(receiver
,key
);
6018 addReply(receiver
,shared
.crlf
);
6019 addReplyBulkLen(receiver
,ele
);
6020 addReply(receiver
,ele
);
6021 addReply(receiver
,shared
.crlf
);
6022 unblockClient(receiver
);
6026 /* Blocking RPOP/LPOP */
6027 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
6032 for (j
= 1; j
< c
->argc
-1; j
++) {
6033 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
6035 if (o
->type
!= REDIS_LIST
) {
6036 addReply(c
,shared
.wrongtypeerr
);
6039 list
*list
= o
->ptr
;
6040 if (listLength(list
) != 0) {
6041 /* If the list contains elements fall back to the usual
6042 * non-blocking POP operation */
6043 robj
*argv
[2], **orig_argv
;
6046 /* We need to alter the command arguments before to call
6047 * popGenericCommand() as the command takes a single key. */
6048 orig_argv
= c
->argv
;
6049 orig_argc
= c
->argc
;
6050 argv
[1] = c
->argv
[j
];
6054 /* Also the return value is different, we need to output
6055 * the multi bulk reply header and the key name. The
6056 * "real" command will add the last element (the value)
6057 * for us. If this souds like an hack to you it's just
6058 * because it is... */
6059 addReplySds(c
,sdsnew("*2\r\n"));
6060 addReplyBulkLen(c
,argv
[1]);
6061 addReply(c
,argv
[1]);
6062 addReply(c
,shared
.crlf
);
6063 popGenericCommand(c
,where
);
6065 /* Fix the client structure with the original stuff */
6066 c
->argv
= orig_argv
;
6067 c
->argc
= orig_argc
;
6073 /* If the list is empty or the key does not exists we must block */
6074 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
6075 if (timeout
> 0) timeout
+= time(NULL
);
6076 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
6079 static void blpopCommand(redisClient
*c
) {
6080 blockingPopGenericCommand(c
,REDIS_HEAD
);
6083 static void brpopCommand(redisClient
*c
) {
6084 blockingPopGenericCommand(c
,REDIS_TAIL
);
6087 /* =============================== Replication ============================= */
6089 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6090 ssize_t nwritten
, ret
= size
;
6091 time_t start
= time(NULL
);
6095 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
6096 nwritten
= write(fd
,ptr
,size
);
6097 if (nwritten
== -1) return -1;
6101 if ((time(NULL
)-start
) > timeout
) {
6109 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6110 ssize_t nread
, totread
= 0;
6111 time_t start
= time(NULL
);
6115 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
6116 nread
= read(fd
,ptr
,size
);
6117 if (nread
== -1) return -1;
6122 if ((time(NULL
)-start
) > timeout
) {
6130 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6137 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
6140 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
6151 static void syncCommand(redisClient
*c
) {
6152 /* ignore SYNC if aleady slave or in monitor mode */
6153 if (c
->flags
& REDIS_SLAVE
) return;
6155 /* SYNC can't be issued when the server has pending data to send to
6156 * the client about already issued commands. We need a fresh reply
6157 * buffer registering the differences between the BGSAVE and the current
6158 * dataset, so that we can copy to other slaves if needed. */
6159 if (listLength(c
->reply
) != 0) {
6160 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
6164 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
6165 /* Here we need to check if there is a background saving operation
6166 * in progress, or if it is required to start one */
6167 if (server
.bgsavechildpid
!= -1) {
6168 /* Ok a background save is in progress. Let's check if it is a good
6169 * one for replication, i.e. if there is another slave that is
6170 * registering differences since the server forked to save */
6175 listRewind(server
.slaves
,&li
);
6176 while((ln
= listNext(&li
))) {
6178 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
6181 /* Perfect, the server is already registering differences for
6182 * another slave. Set the right state, and copy the buffer. */
6183 listRelease(c
->reply
);
6184 c
->reply
= listDup(slave
->reply
);
6185 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6186 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
6188 /* No way, we need to wait for the next BGSAVE in order to
6189 * register differences */
6190 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6191 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
6194 /* Ok we don't have a BGSAVE in progress, let's start one */
6195 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
6196 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6197 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
6198 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
6201 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6204 c
->flags
|= REDIS_SLAVE
;
6206 listAddNodeTail(server
.slaves
,c
);
6210 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
6211 redisClient
*slave
= privdata
;
6213 REDIS_NOTUSED(mask
);
6214 char buf
[REDIS_IOBUF_LEN
];
6215 ssize_t nwritten
, buflen
;
6217 if (slave
->repldboff
== 0) {
6218 /* Write the bulk write count before to transfer the DB. In theory here
6219 * we don't know how much room there is in the output buffer of the
6220 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
6221 * operations) will never be smaller than the few bytes we need. */
6224 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
6226 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
6234 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
6235 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
6237 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
6238 (buflen
== 0) ? "premature EOF" : strerror(errno
));
6242 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
6243 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
6248 slave
->repldboff
+= nwritten
;
6249 if (slave
->repldboff
== slave
->repldbsize
) {
6250 close(slave
->repldbfd
);
6251 slave
->repldbfd
= -1;
6252 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6253 slave
->replstate
= REDIS_REPL_ONLINE
;
6254 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
6255 sendReplyToClient
, slave
) == AE_ERR
) {
6259 addReplySds(slave
,sdsempty());
6260 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
6264 /* This function is called at the end of every backgrond saving.
6265 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
6266 * otherwise REDIS_ERR is passed to the function.
6268 * The goal of this function is to handle slaves waiting for a successful
6269 * background saving in order to perform non-blocking synchronization. */
6270 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
6272 int startbgsave
= 0;
6275 listRewind(server
.slaves
,&li
);
6276 while((ln
= listNext(&li
))) {
6277 redisClient
*slave
= ln
->value
;
6279 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
6281 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6282 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
6283 struct redis_stat buf
;
6285 if (bgsaveerr
!= REDIS_OK
) {
6287 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
6290 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
6291 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
6293 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
6296 slave
->repldboff
= 0;
6297 slave
->repldbsize
= buf
.st_size
;
6298 slave
->replstate
= REDIS_REPL_SEND_BULK
;
6299 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6300 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
6307 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6310 listRewind(server
.slaves
,&li
);
6311 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
6312 while((ln
= listNext(&li
))) {
6313 redisClient
*slave
= ln
->value
;
6315 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
6322 static int syncWithMaster(void) {
6323 char buf
[1024], tmpfile
[256], authcmd
[1024];
6325 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
6329 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
6334 /* AUTH with the master if required. */
6335 if(server
.masterauth
) {
6336 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
6337 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
6339 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
6343 /* Read the AUTH result. */
6344 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6346 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
6350 if (buf
[0] != '+') {
6352 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
6357 /* Issue the SYNC command */
6358 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
6360 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
6364 /* Read the bulk write count */
6365 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6367 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
6371 if (buf
[0] != '$') {
6373 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6376 dumpsize
= atoi(buf
+1);
6377 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
6378 /* Read the bulk write data on a temp file */
6379 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
6380 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
6383 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
6387 int nread
, nwritten
;
6389 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
6391 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
6397 nwritten
= write(dfd
,buf
,nread
);
6398 if (nwritten
== -1) {
6399 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
6407 if (rename(tmpfile
,server
.dbfilename
) == -1) {
6408 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
6414 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6415 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
6419 server
.master
= createClient(fd
);
6420 server
.master
->flags
|= REDIS_MASTER
;
6421 server
.master
->authenticated
= 1;
6422 server
.replstate
= REDIS_REPL_CONNECTED
;
6426 static void slaveofCommand(redisClient
*c
) {
6427 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
6428 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
6429 if (server
.masterhost
) {
6430 sdsfree(server
.masterhost
);
6431 server
.masterhost
= NULL
;
6432 if (server
.master
) freeClient(server
.master
);
6433 server
.replstate
= REDIS_REPL_NONE
;
6434 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
6437 sdsfree(server
.masterhost
);
6438 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
6439 server
.masterport
= atoi(c
->argv
[2]->ptr
);
6440 if (server
.master
) freeClient(server
.master
);
6441 server
.replstate
= REDIS_REPL_CONNECT
;
6442 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
6443 server
.masterhost
, server
.masterport
);
6445 addReply(c
,shared
.ok
);
6448 /* ============================ Maxmemory directive ======================== */
6450 /* Try to free one object form the pre-allocated objects free list.
6451 * This is useful under low mem conditions as by default we take 1 million
6452 * free objects allocated. On success REDIS_OK is returned, otherwise
6454 static int tryFreeOneObjectFromFreelist(void) {
6457 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
6458 if (listLength(server
.objfreelist
)) {
6459 listNode
*head
= listFirst(server
.objfreelist
);
6460 o
= listNodeValue(head
);
6461 listDelNode(server
.objfreelist
,head
);
6462 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6466 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6471 /* This function gets called when 'maxmemory' is set on the config file to limit
6472 * the max memory used by the server, and we are out of memory.
6473 * This function will try to, in order:
6475 * - Free objects from the free list
6476 * - Try to remove keys with an EXPIRE set
6478 * It is not possible to free enough memory to reach used-memory < maxmemory
6479 * the server will start refusing commands that will enlarge even more the
6482 static void freeMemoryIfNeeded(void) {
6483 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
6484 int j
, k
, freed
= 0;
6486 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
6487 for (j
= 0; j
< server
.dbnum
; j
++) {
6489 robj
*minkey
= NULL
;
6490 struct dictEntry
*de
;
6492 if (dictSize(server
.db
[j
].expires
)) {
6494 /* From a sample of three keys drop the one nearest to
6495 * the natural expire */
6496 for (k
= 0; k
< 3; k
++) {
6499 de
= dictGetRandomKey(server
.db
[j
].expires
);
6500 t
= (time_t) dictGetEntryVal(de
);
6501 if (minttl
== -1 || t
< minttl
) {
6502 minkey
= dictGetEntryKey(de
);
6506 deleteKey(server
.db
+j
,minkey
);
6509 if (!freed
) return; /* nothing to free... */
6513 /* ============================== Append Only file ========================== */
6515 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
6516 sds buf
= sdsempty();
6522 /* The DB this command was targetting is not the same as the last command
6523 * we appendend. To issue a SELECT command is needed. */
6524 if (dictid
!= server
.appendseldb
) {
6527 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
6528 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
6529 (unsigned long)strlen(seldb
),seldb
);
6530 server
.appendseldb
= dictid
;
6533 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6534 * EXPIREs into EXPIREATs calls */
6535 if (cmd
->proc
== expireCommand
) {
6538 tmpargv
[0] = createStringObject("EXPIREAT",8);
6539 tmpargv
[1] = argv
[1];
6540 incrRefCount(argv
[1]);
6541 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
6542 tmpargv
[2] = createObject(REDIS_STRING
,
6543 sdscatprintf(sdsempty(),"%ld",when
));
6547 /* Append the actual command */
6548 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
6549 for (j
= 0; j
< argc
; j
++) {
6552 o
= getDecodedObject(o
);
6553 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
6554 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
6555 buf
= sdscatlen(buf
,"\r\n",2);
6559 /* Free the objects from the modified argv for EXPIREAT */
6560 if (cmd
->proc
== expireCommand
) {
6561 for (j
= 0; j
< 3; j
++)
6562 decrRefCount(argv
[j
]);
6565 /* We want to perform a single write. This should be guaranteed atomic
6566 * at least if the filesystem we are writing is a real physical one.
6567 * While this will save us against the server being killed I don't think
6568 * there is much to do about the whole server stopping for power problems
6570 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
6571 if (nwritten
!= (signed)sdslen(buf
)) {
6572 /* Ooops, we are in troubles. The best thing to do for now is
6573 * to simply exit instead to give the illusion that everything is
6574 * working as expected. */
6575 if (nwritten
== -1) {
6576 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
6578 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
6582 /* If a background append only file rewriting is in progress we want to
6583 * accumulate the differences between the child DB and the current one
6584 * in a buffer, so that when the child process will do its work we
6585 * can append the differences to the new append only file. */
6586 if (server
.bgrewritechildpid
!= -1)
6587 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
6591 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
6592 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
6593 now
-server
.lastfsync
> 1))
6595 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
6596 server
.lastfsync
= now
;
6600 /* In Redis commands are always executed in the context of a client, so in
6601 * order to load the append only file we need to create a fake client. */
6602 static struct redisClient
*createFakeClient(void) {
6603 struct redisClient
*c
= zmalloc(sizeof(*c
));
6607 c
->querybuf
= sdsempty();
6611 /* We set the fake client as a slave waiting for the synchronization
6612 * so that Redis will not try to send replies to this client. */
6613 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6614 c
->reply
= listCreate();
6615 listSetFreeMethod(c
->reply
,decrRefCount
);
6616 listSetDupMethod(c
->reply
,dupClientReplyValue
);
6620 static void freeFakeClient(struct redisClient
*c
) {
6621 sdsfree(c
->querybuf
);
6622 listRelease(c
->reply
);
6626 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
6627 * error (the append only file is zero-length) REDIS_ERR is returned. On
6628 * fatal error an error message is logged and the program exists. */
6629 int loadAppendOnlyFile(char *filename
) {
6630 struct redisClient
*fakeClient
;
6631 FILE *fp
= fopen(filename
,"r");
6632 struct redis_stat sb
;
6633 unsigned long long loadedkeys
= 0;
6635 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
6639 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
6643 fakeClient
= createFakeClient();
6650 struct redisCommand
*cmd
;
6652 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
6658 if (buf
[0] != '*') goto fmterr
;
6660 argv
= zmalloc(sizeof(robj
*)*argc
);
6661 for (j
= 0; j
< argc
; j
++) {
6662 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
6663 if (buf
[0] != '$') goto fmterr
;
6664 len
= strtol(buf
+1,NULL
,10);
6665 argsds
= sdsnewlen(NULL
,len
);
6666 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
6667 argv
[j
] = createObject(REDIS_STRING
,argsds
);
6668 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
6671 /* Command lookup */
6672 cmd
= lookupCommand(argv
[0]->ptr
);
6674 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
6677 /* Try object sharing and encoding */
6678 if (server
.shareobjects
) {
6680 for(j
= 1; j
< argc
; j
++)
6681 argv
[j
] = tryObjectSharing(argv
[j
]);
6683 if (cmd
->flags
& REDIS_CMD_BULK
)
6684 tryObjectEncoding(argv
[argc
-1]);
6685 /* Run the command in the context of a fake client */
6686 fakeClient
->argc
= argc
;
6687 fakeClient
->argv
= argv
;
6688 cmd
->proc(fakeClient
);
6689 /* Discard the reply objects list from the fake client */
6690 while(listLength(fakeClient
->reply
))
6691 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
6692 /* Clean up, ready for the next command */
6693 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
6695 /* Handle swapping while loading big datasets when VM is on */
6697 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
6698 while (zmalloc_used_memory() > server
.vm_max_memory
) {
6699 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
6704 freeFakeClient(fakeClient
);
6709 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
6711 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
6715 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
6719 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6720 static int fwriteBulk(FILE *fp
, robj
*obj
) {
6724 /* Avoid the incr/decr ref count business if possible to help
6725 * copy-on-write (we are often in a child process when this function
6727 * Also makes sure that key objects don't get incrRefCount-ed when VM
6729 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
6730 obj
= getDecodedObject(obj
);
6733 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
6734 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
6735 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
6737 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
6738 if (decrrc
) decrRefCount(obj
);
6741 if (decrrc
) decrRefCount(obj
);
6745 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6746 static int fwriteBulkDouble(FILE *fp
, double d
) {
6747 char buf
[128], dbuf
[128];
6749 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
6750 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
6751 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6752 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
6756 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6757 static int fwriteBulkLong(FILE *fp
, long l
) {
6758 char buf
[128], lbuf
[128];
6760 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
6761 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
6762 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6763 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
6767 /* Write a sequence of commands able to fully rebuild the dataset into
6768 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6769 static int rewriteAppendOnlyFile(char *filename
) {
6770 dictIterator
*di
= NULL
;
6775 time_t now
= time(NULL
);
6777 /* Note that we have to use a different temp name here compared to the
6778 * one used by rewriteAppendOnlyFileBackground() function. */
6779 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
6780 fp
= fopen(tmpfile
,"w");
6782 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
6785 for (j
= 0; j
< server
.dbnum
; j
++) {
6786 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
6787 redisDb
*db
= server
.db
+j
;
6789 if (dictSize(d
) == 0) continue;
6790 di
= dictGetIterator(d
);
6796 /* SELECT the new DB */
6797 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
6798 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
6800 /* Iterate this DB writing every entry */
6801 while((de
= dictNext(di
)) != NULL
) {
6806 key
= dictGetEntryKey(de
);
6807 /* If the value for this key is swapped, load a preview in memory.
6808 * We use a "swapped" flag to remember if we need to free the
6809 * value object instead to just increment the ref count anyway
6810 * in order to avoid copy-on-write of pages if we are forked() */
6811 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
6812 key
->storage
== REDIS_VM_SWAPPING
) {
6813 o
= dictGetEntryVal(de
);
6816 o
= vmPreviewObject(key
);
6819 expiretime
= getExpire(db
,key
);
6821 /* Save the key and associated value */
6822 if (o
->type
== REDIS_STRING
) {
6823 /* Emit a SET command */
6824 char cmd
[]="*3\r\n$3\r\nSET\r\n";
6825 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6827 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6828 if (fwriteBulk(fp
,o
) == 0) goto werr
;
6829 } else if (o
->type
== REDIS_LIST
) {
6830 /* Emit the RPUSHes needed to rebuild the list */
6831 list
*list
= o
->ptr
;
6835 listRewind(list
,&li
);
6836 while((ln
= listNext(&li
))) {
6837 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
6838 robj
*eleobj
= listNodeValue(ln
);
6840 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6841 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6842 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6844 } else if (o
->type
== REDIS_SET
) {
6845 /* Emit the SADDs needed to rebuild the set */
6847 dictIterator
*di
= dictGetIterator(set
);
6850 while((de
= dictNext(di
)) != NULL
) {
6851 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
6852 robj
*eleobj
= dictGetEntryKey(de
);
6854 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6855 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6856 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6858 dictReleaseIterator(di
);
6859 } else if (o
->type
== REDIS_ZSET
) {
6860 /* Emit the ZADDs needed to rebuild the sorted set */
6862 dictIterator
*di
= dictGetIterator(zs
->dict
);
6865 while((de
= dictNext(di
)) != NULL
) {
6866 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
6867 robj
*eleobj
= dictGetEntryKey(de
);
6868 double *score
= dictGetEntryVal(de
);
6870 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6871 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6872 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
6873 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6875 dictReleaseIterator(di
);
6877 redisAssert(0 != 0);
6879 /* Save the expire time */
6880 if (expiretime
!= -1) {
6881 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
6882 /* If this key is already expired skip it */
6883 if (expiretime
< now
) continue;
6884 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6885 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6886 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
6888 if (swapped
) decrRefCount(o
);
6890 dictReleaseIterator(di
);
6893 /* Make sure data will not remain on the OS's output buffers */
6898 /* Use RENAME to make sure the DB file is changed atomically only
6899 * if the generate DB file is ok. */
6900 if (rename(tmpfile
,filename
) == -1) {
6901 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
6905 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
6911 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
6912 if (di
) dictReleaseIterator(di
);
6916 /* This is how rewriting of the append only file in background works:
6918 * 1) The user calls BGREWRITEAOF
6919 * 2) Redis calls this function, that forks():
6920 * 2a) the child rewrite the append only file in a temp file.
6921 * 2b) the parent accumulates differences in server.bgrewritebuf.
6922 * 3) When the child finished '2a' exists.
6923 * 4) The parent will trap the exit code, if it's OK, will append the
6924 * data accumulated into server.bgrewritebuf into the temp file, and
6925 * finally will rename(2) the temp file in the actual file name.
6926 * The the new file is reopened as the new append only file. Profit!
6928 static int rewriteAppendOnlyFileBackground(void) {
6931 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
6932 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
6933 if ((childpid
= fork()) == 0) {
6937 if (server
.vm_enabled
) vmReopenSwapFile();
6939 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6940 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
6947 if (childpid
== -1) {
6948 redisLog(REDIS_WARNING
,
6949 "Can't rewrite append only file in background: fork: %s",
6953 redisLog(REDIS_NOTICE
,
6954 "Background append only file rewriting started by pid %d",childpid
);
6955 server
.bgrewritechildpid
= childpid
;
6956 /* We set appendseldb to -1 in order to force the next call to the
6957 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6958 * accumulated by the parent into server.bgrewritebuf will start
6959 * with a SELECT statement and it will be safe to merge. */
6960 server
.appendseldb
= -1;
6963 return REDIS_OK
; /* unreached */
6966 static void bgrewriteaofCommand(redisClient
*c
) {
6967 if (server
.bgrewritechildpid
!= -1) {
6968 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6971 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
6972 char *status
= "+Background append only file rewriting started\r\n";
6973 addReplySds(c
,sdsnew(status
));
6975 addReply(c
,shared
.err
);
6979 static void aofRemoveTempFile(pid_t childpid
) {
6982 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
6986 /* Virtual Memory is composed mainly of two subsystems:
6987 * - Blocking Virutal Memory
6988 * - Threaded Virtual Memory I/O
6989 * The two parts are not fully decoupled, but functions are split among two
6990 * different sections of the source code (delimited by comments) in order to
6991 * make more clear what functionality is about the blocking VM and what about
6992 * the threaded (not blocking) VM.
6996 * Redis VM is a blocking VM (one that blocks reading swapped values from
6997 * disk into memory when a value swapped out is needed in memory) that is made
6998 * unblocking by trying to examine the command argument vector in order to
6999 * load in background values that will likely be needed in order to exec
7000 * the command. The command is executed only once all the relevant keys
7001 * are loaded into memory.
7003 * This basically is almost as simple of a blocking VM, but almost as parallel
7004 * as a fully non-blocking VM.
7007 /* =================== Virtual Memory - Blocking Side ====================== */
7009 /* substitute the first occurrence of '%p' with the process pid in the
7010 * swap file name. */
7011 static void expandVmSwapFilename(void) {
7012 char *p
= strstr(server
.vm_swap_file
,"%p");
7018 new = sdscat(new,server
.vm_swap_file
);
7019 new = sdscatprintf(new,"%ld",(long) getpid());
7020 new = sdscat(new,p
+2);
7021 zfree(server
.vm_swap_file
);
7022 server
.vm_swap_file
= new;
7025 static void vmInit(void) {
7030 if (server
.vm_max_threads
!= 0)
7031 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
7033 expandVmSwapFilename();
7034 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
7035 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
7036 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
7038 if (server
.vm_fp
== NULL
) {
7039 redisLog(REDIS_WARNING
,
7040 "Impossible to open the swap file: %s. Exiting.",
7044 server
.vm_fd
= fileno(server
.vm_fp
);
7045 server
.vm_next_page
= 0;
7046 server
.vm_near_pages
= 0;
7047 server
.vm_stats_used_pages
= 0;
7048 server
.vm_stats_swapped_objects
= 0;
7049 server
.vm_stats_swapouts
= 0;
7050 server
.vm_stats_swapins
= 0;
7051 totsize
= server
.vm_pages
*server
.vm_page_size
;
7052 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
7053 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
7054 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
7058 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
7060 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
7061 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
7062 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
7063 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
7065 /* Initialize threaded I/O (used by Virtual Memory) */
7066 server
.io_newjobs
= listCreate();
7067 server
.io_processing
= listCreate();
7068 server
.io_processed
= listCreate();
7069 server
.io_clients
= listCreate();
7070 pthread_mutex_init(&server
.io_mutex
,NULL
);
7071 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
7072 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
7073 server
.io_active_threads
= 0;
7074 if (pipe(pipefds
) == -1) {
7075 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
7079 server
.io_ready_pipe_read
= pipefds
[0];
7080 server
.io_ready_pipe_write
= pipefds
[1];
7081 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
7082 /* LZF requires a lot of stack */
7083 pthread_attr_init(&server
.io_threads_attr
);
7084 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
7085 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
7086 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
7087 /* Listen for events in the threaded I/O pipe */
7088 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
7089 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
7090 oom("creating file event");
7093 /* Mark the page as used */
7094 static void vmMarkPageUsed(off_t page
) {
7095 off_t byte
= page
/8;
7097 redisAssert(vmFreePage(page
) == 1);
7098 server
.vm_bitmap
[byte
] |= 1<<bit
;
7099 redisLog(REDIS_DEBUG
,"Mark used: %lld (byte:%lld bit:%d)\n",
7100 (long long)page
, (long long)byte
, bit
);
7103 /* Mark N contiguous pages as used, with 'page' being the first. */
7104 static void vmMarkPagesUsed(off_t page
, off_t count
) {
7107 for (j
= 0; j
< count
; j
++)
7108 vmMarkPageUsed(page
+j
);
7109 server
.vm_stats_used_pages
+= count
;
7112 /* Mark the page as free */
7113 static void vmMarkPageFree(off_t page
) {
7114 off_t byte
= page
/8;
7116 redisAssert(vmFreePage(page
) == 0);
7117 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
7118 redisLog(REDIS_DEBUG
,"Mark free: %lld (byte:%lld bit:%d)\n",
7119 (long long)page
, (long long)byte
, bit
);
7122 /* Mark N contiguous pages as free, with 'page' being the first. */
7123 static void vmMarkPagesFree(off_t page
, off_t count
) {
7126 for (j
= 0; j
< count
; j
++)
7127 vmMarkPageFree(page
+j
);
7128 server
.vm_stats_used_pages
-= count
;
7129 if (server
.vm_stats_used_pages
> 100000000) {
7134 /* Test if the page is free */
7135 static int vmFreePage(off_t page
) {
7136 off_t byte
= page
/8;
7138 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
7141 /* Find N contiguous free pages storing the first page of the cluster in *first.
7142 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
7143 * REDIS_ERR is returned.
7145 * This function uses a simple algorithm: we try to allocate
7146 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
7147 * again from the start of the swap file searching for free spaces.
7149 * If it looks pretty clear that there are no free pages near our offset
7150 * we try to find less populated places doing a forward jump of
7151 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
7152 * without hurry, and then we jump again and so forth...
7154 * This function can be improved using a free list to avoid to guess
7155 * too much, since we could collect data about freed pages.
7157 * note: I implemented this function just after watching an episode of
7158 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
7160 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
7161 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
7163 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
7164 server
.vm_near_pages
= 0;
7165 server
.vm_next_page
= 0;
7167 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
7168 base
= server
.vm_next_page
;
7170 while(offset
< server
.vm_pages
) {
7171 off_t
this = base
+offset
;
7173 redisLog(REDIS_DEBUG
, "THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
7174 /* If we overflow, restart from page zero */
7175 if (this >= server
.vm_pages
) {
7176 this -= server
.vm_pages
;
7178 /* Just overflowed, what we found on tail is no longer
7179 * interesting, as it's no longer contiguous. */
7183 if (vmFreePage(this)) {
7184 /* This is a free page */
7186 /* Already got N free pages? Return to the caller, with success */
7188 *first
= this-(n
-1);
7189 server
.vm_next_page
= this+1;
7193 /* The current one is not a free page */
7197 /* Fast-forward if the current page is not free and we already
7198 * searched enough near this place. */
7200 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
7201 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
7203 /* Note that even if we rewind after the jump, we are don't need
7204 * to make sure numfree is set to zero as we only jump *if* it
7205 * is set to zero. */
7207 /* Otherwise just check the next page */
7214 /* Write the specified object at the specified page of the swap file */
7215 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
7216 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7217 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7218 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7219 redisLog(REDIS_WARNING
,
7220 "Critical VM problem in vmSwapObjectBlocking(): can't seek: %s",
7224 rdbSaveObject(server
.vm_fp
,o
);
7225 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7229 /* Swap the 'val' object relative to 'key' into disk. Store all the information
7230 * needed to later retrieve the object into the key object.
7231 * If we can't find enough contiguous empty pages to swap the object on disk
7232 * REDIS_ERR is returned. */
7233 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
7234 off_t pages
= rdbSavedObjectPages(val
,NULL
);
7237 assert(key
->storage
== REDIS_VM_MEMORY
);
7238 assert(key
->refcount
== 1);
7239 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
7240 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
7241 key
->vm
.page
= page
;
7242 key
->vm
.usedpages
= pages
;
7243 key
->storage
= REDIS_VM_SWAPPED
;
7244 key
->vtype
= val
->type
;
7245 decrRefCount(val
); /* Deallocate the object from memory. */
7246 vmMarkPagesUsed(page
,pages
);
7247 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
7248 (unsigned char*) key
->ptr
,
7249 (unsigned long long) page
, (unsigned long long) pages
);
7250 server
.vm_stats_swapped_objects
++;
7251 server
.vm_stats_swapouts
++;
7252 fflush(server
.vm_fp
);
7256 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
7259 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7260 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7261 redisLog(REDIS_WARNING
,
7262 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
7266 o
= rdbLoadObject(type
,server
.vm_fp
);
7268 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno
));
7271 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7275 /* Load the value object relative to the 'key' object from swap to memory.
7276 * The newly allocated object is returned.
7278 * If preview is true the unserialized object is returned to the caller but
7279 * no changes are made to the key object, nor the pages are marked as freed */
7280 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
7283 redisAssert(key
->storage
== REDIS_VM_SWAPPED
);
7284 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
7286 key
->storage
= REDIS_VM_MEMORY
;
7287 key
->vm
.atime
= server
.unixtime
;
7288 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7289 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
7290 (unsigned char*) key
->ptr
);
7291 server
.vm_stats_swapped_objects
--;
7293 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
7294 (unsigned char*) key
->ptr
);
7296 server
.vm_stats_swapins
++;
7300 /* Plain object loading, from swap to memory */
7301 static robj
*vmLoadObject(robj
*key
) {
7302 /* If we are loading the object in background, stop it, we
7303 * need to load this object synchronously ASAP. */
7304 if (key
->storage
== REDIS_VM_LOADING
)
7305 vmCancelThreadedIOJob(key
);
7306 return vmGenericLoadObject(key
,0);
7309 /* Just load the value on disk, without to modify the key.
7310 * This is useful when we want to perform some operation on the value
7311 * without to really bring it from swap to memory, like while saving the
7312 * dataset or rewriting the append only log. */
7313 static robj
*vmPreviewObject(robj
*key
) {
7314 return vmGenericLoadObject(key
,1);
7317 /* How a good candidate is this object for swapping?
7318 * The better candidate it is, the greater the returned value.
7320 * Currently we try to perform a fast estimation of the object size in
7321 * memory, and combine it with aging informations.
7323 * Basically swappability = idle-time * log(estimated size)
7325 * Bigger objects are preferred over smaller objects, but not
7326 * proportionally, this is why we use the logarithm. This algorithm is
7327 * just a first try and will probably be tuned later. */
7328 static double computeObjectSwappability(robj
*o
) {
7329 time_t age
= server
.unixtime
- o
->vm
.atime
;
7333 struct dictEntry
*de
;
7336 if (age
<= 0) return 0;
7339 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
7342 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
7347 listNode
*ln
= listFirst(l
);
7349 asize
= sizeof(list
);
7351 robj
*ele
= ln
->value
;
7354 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7355 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7357 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
7362 z
= (o
->type
== REDIS_ZSET
);
7363 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
7365 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
7366 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
7371 de
= dictGetRandomKey(d
);
7372 ele
= dictGetEntryKey(de
);
7373 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7374 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7376 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
7377 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
7381 return (double)asize
*log(1+asize
);
7384 /* Try to swap an object that's a good candidate for swapping.
7385 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
7386 * to swap any object at all.
7388 * If 'usethreaded' is true, Redis will try to swap the object in background
7389 * using I/O threads. */
7390 static int vmSwapOneObject(int usethreads
) {
7392 struct dictEntry
*best
= NULL
;
7393 double best_swappability
= 0;
7394 redisDb
*best_db
= NULL
;
7397 for (j
= 0; j
< server
.dbnum
; j
++) {
7398 redisDb
*db
= server
.db
+j
;
7399 int maxtries
= 1000;
7401 if (dictSize(db
->dict
) == 0) continue;
7402 for (i
= 0; i
< 5; i
++) {
7404 double swappability
;
7406 if (maxtries
) maxtries
--;
7407 de
= dictGetRandomKey(db
->dict
);
7408 key
= dictGetEntryKey(de
);
7409 val
= dictGetEntryVal(de
);
7410 /* Only swap objects that are currently in memory.
7412 * Also don't swap shared objects if threaded VM is on, as we
7413 * try to ensure that the main thread does not touch the
7414 * object while the I/O thread is using it, but we can't
7415 * control other keys without adding additional mutex. */
7416 if (key
->storage
!= REDIS_VM_MEMORY
||
7417 (server
.vm_max_threads
!= 0 && val
->refcount
!= 1)) {
7418 if (maxtries
) i
--; /* don't count this try */
7421 swappability
= computeObjectSwappability(val
);
7422 if (!best
|| swappability
> best_swappability
) {
7424 best_swappability
= swappability
;
7430 redisLog(REDIS_DEBUG
,"No swappable key found!");
7433 key
= dictGetEntryKey(best
);
7434 val
= dictGetEntryVal(best
);
7436 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
7437 key
->ptr
, best_swappability
);
7439 /* Unshare the key if needed */
7440 if (key
->refcount
> 1) {
7441 robj
*newkey
= dupStringObject(key
);
7443 key
= dictGetEntryKey(best
) = newkey
;
7447 vmSwapObjectThreaded(key
,val
,best_db
);
7450 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7451 dictGetEntryVal(best
) = NULL
;
7459 static int vmSwapOneObjectBlocking() {
7460 return vmSwapOneObject(0);
7463 static int vmSwapOneObjectThreaded() {
7464 return vmSwapOneObject(1);
7467 /* Return true if it's safe to swap out objects in a given moment.
7468 * Basically we don't want to swap objects out while there is a BGSAVE
7469 * or a BGAEOREWRITE running in backgroud. */
7470 static int vmCanSwapOut(void) {
7471 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
7474 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
7475 * and was deleted. Otherwise 0 is returned. */
7476 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
7480 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
7481 foundkey
= dictGetEntryKey(de
);
7482 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
7487 /* =================== Virtual Memory - Threaded I/O ======================= */
7489 static void freeIOJob(iojob
*j
) {
7490 if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
7491 j
->type
== REDIS_IOJOB_DO_SWAP
)
7492 decrRefCount(j
->val
);
7493 decrRefCount(j
->key
);
7497 /* Every time a thread finished a Job, it writes a byte into the write side
7498 * of an unix pipe in order to "awake" the main thread, and this function
7500 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
7507 REDIS_NOTUSED(mask
);
7508 REDIS_NOTUSED(privdata
);
7510 /* For every byte we read in the read side of the pipe, there is one
7511 * I/O job completed to process. */
7512 while((retval
= read(fd
,buf
,1)) == 1) {
7516 struct dictEntry
*de
;
7518 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
7520 /* Get the processed element (the oldest one) */
7522 assert(listLength(server
.io_processed
) != 0);
7523 ln
= listFirst(server
.io_processed
);
7525 listDelNode(server
.io_processed
,ln
);
7527 /* If this job is marked as canceled, just ignore it */
7532 /* Post process it in the main thread, as there are things we
7533 * can do just here to avoid race conditions and/or invasive locks */
7534 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
);
7535 de
= dictFind(j
->db
->dict
,j
->key
);
7537 key
= dictGetEntryKey(de
);
7538 if (j
->type
== REDIS_IOJOB_LOAD
) {
7539 /* Key loaded, bring it at home */
7540 key
->storage
= REDIS_VM_MEMORY
;
7541 key
->vm
.atime
= server
.unixtime
;
7542 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7543 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
7544 (unsigned char*) key
->ptr
);
7545 server
.vm_stats_swapped_objects
--;
7546 server
.vm_stats_swapins
++;
7548 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
7549 /* Now we know the amount of pages required to swap this object.
7550 * Let's find some space for it, and queue this task again
7551 * rebranded as REDIS_IOJOB_DO_SWAP. */
7552 if (!vmCanSwapOut() ||
7553 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
7555 /* Ooops... no space or we can't swap as there is
7556 * a fork()ed Redis trying to save stuff on disk. */
7558 key
->storage
= REDIS_VM_MEMORY
; /* undo operation */
7560 /* Note that we need to mark this pages as used now,
7561 * if the job will be canceled, we'll mark them as freed
7563 vmMarkPagesUsed(j
->page
,j
->pages
);
7564 j
->type
= REDIS_IOJOB_DO_SWAP
;
7569 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
7572 /* Key swapped. We can finally free some memory. */
7573 if (key
->storage
!= REDIS_VM_SWAPPING
) {
7574 printf("key->storage: %d\n",key
->storage
);
7575 printf("key->name: %s\n",(char*)key
->ptr
);
7576 printf("key->refcount: %d\n",key
->refcount
);
7577 printf("val: %p\n",(void*)j
->val
);
7578 printf("val->type: %d\n",j
->val
->type
);
7579 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
7581 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
7582 val
= dictGetEntryVal(de
);
7583 key
->vm
.page
= j
->page
;
7584 key
->vm
.usedpages
= j
->pages
;
7585 key
->storage
= REDIS_VM_SWAPPED
;
7586 key
->vtype
= j
->val
->type
;
7587 decrRefCount(val
); /* Deallocate the object from memory. */
7588 dictGetEntryVal(de
) = NULL
;
7589 redisLog(REDIS_DEBUG
,
7590 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
7591 (unsigned char*) key
->ptr
,
7592 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
7593 server
.vm_stats_swapped_objects
++;
7594 server
.vm_stats_swapouts
++;
7596 /* Put a few more swap requests in queue if we are still
7598 if (vmCanSwapOut() && zmalloc_used_memory() > server
.vm_max_memory
){
7602 more
= listLength(server
.io_newjobs
) <
7603 (unsigned) server
.vm_max_threads
;
7605 /* Don't waste CPU time if swappable objects are rare. */
7606 if (vmSwapOneObjectThreaded() == REDIS_ERR
) break;
7611 if (processed
== REDIS_MAX_COMPLETED_JOBS_PROCESSED
) return;
7613 if (retval
< 0 && errno
!= EAGAIN
) {
7614 redisLog(REDIS_WARNING
,
7615 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
7620 static void lockThreadedIO(void) {
7621 pthread_mutex_lock(&server
.io_mutex
);
7624 static void unlockThreadedIO(void) {
7625 pthread_mutex_unlock(&server
.io_mutex
);
7628 /* Remove the specified object from the threaded I/O queue if still not
7629 * processed, otherwise make sure to flag it as canceled. */
7630 static void vmCancelThreadedIOJob(robj
*o
) {
7632 server
.io_newjobs
, /* 0 */
7633 server
.io_processing
, /* 1 */
7634 server
.io_processed
/* 2 */
7638 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
7641 /* Search for a matching key in one of the queues */
7642 for (i
= 0; i
< 3; i
++) {
7646 listRewind(lists
[i
],&li
);
7647 while ((ln
= listNext(&li
)) != NULL
) {
7648 iojob
*job
= ln
->value
;
7650 if (job
->canceled
) continue; /* Skip this, already canceled. */
7651 if (compareStringObjects(job
->key
,o
) == 0) {
7652 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
7653 (void*)job
, (char*)o
->ptr
, job
->type
, i
);
7654 /* Mark the pages as free since the swap didn't happened
7655 * or happened but is now discarded. */
7656 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
7657 vmMarkPagesFree(job
->page
,job
->pages
);
7658 /* Cancel the job. It depends on the list the job is
7661 case 0: /* io_newjobs */
7662 /* If the job was yet not processed the best thing to do
7663 * is to remove it from the queue at all */
7665 listDelNode(lists
[i
],ln
);
7667 case 1: /* io_processing */
7668 /* Oh Shi- the thread is messing with the Job, and
7669 * probably with the object if this is a
7670 * PREPARE_SWAP or DO_SWAP job. Better to wait for the
7671 * job to move into the next queue... */
7672 if (job
->type
!= REDIS_IOJOB_LOAD
) {
7673 /* Yes, we try again and again until the job
7676 /* But let's wait some time for the I/O thread
7677 * to finish with this job. After all this condition
7678 * should be very rare. */
7685 case 2: /* io_processed */
7686 /* The job was already processed, that's easy...
7687 * just mark it as canceled so that we'll ignore it
7688 * when processing completed jobs. */
7692 /* Finally we have to adjust the storage type of the object
7693 * in order to "UNDO" the operaiton. */
7694 if (o
->storage
== REDIS_VM_LOADING
)
7695 o
->storage
= REDIS_VM_SWAPPED
;
7696 else if (o
->storage
== REDIS_VM_SWAPPING
)
7697 o
->storage
= REDIS_VM_MEMORY
;
7704 assert(1 != 1); /* We should never reach this */
7707 static void *IOThreadEntryPoint(void *arg
) {
7712 pthread_detach(pthread_self());
7714 /* Get a new job to process */
7716 if (listLength(server
.io_newjobs
) == 0) {
7717 /* No new jobs in queue, exit. */
7718 redisLog(REDIS_DEBUG
,"Thread %lld exiting, nothing to do",
7719 (long long) pthread_self());
7720 server
.io_active_threads
--;
7724 ln
= listFirst(server
.io_newjobs
);
7726 listDelNode(server
.io_newjobs
,ln
);
7727 /* Add the job in the processing queue */
7728 j
->thread
= pthread_self();
7729 listAddNodeTail(server
.io_processing
,j
);
7730 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
7732 redisLog(REDIS_DEBUG
,"Thread %lld got a new job (type %d): %p about key '%s'",
7733 (long long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
7735 /* Process the Job */
7736 if (j
->type
== REDIS_IOJOB_LOAD
) {
7737 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
7738 FILE *fp
= fopen("/dev/null","w+");
7739 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
7741 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
7742 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
7746 /* Done: insert the job into the processed queue */
7747 redisLog(REDIS_DEBUG
,"Thread %lld completed the job: %p (key %s)",
7748 (long long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
7750 listDelNode(server
.io_processing
,ln
);
7751 listAddNodeTail(server
.io_processed
,j
);
7754 /* Signal the main thread there is new stuff to process */
7755 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
7757 return NULL
; /* never reached */
7760 static void spawnIOThread(void) {
7763 pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
);
7764 server
.io_active_threads
++;
7767 /* We need to wait for the last thread to exit before we are able to
7768 * fork() in order to BGSAVE or BGREWRITEAOF. */
7769 static void waitEmptyIOJobsQueue(void) {
7772 if (listLength(server
.io_newjobs
) == 0 &&
7773 listLength(server
.io_processing
) == 0 &&
7774 server
.io_active_threads
== 0)
7780 usleep(10000); /* 10 milliseconds */
7784 static void vmReopenSwapFile(void) {
7785 fclose(server
.vm_fp
);
7786 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
7787 if (server
.vm_fp
== NULL
) {
7788 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
7789 server
.vm_swap_file
);
7792 server
.vm_fd
= fileno(server
.vm_fp
);
7795 /* This function must be called while with threaded IO locked */
7796 static void queueIOJob(iojob
*j
) {
7797 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
7798 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
7799 listAddNodeTail(server
.io_newjobs
,j
);
7800 if (server
.io_active_threads
< server
.vm_max_threads
)
7804 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
7807 assert(key
->storage
== REDIS_VM_MEMORY
);
7808 assert(key
->refcount
== 1);
7810 j
= zmalloc(sizeof(*j
));
7811 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
7813 j
->key
= dupStringObject(key
);
7817 j
->thread
= (pthread_t
) -1;
7818 key
->storage
= REDIS_VM_SWAPPING
;
7826 /* ================================= Debugging ============================== */
7828 static void debugCommand(redisClient
*c
) {
7829 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
7831 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
7832 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
7833 addReply(c
,shared
.err
);
7837 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
7838 addReply(c
,shared
.err
);
7841 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
7842 addReply(c
,shared
.ok
);
7843 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
7845 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
7846 addReply(c
,shared
.err
);
7849 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
7850 addReply(c
,shared
.ok
);
7851 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
7852 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7856 addReply(c
,shared
.nokeyerr
);
7859 key
= dictGetEntryKey(de
);
7860 val
= dictGetEntryVal(de
);
7861 if (server
.vm_enabled
&& (key
->storage
== REDIS_VM_MEMORY
||
7862 key
->storage
== REDIS_VM_SWAPPING
)) {
7863 addReplySds(c
,sdscatprintf(sdsempty(),
7864 "+Key at:%p refcount:%d, value at:%p refcount:%d "
7865 "encoding:%d serializedlength:%lld\r\n",
7866 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
7867 val
->encoding
, (long long) rdbSavedObjectLen(val
,NULL
)));
7869 addReplySds(c
,sdscatprintf(sdsempty(),
7870 "+Key at:%p refcount:%d, value swapped at: page %llu "
7871 "using %llu pages\r\n",
7872 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
7873 (unsigned long long) key
->vm
.usedpages
));
7875 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
7876 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7879 if (!server
.vm_enabled
) {
7880 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7884 addReply(c
,shared
.nokeyerr
);
7887 key
= dictGetEntryKey(de
);
7888 val
= dictGetEntryVal(de
);
7889 /* If the key is shared we want to create a copy */
7890 if (key
->refcount
> 1) {
7891 robj
*newkey
= dupStringObject(key
);
7893 key
= dictGetEntryKey(de
) = newkey
;
7896 if (key
->storage
!= REDIS_VM_MEMORY
) {
7897 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
7898 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7899 dictGetEntryVal(de
) = NULL
;
7900 addReply(c
,shared
.ok
);
7902 addReply(c
,shared
.err
);
7905 addReplySds(c
,sdsnew(
7906 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7910 static void _redisAssert(char *estr
, char *file
, int line
) {
7911 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
7912 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
);
7913 #ifdef HAVE_BACKTRACE
7914 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
7919 /* =================================== Main! ================================ */
7922 int linuxOvercommitMemoryValue(void) {
7923 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
7927 if (fgets(buf
,64,fp
) == NULL
) {
7936 void linuxOvercommitMemoryWarning(void) {
7937 if (linuxOvercommitMemoryValue() == 0) {
7938 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.");
7941 #endif /* __linux__ */
7943 static void daemonize(void) {
7947 if (fork() != 0) exit(0); /* parent exits */
7948 setsid(); /* create a new session */
7950 /* Every output goes to /dev/null. If Redis is daemonized but
7951 * the 'logfile' is set to 'stdout' in the configuration file
7952 * it will not log at all. */
7953 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
7954 dup2(fd
, STDIN_FILENO
);
7955 dup2(fd
, STDOUT_FILENO
);
7956 dup2(fd
, STDERR_FILENO
);
7957 if (fd
> STDERR_FILENO
) close(fd
);
7959 /* Try to write the pid file */
7960 fp
= fopen(server
.pidfile
,"w");
7962 fprintf(fp
,"%d\n",getpid());
7967 int main(int argc
, char **argv
) {
7970 resetServerSaveParams();
7971 loadServerConfig(argv
[1]);
7972 } else if (argc
> 2) {
7973 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
7976 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'");
7978 if (server
.daemonize
) daemonize();
7980 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
7982 linuxOvercommitMemoryWarning();
7984 if (server
.appendonly
) {
7985 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
7986 redisLog(REDIS_NOTICE
,"DB loaded from append only file");
7988 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
7989 redisLog(REDIS_NOTICE
,"DB loaded from disk");
7991 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
7993 aeDeleteEventLoop(server
.el
);
7997 /* ============================= Backtrace support ========================= */
7999 #ifdef HAVE_BACKTRACE
8000 static char *findFuncName(void *pointer
, unsigned long *offset
);
8002 static void *getMcontextEip(ucontext_t
*uc
) {
8003 #if defined(__FreeBSD__)
8004 return (void*) uc
->uc_mcontext
.mc_eip
;
8005 #elif defined(__dietlibc__)
8006 return (void*) uc
->uc_mcontext
.eip
;
8007 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
8009 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
8011 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
8013 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
8014 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
8015 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
8017 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
8019 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
8020 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
8021 #elif defined(__ia64__) /* Linux IA64 */
8022 return (void*) uc
->uc_mcontext
.sc_ip
;
8028 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
8030 char **messages
= NULL
;
8031 int i
, trace_size
= 0;
8032 unsigned long offset
=0;
8033 ucontext_t
*uc
= (ucontext_t
*) secret
;
8035 REDIS_NOTUSED(info
);
8037 redisLog(REDIS_WARNING
,
8038 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
8039 infostring
= genRedisInfoString();
8040 redisLog(REDIS_WARNING
, "%s",infostring
);
8041 /* It's not safe to sdsfree() the returned string under memory
8042 * corruption conditions. Let it leak as we are going to abort */
8044 trace_size
= backtrace(trace
, 100);
8045 /* overwrite sigaction with caller's address */
8046 if (getMcontextEip(uc
) != NULL
) {
8047 trace
[1] = getMcontextEip(uc
);
8049 messages
= backtrace_symbols(trace
, trace_size
);
8051 for (i
=1; i
<trace_size
; ++i
) {
8052 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
8054 p
= strchr(messages
[i
],'+');
8055 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
8056 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
8058 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
8061 /* free(messages); Don't call free() with possibly corrupted memory. */
8065 static void setupSigSegvAction(void) {
8066 struct sigaction act
;
8068 sigemptyset (&act
.sa_mask
);
8069 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
8070 * is used. Otherwise, sa_handler is used */
8071 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
8072 act
.sa_sigaction
= segvHandler
;
8073 sigaction (SIGSEGV
, &act
, NULL
);
8074 sigaction (SIGBUS
, &act
, NULL
);
8075 sigaction (SIGFPE
, &act
, NULL
);
8076 sigaction (SIGILL
, &act
, NULL
);
8077 sigaction (SIGBUS
, &act
, NULL
);
8081 #include "staticsymbols.h"
8082 /* This function try to convert a pointer into a function name. It's used in
8083 * oreder to provide a backtrace under segmentation fault that's able to
8084 * display functions declared as static (otherwise the backtrace is useless). */
8085 static char *findFuncName(void *pointer
, unsigned long *offset
){
8087 unsigned long off
, minoff
= 0;
8089 /* Try to match against the Symbol with the smallest offset */
8090 for (i
=0; symsTable
[i
].pointer
; i
++) {
8091 unsigned long lp
= (unsigned long) pointer
;
8093 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
8094 off
=lp
-symsTable
[i
].pointer
;
8095 if (ret
< 0 || off
< minoff
) {
8101 if (ret
== -1) return NULL
;
8103 return symsTable
[ret
].name
;
8105 #else /* HAVE_BACKTRACE */
8106 static void setupSigSegvAction(void) {
8108 #endif /* HAVE_BACKTRACE */