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 */
388 unsigned long long vm_max_memory
;
389 /* Virtual memory state */
392 off_t vm_next_page
; /* Next probably empty page */
393 off_t vm_near_pages
; /* Number of pages allocated sequentially */
394 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
395 time_t unixtime
; /* Unix time sampled every second. */
396 /* Virtual memory I/O threads stuff */
397 /* An I/O thread process an element taken from the io_jobs queue and
398 * put the result of the operation in the io_done list. While the
399 * job is being processed, it's put on io_processing queue. */
400 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
401 list
*io_processing
; /* List of VM I/O jobs being processed */
402 list
*io_processed
; /* List of VM I/O jobs already processed */
403 list
*io_clients
; /* All the clients waiting for SWAP I/O operations */
404 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
405 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
406 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
407 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
408 int io_active_threads
; /* Number of running I/O threads */
409 int vm_max_threads
; /* Max number of I/O threads running at the same time */
410 /* Our main thread is blocked on the event loop, locking for sockets ready
411 * to be read or written, so when a threaded I/O operation is ready to be
412 * processed by the main thread, the I/O thread will use a unix pipe to
413 * awake the main thread. The followings are the two pipe FDs. */
414 int io_ready_pipe_read
;
415 int io_ready_pipe_write
;
416 /* Virtual memory stats */
417 unsigned long long vm_stats_used_pages
;
418 unsigned long long vm_stats_swapped_objects
;
419 unsigned long long vm_stats_swapouts
;
420 unsigned long long vm_stats_swapins
;
424 typedef void redisCommandProc(redisClient
*c
);
425 struct redisCommand
{
427 redisCommandProc
*proc
;
432 struct redisFunctionSym
{
434 unsigned long pointer
;
437 typedef struct _redisSortObject
{
445 typedef struct _redisSortOperation
{
448 } redisSortOperation
;
450 /* ZSETs use a specialized version of Skiplists */
452 typedef struct zskiplistNode
{
453 struct zskiplistNode
**forward
;
454 struct zskiplistNode
*backward
;
459 typedef struct zskiplist
{
460 struct zskiplistNode
*header
, *tail
;
461 unsigned long length
;
465 typedef struct zset
{
470 /* Our shared "common" objects */
472 struct sharedObjectsStruct
{
473 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
474 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
475 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
476 *outofrangeerr
, *plus
,
477 *select0
, *select1
, *select2
, *select3
, *select4
,
478 *select5
, *select6
, *select7
, *select8
, *select9
;
481 /* Global vars that are actally used as constants. The following double
482 * values are used for double on-disk serialization, and are initialized
483 * at runtime to avoid strange compiler optimizations. */
485 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
487 /* VM threaded I/O request message */
488 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
489 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
490 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
491 typedef struct iojon
{
492 int type
; /* Request type, REDIS_IOJOB_* */
493 redisDb
*db
;/* Redis database */
494 robj
*key
; /* This I/O request is about swapping this key */
495 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
496 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
497 off_t page
; /* Swap page where to read/write the object */
498 off_t pages
; /* Swap pages needed to safe object. PREPARE_SWAP return val */
499 int canceled
; /* True if this command was canceled by blocking side of VM */
500 pthread_t thread
; /* ID of the thread processing this entry */
503 /*================================ Prototypes =============================== */
505 static void freeStringObject(robj
*o
);
506 static void freeListObject(robj
*o
);
507 static void freeSetObject(robj
*o
);
508 static void decrRefCount(void *o
);
509 static robj
*createObject(int type
, void *ptr
);
510 static void freeClient(redisClient
*c
);
511 static int rdbLoad(char *filename
);
512 static void addReply(redisClient
*c
, robj
*obj
);
513 static void addReplySds(redisClient
*c
, sds s
);
514 static void incrRefCount(robj
*o
);
515 static int rdbSaveBackground(char *filename
);
516 static robj
*createStringObject(char *ptr
, size_t len
);
517 static robj
*dupStringObject(robj
*o
);
518 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
519 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
520 static int syncWithMaster(void);
521 static robj
*tryObjectSharing(robj
*o
);
522 static int tryObjectEncoding(robj
*o
);
523 static robj
*getDecodedObject(robj
*o
);
524 static int removeExpire(redisDb
*db
, robj
*key
);
525 static int expireIfNeeded(redisDb
*db
, robj
*key
);
526 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
527 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
528 static int deleteKey(redisDb
*db
, robj
*key
);
529 static time_t getExpire(redisDb
*db
, robj
*key
);
530 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
531 static void updateSlavesWaitingBgsave(int bgsaveerr
);
532 static void freeMemoryIfNeeded(void);
533 static int processCommand(redisClient
*c
);
534 static void setupSigSegvAction(void);
535 static void rdbRemoveTempFile(pid_t childpid
);
536 static void aofRemoveTempFile(pid_t childpid
);
537 static size_t stringObjectLen(robj
*o
);
538 static void processInputBuffer(redisClient
*c
);
539 static zskiplist
*zslCreate(void);
540 static void zslFree(zskiplist
*zsl
);
541 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
542 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
543 static void initClientMultiState(redisClient
*c
);
544 static void freeClientMultiState(redisClient
*c
);
545 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
546 static void unblockClient(redisClient
*c
);
547 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
548 static void vmInit(void);
549 static void vmMarkPagesFree(off_t page
, off_t count
);
550 static robj
*vmLoadObject(robj
*key
);
551 static robj
*vmPreviewObject(robj
*key
);
552 static int vmSwapOneObjectBlocking(void);
553 static int vmSwapOneObjectThreaded(void);
554 static int vmCanSwapOut(void);
555 static int tryFreeOneObjectFromFreelist(void);
556 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
557 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
558 static void vmCancelThreadedIOJob(robj
*o
);
559 static void lockThreadedIO(void);
560 static void unlockThreadedIO(void);
561 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
562 static void freeIOJob(iojob
*j
);
563 static void queueIOJob(iojob
*j
);
564 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
565 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
566 static void waitZeroActiveThreads(void);
568 static void authCommand(redisClient
*c
);
569 static void pingCommand(redisClient
*c
);
570 static void echoCommand(redisClient
*c
);
571 static void setCommand(redisClient
*c
);
572 static void setnxCommand(redisClient
*c
);
573 static void getCommand(redisClient
*c
);
574 static void delCommand(redisClient
*c
);
575 static void existsCommand(redisClient
*c
);
576 static void incrCommand(redisClient
*c
);
577 static void decrCommand(redisClient
*c
);
578 static void incrbyCommand(redisClient
*c
);
579 static void decrbyCommand(redisClient
*c
);
580 static void selectCommand(redisClient
*c
);
581 static void randomkeyCommand(redisClient
*c
);
582 static void keysCommand(redisClient
*c
);
583 static void dbsizeCommand(redisClient
*c
);
584 static void lastsaveCommand(redisClient
*c
);
585 static void saveCommand(redisClient
*c
);
586 static void bgsaveCommand(redisClient
*c
);
587 static void bgrewriteaofCommand(redisClient
*c
);
588 static void shutdownCommand(redisClient
*c
);
589 static void moveCommand(redisClient
*c
);
590 static void renameCommand(redisClient
*c
);
591 static void renamenxCommand(redisClient
*c
);
592 static void lpushCommand(redisClient
*c
);
593 static void rpushCommand(redisClient
*c
);
594 static void lpopCommand(redisClient
*c
);
595 static void rpopCommand(redisClient
*c
);
596 static void llenCommand(redisClient
*c
);
597 static void lindexCommand(redisClient
*c
);
598 static void lrangeCommand(redisClient
*c
);
599 static void ltrimCommand(redisClient
*c
);
600 static void typeCommand(redisClient
*c
);
601 static void lsetCommand(redisClient
*c
);
602 static void saddCommand(redisClient
*c
);
603 static void sremCommand(redisClient
*c
);
604 static void smoveCommand(redisClient
*c
);
605 static void sismemberCommand(redisClient
*c
);
606 static void scardCommand(redisClient
*c
);
607 static void spopCommand(redisClient
*c
);
608 static void srandmemberCommand(redisClient
*c
);
609 static void sinterCommand(redisClient
*c
);
610 static void sinterstoreCommand(redisClient
*c
);
611 static void sunionCommand(redisClient
*c
);
612 static void sunionstoreCommand(redisClient
*c
);
613 static void sdiffCommand(redisClient
*c
);
614 static void sdiffstoreCommand(redisClient
*c
);
615 static void syncCommand(redisClient
*c
);
616 static void flushdbCommand(redisClient
*c
);
617 static void flushallCommand(redisClient
*c
);
618 static void sortCommand(redisClient
*c
);
619 static void lremCommand(redisClient
*c
);
620 static void rpoplpushcommand(redisClient
*c
);
621 static void infoCommand(redisClient
*c
);
622 static void mgetCommand(redisClient
*c
);
623 static void monitorCommand(redisClient
*c
);
624 static void expireCommand(redisClient
*c
);
625 static void expireatCommand(redisClient
*c
);
626 static void getsetCommand(redisClient
*c
);
627 static void ttlCommand(redisClient
*c
);
628 static void slaveofCommand(redisClient
*c
);
629 static void debugCommand(redisClient
*c
);
630 static void msetCommand(redisClient
*c
);
631 static void msetnxCommand(redisClient
*c
);
632 static void zaddCommand(redisClient
*c
);
633 static void zincrbyCommand(redisClient
*c
);
634 static void zrangeCommand(redisClient
*c
);
635 static void zrangebyscoreCommand(redisClient
*c
);
636 static void zrevrangeCommand(redisClient
*c
);
637 static void zcardCommand(redisClient
*c
);
638 static void zremCommand(redisClient
*c
);
639 static void zscoreCommand(redisClient
*c
);
640 static void zremrangebyscoreCommand(redisClient
*c
);
641 static void multiCommand(redisClient
*c
);
642 static void execCommand(redisClient
*c
);
643 static void blpopCommand(redisClient
*c
);
644 static void brpopCommand(redisClient
*c
);
646 /*================================= Globals ================================= */
649 static struct redisServer server
; /* server global state */
650 static struct redisCommand cmdTable
[] = {
651 {"get",getCommand
,2,REDIS_CMD_INLINE
},
652 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
653 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
654 {"del",delCommand
,-2,REDIS_CMD_INLINE
},
655 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
656 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
657 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
658 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
659 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
660 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
661 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
662 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
663 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
},
664 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
},
665 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
666 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
667 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
668 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
669 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
670 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
671 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
672 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
673 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
674 {"smove",smoveCommand
,4,REDIS_CMD_BULK
},
675 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
676 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
677 {"spop",spopCommand
,2,REDIS_CMD_INLINE
},
678 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
},
679 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
680 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
681 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
682 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
683 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
684 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
685 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
686 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
687 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
688 {"zrem",zremCommand
,3,REDIS_CMD_BULK
},
689 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
},
690 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
},
691 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
},
692 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
},
693 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
},
694 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
695 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
696 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
697 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
698 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
699 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
700 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
701 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
702 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
703 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
704 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
705 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
706 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
},
707 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
708 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
709 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
710 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
711 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
712 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
713 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
714 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
},
715 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
716 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
717 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
718 {"multi",multiCommand
,1,REDIS_CMD_INLINE
},
719 {"exec",execCommand
,1,REDIS_CMD_INLINE
},
720 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
721 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
722 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
723 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
724 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
725 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
726 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
},
727 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
},
728 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
},
732 /*============================ Utility functions ============================ */
734 /* Glob-style pattern matching. */
735 int stringmatchlen(const char *pattern
, int patternLen
,
736 const char *string
, int stringLen
, int nocase
)
741 while (pattern
[1] == '*') {
746 return 1; /* match */
748 if (stringmatchlen(pattern
+1, patternLen
-1,
749 string
, stringLen
, nocase
))
750 return 1; /* match */
754 return 0; /* no match */
758 return 0; /* no match */
768 not = pattern
[0] == '^';
775 if (pattern
[0] == '\\') {
778 if (pattern
[0] == string
[0])
780 } else if (pattern
[0] == ']') {
782 } else if (patternLen
== 0) {
786 } else if (pattern
[1] == '-' && patternLen
>= 3) {
787 int start
= pattern
[0];
788 int end
= pattern
[2];
796 start
= tolower(start
);
802 if (c
>= start
&& c
<= end
)
806 if (pattern
[0] == string
[0])
809 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
819 return 0; /* no match */
825 if (patternLen
>= 2) {
832 if (pattern
[0] != string
[0])
833 return 0; /* no match */
835 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
836 return 0; /* no match */
844 if (stringLen
== 0) {
845 while(*pattern
== '*') {
852 if (patternLen
== 0 && stringLen
== 0)
857 static void redisLog(int level
, const char *fmt
, ...) {
861 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
865 if (level
>= server
.verbosity
) {
871 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
872 fprintf(fp
,"%s %c ",buf
,c
[level
]);
873 vfprintf(fp
, fmt
, ap
);
879 if (server
.logfile
) fclose(fp
);
882 /*====================== Hash table type implementation ==================== */
884 /* This is an hash table type that uses the SDS dynamic strings libary as
885 * keys and radis objects as values (objects can hold SDS strings,
888 static void dictVanillaFree(void *privdata
, void *val
)
890 DICT_NOTUSED(privdata
);
894 static void dictListDestructor(void *privdata
, void *val
)
896 DICT_NOTUSED(privdata
);
897 listRelease((list
*)val
);
900 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
904 DICT_NOTUSED(privdata
);
906 l1
= sdslen((sds
)key1
);
907 l2
= sdslen((sds
)key2
);
908 if (l1
!= l2
) return 0;
909 return memcmp(key1
, key2
, l1
) == 0;
912 static void dictRedisObjectDestructor(void *privdata
, void *val
)
914 DICT_NOTUSED(privdata
);
916 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
920 static int dictObjKeyCompare(void *privdata
, const void *key1
,
923 const robj
*o1
= key1
, *o2
= key2
;
924 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
927 static unsigned int dictObjHash(const void *key
) {
929 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
932 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
935 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
938 o1
= getDecodedObject(o1
);
939 o2
= getDecodedObject(o2
);
940 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
946 static unsigned int dictEncObjHash(const void *key
) {
947 robj
*o
= (robj
*) key
;
949 o
= getDecodedObject(o
);
950 unsigned int hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
955 /* Sets type and expires */
956 static dictType setDictType
= {
957 dictEncObjHash
, /* hash function */
960 dictEncObjKeyCompare
, /* key compare */
961 dictRedisObjectDestructor
, /* key destructor */
962 NULL
/* val destructor */
965 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
966 static dictType zsetDictType
= {
967 dictEncObjHash
, /* hash function */
970 dictEncObjKeyCompare
, /* key compare */
971 dictRedisObjectDestructor
, /* key destructor */
972 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
976 static dictType hashDictType
= {
977 dictObjHash
, /* hash function */
980 dictObjKeyCompare
, /* key compare */
981 dictRedisObjectDestructor
, /* key destructor */
982 dictRedisObjectDestructor
/* val destructor */
986 static dictType keyptrDictType
= {
987 dictObjHash
, /* hash function */
990 dictObjKeyCompare
, /* key compare */
991 dictRedisObjectDestructor
, /* key destructor */
992 NULL
/* val destructor */
995 /* Keylist hash table type has unencoded redis objects as keys and
996 * lists as values. It's used for blocking operations (BLPOP) */
997 static dictType keylistDictType
= {
998 dictObjHash
, /* hash function */
1001 dictObjKeyCompare
, /* key compare */
1002 dictRedisObjectDestructor
, /* key destructor */
1003 dictListDestructor
/* val destructor */
1006 /* ========================= Random utility functions ======================= */
1008 /* Redis generally does not try to recover from out of memory conditions
1009 * when allocating objects or strings, it is not clear if it will be possible
1010 * to report this condition to the client since the networking layer itself
1011 * is based on heap allocation for send buffers, so we simply abort.
1012 * At least the code will be simpler to read... */
1013 static void oom(const char *msg
) {
1014 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1019 /* ====================== Redis server networking stuff ===================== */
1020 static void closeTimedoutClients(void) {
1023 time_t now
= time(NULL
);
1026 listRewind(server
.clients
,&li
);
1027 while ((ln
= listNext(&li
)) != NULL
) {
1028 c
= listNodeValue(ln
);
1029 if (server
.maxidletime
&&
1030 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1031 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1032 (now
- c
->lastinteraction
> server
.maxidletime
))
1034 redisLog(REDIS_VERBOSE
,"Closing idle client");
1036 } else if (c
->flags
& REDIS_BLOCKED
) {
1037 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1038 addReply(c
,shared
.nullmultibulk
);
1045 static int htNeedsResize(dict
*dict
) {
1046 long long size
, used
;
1048 size
= dictSlots(dict
);
1049 used
= dictSize(dict
);
1050 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1051 (used
*100/size
< REDIS_HT_MINFILL
));
1054 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1055 * we resize the hash table to save memory */
1056 static void tryResizeHashTables(void) {
1059 for (j
= 0; j
< server
.dbnum
; j
++) {
1060 if (htNeedsResize(server
.db
[j
].dict
)) {
1061 redisLog(REDIS_VERBOSE
,"The hash table %d is too sparse, resize it...",j
);
1062 dictResize(server
.db
[j
].dict
);
1063 redisLog(REDIS_VERBOSE
,"Hash table %d resized.",j
);
1065 if (htNeedsResize(server
.db
[j
].expires
))
1066 dictResize(server
.db
[j
].expires
);
1070 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1071 void backgroundSaveDoneHandler(int statloc
) {
1072 int exitcode
= WEXITSTATUS(statloc
);
1073 int bysignal
= WIFSIGNALED(statloc
);
1075 if (!bysignal
&& exitcode
== 0) {
1076 redisLog(REDIS_NOTICE
,
1077 "Background saving terminated with success");
1079 server
.lastsave
= time(NULL
);
1080 } else if (!bysignal
&& exitcode
!= 0) {
1081 redisLog(REDIS_WARNING
, "Background saving error");
1083 redisLog(REDIS_WARNING
,
1084 "Background saving terminated by signal");
1085 rdbRemoveTempFile(server
.bgsavechildpid
);
1087 server
.bgsavechildpid
= -1;
1088 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1089 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1090 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1093 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1095 void backgroundRewriteDoneHandler(int statloc
) {
1096 int exitcode
= WEXITSTATUS(statloc
);
1097 int bysignal
= WIFSIGNALED(statloc
);
1099 if (!bysignal
&& exitcode
== 0) {
1103 redisLog(REDIS_NOTICE
,
1104 "Background append only file rewriting terminated with success");
1105 /* Now it's time to flush the differences accumulated by the parent */
1106 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1107 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1109 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1112 /* Flush our data... */
1113 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1114 (signed) sdslen(server
.bgrewritebuf
)) {
1115 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
));
1119 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1120 /* Now our work is to rename the temp file into the stable file. And
1121 * switch the file descriptor used by the server for append only. */
1122 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1123 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1127 /* Mission completed... almost */
1128 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1129 if (server
.appendfd
!= -1) {
1130 /* If append only is actually enabled... */
1131 close(server
.appendfd
);
1132 server
.appendfd
= fd
;
1134 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1135 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1137 /* If append only is disabled we just generate a dump in this
1138 * format. Why not? */
1141 } else if (!bysignal
&& exitcode
!= 0) {
1142 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1144 redisLog(REDIS_WARNING
,
1145 "Background append only file rewriting terminated by signal");
1148 sdsfree(server
.bgrewritebuf
);
1149 server
.bgrewritebuf
= sdsempty();
1150 aofRemoveTempFile(server
.bgrewritechildpid
);
1151 server
.bgrewritechildpid
= -1;
1154 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1155 int j
, loops
= server
.cronloops
++;
1156 REDIS_NOTUSED(eventLoop
);
1158 REDIS_NOTUSED(clientData
);
1160 /* We take a cached value of the unix time in the global state because
1161 * with virtual memory and aging there is to store the current time
1162 * in objects at every object access, and accuracy is not needed.
1163 * To access a global var is faster than calling time(NULL) */
1164 server
.unixtime
= time(NULL
);
1166 /* Update the global state with the amount of used memory */
1167 server
.usedmemory
= zmalloc_used_memory();
1169 /* Show some info about non-empty databases */
1170 for (j
= 0; j
< server
.dbnum
; j
++) {
1171 long long size
, used
, vkeys
;
1173 size
= dictSlots(server
.db
[j
].dict
);
1174 used
= dictSize(server
.db
[j
].dict
);
1175 vkeys
= dictSize(server
.db
[j
].expires
);
1176 if (!(loops
% 5) && (used
|| vkeys
)) {
1177 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1178 /* dictPrintStats(server.dict); */
1182 /* We don't want to resize the hash tables while a bacground saving
1183 * is in progress: the saving child is created using fork() that is
1184 * implemented with a copy-on-write semantic in most modern systems, so
1185 * if we resize the HT while there is the saving child at work actually
1186 * a lot of memory movements in the parent will cause a lot of pages
1188 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1190 /* Show information about connected clients */
1192 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1193 listLength(server
.clients
)-listLength(server
.slaves
),
1194 listLength(server
.slaves
),
1196 dictSize(server
.sharingpool
));
1199 /* Close connections of timedout clients */
1200 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blockedclients
)
1201 closeTimedoutClients();
1203 /* Check if a background saving or AOF rewrite in progress terminated */
1204 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1208 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1209 if (pid
== server
.bgsavechildpid
) {
1210 backgroundSaveDoneHandler(statloc
);
1212 backgroundRewriteDoneHandler(statloc
);
1216 /* If there is not a background saving in progress check if
1217 * we have to save now */
1218 time_t now
= time(NULL
);
1219 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1220 struct saveparam
*sp
= server
.saveparams
+j
;
1222 if (server
.dirty
>= sp
->changes
&&
1223 now
-server
.lastsave
> sp
->seconds
) {
1224 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1225 sp
->changes
, sp
->seconds
);
1226 rdbSaveBackground(server
.dbfilename
);
1232 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1233 * will use few CPU cycles if there are few expiring keys, otherwise
1234 * it will get more aggressive to avoid that too much memory is used by
1235 * keys that can be removed from the keyspace. */
1236 for (j
= 0; j
< server
.dbnum
; j
++) {
1238 redisDb
*db
= server
.db
+j
;
1240 /* Continue to expire if at the end of the cycle more than 25%
1241 * of the keys were expired. */
1243 long num
= dictSize(db
->expires
);
1244 time_t now
= time(NULL
);
1247 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1248 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1253 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1254 t
= (time_t) dictGetEntryVal(de
);
1256 deleteKey(db
,dictGetEntryKey(de
));
1260 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1263 /* Swap a few keys on disk if we are over the memory limit and VM
1264 * is enbled. Try to free objects from the free list first. */
1265 if (vmCanSwapOut()) {
1266 while (server
.vm_enabled
&& zmalloc_used_memory() >
1267 server
.vm_max_memory
)
1271 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1272 retval
= (server
.vm_max_threads
== 0) ?
1273 vmSwapOneObjectBlocking() :
1274 vmSwapOneObjectThreaded();
1275 if (retval
== REDIS_ERR
&& (loops
% 30) == 0 &&
1276 zmalloc_used_memory() >
1277 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1279 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1281 /* Note that when using threade I/O we free just one object,
1282 * because anyway when the I/O thread in charge to swap this
1283 * object out will finish, the handler of completed jobs
1284 * will try to swap more objects if we are still out of memory. */
1285 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1289 /* Check if we should connect to a MASTER */
1290 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1291 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1292 if (syncWithMaster() == REDIS_OK
) {
1293 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1299 static void createSharedObjects(void) {
1300 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1301 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1302 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1303 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1304 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1305 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1306 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1307 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1308 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1309 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1310 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1311 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1312 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1313 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1314 "-ERR no such key\r\n"));
1315 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1316 "-ERR syntax error\r\n"));
1317 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1318 "-ERR source and destination objects are the same\r\n"));
1319 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1320 "-ERR index out of range\r\n"));
1321 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1322 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1323 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1324 shared
.select0
= createStringObject("select 0\r\n",10);
1325 shared
.select1
= createStringObject("select 1\r\n",10);
1326 shared
.select2
= createStringObject("select 2\r\n",10);
1327 shared
.select3
= createStringObject("select 3\r\n",10);
1328 shared
.select4
= createStringObject("select 4\r\n",10);
1329 shared
.select5
= createStringObject("select 5\r\n",10);
1330 shared
.select6
= createStringObject("select 6\r\n",10);
1331 shared
.select7
= createStringObject("select 7\r\n",10);
1332 shared
.select8
= createStringObject("select 8\r\n",10);
1333 shared
.select9
= createStringObject("select 9\r\n",10);
1336 static void appendServerSaveParams(time_t seconds
, int changes
) {
1337 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1338 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1339 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1340 server
.saveparamslen
++;
1343 static void resetServerSaveParams() {
1344 zfree(server
.saveparams
);
1345 server
.saveparams
= NULL
;
1346 server
.saveparamslen
= 0;
1349 static void initServerConfig() {
1350 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1351 server
.port
= REDIS_SERVERPORT
;
1352 server
.verbosity
= REDIS_VERBOSE
;
1353 server
.maxidletime
= REDIS_MAXIDLETIME
;
1354 server
.saveparams
= NULL
;
1355 server
.logfile
= NULL
; /* NULL = log on standard output */
1356 server
.bindaddr
= NULL
;
1357 server
.glueoutputbuf
= 1;
1358 server
.daemonize
= 0;
1359 server
.appendonly
= 0;
1360 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1361 server
.lastfsync
= time(NULL
);
1362 server
.appendfd
= -1;
1363 server
.appendseldb
= -1; /* Make sure the first time will not match */
1364 server
.pidfile
= "/var/run/redis.pid";
1365 server
.dbfilename
= "dump.rdb";
1366 server
.appendfilename
= "appendonly.aof";
1367 server
.requirepass
= NULL
;
1368 server
.shareobjects
= 0;
1369 server
.rdbcompression
= 1;
1370 server
.sharingpoolsize
= 1024;
1371 server
.maxclients
= 0;
1372 server
.blockedclients
= 0;
1373 server
.maxmemory
= 0;
1374 server
.vm_enabled
= 0;
1375 server
.vm_page_size
= 256; /* 256 bytes per page */
1376 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1377 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1378 server
.vm_max_threads
= 4;
1380 resetServerSaveParams();
1382 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1383 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1384 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1385 /* Replication related */
1387 server
.masterauth
= NULL
;
1388 server
.masterhost
= NULL
;
1389 server
.masterport
= 6379;
1390 server
.master
= NULL
;
1391 server
.replstate
= REDIS_REPL_NONE
;
1393 /* Double constants initialization */
1395 R_PosInf
= 1.0/R_Zero
;
1396 R_NegInf
= -1.0/R_Zero
;
1397 R_Nan
= R_Zero
/R_Zero
;
1400 static void initServer() {
1403 signal(SIGHUP
, SIG_IGN
);
1404 signal(SIGPIPE
, SIG_IGN
);
1405 setupSigSegvAction();
1407 server
.devnull
= fopen("/dev/null","w");
1408 if (server
.devnull
== NULL
) {
1409 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1412 server
.clients
= listCreate();
1413 server
.slaves
= listCreate();
1414 server
.monitors
= listCreate();
1415 server
.objfreelist
= listCreate();
1416 createSharedObjects();
1417 server
.el
= aeCreateEventLoop();
1418 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1419 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1420 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1421 if (server
.fd
== -1) {
1422 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1425 for (j
= 0; j
< server
.dbnum
; j
++) {
1426 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
1427 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1428 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1429 server
.db
[j
].id
= j
;
1431 server
.cronloops
= 0;
1432 server
.bgsavechildpid
= -1;
1433 server
.bgrewritechildpid
= -1;
1434 server
.bgrewritebuf
= sdsempty();
1435 server
.lastsave
= time(NULL
);
1437 server
.usedmemory
= 0;
1438 server
.stat_numcommands
= 0;
1439 server
.stat_numconnections
= 0;
1440 server
.stat_starttime
= time(NULL
);
1441 server
.unixtime
= time(NULL
);
1442 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1443 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1444 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1446 if (server
.appendonly
) {
1447 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1448 if (server
.appendfd
== -1) {
1449 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1455 if (server
.vm_enabled
) vmInit();
1458 /* Empty the whole database */
1459 static long long emptyDb() {
1461 long long removed
= 0;
1463 for (j
= 0; j
< server
.dbnum
; j
++) {
1464 removed
+= dictSize(server
.db
[j
].dict
);
1465 dictEmpty(server
.db
[j
].dict
);
1466 dictEmpty(server
.db
[j
].expires
);
1471 static int yesnotoi(char *s
) {
1472 if (!strcasecmp(s
,"yes")) return 1;
1473 else if (!strcasecmp(s
,"no")) return 0;
1477 /* I agree, this is a very rudimental way to load a configuration...
1478 will improve later if the config gets more complex */
1479 static void loadServerConfig(char *filename
) {
1481 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1485 if (filename
[0] == '-' && filename
[1] == '\0')
1488 if ((fp
= fopen(filename
,"r")) == NULL
) {
1489 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1494 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1500 line
= sdstrim(line
," \t\r\n");
1502 /* Skip comments and blank lines*/
1503 if (line
[0] == '#' || line
[0] == '\0') {
1508 /* Split into arguments */
1509 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1510 sdstolower(argv
[0]);
1512 /* Execute config directives */
1513 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1514 server
.maxidletime
= atoi(argv
[1]);
1515 if (server
.maxidletime
< 0) {
1516 err
= "Invalid timeout value"; goto loaderr
;
1518 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1519 server
.port
= atoi(argv
[1]);
1520 if (server
.port
< 1 || server
.port
> 65535) {
1521 err
= "Invalid port"; goto loaderr
;
1523 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1524 server
.bindaddr
= zstrdup(argv
[1]);
1525 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1526 int seconds
= atoi(argv
[1]);
1527 int changes
= atoi(argv
[2]);
1528 if (seconds
< 1 || changes
< 0) {
1529 err
= "Invalid save parameters"; goto loaderr
;
1531 appendServerSaveParams(seconds
,changes
);
1532 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1533 if (chdir(argv
[1]) == -1) {
1534 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1535 argv
[1], strerror(errno
));
1538 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1539 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1540 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1541 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1542 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1544 err
= "Invalid log level. Must be one of debug, notice, warning";
1547 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1550 server
.logfile
= zstrdup(argv
[1]);
1551 if (!strcasecmp(server
.logfile
,"stdout")) {
1552 zfree(server
.logfile
);
1553 server
.logfile
= NULL
;
1555 if (server
.logfile
) {
1556 /* Test if we are able to open the file. The server will not
1557 * be able to abort just for this problem later... */
1558 logfp
= fopen(server
.logfile
,"a");
1559 if (logfp
== NULL
) {
1560 err
= sdscatprintf(sdsempty(),
1561 "Can't open the log file: %s", strerror(errno
));
1566 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1567 server
.dbnum
= atoi(argv
[1]);
1568 if (server
.dbnum
< 1) {
1569 err
= "Invalid number of databases"; goto loaderr
;
1571 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1572 server
.maxclients
= atoi(argv
[1]);
1573 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1574 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1575 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1576 server
.masterhost
= sdsnew(argv
[1]);
1577 server
.masterport
= atoi(argv
[2]);
1578 server
.replstate
= REDIS_REPL_CONNECT
;
1579 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1580 server
.masterauth
= zstrdup(argv
[1]);
1581 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1582 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1583 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1585 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1586 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1587 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1589 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1590 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1591 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1593 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1594 server
.sharingpoolsize
= atoi(argv
[1]);
1595 if (server
.sharingpoolsize
< 1) {
1596 err
= "invalid object sharing pool size"; goto loaderr
;
1598 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1599 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1600 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1602 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1603 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1604 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1606 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1607 if (!strcasecmp(argv
[1],"no")) {
1608 server
.appendfsync
= APPENDFSYNC_NO
;
1609 } else if (!strcasecmp(argv
[1],"always")) {
1610 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1611 } else if (!strcasecmp(argv
[1],"everysec")) {
1612 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1614 err
= "argument must be 'no', 'always' or 'everysec'";
1617 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1618 server
.requirepass
= zstrdup(argv
[1]);
1619 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1620 server
.pidfile
= zstrdup(argv
[1]);
1621 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1622 server
.dbfilename
= zstrdup(argv
[1]);
1623 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1624 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1625 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1627 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1628 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1629 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1630 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1631 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1632 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1633 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1634 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1636 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1638 for (j
= 0; j
< argc
; j
++)
1643 if (fp
!= stdin
) fclose(fp
);
1647 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1648 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1649 fprintf(stderr
, ">>> '%s'\n", line
);
1650 fprintf(stderr
, "%s\n", err
);
1654 static void freeClientArgv(redisClient
*c
) {
1657 for (j
= 0; j
< c
->argc
; j
++)
1658 decrRefCount(c
->argv
[j
]);
1659 for (j
= 0; j
< c
->mbargc
; j
++)
1660 decrRefCount(c
->mbargv
[j
]);
1665 static void freeClient(redisClient
*c
) {
1668 /* Note that if the client we are freeing is blocked into a blocking
1669 * call, we have to set querybuf to NULL *before* to call unblockClient()
1670 * to avoid processInputBuffer() will get called. Also it is important
1671 * to remove the file events after this, because this call adds
1672 * the READABLE event. */
1673 sdsfree(c
->querybuf
);
1675 if (c
->flags
& REDIS_BLOCKED
)
1678 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1679 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1680 listRelease(c
->reply
);
1683 /* Remove from the list of clients */
1684 ln
= listSearchKey(server
.clients
,c
);
1685 redisAssert(ln
!= NULL
);
1686 listDelNode(server
.clients
,ln
);
1687 /* Remove from the list of clients waiting for VM operations */
1688 if (server
.vm_enabled
&& listLength(c
->io_keys
)) {
1689 ln
= listSearchKey(server
.io_clients
,c
);
1690 if (ln
) listDelNode(server
.io_clients
,ln
);
1691 listRelease(c
->io_keys
);
1693 listRelease(c
->io_keys
);
1695 if (c
->flags
& REDIS_SLAVE
) {
1696 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1698 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1699 ln
= listSearchKey(l
,c
);
1700 redisAssert(ln
!= NULL
);
1703 if (c
->flags
& REDIS_MASTER
) {
1704 server
.master
= NULL
;
1705 server
.replstate
= REDIS_REPL_CONNECT
;
1709 freeClientMultiState(c
);
1713 #define GLUEREPLY_UP_TO (1024)
1714 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1716 char buf
[GLUEREPLY_UP_TO
];
1721 listRewind(c
->reply
,&li
);
1722 while((ln
= listNext(&li
))) {
1726 objlen
= sdslen(o
->ptr
);
1727 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1728 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1730 listDelNode(c
->reply
,ln
);
1732 if (copylen
== 0) return;
1736 /* Now the output buffer is empty, add the new single element */
1737 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1738 listAddNodeHead(c
->reply
,o
);
1741 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1742 redisClient
*c
= privdata
;
1743 int nwritten
= 0, totwritten
= 0, objlen
;
1746 REDIS_NOTUSED(mask
);
1748 /* Use writev() if we have enough buffers to send */
1749 if (!server
.glueoutputbuf
&&
1750 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1751 !(c
->flags
& REDIS_MASTER
))
1753 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1757 while(listLength(c
->reply
)) {
1758 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1759 glueReplyBuffersIfNeeded(c
);
1761 o
= listNodeValue(listFirst(c
->reply
));
1762 objlen
= sdslen(o
->ptr
);
1765 listDelNode(c
->reply
,listFirst(c
->reply
));
1769 if (c
->flags
& REDIS_MASTER
) {
1770 /* Don't reply to a master */
1771 nwritten
= objlen
- c
->sentlen
;
1773 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1774 if (nwritten
<= 0) break;
1776 c
->sentlen
+= nwritten
;
1777 totwritten
+= nwritten
;
1778 /* If we fully sent the object on head go to the next one */
1779 if (c
->sentlen
== objlen
) {
1780 listDelNode(c
->reply
,listFirst(c
->reply
));
1783 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1784 * bytes, in a single threaded server it's a good idea to serve
1785 * other clients as well, even if a very large request comes from
1786 * super fast link that is always able to accept data (in real world
1787 * scenario think about 'KEYS *' against the loopback interfae) */
1788 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1790 if (nwritten
== -1) {
1791 if (errno
== EAGAIN
) {
1794 redisLog(REDIS_VERBOSE
,
1795 "Error writing to client: %s", strerror(errno
));
1800 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1801 if (listLength(c
->reply
) == 0) {
1803 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1807 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1809 redisClient
*c
= privdata
;
1810 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1812 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1813 int offset
, ion
= 0;
1815 REDIS_NOTUSED(mask
);
1818 while (listLength(c
->reply
)) {
1819 offset
= c
->sentlen
;
1823 /* fill-in the iov[] array */
1824 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1825 o
= listNodeValue(node
);
1826 objlen
= sdslen(o
->ptr
);
1828 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1831 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1832 break; /* no more iovecs */
1834 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1835 iov
[ion
].iov_len
= objlen
- offset
;
1836 willwrite
+= objlen
- offset
;
1837 offset
= 0; /* just for the first item */
1844 /* write all collected blocks at once */
1845 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1846 if (errno
!= EAGAIN
) {
1847 redisLog(REDIS_VERBOSE
,
1848 "Error writing to client: %s", strerror(errno
));
1855 totwritten
+= nwritten
;
1856 offset
= c
->sentlen
;
1858 /* remove written robjs from c->reply */
1859 while (nwritten
&& listLength(c
->reply
)) {
1860 o
= listNodeValue(listFirst(c
->reply
));
1861 objlen
= sdslen(o
->ptr
);
1863 if(nwritten
>= objlen
- offset
) {
1864 listDelNode(c
->reply
, listFirst(c
->reply
));
1865 nwritten
-= objlen
- offset
;
1869 c
->sentlen
+= nwritten
;
1877 c
->lastinteraction
= time(NULL
);
1879 if (listLength(c
->reply
) == 0) {
1881 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1885 static struct redisCommand
*lookupCommand(char *name
) {
1887 while(cmdTable
[j
].name
!= NULL
) {
1888 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1894 /* resetClient prepare the client to process the next command */
1895 static void resetClient(redisClient
*c
) {
1901 /* Call() is the core of Redis execution of a command */
1902 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
1905 dirty
= server
.dirty
;
1907 if (server
.appendonly
&& server
.dirty
-dirty
)
1908 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1909 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
1910 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1911 if (listLength(server
.monitors
))
1912 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1913 server
.stat_numcommands
++;
1916 /* If this function gets called we already read a whole
1917 * command, argments are in the client argv/argc fields.
1918 * processCommand() execute the command or prepare the
1919 * server for a bulk read from the client.
1921 * If 1 is returned the client is still alive and valid and
1922 * and other operations can be performed by the caller. Otherwise
1923 * if 0 is returned the client was destroied (i.e. after QUIT). */
1924 static int processCommand(redisClient
*c
) {
1925 struct redisCommand
*cmd
;
1927 /* Free some memory if needed (maxmemory setting) */
1928 if (server
.maxmemory
) freeMemoryIfNeeded();
1930 /* Handle the multi bulk command type. This is an alternative protocol
1931 * supported by Redis in order to receive commands that are composed of
1932 * multiple binary-safe "bulk" arguments. The latency of processing is
1933 * a bit higher but this allows things like multi-sets, so if this
1934 * protocol is used only for MSET and similar commands this is a big win. */
1935 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
1936 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1937 if (c
->multibulk
<= 0) {
1941 decrRefCount(c
->argv
[c
->argc
-1]);
1945 } else if (c
->multibulk
) {
1946 if (c
->bulklen
== -1) {
1947 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
1948 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
1952 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1953 decrRefCount(c
->argv
[0]);
1954 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1956 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1961 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1965 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
1966 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
1970 if (c
->multibulk
== 0) {
1974 /* Here we need to swap the multi-bulk argc/argv with the
1975 * normal argc/argv of the client structure. */
1977 c
->argv
= c
->mbargv
;
1978 c
->mbargv
= auxargv
;
1981 c
->argc
= c
->mbargc
;
1982 c
->mbargc
= auxargc
;
1984 /* We need to set bulklen to something different than -1
1985 * in order for the code below to process the command without
1986 * to try to read the last argument of a bulk command as
1987 * a special argument. */
1989 /* continue below and process the command */
1996 /* -- end of multi bulk commands processing -- */
1998 /* The QUIT command is handled as a special case. Normal command
1999 * procs are unable to close the client connection safely */
2000 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2004 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2007 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2008 (char*)c
->argv
[0]->ptr
));
2011 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2012 (c
->argc
< -cmd
->arity
)) {
2014 sdscatprintf(sdsempty(),
2015 "-ERR wrong number of arguments for '%s' command\r\n",
2019 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
2020 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2023 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2024 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2026 decrRefCount(c
->argv
[c
->argc
-1]);
2027 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2029 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2034 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2035 /* It is possible that the bulk read is already in the
2036 * buffer. Check this condition and handle it accordingly.
2037 * This is just a fast path, alternative to call processInputBuffer().
2038 * It's a good idea since the code is small and this condition
2039 * happens most of the times. */
2040 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2041 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2043 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2048 /* Let's try to share objects on the command arguments vector */
2049 if (server
.shareobjects
) {
2051 for(j
= 1; j
< c
->argc
; j
++)
2052 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
2054 /* Let's try to encode the bulk object to save space. */
2055 if (cmd
->flags
& REDIS_CMD_BULK
)
2056 tryObjectEncoding(c
->argv
[c
->argc
-1]);
2058 /* Check if the user is authenticated */
2059 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2060 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2065 /* Exec the command */
2066 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
) {
2067 queueMultiCommand(c
,cmd
);
2068 addReply(c
,shared
.queued
);
2073 /* Prepare the client for the next command */
2074 if (c
->flags
& REDIS_CLOSE
) {
2082 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
2087 /* (args*2)+1 is enough room for args, spaces, newlines */
2088 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
2090 if (argc
<= REDIS_STATIC_ARGS
) {
2093 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
2096 for (j
= 0; j
< argc
; j
++) {
2097 if (j
!= 0) outv
[outc
++] = shared
.space
;
2098 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
2101 lenobj
= createObject(REDIS_STRING
,
2102 sdscatprintf(sdsempty(),"%lu\r\n",
2103 (unsigned long) stringObjectLen(argv
[j
])));
2104 lenobj
->refcount
= 0;
2105 outv
[outc
++] = lenobj
;
2107 outv
[outc
++] = argv
[j
];
2109 outv
[outc
++] = shared
.crlf
;
2111 /* Increment all the refcounts at start and decrement at end in order to
2112 * be sure to free objects if there is no slave in a replication state
2113 * able to be feed with commands */
2114 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2115 listRewind(slaves
,&li
);
2116 while((ln
= listNext(&li
))) {
2117 redisClient
*slave
= ln
->value
;
2119 /* Don't feed slaves that are still waiting for BGSAVE to start */
2120 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2122 /* Feed all the other slaves, MONITORs and so on */
2123 if (slave
->slaveseldb
!= dictid
) {
2127 case 0: selectcmd
= shared
.select0
; break;
2128 case 1: selectcmd
= shared
.select1
; break;
2129 case 2: selectcmd
= shared
.select2
; break;
2130 case 3: selectcmd
= shared
.select3
; break;
2131 case 4: selectcmd
= shared
.select4
; break;
2132 case 5: selectcmd
= shared
.select5
; break;
2133 case 6: selectcmd
= shared
.select6
; break;
2134 case 7: selectcmd
= shared
.select7
; break;
2135 case 8: selectcmd
= shared
.select8
; break;
2136 case 9: selectcmd
= shared
.select9
; break;
2138 selectcmd
= createObject(REDIS_STRING
,
2139 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2140 selectcmd
->refcount
= 0;
2143 addReply(slave
,selectcmd
);
2144 slave
->slaveseldb
= dictid
;
2146 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2148 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2149 if (outv
!= static_outv
) zfree(outv
);
2152 static void processInputBuffer(redisClient
*c
) {
2154 /* Before to process the input buffer, make sure the client is not
2155 * waitig for a blocking operation such as BLPOP. Note that the first
2156 * iteration the client is never blocked, otherwise the processInputBuffer
2157 * would not be called at all, but after the execution of the first commands
2158 * in the input buffer the client may be blocked, and the "goto again"
2159 * will try to reiterate. The following line will make it return asap. */
2160 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2161 if (c
->bulklen
== -1) {
2162 /* Read the first line of the query */
2163 char *p
= strchr(c
->querybuf
,'\n');
2170 query
= c
->querybuf
;
2171 c
->querybuf
= sdsempty();
2172 querylen
= 1+(p
-(query
));
2173 if (sdslen(query
) > querylen
) {
2174 /* leave data after the first line of the query in the buffer */
2175 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2177 *p
= '\0'; /* remove "\n" */
2178 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2179 sdsupdatelen(query
);
2181 /* Now we can split the query in arguments */
2182 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2185 if (c
->argv
) zfree(c
->argv
);
2186 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2188 for (j
= 0; j
< argc
; j
++) {
2189 if (sdslen(argv
[j
])) {
2190 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2198 /* Execute the command. If the client is still valid
2199 * after processCommand() return and there is something
2200 * on the query buffer try to process the next command. */
2201 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2203 /* Nothing to process, argc == 0. Just process the query
2204 * buffer if it's not empty or return to the caller */
2205 if (sdslen(c
->querybuf
)) goto again
;
2208 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2209 redisLog(REDIS_VERBOSE
, "Client protocol error");
2214 /* Bulk read handling. Note that if we are at this point
2215 the client already sent a command terminated with a newline,
2216 we are reading the bulk data that is actually the last
2217 argument of the command. */
2218 int qbl
= sdslen(c
->querybuf
);
2220 if (c
->bulklen
<= qbl
) {
2221 /* Copy everything but the final CRLF as final argument */
2222 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2224 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2225 /* Process the command. If the client is still valid after
2226 * the processing and there is more data in the buffer
2227 * try to parse it. */
2228 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2234 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2235 redisClient
*c
= (redisClient
*) privdata
;
2236 char buf
[REDIS_IOBUF_LEN
];
2239 REDIS_NOTUSED(mask
);
2241 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2243 if (errno
== EAGAIN
) {
2246 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2250 } else if (nread
== 0) {
2251 redisLog(REDIS_VERBOSE
, "Client closed connection");
2256 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2257 c
->lastinteraction
= time(NULL
);
2261 processInputBuffer(c
);
2264 static int selectDb(redisClient
*c
, int id
) {
2265 if (id
< 0 || id
>= server
.dbnum
)
2267 c
->db
= &server
.db
[id
];
2271 static void *dupClientReplyValue(void *o
) {
2272 incrRefCount((robj
*)o
);
2276 static redisClient
*createClient(int fd
) {
2277 redisClient
*c
= zmalloc(sizeof(*c
));
2279 anetNonBlock(NULL
,fd
);
2280 anetTcpNoDelay(NULL
,fd
);
2281 if (!c
) return NULL
;
2284 c
->querybuf
= sdsempty();
2293 c
->lastinteraction
= time(NULL
);
2294 c
->authenticated
= 0;
2295 c
->replstate
= REDIS_REPL_NONE
;
2296 c
->reply
= listCreate();
2297 listSetFreeMethod(c
->reply
,decrRefCount
);
2298 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2299 c
->blockingkeys
= NULL
;
2300 c
->blockingkeysnum
= 0;
2301 c
->io_keys
= listCreate();
2302 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2303 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2304 readQueryFromClient
, c
) == AE_ERR
) {
2308 listAddNodeTail(server
.clients
,c
);
2309 initClientMultiState(c
);
2313 static void addReply(redisClient
*c
, robj
*obj
) {
2314 if (listLength(c
->reply
) == 0 &&
2315 (c
->replstate
== REDIS_REPL_NONE
||
2316 c
->replstate
== REDIS_REPL_ONLINE
) &&
2317 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2318 sendReplyToClient
, c
) == AE_ERR
) return;
2320 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2321 obj
= dupStringObject(obj
);
2322 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2324 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2327 static void addReplySds(redisClient
*c
, sds s
) {
2328 robj
*o
= createObject(REDIS_STRING
,s
);
2333 static void addReplyDouble(redisClient
*c
, double d
) {
2336 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2337 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2338 (unsigned long) strlen(buf
),buf
));
2341 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2344 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2345 len
= sdslen(obj
->ptr
);
2347 long n
= (long)obj
->ptr
;
2349 /* Compute how many bytes will take this integer as a radix 10 string */
2355 while((n
= n
/10) != 0) {
2359 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2362 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2367 REDIS_NOTUSED(mask
);
2368 REDIS_NOTUSED(privdata
);
2370 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2371 if (cfd
== AE_ERR
) {
2372 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2375 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2376 if ((c
= createClient(cfd
)) == NULL
) {
2377 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2378 close(cfd
); /* May be already closed, just ingore errors */
2381 /* If maxclient directive is set and this is one client more... close the
2382 * connection. Note that we create the client instead to check before
2383 * for this condition, since now the socket is already set in nonblocking
2384 * mode and we can send an error for free using the Kernel I/O */
2385 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2386 char *err
= "-ERR max number of clients reached\r\n";
2388 /* That's a best effort error message, don't check write errors */
2389 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2390 /* Nothing to do, Just to avoid the warning... */
2395 server
.stat_numconnections
++;
2398 /* ======================= Redis objects implementation ===================== */
2400 static robj
*createObject(int type
, void *ptr
) {
2403 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2404 if (listLength(server
.objfreelist
)) {
2405 listNode
*head
= listFirst(server
.objfreelist
);
2406 o
= listNodeValue(head
);
2407 listDelNode(server
.objfreelist
,head
);
2408 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2410 if (server
.vm_enabled
) {
2411 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2412 o
= zmalloc(sizeof(*o
));
2414 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2418 o
->encoding
= REDIS_ENCODING_RAW
;
2421 if (server
.vm_enabled
) {
2422 o
->vm
.atime
= server
.unixtime
;
2423 o
->storage
= REDIS_VM_MEMORY
;
2428 static robj
*createStringObject(char *ptr
, size_t len
) {
2429 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2432 static robj
*dupStringObject(robj
*o
) {
2433 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2434 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2437 static robj
*createListObject(void) {
2438 list
*l
= listCreate();
2440 listSetFreeMethod(l
,decrRefCount
);
2441 return createObject(REDIS_LIST
,l
);
2444 static robj
*createSetObject(void) {
2445 dict
*d
= dictCreate(&setDictType
,NULL
);
2446 return createObject(REDIS_SET
,d
);
2449 static robj
*createZsetObject(void) {
2450 zset
*zs
= zmalloc(sizeof(*zs
));
2452 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2453 zs
->zsl
= zslCreate();
2454 return createObject(REDIS_ZSET
,zs
);
2457 static void freeStringObject(robj
*o
) {
2458 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2463 static void freeListObject(robj
*o
) {
2464 listRelease((list
*) o
->ptr
);
2467 static void freeSetObject(robj
*o
) {
2468 dictRelease((dict
*) o
->ptr
);
2471 static void freeZsetObject(robj
*o
) {
2474 dictRelease(zs
->dict
);
2479 static void freeHashObject(robj
*o
) {
2480 dictRelease((dict
*) o
->ptr
);
2483 static void incrRefCount(robj
*o
) {
2484 redisAssert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2488 static void decrRefCount(void *obj
) {
2491 /* Object is swapped out, or in the process of being loaded. */
2492 if (server
.vm_enabled
&&
2493 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
2495 if (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
) {
2496 redisAssert(o
->refcount
== 1);
2498 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
2499 redisAssert(o
->type
== REDIS_STRING
);
2500 freeStringObject(o
);
2501 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2502 pthread_mutex_lock(&server
.obj_freelist_mutex
);
2503 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2504 !listAddNodeHead(server
.objfreelist
,o
))
2506 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2507 server
.vm_stats_swapped_objects
--;
2510 /* Object is in memory, or in the process of being swapped out. */
2511 if (--(o
->refcount
) == 0) {
2512 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
2513 vmCancelThreadedIOJob(obj
);
2515 case REDIS_STRING
: freeStringObject(o
); break;
2516 case REDIS_LIST
: freeListObject(o
); break;
2517 case REDIS_SET
: freeSetObject(o
); break;
2518 case REDIS_ZSET
: freeZsetObject(o
); break;
2519 case REDIS_HASH
: freeHashObject(o
); break;
2520 default: redisAssert(0 != 0); break;
2522 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2523 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2524 !listAddNodeHead(server
.objfreelist
,o
))
2526 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2530 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2531 dictEntry
*de
= dictFind(db
->dict
,key
);
2533 robj
*key
= dictGetEntryKey(de
);
2534 robj
*val
= dictGetEntryVal(de
);
2536 if (server
.vm_enabled
) {
2537 if (key
->storage
== REDIS_VM_MEMORY
||
2538 key
->storage
== REDIS_VM_SWAPPING
)
2540 /* If we were swapping the object out, stop it, this key
2542 if (key
->storage
== REDIS_VM_SWAPPING
)
2543 vmCancelThreadedIOJob(key
);
2544 /* Update the access time of the key for the aging algorithm. */
2545 key
->vm
.atime
= server
.unixtime
;
2547 /* Our value was swapped on disk. Bring it at home. */
2548 redisAssert(val
== NULL
);
2549 val
= vmLoadObject(key
);
2550 dictGetEntryVal(de
) = val
;
2559 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2560 expireIfNeeded(db
,key
);
2561 return lookupKey(db
,key
);
2564 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2565 deleteIfVolatile(db
,key
);
2566 return lookupKey(db
,key
);
2569 static int deleteKey(redisDb
*db
, robj
*key
) {
2572 /* We need to protect key from destruction: after the first dictDelete()
2573 * it may happen that 'key' is no longer valid if we don't increment
2574 * it's count. This may happen when we get the object reference directly
2575 * from the hash table with dictRandomKey() or dict iterators */
2577 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2578 retval
= dictDelete(db
->dict
,key
);
2581 return retval
== DICT_OK
;
2584 /* Try to share an object against the shared objects pool */
2585 static robj
*tryObjectSharing(robj
*o
) {
2586 struct dictEntry
*de
;
2589 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2591 redisAssert(o
->type
== REDIS_STRING
);
2592 de
= dictFind(server
.sharingpool
,o
);
2594 robj
*shared
= dictGetEntryKey(de
);
2596 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2597 dictGetEntryVal(de
) = (void*) c
;
2598 incrRefCount(shared
);
2602 /* Here we are using a stream algorihtm: Every time an object is
2603 * shared we increment its count, everytime there is a miss we
2604 * recrement the counter of a random object. If this object reaches
2605 * zero we remove the object and put the current object instead. */
2606 if (dictSize(server
.sharingpool
) >=
2607 server
.sharingpoolsize
) {
2608 de
= dictGetRandomKey(server
.sharingpool
);
2609 redisAssert(de
!= NULL
);
2610 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2611 dictGetEntryVal(de
) = (void*) c
;
2613 dictDelete(server
.sharingpool
,de
->key
);
2616 c
= 0; /* If the pool is empty we want to add this object */
2621 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2622 redisAssert(retval
== DICT_OK
);
2629 /* Check if the nul-terminated string 's' can be represented by a long
2630 * (that is, is a number that fits into long without any other space or
2631 * character before or after the digits).
2633 * If so, the function returns REDIS_OK and *longval is set to the value
2634 * of the number. Otherwise REDIS_ERR is returned */
2635 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2636 char buf
[32], *endptr
;
2640 value
= strtol(s
, &endptr
, 10);
2641 if (endptr
[0] != '\0') return REDIS_ERR
;
2642 slen
= snprintf(buf
,32,"%ld",value
);
2644 /* If the number converted back into a string is not identical
2645 * then it's not possible to encode the string as integer */
2646 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2647 if (longval
) *longval
= value
;
2651 /* Try to encode a string object in order to save space */
2652 static int tryObjectEncoding(robj
*o
) {
2656 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2657 return REDIS_ERR
; /* Already encoded */
2659 /* It's not save to encode shared objects: shared objects can be shared
2660 * everywhere in the "object space" of Redis. Encoded objects can only
2661 * appear as "values" (and not, for instance, as keys) */
2662 if (o
->refcount
> 1) return REDIS_ERR
;
2664 /* Currently we try to encode only strings */
2665 redisAssert(o
->type
== REDIS_STRING
);
2667 /* Check if we can represent this string as a long integer */
2668 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2670 /* Ok, this object can be encoded */
2671 o
->encoding
= REDIS_ENCODING_INT
;
2673 o
->ptr
= (void*) value
;
2677 /* Get a decoded version of an encoded object (returned as a new object).
2678 * If the object is already raw-encoded just increment the ref count. */
2679 static robj
*getDecodedObject(robj
*o
) {
2682 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2686 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2689 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2690 dec
= createStringObject(buf
,strlen(buf
));
2693 redisAssert(1 != 1);
2697 /* Compare two string objects via strcmp() or alike.
2698 * Note that the objects may be integer-encoded. In such a case we
2699 * use snprintf() to get a string representation of the numbers on the stack
2700 * and compare the strings, it's much faster than calling getDecodedObject().
2702 * Important note: if objects are not integer encoded, but binary-safe strings,
2703 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2705 static int compareStringObjects(robj
*a
, robj
*b
) {
2706 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2707 char bufa
[128], bufb
[128], *astr
, *bstr
;
2710 if (a
== b
) return 0;
2711 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2712 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2718 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2719 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2725 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2728 static size_t stringObjectLen(robj
*o
) {
2729 redisAssert(o
->type
== REDIS_STRING
);
2730 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2731 return sdslen(o
->ptr
);
2735 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2739 /*============================ RDB saving/loading =========================== */
2741 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2742 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2746 static int rdbSaveTime(FILE *fp
, time_t t
) {
2747 int32_t t32
= (int32_t) t
;
2748 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2752 /* check rdbLoadLen() comments for more info */
2753 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2754 unsigned char buf
[2];
2757 /* Save a 6 bit len */
2758 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2759 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2760 } else if (len
< (1<<14)) {
2761 /* Save a 14 bit len */
2762 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2764 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2766 /* Save a 32 bit len */
2767 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2768 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2770 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2775 /* String objects in the form "2391" "-100" without any space and with a
2776 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2777 * encoded as integers to save space */
2778 static int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
2780 char *endptr
, buf
[32];
2782 /* Check if it's possible to encode this value as a number */
2783 value
= strtoll(s
, &endptr
, 10);
2784 if (endptr
[0] != '\0') return 0;
2785 snprintf(buf
,32,"%lld",value
);
2787 /* If the number converted back into a string is not identical
2788 * then it's not possible to encode the string as integer */
2789 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
2791 /* Finally check if it fits in our ranges */
2792 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2793 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2794 enc
[1] = value
&0xFF;
2796 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2797 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2798 enc
[1] = value
&0xFF;
2799 enc
[2] = (value
>>8)&0xFF;
2801 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2802 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2803 enc
[1] = value
&0xFF;
2804 enc
[2] = (value
>>8)&0xFF;
2805 enc
[3] = (value
>>16)&0xFF;
2806 enc
[4] = (value
>>24)&0xFF;
2813 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
2814 unsigned int comprlen
, outlen
;
2818 /* We require at least four bytes compression for this to be worth it */
2819 outlen
= sdslen(obj
->ptr
)-4;
2820 if (outlen
<= 0) return 0;
2821 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2822 printf("Calling LZF with ptr: %p\n", (void*)obj
->ptr
);
2824 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
2825 if (comprlen
== 0) {
2829 /* Data compressed! Let's save it on disk */
2830 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
2831 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
2832 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
2833 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
2834 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
2843 /* Save a string objet as [len][data] on disk. If the object is a string
2844 * representation of an integer value we try to safe it in a special form */
2845 static int rdbSaveStringObjectRaw(FILE *fp
, robj
*obj
) {
2849 len
= sdslen(obj
->ptr
);
2851 /* Try integer encoding */
2853 unsigned char buf
[5];
2854 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
2855 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
2860 /* Try LZF compression - under 20 bytes it's unable to compress even
2861 * aaaaaaaaaaaaaaaaaa so skip it */
2862 if (server
.rdbcompression
&& len
> 20) {
2865 retval
= rdbSaveLzfStringObject(fp
,obj
);
2866 if (retval
== -1) return -1;
2867 if (retval
> 0) return 0;
2868 /* retval == 0 means data can't be compressed, save the old way */
2871 /* Store verbatim */
2872 if (rdbSaveLen(fp
,len
) == -1) return -1;
2873 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
2877 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
2878 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
2881 /* Avoid incr/decr ref count business when possible.
2882 * This plays well with copy-on-write given that we are probably
2883 * in a child process (BGSAVE). Also this makes sure key objects
2884 * of swapped objects are not incRefCount-ed (an assert does not allow
2885 * this in order to avoid bugs) */
2886 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
2887 obj
= getDecodedObject(obj
);
2888 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2891 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2896 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
2897 * 8 bit integer specifing the length of the representation.
2898 * This 8 bit integer has special values in order to specify the following
2904 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
2905 unsigned char buf
[128];
2911 } else if (!isfinite(val
)) {
2913 buf
[0] = (val
< 0) ? 255 : 254;
2915 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
2916 buf
[0] = strlen((char*)buf
+1);
2919 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
2923 /* Save a Redis object. */
2924 static int rdbSaveObject(FILE *fp
, robj
*o
) {
2925 if (o
->type
== REDIS_STRING
) {
2926 /* Save a string value */
2927 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
2928 } else if (o
->type
== REDIS_LIST
) {
2929 /* Save a list value */
2930 list
*list
= o
->ptr
;
2934 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
2935 listRewind(list
,&li
);
2936 while((ln
= listNext(&li
))) {
2937 robj
*eleobj
= listNodeValue(ln
);
2939 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2941 } else if (o
->type
== REDIS_SET
) {
2942 /* Save a set value */
2944 dictIterator
*di
= dictGetIterator(set
);
2947 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
2948 while((de
= dictNext(di
)) != NULL
) {
2949 robj
*eleobj
= dictGetEntryKey(de
);
2951 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2953 dictReleaseIterator(di
);
2954 } else if (o
->type
== REDIS_ZSET
) {
2955 /* Save a set value */
2957 dictIterator
*di
= dictGetIterator(zs
->dict
);
2960 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
2961 while((de
= dictNext(di
)) != NULL
) {
2962 robj
*eleobj
= dictGetEntryKey(de
);
2963 double *score
= dictGetEntryVal(de
);
2965 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2966 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
2968 dictReleaseIterator(di
);
2970 redisAssert(0 != 0);
2975 /* Return the length the object will have on disk if saved with
2976 * the rdbSaveObject() function. Currently we use a trick to get
2977 * this length with very little changes to the code. In the future
2978 * we could switch to a faster solution. */
2979 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
2980 if (fp
== NULL
) fp
= server
.devnull
;
2982 assert(rdbSaveObject(fp
,o
) != 1);
2986 /* Return the number of pages required to save this object in the swap file */
2987 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
2988 off_t bytes
= rdbSavedObjectLen(o
,fp
);
2990 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
2993 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
2994 static int rdbSave(char *filename
) {
2995 dictIterator
*di
= NULL
;
3000 time_t now
= time(NULL
);
3002 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3003 fp
= fopen(tmpfile
,"w");
3005 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3008 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3009 for (j
= 0; j
< server
.dbnum
; j
++) {
3010 redisDb
*db
= server
.db
+j
;
3012 if (dictSize(d
) == 0) continue;
3013 di
= dictGetIterator(d
);
3019 /* Write the SELECT DB opcode */
3020 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3021 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3023 /* Iterate this DB writing every entry */
3024 while((de
= dictNext(di
)) != NULL
) {
3025 robj
*key
= dictGetEntryKey(de
);
3026 robj
*o
= dictGetEntryVal(de
);
3027 time_t expiretime
= getExpire(db
,key
);
3029 /* Save the expire time */
3030 if (expiretime
!= -1) {
3031 /* If this key is already expired skip it */
3032 if (expiretime
< now
) continue;
3033 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3034 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3036 /* Save the key and associated value. This requires special
3037 * handling if the value is swapped out. */
3038 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3039 key
->storage
== REDIS_VM_SWAPPING
) {
3040 /* Save type, key, value */
3041 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3042 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3043 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3045 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3047 /* Get a preview of the object in memory */
3048 po
= vmPreviewObject(key
);
3049 /* Save type, key, value */
3050 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3051 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3052 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3053 /* Remove the loaded object from memory */
3057 dictReleaseIterator(di
);
3060 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3062 /* Make sure data will not remain on the OS's output buffers */
3067 /* Use RENAME to make sure the DB file is changed atomically only
3068 * if the generate DB file is ok. */
3069 if (rename(tmpfile
,filename
) == -1) {
3070 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3074 redisLog(REDIS_NOTICE
,"DB saved on disk");
3076 server
.lastsave
= time(NULL
);
3082 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3083 if (di
) dictReleaseIterator(di
);
3087 static int rdbSaveBackground(char *filename
) {
3090 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3091 if (server
.vm_enabled
) waitZeroActiveThreads();
3092 if ((childpid
= fork()) == 0) {
3095 if (rdbSave(filename
) == REDIS_OK
) {
3102 if (childpid
== -1) {
3103 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3107 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3108 server
.bgsavechildpid
= childpid
;
3111 return REDIS_OK
; /* unreached */
3114 static void rdbRemoveTempFile(pid_t childpid
) {
3117 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3121 static int rdbLoadType(FILE *fp
) {
3123 if (fread(&type
,1,1,fp
) == 0) return -1;
3127 static time_t rdbLoadTime(FILE *fp
) {
3129 if (fread(&t32
,4,1,fp
) == 0) return -1;
3130 return (time_t) t32
;
3133 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3134 * of this file for a description of how this are stored on disk.
3136 * isencoded is set to 1 if the readed length is not actually a length but
3137 * an "encoding type", check the above comments for more info */
3138 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3139 unsigned char buf
[2];
3143 if (isencoded
) *isencoded
= 0;
3144 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3145 type
= (buf
[0]&0xC0)>>6;
3146 if (type
== REDIS_RDB_6BITLEN
) {
3147 /* Read a 6 bit len */
3149 } else if (type
== REDIS_RDB_ENCVAL
) {
3150 /* Read a 6 bit len encoding type */
3151 if (isencoded
) *isencoded
= 1;
3153 } else if (type
== REDIS_RDB_14BITLEN
) {
3154 /* Read a 14 bit len */
3155 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3156 return ((buf
[0]&0x3F)<<8)|buf
[1];
3158 /* Read a 32 bit len */
3159 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3164 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
3165 unsigned char enc
[4];
3168 if (enctype
== REDIS_RDB_ENC_INT8
) {
3169 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3170 val
= (signed char)enc
[0];
3171 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3173 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3174 v
= enc
[0]|(enc
[1]<<8);
3176 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3178 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3179 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3182 val
= 0; /* anti-warning */
3185 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3188 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3189 unsigned int len
, clen
;
3190 unsigned char *c
= NULL
;
3193 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3194 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3195 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3196 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3197 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3198 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3200 return createObject(REDIS_STRING
,val
);
3207 static robj
*rdbLoadStringObject(FILE*fp
) {
3212 len
= rdbLoadLen(fp
,&isencoded
);
3215 case REDIS_RDB_ENC_INT8
:
3216 case REDIS_RDB_ENC_INT16
:
3217 case REDIS_RDB_ENC_INT32
:
3218 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3219 case REDIS_RDB_ENC_LZF
:
3220 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3226 if (len
== REDIS_RDB_LENERR
) return NULL
;
3227 val
= sdsnewlen(NULL
,len
);
3228 if (len
&& fread(val
,len
,1,fp
) == 0) {
3232 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3235 /* For information about double serialization check rdbSaveDoubleValue() */
3236 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3240 if (fread(&len
,1,1,fp
) == 0) return -1;
3242 case 255: *val
= R_NegInf
; return 0;
3243 case 254: *val
= R_PosInf
; return 0;
3244 case 253: *val
= R_Nan
; return 0;
3246 if (fread(buf
,len
,1,fp
) == 0) return -1;
3248 sscanf(buf
, "%lg", val
);
3253 /* Load a Redis object of the specified type from the specified file.
3254 * On success a newly allocated object is returned, otherwise NULL. */
3255 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3258 if (type
== REDIS_STRING
) {
3259 /* Read string value */
3260 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3261 tryObjectEncoding(o
);
3262 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3263 /* Read list/set value */
3266 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3267 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3268 /* Load every single element of the list/set */
3272 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3273 tryObjectEncoding(ele
);
3274 if (type
== REDIS_LIST
) {
3275 listAddNodeTail((list
*)o
->ptr
,ele
);
3277 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3280 } else if (type
== REDIS_ZSET
) {
3281 /* Read list/set value */
3285 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3286 o
= createZsetObject();
3288 /* Load every single element of the list/set */
3291 double *score
= zmalloc(sizeof(double));
3293 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3294 tryObjectEncoding(ele
);
3295 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3296 dictAdd(zs
->dict
,ele
,score
);
3297 zslInsert(zs
->zsl
,*score
,ele
);
3298 incrRefCount(ele
); /* added to skiplist */
3301 redisAssert(0 != 0);
3306 static int rdbLoad(char *filename
) {
3308 robj
*keyobj
= NULL
;
3310 int type
, retval
, rdbver
;
3311 dict
*d
= server
.db
[0].dict
;
3312 redisDb
*db
= server
.db
+0;
3314 time_t expiretime
= -1, now
= time(NULL
);
3315 long long loadedkeys
= 0;
3317 fp
= fopen(filename
,"r");
3318 if (!fp
) return REDIS_ERR
;
3319 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3321 if (memcmp(buf
,"REDIS",5) != 0) {
3323 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3326 rdbver
= atoi(buf
+5);
3329 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3336 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3337 if (type
== REDIS_EXPIRETIME
) {
3338 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3339 /* We read the time so we need to read the object type again */
3340 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3342 if (type
== REDIS_EOF
) break;
3343 /* Handle SELECT DB opcode as a special case */
3344 if (type
== REDIS_SELECTDB
) {
3345 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3347 if (dbid
>= (unsigned)server
.dbnum
) {
3348 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3351 db
= server
.db
+dbid
;
3356 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3358 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3359 /* Add the new object in the hash table */
3360 retval
= dictAdd(d
,keyobj
,o
);
3361 if (retval
== DICT_ERR
) {
3362 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3365 /* Set the expire time if needed */
3366 if (expiretime
!= -1) {
3367 setExpire(db
,keyobj
,expiretime
);
3368 /* Delete this key if already expired */
3369 if (expiretime
< now
) deleteKey(db
,keyobj
);
3373 /* Handle swapping while loading big datasets when VM is on */
3375 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
3376 while (zmalloc_used_memory() > server
.vm_max_memory
) {
3377 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
3384 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3385 if (keyobj
) decrRefCount(keyobj
);
3386 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3388 return REDIS_ERR
; /* Just to avoid warning */
3391 /*================================== Commands =============================== */
3393 static void authCommand(redisClient
*c
) {
3394 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3395 c
->authenticated
= 1;
3396 addReply(c
,shared
.ok
);
3398 c
->authenticated
= 0;
3399 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3403 static void pingCommand(redisClient
*c
) {
3404 addReply(c
,shared
.pong
);
3407 static void echoCommand(redisClient
*c
) {
3408 addReplyBulkLen(c
,c
->argv
[1]);
3409 addReply(c
,c
->argv
[1]);
3410 addReply(c
,shared
.crlf
);
3413 /*=================================== Strings =============================== */
3415 static void setGenericCommand(redisClient
*c
, int nx
) {
3418 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3419 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3420 if (retval
== DICT_ERR
) {
3422 /* If the key is about a swapped value, we want a new key object
3423 * to overwrite the old. So we delete the old key in the database.
3424 * This will also make sure that swap pages about the old object
3425 * will be marked as free. */
3426 if (deleteIfSwapped(c
->db
,c
->argv
[1]))
3427 incrRefCount(c
->argv
[1]);
3428 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3429 incrRefCount(c
->argv
[2]);
3431 addReply(c
,shared
.czero
);
3435 incrRefCount(c
->argv
[1]);
3436 incrRefCount(c
->argv
[2]);
3439 removeExpire(c
->db
,c
->argv
[1]);
3440 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3443 static void setCommand(redisClient
*c
) {
3444 setGenericCommand(c
,0);
3447 static void setnxCommand(redisClient
*c
) {
3448 setGenericCommand(c
,1);
3451 static int getGenericCommand(redisClient
*c
) {
3452 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3455 addReply(c
,shared
.nullbulk
);
3458 if (o
->type
!= REDIS_STRING
) {
3459 addReply(c
,shared
.wrongtypeerr
);
3462 addReplyBulkLen(c
,o
);
3464 addReply(c
,shared
.crlf
);
3470 static void getCommand(redisClient
*c
) {
3471 getGenericCommand(c
);
3474 static void getsetCommand(redisClient
*c
) {
3475 if (getGenericCommand(c
) == REDIS_ERR
) return;
3476 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3477 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3479 incrRefCount(c
->argv
[1]);
3481 incrRefCount(c
->argv
[2]);
3483 removeExpire(c
->db
,c
->argv
[1]);
3486 static void mgetCommand(redisClient
*c
) {
3489 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3490 for (j
= 1; j
< c
->argc
; j
++) {
3491 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3493 addReply(c
,shared
.nullbulk
);
3495 if (o
->type
!= REDIS_STRING
) {
3496 addReply(c
,shared
.nullbulk
);
3498 addReplyBulkLen(c
,o
);
3500 addReply(c
,shared
.crlf
);
3506 static void msetGenericCommand(redisClient
*c
, int nx
) {
3507 int j
, busykeys
= 0;
3509 if ((c
->argc
% 2) == 0) {
3510 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3513 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3514 * set nothing at all if at least one already key exists. */
3516 for (j
= 1; j
< c
->argc
; j
+= 2) {
3517 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3523 addReply(c
, shared
.czero
);
3527 for (j
= 1; j
< c
->argc
; j
+= 2) {
3530 tryObjectEncoding(c
->argv
[j
+1]);
3531 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3532 if (retval
== DICT_ERR
) {
3533 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3534 incrRefCount(c
->argv
[j
+1]);
3536 incrRefCount(c
->argv
[j
]);
3537 incrRefCount(c
->argv
[j
+1]);
3539 removeExpire(c
->db
,c
->argv
[j
]);
3541 server
.dirty
+= (c
->argc
-1)/2;
3542 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3545 static void msetCommand(redisClient
*c
) {
3546 msetGenericCommand(c
,0);
3549 static void msetnxCommand(redisClient
*c
) {
3550 msetGenericCommand(c
,1);
3553 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3558 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3562 if (o
->type
!= REDIS_STRING
) {
3567 if (o
->encoding
== REDIS_ENCODING_RAW
)
3568 value
= strtoll(o
->ptr
, &eptr
, 10);
3569 else if (o
->encoding
== REDIS_ENCODING_INT
)
3570 value
= (long)o
->ptr
;
3572 redisAssert(1 != 1);
3577 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3578 tryObjectEncoding(o
);
3579 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3580 if (retval
== DICT_ERR
) {
3581 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3582 removeExpire(c
->db
,c
->argv
[1]);
3584 incrRefCount(c
->argv
[1]);
3587 addReply(c
,shared
.colon
);
3589 addReply(c
,shared
.crlf
);
3592 static void incrCommand(redisClient
*c
) {
3593 incrDecrCommand(c
,1);
3596 static void decrCommand(redisClient
*c
) {
3597 incrDecrCommand(c
,-1);
3600 static void incrbyCommand(redisClient
*c
) {
3601 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3602 incrDecrCommand(c
,incr
);
3605 static void decrbyCommand(redisClient
*c
) {
3606 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3607 incrDecrCommand(c
,-incr
);
3610 /* ========================= Type agnostic commands ========================= */
3612 static void delCommand(redisClient
*c
) {
3615 for (j
= 1; j
< c
->argc
; j
++) {
3616 if (deleteKey(c
->db
,c
->argv
[j
])) {
3623 addReply(c
,shared
.czero
);
3626 addReply(c
,shared
.cone
);
3629 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3634 static void existsCommand(redisClient
*c
) {
3635 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3638 static void selectCommand(redisClient
*c
) {
3639 int id
= atoi(c
->argv
[1]->ptr
);
3641 if (selectDb(c
,id
) == REDIS_ERR
) {
3642 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3644 addReply(c
,shared
.ok
);
3648 static void randomkeyCommand(redisClient
*c
) {
3652 de
= dictGetRandomKey(c
->db
->dict
);
3653 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3656 addReply(c
,shared
.plus
);
3657 addReply(c
,shared
.crlf
);
3659 addReply(c
,shared
.plus
);
3660 addReply(c
,dictGetEntryKey(de
));
3661 addReply(c
,shared
.crlf
);
3665 static void keysCommand(redisClient
*c
) {
3668 sds pattern
= c
->argv
[1]->ptr
;
3669 int plen
= sdslen(pattern
);
3670 unsigned long numkeys
= 0, keyslen
= 0;
3671 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
3673 di
= dictGetIterator(c
->db
->dict
);
3675 decrRefCount(lenobj
);
3676 while((de
= dictNext(di
)) != NULL
) {
3677 robj
*keyobj
= dictGetEntryKey(de
);
3679 sds key
= keyobj
->ptr
;
3680 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
3681 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
3682 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
3684 addReply(c
,shared
.space
);
3687 keyslen
+= sdslen(key
);
3691 dictReleaseIterator(di
);
3692 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
3693 addReply(c
,shared
.crlf
);
3696 static void dbsizeCommand(redisClient
*c
) {
3698 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
3701 static void lastsaveCommand(redisClient
*c
) {
3703 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
3706 static void typeCommand(redisClient
*c
) {
3710 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3715 case REDIS_STRING
: type
= "+string"; break;
3716 case REDIS_LIST
: type
= "+list"; break;
3717 case REDIS_SET
: type
= "+set"; break;
3718 case REDIS_ZSET
: type
= "+zset"; break;
3719 default: type
= "unknown"; break;
3722 addReplySds(c
,sdsnew(type
));
3723 addReply(c
,shared
.crlf
);
3726 static void saveCommand(redisClient
*c
) {
3727 if (server
.bgsavechildpid
!= -1) {
3728 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
3731 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3732 addReply(c
,shared
.ok
);
3734 addReply(c
,shared
.err
);
3738 static void bgsaveCommand(redisClient
*c
) {
3739 if (server
.bgsavechildpid
!= -1) {
3740 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
3743 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
3744 char *status
= "+Background saving started\r\n";
3745 addReplySds(c
,sdsnew(status
));
3747 addReply(c
,shared
.err
);
3751 static void shutdownCommand(redisClient
*c
) {
3752 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
3753 /* Kill the saving child if there is a background saving in progress.
3754 We want to avoid race conditions, for instance our saving child may
3755 overwrite the synchronous saving did by SHUTDOWN. */
3756 if (server
.bgsavechildpid
!= -1) {
3757 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
3758 kill(server
.bgsavechildpid
,SIGKILL
);
3759 rdbRemoveTempFile(server
.bgsavechildpid
);
3761 if (server
.appendonly
) {
3762 /* Append only file: fsync() the AOF and exit */
3763 fsync(server
.appendfd
);
3766 /* Snapshotting. Perform a SYNC SAVE and exit */
3767 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3768 if (server
.daemonize
)
3769 unlink(server
.pidfile
);
3770 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
3771 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
3774 /* Ooops.. error saving! The best we can do is to continue operating.
3775 * Note that if there was a background saving process, in the next
3776 * cron() Redis will be notified that the background saving aborted,
3777 * handling special stuff like slaves pending for synchronization... */
3778 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
3779 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3784 static void renameGenericCommand(redisClient
*c
, int nx
) {
3787 /* To use the same key as src and dst is probably an error */
3788 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
3789 addReply(c
,shared
.sameobjecterr
);
3793 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3795 addReply(c
,shared
.nokeyerr
);
3799 deleteIfVolatile(c
->db
,c
->argv
[2]);
3800 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
3803 addReply(c
,shared
.czero
);
3806 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
3808 incrRefCount(c
->argv
[2]);
3810 deleteKey(c
->db
,c
->argv
[1]);
3812 addReply(c
,nx
? shared
.cone
: shared
.ok
);
3815 static void renameCommand(redisClient
*c
) {
3816 renameGenericCommand(c
,0);
3819 static void renamenxCommand(redisClient
*c
) {
3820 renameGenericCommand(c
,1);
3823 static void moveCommand(redisClient
*c
) {
3828 /* Obtain source and target DB pointers */
3831 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
3832 addReply(c
,shared
.outofrangeerr
);
3836 selectDb(c
,srcid
); /* Back to the source DB */
3838 /* If the user is moving using as target the same
3839 * DB as the source DB it is probably an error. */
3841 addReply(c
,shared
.sameobjecterr
);
3845 /* Check if the element exists and get a reference */
3846 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3848 addReply(c
,shared
.czero
);
3852 /* Try to add the element to the target DB */
3853 deleteIfVolatile(dst
,c
->argv
[1]);
3854 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
3855 addReply(c
,shared
.czero
);
3858 incrRefCount(c
->argv
[1]);
3861 /* OK! key moved, free the entry in the source DB */
3862 deleteKey(src
,c
->argv
[1]);
3864 addReply(c
,shared
.cone
);
3867 /* =================================== Lists ================================ */
3868 static void pushGenericCommand(redisClient
*c
, int where
) {
3872 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3874 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3875 addReply(c
,shared
.ok
);
3878 lobj
= createListObject();
3880 if (where
== REDIS_HEAD
) {
3881 listAddNodeHead(list
,c
->argv
[2]);
3883 listAddNodeTail(list
,c
->argv
[2]);
3885 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
3886 incrRefCount(c
->argv
[1]);
3887 incrRefCount(c
->argv
[2]);
3889 if (lobj
->type
!= REDIS_LIST
) {
3890 addReply(c
,shared
.wrongtypeerr
);
3893 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3894 addReply(c
,shared
.ok
);
3898 if (where
== REDIS_HEAD
) {
3899 listAddNodeHead(list
,c
->argv
[2]);
3901 listAddNodeTail(list
,c
->argv
[2]);
3903 incrRefCount(c
->argv
[2]);
3906 addReply(c
,shared
.ok
);
3909 static void lpushCommand(redisClient
*c
) {
3910 pushGenericCommand(c
,REDIS_HEAD
);
3913 static void rpushCommand(redisClient
*c
) {
3914 pushGenericCommand(c
,REDIS_TAIL
);
3917 static void llenCommand(redisClient
*c
) {
3921 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3923 addReply(c
,shared
.czero
);
3926 if (o
->type
!= REDIS_LIST
) {
3927 addReply(c
,shared
.wrongtypeerr
);
3930 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
3935 static void lindexCommand(redisClient
*c
) {
3937 int index
= atoi(c
->argv
[2]->ptr
);
3939 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3941 addReply(c
,shared
.nullbulk
);
3943 if (o
->type
!= REDIS_LIST
) {
3944 addReply(c
,shared
.wrongtypeerr
);
3946 list
*list
= o
->ptr
;
3949 ln
= listIndex(list
, index
);
3951 addReply(c
,shared
.nullbulk
);
3953 robj
*ele
= listNodeValue(ln
);
3954 addReplyBulkLen(c
,ele
);
3956 addReply(c
,shared
.crlf
);
3962 static void lsetCommand(redisClient
*c
) {
3964 int index
= atoi(c
->argv
[2]->ptr
);
3966 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3968 addReply(c
,shared
.nokeyerr
);
3970 if (o
->type
!= REDIS_LIST
) {
3971 addReply(c
,shared
.wrongtypeerr
);
3973 list
*list
= o
->ptr
;
3976 ln
= listIndex(list
, index
);
3978 addReply(c
,shared
.outofrangeerr
);
3980 robj
*ele
= listNodeValue(ln
);
3983 listNodeValue(ln
) = c
->argv
[3];
3984 incrRefCount(c
->argv
[3]);
3985 addReply(c
,shared
.ok
);
3992 static void popGenericCommand(redisClient
*c
, int where
) {
3995 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3997 addReply(c
,shared
.nullbulk
);
3999 if (o
->type
!= REDIS_LIST
) {
4000 addReply(c
,shared
.wrongtypeerr
);
4002 list
*list
= o
->ptr
;
4005 if (where
== REDIS_HEAD
)
4006 ln
= listFirst(list
);
4008 ln
= listLast(list
);
4011 addReply(c
,shared
.nullbulk
);
4013 robj
*ele
= listNodeValue(ln
);
4014 addReplyBulkLen(c
,ele
);
4016 addReply(c
,shared
.crlf
);
4017 listDelNode(list
,ln
);
4024 static void lpopCommand(redisClient
*c
) {
4025 popGenericCommand(c
,REDIS_HEAD
);
4028 static void rpopCommand(redisClient
*c
) {
4029 popGenericCommand(c
,REDIS_TAIL
);
4032 static void lrangeCommand(redisClient
*c
) {
4034 int start
= atoi(c
->argv
[2]->ptr
);
4035 int end
= atoi(c
->argv
[3]->ptr
);
4037 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4039 addReply(c
,shared
.nullmultibulk
);
4041 if (o
->type
!= REDIS_LIST
) {
4042 addReply(c
,shared
.wrongtypeerr
);
4044 list
*list
= o
->ptr
;
4046 int llen
= listLength(list
);
4050 /* convert negative indexes */
4051 if (start
< 0) start
= llen
+start
;
4052 if (end
< 0) end
= llen
+end
;
4053 if (start
< 0) start
= 0;
4054 if (end
< 0) end
= 0;
4056 /* indexes sanity checks */
4057 if (start
> end
|| start
>= llen
) {
4058 /* Out of range start or start > end result in empty list */
4059 addReply(c
,shared
.emptymultibulk
);
4062 if (end
>= llen
) end
= llen
-1;
4063 rangelen
= (end
-start
)+1;
4065 /* Return the result in form of a multi-bulk reply */
4066 ln
= listIndex(list
, start
);
4067 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4068 for (j
= 0; j
< rangelen
; j
++) {
4069 ele
= listNodeValue(ln
);
4070 addReplyBulkLen(c
,ele
);
4072 addReply(c
,shared
.crlf
);
4079 static void ltrimCommand(redisClient
*c
) {
4081 int start
= atoi(c
->argv
[2]->ptr
);
4082 int end
= atoi(c
->argv
[3]->ptr
);
4084 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4086 addReply(c
,shared
.ok
);
4088 if (o
->type
!= REDIS_LIST
) {
4089 addReply(c
,shared
.wrongtypeerr
);
4091 list
*list
= o
->ptr
;
4093 int llen
= listLength(list
);
4094 int j
, ltrim
, rtrim
;
4096 /* convert negative indexes */
4097 if (start
< 0) start
= llen
+start
;
4098 if (end
< 0) end
= llen
+end
;
4099 if (start
< 0) start
= 0;
4100 if (end
< 0) end
= 0;
4102 /* indexes sanity checks */
4103 if (start
> end
|| start
>= llen
) {
4104 /* Out of range start or start > end result in empty list */
4108 if (end
>= llen
) end
= llen
-1;
4113 /* Remove list elements to perform the trim */
4114 for (j
= 0; j
< ltrim
; j
++) {
4115 ln
= listFirst(list
);
4116 listDelNode(list
,ln
);
4118 for (j
= 0; j
< rtrim
; j
++) {
4119 ln
= listLast(list
);
4120 listDelNode(list
,ln
);
4123 addReply(c
,shared
.ok
);
4128 static void lremCommand(redisClient
*c
) {
4131 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4133 addReply(c
,shared
.czero
);
4135 if (o
->type
!= REDIS_LIST
) {
4136 addReply(c
,shared
.wrongtypeerr
);
4138 list
*list
= o
->ptr
;
4139 listNode
*ln
, *next
;
4140 int toremove
= atoi(c
->argv
[2]->ptr
);
4145 toremove
= -toremove
;
4148 ln
= fromtail
? list
->tail
: list
->head
;
4150 robj
*ele
= listNodeValue(ln
);
4152 next
= fromtail
? ln
->prev
: ln
->next
;
4153 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
4154 listDelNode(list
,ln
);
4157 if (toremove
&& removed
== toremove
) break;
4161 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4166 /* This is the semantic of this command:
4167 * RPOPLPUSH srclist dstlist:
4168 * IF LLEN(srclist) > 0
4169 * element = RPOP srclist
4170 * LPUSH dstlist element
4177 * The idea is to be able to get an element from a list in a reliable way
4178 * since the element is not just returned but pushed against another list
4179 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4181 static void rpoplpushcommand(redisClient
*c
) {
4184 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4186 addReply(c
,shared
.nullbulk
);
4188 if (sobj
->type
!= REDIS_LIST
) {
4189 addReply(c
,shared
.wrongtypeerr
);
4191 list
*srclist
= sobj
->ptr
;
4192 listNode
*ln
= listLast(srclist
);
4195 addReply(c
,shared
.nullbulk
);
4197 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4198 robj
*ele
= listNodeValue(ln
);
4201 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4202 addReply(c
,shared
.wrongtypeerr
);
4206 /* Add the element to the target list (unless it's directly
4207 * passed to some BLPOP-ing client */
4208 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4210 /* Create the list if the key does not exist */
4211 dobj
= createListObject();
4212 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4213 incrRefCount(c
->argv
[2]);
4215 dstlist
= dobj
->ptr
;
4216 listAddNodeHead(dstlist
,ele
);
4220 /* Send the element to the client as reply as well */
4221 addReplyBulkLen(c
,ele
);
4223 addReply(c
,shared
.crlf
);
4225 /* Finally remove the element from the source list */
4226 listDelNode(srclist
,ln
);
4234 /* ==================================== Sets ================================ */
4236 static void saddCommand(redisClient
*c
) {
4239 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4241 set
= createSetObject();
4242 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4243 incrRefCount(c
->argv
[1]);
4245 if (set
->type
!= REDIS_SET
) {
4246 addReply(c
,shared
.wrongtypeerr
);
4250 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4251 incrRefCount(c
->argv
[2]);
4253 addReply(c
,shared
.cone
);
4255 addReply(c
,shared
.czero
);
4259 static void sremCommand(redisClient
*c
) {
4262 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4264 addReply(c
,shared
.czero
);
4266 if (set
->type
!= REDIS_SET
) {
4267 addReply(c
,shared
.wrongtypeerr
);
4270 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4272 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4273 addReply(c
,shared
.cone
);
4275 addReply(c
,shared
.czero
);
4280 static void smoveCommand(redisClient
*c
) {
4281 robj
*srcset
, *dstset
;
4283 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4284 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4286 /* If the source key does not exist return 0, if it's of the wrong type
4288 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4289 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4292 /* Error if the destination key is not a set as well */
4293 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4294 addReply(c
,shared
.wrongtypeerr
);
4297 /* Remove the element from the source set */
4298 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4299 /* Key not found in the src set! return zero */
4300 addReply(c
,shared
.czero
);
4304 /* Add the element to the destination set */
4306 dstset
= createSetObject();
4307 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4308 incrRefCount(c
->argv
[2]);
4310 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4311 incrRefCount(c
->argv
[3]);
4312 addReply(c
,shared
.cone
);
4315 static void sismemberCommand(redisClient
*c
) {
4318 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4320 addReply(c
,shared
.czero
);
4322 if (set
->type
!= REDIS_SET
) {
4323 addReply(c
,shared
.wrongtypeerr
);
4326 if (dictFind(set
->ptr
,c
->argv
[2]))
4327 addReply(c
,shared
.cone
);
4329 addReply(c
,shared
.czero
);
4333 static void scardCommand(redisClient
*c
) {
4337 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4339 addReply(c
,shared
.czero
);
4342 if (o
->type
!= REDIS_SET
) {
4343 addReply(c
,shared
.wrongtypeerr
);
4346 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4352 static void spopCommand(redisClient
*c
) {
4356 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4358 addReply(c
,shared
.nullbulk
);
4360 if (set
->type
!= REDIS_SET
) {
4361 addReply(c
,shared
.wrongtypeerr
);
4364 de
= dictGetRandomKey(set
->ptr
);
4366 addReply(c
,shared
.nullbulk
);
4368 robj
*ele
= dictGetEntryKey(de
);
4370 addReplyBulkLen(c
,ele
);
4372 addReply(c
,shared
.crlf
);
4373 dictDelete(set
->ptr
,ele
);
4374 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4380 static void srandmemberCommand(redisClient
*c
) {
4384 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4386 addReply(c
,shared
.nullbulk
);
4388 if (set
->type
!= REDIS_SET
) {
4389 addReply(c
,shared
.wrongtypeerr
);
4392 de
= dictGetRandomKey(set
->ptr
);
4394 addReply(c
,shared
.nullbulk
);
4396 robj
*ele
= dictGetEntryKey(de
);
4398 addReplyBulkLen(c
,ele
);
4400 addReply(c
,shared
.crlf
);
4405 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4406 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4408 return dictSize(*d1
)-dictSize(*d2
);
4411 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4412 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4415 robj
*lenobj
= NULL
, *dstset
= NULL
;
4416 unsigned long j
, cardinality
= 0;
4418 for (j
= 0; j
< setsnum
; j
++) {
4422 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4423 lookupKeyRead(c
->db
,setskeys
[j
]);
4427 if (deleteKey(c
->db
,dstkey
))
4429 addReply(c
,shared
.czero
);
4431 addReply(c
,shared
.nullmultibulk
);
4435 if (setobj
->type
!= REDIS_SET
) {
4437 addReply(c
,shared
.wrongtypeerr
);
4440 dv
[j
] = setobj
->ptr
;
4442 /* Sort sets from the smallest to largest, this will improve our
4443 * algorithm's performace */
4444 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4446 /* The first thing we should output is the total number of elements...
4447 * since this is a multi-bulk write, but at this stage we don't know
4448 * the intersection set size, so we use a trick, append an empty object
4449 * to the output list and save the pointer to later modify it with the
4452 lenobj
= createObject(REDIS_STRING
,NULL
);
4454 decrRefCount(lenobj
);
4456 /* If we have a target key where to store the resulting set
4457 * create this key with an empty set inside */
4458 dstset
= createSetObject();
4461 /* Iterate all the elements of the first (smallest) set, and test
4462 * the element against all the other sets, if at least one set does
4463 * not include the element it is discarded */
4464 di
= dictGetIterator(dv
[0]);
4466 while((de
= dictNext(di
)) != NULL
) {
4469 for (j
= 1; j
< setsnum
; j
++)
4470 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4472 continue; /* at least one set does not contain the member */
4473 ele
= dictGetEntryKey(de
);
4475 addReplyBulkLen(c
,ele
);
4477 addReply(c
,shared
.crlf
);
4480 dictAdd(dstset
->ptr
,ele
,NULL
);
4484 dictReleaseIterator(di
);
4487 /* Store the resulting set into the target */
4488 deleteKey(c
->db
,dstkey
);
4489 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4490 incrRefCount(dstkey
);
4494 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4496 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4497 dictSize((dict
*)dstset
->ptr
)));
4503 static void sinterCommand(redisClient
*c
) {
4504 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4507 static void sinterstoreCommand(redisClient
*c
) {
4508 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4511 #define REDIS_OP_UNION 0
4512 #define REDIS_OP_DIFF 1
4514 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4515 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4518 robj
*dstset
= NULL
;
4519 int j
, cardinality
= 0;
4521 for (j
= 0; j
< setsnum
; j
++) {
4525 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4526 lookupKeyRead(c
->db
,setskeys
[j
]);
4531 if (setobj
->type
!= REDIS_SET
) {
4533 addReply(c
,shared
.wrongtypeerr
);
4536 dv
[j
] = setobj
->ptr
;
4539 /* We need a temp set object to store our union. If the dstkey
4540 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4541 * this set object will be the resulting object to set into the target key*/
4542 dstset
= createSetObject();
4544 /* Iterate all the elements of all the sets, add every element a single
4545 * time to the result set */
4546 for (j
= 0; j
< setsnum
; j
++) {
4547 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4548 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4550 di
= dictGetIterator(dv
[j
]);
4552 while((de
= dictNext(di
)) != NULL
) {
4555 /* dictAdd will not add the same element multiple times */
4556 ele
= dictGetEntryKey(de
);
4557 if (op
== REDIS_OP_UNION
|| j
== 0) {
4558 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4562 } else if (op
== REDIS_OP_DIFF
) {
4563 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4568 dictReleaseIterator(di
);
4570 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4573 /* Output the content of the resulting set, if not in STORE mode */
4575 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4576 di
= dictGetIterator(dstset
->ptr
);
4577 while((de
= dictNext(di
)) != NULL
) {
4580 ele
= dictGetEntryKey(de
);
4581 addReplyBulkLen(c
,ele
);
4583 addReply(c
,shared
.crlf
);
4585 dictReleaseIterator(di
);
4587 /* If we have a target key where to store the resulting set
4588 * create this key with the result set inside */
4589 deleteKey(c
->db
,dstkey
);
4590 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4591 incrRefCount(dstkey
);
4596 decrRefCount(dstset
);
4598 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4599 dictSize((dict
*)dstset
->ptr
)));
4605 static void sunionCommand(redisClient
*c
) {
4606 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4609 static void sunionstoreCommand(redisClient
*c
) {
4610 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4613 static void sdiffCommand(redisClient
*c
) {
4614 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4617 static void sdiffstoreCommand(redisClient
*c
) {
4618 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4621 /* ==================================== ZSets =============================== */
4623 /* ZSETs are ordered sets using two data structures to hold the same elements
4624 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4627 * The elements are added to an hash table mapping Redis objects to scores.
4628 * At the same time the elements are added to a skip list mapping scores
4629 * to Redis objects (so objects are sorted by scores in this "view"). */
4631 /* This skiplist implementation is almost a C translation of the original
4632 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4633 * Alternative to Balanced Trees", modified in three ways:
4634 * a) this implementation allows for repeated values.
4635 * b) the comparison is not just by key (our 'score') but by satellite data.
4636 * c) there is a back pointer, so it's a doubly linked list with the back
4637 * pointers being only at "level 1". This allows to traverse the list
4638 * from tail to head, useful for ZREVRANGE. */
4640 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4641 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4643 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4649 static zskiplist
*zslCreate(void) {
4653 zsl
= zmalloc(sizeof(*zsl
));
4656 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4657 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++)
4658 zsl
->header
->forward
[j
] = NULL
;
4659 zsl
->header
->backward
= NULL
;
4664 static void zslFreeNode(zskiplistNode
*node
) {
4665 decrRefCount(node
->obj
);
4666 zfree(node
->forward
);
4670 static void zslFree(zskiplist
*zsl
) {
4671 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4673 zfree(zsl
->header
->forward
);
4676 next
= node
->forward
[0];
4683 static int zslRandomLevel(void) {
4685 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
4690 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
4691 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4695 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4696 while (x
->forward
[i
] &&
4697 (x
->forward
[i
]->score
< score
||
4698 (x
->forward
[i
]->score
== score
&&
4699 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4703 /* we assume the key is not already inside, since we allow duplicated
4704 * scores, and the re-insertion of score and redis object should never
4705 * happpen since the caller of zslInsert() should test in the hash table
4706 * if the element is already inside or not. */
4707 level
= zslRandomLevel();
4708 if (level
> zsl
->level
) {
4709 for (i
= zsl
->level
; i
< level
; i
++)
4710 update
[i
] = zsl
->header
;
4713 x
= zslCreateNode(level
,score
,obj
);
4714 for (i
= 0; i
< level
; i
++) {
4715 x
->forward
[i
] = update
[i
]->forward
[i
];
4716 update
[i
]->forward
[i
] = x
;
4718 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
4720 x
->forward
[0]->backward
= x
;
4726 /* Delete an element with matching score/object from the skiplist. */
4727 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
4728 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4732 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4733 while (x
->forward
[i
] &&
4734 (x
->forward
[i
]->score
< score
||
4735 (x
->forward
[i
]->score
== score
&&
4736 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4740 /* We may have multiple elements with the same score, what we need
4741 * is to find the element with both the right score and object. */
4743 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
4744 for (i
= 0; i
< zsl
->level
; i
++) {
4745 if (update
[i
]->forward
[i
] != x
) break;
4746 update
[i
]->forward
[i
] = x
->forward
[i
];
4748 if (x
->forward
[0]) {
4749 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4752 zsl
->tail
= x
->backward
;
4755 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4760 return 0; /* not found */
4762 return 0; /* not found */
4765 /* Delete all the elements with score between min and max from the skiplist.
4766 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4767 * Note that this function takes the reference to the hash table view of the
4768 * sorted set, in order to remove the elements from the hash table too. */
4769 static unsigned long zslDeleteRange(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
4770 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4771 unsigned long removed
= 0;
4775 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4776 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
4780 /* We may have multiple elements with the same score, what we need
4781 * is to find the element with both the right score and object. */
4783 while (x
&& x
->score
<= max
) {
4784 zskiplistNode
*next
;
4786 for (i
= 0; i
< zsl
->level
; i
++) {
4787 if (update
[i
]->forward
[i
] != x
) break;
4788 update
[i
]->forward
[i
] = x
->forward
[i
];
4790 if (x
->forward
[0]) {
4791 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4794 zsl
->tail
= x
->backward
;
4796 next
= x
->forward
[0];
4797 dictDelete(dict
,x
->obj
);
4799 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4805 return removed
; /* not found */
4808 /* Find the first node having a score equal or greater than the specified one.
4809 * Returns NULL if there is no match. */
4810 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
4815 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4816 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
4819 /* We may have multiple elements with the same score, what we need
4820 * is to find the element with both the right score and object. */
4821 return x
->forward
[0];
4824 /* The actual Z-commands implementations */
4826 /* This generic command implements both ZADD and ZINCRBY.
4827 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
4828 * the increment if the operation is a ZINCRBY (doincrement == 1). */
4829 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
4834 zsetobj
= lookupKeyWrite(c
->db
,key
);
4835 if (zsetobj
== NULL
) {
4836 zsetobj
= createZsetObject();
4837 dictAdd(c
->db
->dict
,key
,zsetobj
);
4840 if (zsetobj
->type
!= REDIS_ZSET
) {
4841 addReply(c
,shared
.wrongtypeerr
);
4847 /* Ok now since we implement both ZADD and ZINCRBY here the code
4848 * needs to handle the two different conditions. It's all about setting
4849 * '*score', that is, the new score to set, to the right value. */
4850 score
= zmalloc(sizeof(double));
4854 /* Read the old score. If the element was not present starts from 0 */
4855 de
= dictFind(zs
->dict
,ele
);
4857 double *oldscore
= dictGetEntryVal(de
);
4858 *score
= *oldscore
+ scoreval
;
4866 /* What follows is a simple remove and re-insert operation that is common
4867 * to both ZADD and ZINCRBY... */
4868 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
4869 /* case 1: New element */
4870 incrRefCount(ele
); /* added to hash */
4871 zslInsert(zs
->zsl
,*score
,ele
);
4872 incrRefCount(ele
); /* added to skiplist */
4875 addReplyDouble(c
,*score
);
4877 addReply(c
,shared
.cone
);
4882 /* case 2: Score update operation */
4883 de
= dictFind(zs
->dict
,ele
);
4884 redisAssert(de
!= NULL
);
4885 oldscore
= dictGetEntryVal(de
);
4886 if (*score
!= *oldscore
) {
4889 /* Remove and insert the element in the skip list with new score */
4890 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
4891 redisAssert(deleted
!= 0);
4892 zslInsert(zs
->zsl
,*score
,ele
);
4894 /* Update the score in the hash table */
4895 dictReplace(zs
->dict
,ele
,score
);
4901 addReplyDouble(c
,*score
);
4903 addReply(c
,shared
.czero
);
4907 static void zaddCommand(redisClient
*c
) {
4910 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4911 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
4914 static void zincrbyCommand(redisClient
*c
) {
4917 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4918 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
4921 static void zremCommand(redisClient
*c
) {
4925 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4926 if (zsetobj
== NULL
) {
4927 addReply(c
,shared
.czero
);
4933 if (zsetobj
->type
!= REDIS_ZSET
) {
4934 addReply(c
,shared
.wrongtypeerr
);
4938 de
= dictFind(zs
->dict
,c
->argv
[2]);
4940 addReply(c
,shared
.czero
);
4943 /* Delete from the skiplist */
4944 oldscore
= dictGetEntryVal(de
);
4945 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
4946 redisAssert(deleted
!= 0);
4948 /* Delete from the hash table */
4949 dictDelete(zs
->dict
,c
->argv
[2]);
4950 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4952 addReply(c
,shared
.cone
);
4956 static void zremrangebyscoreCommand(redisClient
*c
) {
4957 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4958 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4962 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4963 if (zsetobj
== NULL
) {
4964 addReply(c
,shared
.czero
);
4968 if (zsetobj
->type
!= REDIS_ZSET
) {
4969 addReply(c
,shared
.wrongtypeerr
);
4973 deleted
= zslDeleteRange(zs
->zsl
,min
,max
,zs
->dict
);
4974 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4975 server
.dirty
+= deleted
;
4976 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
4980 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
4982 int start
= atoi(c
->argv
[2]->ptr
);
4983 int end
= atoi(c
->argv
[3]->ptr
);
4986 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
4988 } else if (c
->argc
>= 5) {
4989 addReply(c
,shared
.syntaxerr
);
4993 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4995 addReply(c
,shared
.nullmultibulk
);
4997 if (o
->type
!= REDIS_ZSET
) {
4998 addReply(c
,shared
.wrongtypeerr
);
5000 zset
*zsetobj
= o
->ptr
;
5001 zskiplist
*zsl
= zsetobj
->zsl
;
5004 int llen
= zsl
->length
;
5008 /* convert negative indexes */
5009 if (start
< 0) start
= llen
+start
;
5010 if (end
< 0) end
= llen
+end
;
5011 if (start
< 0) start
= 0;
5012 if (end
< 0) end
= 0;
5014 /* indexes sanity checks */
5015 if (start
> end
|| start
>= llen
) {
5016 /* Out of range start or start > end result in empty list */
5017 addReply(c
,shared
.emptymultibulk
);
5020 if (end
>= llen
) end
= llen
-1;
5021 rangelen
= (end
-start
)+1;
5023 /* Return the result in form of a multi-bulk reply */
5029 ln
= zsl
->header
->forward
[0];
5031 ln
= ln
->forward
[0];
5034 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
5035 withscores
? (rangelen
*2) : rangelen
));
5036 for (j
= 0; j
< rangelen
; j
++) {
5038 addReplyBulkLen(c
,ele
);
5040 addReply(c
,shared
.crlf
);
5042 addReplyDouble(c
,ln
->score
);
5043 ln
= reverse
? ln
->backward
: ln
->forward
[0];
5049 static void zrangeCommand(redisClient
*c
) {
5050 zrangeGenericCommand(c
,0);
5053 static void zrevrangeCommand(redisClient
*c
) {
5054 zrangeGenericCommand(c
,1);
5057 static void zrangebyscoreCommand(redisClient
*c
) {
5059 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
5060 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
5061 int offset
= 0, limit
= -1;
5063 if (c
->argc
!= 4 && c
->argc
!= 7) {
5065 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5067 } else if (c
->argc
== 7 && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
5068 addReply(c
,shared
.syntaxerr
);
5070 } else if (c
->argc
== 7) {
5071 offset
= atoi(c
->argv
[5]->ptr
);
5072 limit
= atoi(c
->argv
[6]->ptr
);
5073 if (offset
< 0) offset
= 0;
5076 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5078 addReply(c
,shared
.nullmultibulk
);
5080 if (o
->type
!= REDIS_ZSET
) {
5081 addReply(c
,shared
.wrongtypeerr
);
5083 zset
*zsetobj
= o
->ptr
;
5084 zskiplist
*zsl
= zsetobj
->zsl
;
5087 unsigned int rangelen
= 0;
5089 /* Get the first node with the score >= min */
5090 ln
= zslFirstWithScore(zsl
,min
);
5092 /* No element matching the speciifed interval */
5093 addReply(c
,shared
.emptymultibulk
);
5097 /* We don't know in advance how many matching elements there
5098 * are in the list, so we push this object that will represent
5099 * the multi-bulk length in the output buffer, and will "fix"
5101 lenobj
= createObject(REDIS_STRING
,NULL
);
5103 decrRefCount(lenobj
);
5105 while(ln
&& ln
->score
<= max
) {
5108 ln
= ln
->forward
[0];
5111 if (limit
== 0) break;
5113 addReplyBulkLen(c
,ele
);
5115 addReply(c
,shared
.crlf
);
5116 ln
= ln
->forward
[0];
5118 if (limit
> 0) limit
--;
5120 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",rangelen
);
5125 static void zcardCommand(redisClient
*c
) {
5129 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5131 addReply(c
,shared
.czero
);
5134 if (o
->type
!= REDIS_ZSET
) {
5135 addReply(c
,shared
.wrongtypeerr
);
5138 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
5143 static void zscoreCommand(redisClient
*c
) {
5147 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5149 addReply(c
,shared
.nullbulk
);
5152 if (o
->type
!= REDIS_ZSET
) {
5153 addReply(c
,shared
.wrongtypeerr
);
5158 de
= dictFind(zs
->dict
,c
->argv
[2]);
5160 addReply(c
,shared
.nullbulk
);
5162 double *score
= dictGetEntryVal(de
);
5164 addReplyDouble(c
,*score
);
5170 /* ========================= Non type-specific commands ==================== */
5172 static void flushdbCommand(redisClient
*c
) {
5173 server
.dirty
+= dictSize(c
->db
->dict
);
5174 dictEmpty(c
->db
->dict
);
5175 dictEmpty(c
->db
->expires
);
5176 addReply(c
,shared
.ok
);
5179 static void flushallCommand(redisClient
*c
) {
5180 server
.dirty
+= emptyDb();
5181 addReply(c
,shared
.ok
);
5182 rdbSave(server
.dbfilename
);
5186 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
5187 redisSortOperation
*so
= zmalloc(sizeof(*so
));
5189 so
->pattern
= pattern
;
5193 /* Return the value associated to the key with a name obtained
5194 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5195 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
5199 int prefixlen
, sublen
, postfixlen
;
5200 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5204 char buf
[REDIS_SORTKEY_MAX
+1];
5207 /* If the pattern is "#" return the substitution object itself in order
5208 * to implement the "SORT ... GET #" feature. */
5209 spat
= pattern
->ptr
;
5210 if (spat
[0] == '#' && spat
[1] == '\0') {
5214 /* The substitution object may be specially encoded. If so we create
5215 * a decoded object on the fly. Otherwise getDecodedObject will just
5216 * increment the ref count, that we'll decrement later. */
5217 subst
= getDecodedObject(subst
);
5220 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
5221 p
= strchr(spat
,'*');
5223 decrRefCount(subst
);
5228 sublen
= sdslen(ssub
);
5229 postfixlen
= sdslen(spat
)-(prefixlen
+1);
5230 memcpy(keyname
.buf
,spat
,prefixlen
);
5231 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
5232 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
5233 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
5234 keyname
.len
= prefixlen
+sublen
+postfixlen
;
5236 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
5237 decrRefCount(subst
);
5239 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5240 return lookupKeyRead(db
,&keyobj
);
5243 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5244 * the additional parameter is not standard but a BSD-specific we have to
5245 * pass sorting parameters via the global 'server' structure */
5246 static int sortCompare(const void *s1
, const void *s2
) {
5247 const redisSortObject
*so1
= s1
, *so2
= s2
;
5250 if (!server
.sort_alpha
) {
5251 /* Numeric sorting. Here it's trivial as we precomputed scores */
5252 if (so1
->u
.score
> so2
->u
.score
) {
5254 } else if (so1
->u
.score
< so2
->u
.score
) {
5260 /* Alphanumeric sorting */
5261 if (server
.sort_bypattern
) {
5262 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
5263 /* At least one compare object is NULL */
5264 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
5266 else if (so1
->u
.cmpobj
== NULL
)
5271 /* We have both the objects, use strcoll */
5272 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
5275 /* Compare elements directly */
5278 dec1
= getDecodedObject(so1
->obj
);
5279 dec2
= getDecodedObject(so2
->obj
);
5280 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
5285 return server
.sort_desc
? -cmp
: cmp
;
5288 /* The SORT command is the most complex command in Redis. Warning: this code
5289 * is optimized for speed and a bit less for readability */
5290 static void sortCommand(redisClient
*c
) {
5293 int desc
= 0, alpha
= 0;
5294 int limit_start
= 0, limit_count
= -1, start
, end
;
5295 int j
, dontsort
= 0, vectorlen
;
5296 int getop
= 0; /* GET operation counter */
5297 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
5298 redisSortObject
*vector
; /* Resulting vector to sort */
5300 /* Lookup the key to sort. It must be of the right types */
5301 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
5302 if (sortval
== NULL
) {
5303 addReply(c
,shared
.nullmultibulk
);
5306 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
5307 sortval
->type
!= REDIS_ZSET
)
5309 addReply(c
,shared
.wrongtypeerr
);
5313 /* Create a list of operations to perform for every sorted element.
5314 * Operations can be GET/DEL/INCR/DECR */
5315 operations
= listCreate();
5316 listSetFreeMethod(operations
,zfree
);
5319 /* Now we need to protect sortval incrementing its count, in the future
5320 * SORT may have options able to overwrite/delete keys during the sorting
5321 * and the sorted key itself may get destroied */
5322 incrRefCount(sortval
);
5324 /* The SORT command has an SQL-alike syntax, parse it */
5325 while(j
< c
->argc
) {
5326 int leftargs
= c
->argc
-j
-1;
5327 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
5329 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
5331 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
5333 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
5334 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
5335 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
5337 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
5338 storekey
= c
->argv
[j
+1];
5340 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
5341 sortby
= c
->argv
[j
+1];
5342 /* If the BY pattern does not contain '*', i.e. it is constant,
5343 * we don't need to sort nor to lookup the weight keys. */
5344 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
5346 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
5347 listAddNodeTail(operations
,createSortOperation(
5348 REDIS_SORT_GET
,c
->argv
[j
+1]));
5352 decrRefCount(sortval
);
5353 listRelease(operations
);
5354 addReply(c
,shared
.syntaxerr
);
5360 /* Load the sorting vector with all the objects to sort */
5361 switch(sortval
->type
) {
5362 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
5363 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
5364 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
5365 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
5367 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
5370 if (sortval
->type
== REDIS_LIST
) {
5371 list
*list
= sortval
->ptr
;
5375 listRewind(list
,&li
);
5376 while((ln
= listNext(&li
))) {
5377 robj
*ele
= ln
->value
;
5378 vector
[j
].obj
= ele
;
5379 vector
[j
].u
.score
= 0;
5380 vector
[j
].u
.cmpobj
= NULL
;
5388 if (sortval
->type
== REDIS_SET
) {
5391 zset
*zs
= sortval
->ptr
;
5395 di
= dictGetIterator(set
);
5396 while((setele
= dictNext(di
)) != NULL
) {
5397 vector
[j
].obj
= dictGetEntryKey(setele
);
5398 vector
[j
].u
.score
= 0;
5399 vector
[j
].u
.cmpobj
= NULL
;
5402 dictReleaseIterator(di
);
5404 redisAssert(j
== vectorlen
);
5406 /* Now it's time to load the right scores in the sorting vector */
5407 if (dontsort
== 0) {
5408 for (j
= 0; j
< vectorlen
; j
++) {
5412 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
5413 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
5415 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
5417 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
5418 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
5420 /* Don't need to decode the object if it's
5421 * integer-encoded (the only encoding supported) so
5422 * far. We can just cast it */
5423 if (byval
->encoding
== REDIS_ENCODING_INT
) {
5424 vector
[j
].u
.score
= (long)byval
->ptr
;
5426 redisAssert(1 != 1);
5431 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
5432 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
5434 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
5435 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
5437 redisAssert(1 != 1);
5444 /* We are ready to sort the vector... perform a bit of sanity check
5445 * on the LIMIT option too. We'll use a partial version of quicksort. */
5446 start
= (limit_start
< 0) ? 0 : limit_start
;
5447 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
5448 if (start
>= vectorlen
) {
5449 start
= vectorlen
-1;
5452 if (end
>= vectorlen
) end
= vectorlen
-1;
5454 if (dontsort
== 0) {
5455 server
.sort_desc
= desc
;
5456 server
.sort_alpha
= alpha
;
5457 server
.sort_bypattern
= sortby
? 1 : 0;
5458 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
5459 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
5461 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
5464 /* Send command output to the output buffer, performing the specified
5465 * GET/DEL/INCR/DECR operations if any. */
5466 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
5467 if (storekey
== NULL
) {
5468 /* STORE option not specified, sent the sorting result to client */
5469 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
5470 for (j
= start
; j
<= end
; j
++) {
5475 addReplyBulkLen(c
,vector
[j
].obj
);
5476 addReply(c
,vector
[j
].obj
);
5477 addReply(c
,shared
.crlf
);
5479 listRewind(operations
,&li
);
5480 while((ln
= listNext(&li
))) {
5481 redisSortOperation
*sop
= ln
->value
;
5482 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5485 if (sop
->type
== REDIS_SORT_GET
) {
5486 if (!val
|| val
->type
!= REDIS_STRING
) {
5487 addReply(c
,shared
.nullbulk
);
5489 addReplyBulkLen(c
,val
);
5491 addReply(c
,shared
.crlf
);
5494 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5499 robj
*listObject
= createListObject();
5500 list
*listPtr
= (list
*) listObject
->ptr
;
5502 /* STORE option specified, set the sorting result as a List object */
5503 for (j
= start
; j
<= end
; j
++) {
5508 listAddNodeTail(listPtr
,vector
[j
].obj
);
5509 incrRefCount(vector
[j
].obj
);
5511 listRewind(operations
,&li
);
5512 while((ln
= listNext(&li
))) {
5513 redisSortOperation
*sop
= ln
->value
;
5514 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5517 if (sop
->type
== REDIS_SORT_GET
) {
5518 if (!val
|| val
->type
!= REDIS_STRING
) {
5519 listAddNodeTail(listPtr
,createStringObject("",0));
5521 listAddNodeTail(listPtr
,val
);
5525 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5529 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
5530 incrRefCount(storekey
);
5532 /* Note: we add 1 because the DB is dirty anyway since even if the
5533 * SORT result is empty a new key is set and maybe the old content
5535 server
.dirty
+= 1+outputlen
;
5536 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
5540 decrRefCount(sortval
);
5541 listRelease(operations
);
5542 for (j
= 0; j
< vectorlen
; j
++) {
5543 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
5544 decrRefCount(vector
[j
].u
.cmpobj
);
5549 /* Convert an amount of bytes into a human readable string in the form
5550 * of 100B, 2G, 100M, 4K, and so forth. */
5551 static void bytesToHuman(char *s
, unsigned long long n
) {
5556 sprintf(s
,"%lluB",n
);
5558 } else if (n
< (1024*1024)) {
5559 d
= (double)n
/(1024);
5560 sprintf(s
,"%.2fK",d
);
5561 } else if (n
< (1024LL*1024*1024)) {
5562 d
= (double)n
/(1024*1024);
5563 sprintf(s
,"%.2fM",d
);
5564 } else if (n
< (1024LL*1024*1024*1024)) {
5565 d
= (double)n
/(1024LL*1024*1024);
5566 sprintf(s
,"%.2fM",d
);
5570 /* Create the string returned by the INFO command. This is decoupled
5571 * by the INFO command itself as we need to report the same information
5572 * on memory corruption problems. */
5573 static sds
genRedisInfoString(void) {
5575 time_t uptime
= time(NULL
)-server
.stat_starttime
;
5579 bytesToHuman(hmem
,server
.usedmemory
);
5580 info
= sdscatprintf(sdsempty(),
5581 "redis_version:%s\r\n"
5583 "multiplexing_api:%s\r\n"
5584 "process_id:%ld\r\n"
5585 "uptime_in_seconds:%ld\r\n"
5586 "uptime_in_days:%ld\r\n"
5587 "connected_clients:%d\r\n"
5588 "connected_slaves:%d\r\n"
5589 "blocked_clients:%d\r\n"
5590 "used_memory:%zu\r\n"
5591 "used_memory_human:%s\r\n"
5592 "changes_since_last_save:%lld\r\n"
5593 "bgsave_in_progress:%d\r\n"
5594 "last_save_time:%ld\r\n"
5595 "bgrewriteaof_in_progress:%d\r\n"
5596 "total_connections_received:%lld\r\n"
5597 "total_commands_processed:%lld\r\n"
5601 (sizeof(long) == 8) ? "64" : "32",
5606 listLength(server
.clients
)-listLength(server
.slaves
),
5607 listLength(server
.slaves
),
5608 server
.blockedclients
,
5612 server
.bgsavechildpid
!= -1,
5614 server
.bgrewritechildpid
!= -1,
5615 server
.stat_numconnections
,
5616 server
.stat_numcommands
,
5617 server
.vm_enabled
!= 0,
5618 server
.masterhost
== NULL
? "master" : "slave"
5620 if (server
.masterhost
) {
5621 info
= sdscatprintf(info
,
5622 "master_host:%s\r\n"
5623 "master_port:%d\r\n"
5624 "master_link_status:%s\r\n"
5625 "master_last_io_seconds_ago:%d\r\n"
5628 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
5630 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
5633 if (server
.vm_enabled
) {
5634 info
= sdscatprintf(info
,
5635 "vm_conf_max_memory:%llu\r\n"
5636 "vm_conf_page_size:%llu\r\n"
5637 "vm_conf_pages:%llu\r\n"
5638 "vm_stats_used_pages:%llu\r\n"
5639 "vm_stats_swapped_objects:%llu\r\n"
5640 "vm_stats_swappin_count:%llu\r\n"
5641 "vm_stats_swappout_count:%llu\r\n"
5642 "vm_stats_io_newjobs_len:%lu\r\n"
5643 "vm_stats_io_processing_len:%lu\r\n"
5644 "vm_stats_io_processed_len:%lu\r\n"
5645 "vm_stats_io_waiting_clients:%lu\r\n"
5646 "vm_stats_io_active_threads:%lu\r\n"
5647 ,(unsigned long long) server
.vm_max_memory
,
5648 (unsigned long long) server
.vm_page_size
,
5649 (unsigned long long) server
.vm_pages
,
5650 (unsigned long long) server
.vm_stats_used_pages
,
5651 (unsigned long long) server
.vm_stats_swapped_objects
,
5652 (unsigned long long) server
.vm_stats_swapins
,
5653 (unsigned long long) server
.vm_stats_swapouts
,
5654 (unsigned long) listLength(server
.io_newjobs
),
5655 (unsigned long) listLength(server
.io_processing
),
5656 (unsigned long) listLength(server
.io_processed
),
5657 (unsigned long) listLength(server
.io_clients
),
5658 (unsigned long) server
.io_active_threads
5661 for (j
= 0; j
< server
.dbnum
; j
++) {
5662 long long keys
, vkeys
;
5664 keys
= dictSize(server
.db
[j
].dict
);
5665 vkeys
= dictSize(server
.db
[j
].expires
);
5666 if (keys
|| vkeys
) {
5667 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
5674 static void infoCommand(redisClient
*c
) {
5675 sds info
= genRedisInfoString();
5676 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
5677 (unsigned long)sdslen(info
)));
5678 addReplySds(c
,info
);
5679 addReply(c
,shared
.crlf
);
5682 static void monitorCommand(redisClient
*c
) {
5683 /* ignore MONITOR if aleady slave or in monitor mode */
5684 if (c
->flags
& REDIS_SLAVE
) return;
5686 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
5688 listAddNodeTail(server
.monitors
,c
);
5689 addReply(c
,shared
.ok
);
5692 /* ================================= Expire ================================= */
5693 static int removeExpire(redisDb
*db
, robj
*key
) {
5694 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
5701 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
5702 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
5710 /* Return the expire time of the specified key, or -1 if no expire
5711 * is associated with this key (i.e. the key is non volatile) */
5712 static time_t getExpire(redisDb
*db
, robj
*key
) {
5715 /* No expire? return ASAP */
5716 if (dictSize(db
->expires
) == 0 ||
5717 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
5719 return (time_t) dictGetEntryVal(de
);
5722 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
5726 /* No expire? return ASAP */
5727 if (dictSize(db
->expires
) == 0 ||
5728 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5730 /* Lookup the expire */
5731 when
= (time_t) dictGetEntryVal(de
);
5732 if (time(NULL
) <= when
) return 0;
5734 /* Delete the key */
5735 dictDelete(db
->expires
,key
);
5736 return dictDelete(db
->dict
,key
) == DICT_OK
;
5739 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
5742 /* No expire? return ASAP */
5743 if (dictSize(db
->expires
) == 0 ||
5744 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5746 /* Delete the key */
5748 dictDelete(db
->expires
,key
);
5749 return dictDelete(db
->dict
,key
) == DICT_OK
;
5752 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
5755 de
= dictFind(c
->db
->dict
,key
);
5757 addReply(c
,shared
.czero
);
5761 if (deleteKey(c
->db
,key
)) server
.dirty
++;
5762 addReply(c
, shared
.cone
);
5765 time_t when
= time(NULL
)+seconds
;
5766 if (setExpire(c
->db
,key
,when
)) {
5767 addReply(c
,shared
.cone
);
5770 addReply(c
,shared
.czero
);
5776 static void expireCommand(redisClient
*c
) {
5777 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
5780 static void expireatCommand(redisClient
*c
) {
5781 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
5784 static void ttlCommand(redisClient
*c
) {
5788 expire
= getExpire(c
->db
,c
->argv
[1]);
5790 ttl
= (int) (expire
-time(NULL
));
5791 if (ttl
< 0) ttl
= -1;
5793 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
5796 /* ================================ MULTI/EXEC ============================== */
5798 /* Client state initialization for MULTI/EXEC */
5799 static void initClientMultiState(redisClient
*c
) {
5800 c
->mstate
.commands
= NULL
;
5801 c
->mstate
.count
= 0;
5804 /* Release all the resources associated with MULTI/EXEC state */
5805 static void freeClientMultiState(redisClient
*c
) {
5808 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5810 multiCmd
*mc
= c
->mstate
.commands
+j
;
5812 for (i
= 0; i
< mc
->argc
; i
++)
5813 decrRefCount(mc
->argv
[i
]);
5816 zfree(c
->mstate
.commands
);
5819 /* Add a new command into the MULTI commands queue */
5820 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
5824 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
5825 sizeof(multiCmd
)*(c
->mstate
.count
+1));
5826 mc
= c
->mstate
.commands
+c
->mstate
.count
;
5829 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
5830 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
5831 for (j
= 0; j
< c
->argc
; j
++)
5832 incrRefCount(mc
->argv
[j
]);
5836 static void multiCommand(redisClient
*c
) {
5837 c
->flags
|= REDIS_MULTI
;
5838 addReply(c
,shared
.ok
);
5841 static void execCommand(redisClient
*c
) {
5846 if (!(c
->flags
& REDIS_MULTI
)) {
5847 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
5851 orig_argv
= c
->argv
;
5852 orig_argc
= c
->argc
;
5853 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
5854 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5855 c
->argc
= c
->mstate
.commands
[j
].argc
;
5856 c
->argv
= c
->mstate
.commands
[j
].argv
;
5857 call(c
,c
->mstate
.commands
[j
].cmd
);
5859 c
->argv
= orig_argv
;
5860 c
->argc
= orig_argc
;
5861 freeClientMultiState(c
);
5862 initClientMultiState(c
);
5863 c
->flags
&= (~REDIS_MULTI
);
5866 /* =========================== Blocking Operations ========================= */
5868 /* Currently Redis blocking operations support is limited to list POP ops,
5869 * so the current implementation is not fully generic, but it is also not
5870 * completely specific so it will not require a rewrite to support new
5871 * kind of blocking operations in the future.
5873 * Still it's important to note that list blocking operations can be already
5874 * used as a notification mechanism in order to implement other blocking
5875 * operations at application level, so there must be a very strong evidence
5876 * of usefulness and generality before new blocking operations are implemented.
5878 * This is how the current blocking POP works, we use BLPOP as example:
5879 * - If the user calls BLPOP and the key exists and contains a non empty list
5880 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5881 * if there is not to block.
5882 * - If instead BLPOP is called and the key does not exists or the list is
5883 * empty we need to block. In order to do so we remove the notification for
5884 * new data to read in the client socket (so that we'll not serve new
5885 * requests if the blocking request is not served). Also we put the client
5886 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
5887 * blocking for this keys.
5888 * - If a PUSH operation against a key with blocked clients waiting is
5889 * performed, we serve the first in the list: basically instead to push
5890 * the new element inside the list we return it to the (first / oldest)
5891 * blocking client, unblock the client, and remove it form the list.
5893 * The above comment and the source code should be enough in order to understand
5894 * the implementation and modify / fix it later.
5897 /* Set a client in blocking mode for the specified key, with the specified
5899 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
5904 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
5905 c
->blockingkeysnum
= numkeys
;
5906 c
->blockingto
= timeout
;
5907 for (j
= 0; j
< numkeys
; j
++) {
5908 /* Add the key in the client structure, to map clients -> keys */
5909 c
->blockingkeys
[j
] = keys
[j
];
5910 incrRefCount(keys
[j
]);
5912 /* And in the other "side", to map keys -> clients */
5913 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
5917 /* For every key we take a list of clients blocked for it */
5919 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
5920 incrRefCount(keys
[j
]);
5921 assert(retval
== DICT_OK
);
5923 l
= dictGetEntryVal(de
);
5925 listAddNodeTail(l
,c
);
5927 /* Mark the client as a blocked client */
5928 c
->flags
|= REDIS_BLOCKED
;
5929 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
5930 server
.blockedclients
++;
5933 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
5934 static void unblockClient(redisClient
*c
) {
5939 assert(c
->blockingkeys
!= NULL
);
5940 /* The client may wait for multiple keys, so unblock it for every key. */
5941 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
5942 /* Remove this client from the list of clients waiting for this key. */
5943 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5945 l
= dictGetEntryVal(de
);
5946 listDelNode(l
,listSearchKey(l
,c
));
5947 /* If the list is empty we need to remove it to avoid wasting memory */
5948 if (listLength(l
) == 0)
5949 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5950 decrRefCount(c
->blockingkeys
[j
]);
5952 /* Cleanup the client structure */
5953 zfree(c
->blockingkeys
);
5954 c
->blockingkeys
= NULL
;
5955 c
->flags
&= (~REDIS_BLOCKED
);
5956 server
.blockedclients
--;
5957 /* Ok now we are ready to get read events from socket, note that we
5958 * can't trap errors here as it's possible that unblockClients() is
5959 * called from freeClient() itself, and the only thing we can do
5960 * if we failed to register the READABLE event is to kill the client.
5961 * Still the following function should never fail in the real world as
5962 * we are sure the file descriptor is sane, and we exit on out of mem. */
5963 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, readQueryFromClient
, c
);
5964 /* As a final step we want to process data if there is some command waiting
5965 * in the input buffer. Note that this is safe even if unblockClient()
5966 * gets called from freeClient() because freeClient() will be smart
5967 * enough to call this function *after* c->querybuf was set to NULL. */
5968 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
5971 /* This should be called from any function PUSHing into lists.
5972 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5973 * 'ele' is the element pushed.
5975 * If the function returns 0 there was no client waiting for a list push
5978 * If the function returns 1 there was a client waiting for a list push
5979 * against this key, the element was passed to this client thus it's not
5980 * needed to actually add it to the list and the caller should return asap. */
5981 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
5982 struct dictEntry
*de
;
5983 redisClient
*receiver
;
5987 de
= dictFind(c
->db
->blockingkeys
,key
);
5988 if (de
== NULL
) return 0;
5989 l
= dictGetEntryVal(de
);
5992 receiver
= ln
->value
;
5994 addReplySds(receiver
,sdsnew("*2\r\n"));
5995 addReplyBulkLen(receiver
,key
);
5996 addReply(receiver
,key
);
5997 addReply(receiver
,shared
.crlf
);
5998 addReplyBulkLen(receiver
,ele
);
5999 addReply(receiver
,ele
);
6000 addReply(receiver
,shared
.crlf
);
6001 unblockClient(receiver
);
6005 /* Blocking RPOP/LPOP */
6006 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
6011 for (j
= 1; j
< c
->argc
-1; j
++) {
6012 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
6014 if (o
->type
!= REDIS_LIST
) {
6015 addReply(c
,shared
.wrongtypeerr
);
6018 list
*list
= o
->ptr
;
6019 if (listLength(list
) != 0) {
6020 /* If the list contains elements fall back to the usual
6021 * non-blocking POP operation */
6022 robj
*argv
[2], **orig_argv
;
6025 /* We need to alter the command arguments before to call
6026 * popGenericCommand() as the command takes a single key. */
6027 orig_argv
= c
->argv
;
6028 orig_argc
= c
->argc
;
6029 argv
[1] = c
->argv
[j
];
6033 /* Also the return value is different, we need to output
6034 * the multi bulk reply header and the key name. The
6035 * "real" command will add the last element (the value)
6036 * for us. If this souds like an hack to you it's just
6037 * because it is... */
6038 addReplySds(c
,sdsnew("*2\r\n"));
6039 addReplyBulkLen(c
,argv
[1]);
6040 addReply(c
,argv
[1]);
6041 addReply(c
,shared
.crlf
);
6042 popGenericCommand(c
,where
);
6044 /* Fix the client structure with the original stuff */
6045 c
->argv
= orig_argv
;
6046 c
->argc
= orig_argc
;
6052 /* If the list is empty or the key does not exists we must block */
6053 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
6054 if (timeout
> 0) timeout
+= time(NULL
);
6055 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
6058 static void blpopCommand(redisClient
*c
) {
6059 blockingPopGenericCommand(c
,REDIS_HEAD
);
6062 static void brpopCommand(redisClient
*c
) {
6063 blockingPopGenericCommand(c
,REDIS_TAIL
);
6066 /* =============================== Replication ============================= */
6068 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6069 ssize_t nwritten
, ret
= size
;
6070 time_t start
= time(NULL
);
6074 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
6075 nwritten
= write(fd
,ptr
,size
);
6076 if (nwritten
== -1) return -1;
6080 if ((time(NULL
)-start
) > timeout
) {
6088 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6089 ssize_t nread
, totread
= 0;
6090 time_t start
= time(NULL
);
6094 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
6095 nread
= read(fd
,ptr
,size
);
6096 if (nread
== -1) return -1;
6101 if ((time(NULL
)-start
) > timeout
) {
6109 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6116 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
6119 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
6130 static void syncCommand(redisClient
*c
) {
6131 /* ignore SYNC if aleady slave or in monitor mode */
6132 if (c
->flags
& REDIS_SLAVE
) return;
6134 /* SYNC can't be issued when the server has pending data to send to
6135 * the client about already issued commands. We need a fresh reply
6136 * buffer registering the differences between the BGSAVE and the current
6137 * dataset, so that we can copy to other slaves if needed. */
6138 if (listLength(c
->reply
) != 0) {
6139 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
6143 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
6144 /* Here we need to check if there is a background saving operation
6145 * in progress, or if it is required to start one */
6146 if (server
.bgsavechildpid
!= -1) {
6147 /* Ok a background save is in progress. Let's check if it is a good
6148 * one for replication, i.e. if there is another slave that is
6149 * registering differences since the server forked to save */
6154 listRewind(server
.slaves
,&li
);
6155 while((ln
= listNext(&li
))) {
6157 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
6160 /* Perfect, the server is already registering differences for
6161 * another slave. Set the right state, and copy the buffer. */
6162 listRelease(c
->reply
);
6163 c
->reply
= listDup(slave
->reply
);
6164 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6165 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
6167 /* No way, we need to wait for the next BGSAVE in order to
6168 * register differences */
6169 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6170 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
6173 /* Ok we don't have a BGSAVE in progress, let's start one */
6174 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
6175 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6176 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
6177 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
6180 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6183 c
->flags
|= REDIS_SLAVE
;
6185 listAddNodeTail(server
.slaves
,c
);
6189 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
6190 redisClient
*slave
= privdata
;
6192 REDIS_NOTUSED(mask
);
6193 char buf
[REDIS_IOBUF_LEN
];
6194 ssize_t nwritten
, buflen
;
6196 if (slave
->repldboff
== 0) {
6197 /* Write the bulk write count before to transfer the DB. In theory here
6198 * we don't know how much room there is in the output buffer of the
6199 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
6200 * operations) will never be smaller than the few bytes we need. */
6203 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
6205 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
6213 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
6214 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
6216 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
6217 (buflen
== 0) ? "premature EOF" : strerror(errno
));
6221 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
6222 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
6227 slave
->repldboff
+= nwritten
;
6228 if (slave
->repldboff
== slave
->repldbsize
) {
6229 close(slave
->repldbfd
);
6230 slave
->repldbfd
= -1;
6231 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6232 slave
->replstate
= REDIS_REPL_ONLINE
;
6233 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
6234 sendReplyToClient
, slave
) == AE_ERR
) {
6238 addReplySds(slave
,sdsempty());
6239 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
6243 /* This function is called at the end of every backgrond saving.
6244 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
6245 * otherwise REDIS_ERR is passed to the function.
6247 * The goal of this function is to handle slaves waiting for a successful
6248 * background saving in order to perform non-blocking synchronization. */
6249 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
6251 int startbgsave
= 0;
6254 listRewind(server
.slaves
,&li
);
6255 while((ln
= listNext(&li
))) {
6256 redisClient
*slave
= ln
->value
;
6258 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
6260 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6261 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
6262 struct redis_stat buf
;
6264 if (bgsaveerr
!= REDIS_OK
) {
6266 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
6269 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
6270 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
6272 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
6275 slave
->repldboff
= 0;
6276 slave
->repldbsize
= buf
.st_size
;
6277 slave
->replstate
= REDIS_REPL_SEND_BULK
;
6278 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6279 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
6286 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6289 listRewind(server
.slaves
,&li
);
6290 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
6291 while((ln
= listNext(&li
))) {
6292 redisClient
*slave
= ln
->value
;
6294 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
6301 static int syncWithMaster(void) {
6302 char buf
[1024], tmpfile
[256], authcmd
[1024];
6304 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
6308 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
6313 /* AUTH with the master if required. */
6314 if(server
.masterauth
) {
6315 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
6316 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
6318 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
6322 /* Read the AUTH result. */
6323 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6325 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
6329 if (buf
[0] != '+') {
6331 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
6336 /* Issue the SYNC command */
6337 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
6339 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
6343 /* Read the bulk write count */
6344 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6346 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
6350 if (buf
[0] != '$') {
6352 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6355 dumpsize
= atoi(buf
+1);
6356 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
6357 /* Read the bulk write data on a temp file */
6358 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
6359 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
6362 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
6366 int nread
, nwritten
;
6368 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
6370 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
6376 nwritten
= write(dfd
,buf
,nread
);
6377 if (nwritten
== -1) {
6378 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
6386 if (rename(tmpfile
,server
.dbfilename
) == -1) {
6387 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
6393 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6394 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
6398 server
.master
= createClient(fd
);
6399 server
.master
->flags
|= REDIS_MASTER
;
6400 server
.master
->authenticated
= 1;
6401 server
.replstate
= REDIS_REPL_CONNECTED
;
6405 static void slaveofCommand(redisClient
*c
) {
6406 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
6407 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
6408 if (server
.masterhost
) {
6409 sdsfree(server
.masterhost
);
6410 server
.masterhost
= NULL
;
6411 if (server
.master
) freeClient(server
.master
);
6412 server
.replstate
= REDIS_REPL_NONE
;
6413 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
6416 sdsfree(server
.masterhost
);
6417 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
6418 server
.masterport
= atoi(c
->argv
[2]->ptr
);
6419 if (server
.master
) freeClient(server
.master
);
6420 server
.replstate
= REDIS_REPL_CONNECT
;
6421 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
6422 server
.masterhost
, server
.masterport
);
6424 addReply(c
,shared
.ok
);
6427 /* ============================ Maxmemory directive ======================== */
6429 /* Try to free one object form the pre-allocated objects free list.
6430 * This is useful under low mem conditions as by default we take 1 million
6431 * free objects allocated. On success REDIS_OK is returned, otherwise
6433 static int tryFreeOneObjectFromFreelist(void) {
6436 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
6437 if (listLength(server
.objfreelist
)) {
6438 listNode
*head
= listFirst(server
.objfreelist
);
6439 o
= listNodeValue(head
);
6440 listDelNode(server
.objfreelist
,head
);
6441 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6445 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6450 /* This function gets called when 'maxmemory' is set on the config file to limit
6451 * the max memory used by the server, and we are out of memory.
6452 * This function will try to, in order:
6454 * - Free objects from the free list
6455 * - Try to remove keys with an EXPIRE set
6457 * It is not possible to free enough memory to reach used-memory < maxmemory
6458 * the server will start refusing commands that will enlarge even more the
6461 static void freeMemoryIfNeeded(void) {
6462 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
6463 int j
, k
, freed
= 0;
6465 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
6466 for (j
= 0; j
< server
.dbnum
; j
++) {
6468 robj
*minkey
= NULL
;
6469 struct dictEntry
*de
;
6471 if (dictSize(server
.db
[j
].expires
)) {
6473 /* From a sample of three keys drop the one nearest to
6474 * the natural expire */
6475 for (k
= 0; k
< 3; k
++) {
6478 de
= dictGetRandomKey(server
.db
[j
].expires
);
6479 t
= (time_t) dictGetEntryVal(de
);
6480 if (minttl
== -1 || t
< minttl
) {
6481 minkey
= dictGetEntryKey(de
);
6485 deleteKey(server
.db
+j
,minkey
);
6488 if (!freed
) return; /* nothing to free... */
6492 /* ============================== Append Only file ========================== */
6494 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
6495 sds buf
= sdsempty();
6501 /* The DB this command was targetting is not the same as the last command
6502 * we appendend. To issue a SELECT command is needed. */
6503 if (dictid
!= server
.appendseldb
) {
6506 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
6507 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
6508 (unsigned long)strlen(seldb
),seldb
);
6509 server
.appendseldb
= dictid
;
6512 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6513 * EXPIREs into EXPIREATs calls */
6514 if (cmd
->proc
== expireCommand
) {
6517 tmpargv
[0] = createStringObject("EXPIREAT",8);
6518 tmpargv
[1] = argv
[1];
6519 incrRefCount(argv
[1]);
6520 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
6521 tmpargv
[2] = createObject(REDIS_STRING
,
6522 sdscatprintf(sdsempty(),"%ld",when
));
6526 /* Append the actual command */
6527 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
6528 for (j
= 0; j
< argc
; j
++) {
6531 o
= getDecodedObject(o
);
6532 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
6533 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
6534 buf
= sdscatlen(buf
,"\r\n",2);
6538 /* Free the objects from the modified argv for EXPIREAT */
6539 if (cmd
->proc
== expireCommand
) {
6540 for (j
= 0; j
< 3; j
++)
6541 decrRefCount(argv
[j
]);
6544 /* We want to perform a single write. This should be guaranteed atomic
6545 * at least if the filesystem we are writing is a real physical one.
6546 * While this will save us against the server being killed I don't think
6547 * there is much to do about the whole server stopping for power problems
6549 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
6550 if (nwritten
!= (signed)sdslen(buf
)) {
6551 /* Ooops, we are in troubles. The best thing to do for now is
6552 * to simply exit instead to give the illusion that everything is
6553 * working as expected. */
6554 if (nwritten
== -1) {
6555 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
6557 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
6561 /* If a background append only file rewriting is in progress we want to
6562 * accumulate the differences between the child DB and the current one
6563 * in a buffer, so that when the child process will do its work we
6564 * can append the differences to the new append only file. */
6565 if (server
.bgrewritechildpid
!= -1)
6566 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
6570 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
6571 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
6572 now
-server
.lastfsync
> 1))
6574 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
6575 server
.lastfsync
= now
;
6579 /* In Redis commands are always executed in the context of a client, so in
6580 * order to load the append only file we need to create a fake client. */
6581 static struct redisClient
*createFakeClient(void) {
6582 struct redisClient
*c
= zmalloc(sizeof(*c
));
6586 c
->querybuf
= sdsempty();
6590 /* We set the fake client as a slave waiting for the synchronization
6591 * so that Redis will not try to send replies to this client. */
6592 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6593 c
->reply
= listCreate();
6594 listSetFreeMethod(c
->reply
,decrRefCount
);
6595 listSetDupMethod(c
->reply
,dupClientReplyValue
);
6599 static void freeFakeClient(struct redisClient
*c
) {
6600 sdsfree(c
->querybuf
);
6601 listRelease(c
->reply
);
6605 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
6606 * error (the append only file is zero-length) REDIS_ERR is returned. On
6607 * fatal error an error message is logged and the program exists. */
6608 int loadAppendOnlyFile(char *filename
) {
6609 struct redisClient
*fakeClient
;
6610 FILE *fp
= fopen(filename
,"r");
6611 struct redis_stat sb
;
6612 unsigned long long loadedkeys
= 0;
6614 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
6618 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
6622 fakeClient
= createFakeClient();
6629 struct redisCommand
*cmd
;
6631 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
6637 if (buf
[0] != '*') goto fmterr
;
6639 argv
= zmalloc(sizeof(robj
*)*argc
);
6640 for (j
= 0; j
< argc
; j
++) {
6641 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
6642 if (buf
[0] != '$') goto fmterr
;
6643 len
= strtol(buf
+1,NULL
,10);
6644 argsds
= sdsnewlen(NULL
,len
);
6645 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
6646 argv
[j
] = createObject(REDIS_STRING
,argsds
);
6647 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
6650 /* Command lookup */
6651 cmd
= lookupCommand(argv
[0]->ptr
);
6653 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
6656 /* Try object sharing and encoding */
6657 if (server
.shareobjects
) {
6659 for(j
= 1; j
< argc
; j
++)
6660 argv
[j
] = tryObjectSharing(argv
[j
]);
6662 if (cmd
->flags
& REDIS_CMD_BULK
)
6663 tryObjectEncoding(argv
[argc
-1]);
6664 /* Run the command in the context of a fake client */
6665 fakeClient
->argc
= argc
;
6666 fakeClient
->argv
= argv
;
6667 cmd
->proc(fakeClient
);
6668 /* Discard the reply objects list from the fake client */
6669 while(listLength(fakeClient
->reply
))
6670 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
6671 /* Clean up, ready for the next command */
6672 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
6674 /* Handle swapping while loading big datasets when VM is on */
6676 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
6677 while (zmalloc_used_memory() > server
.vm_max_memory
) {
6678 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
6683 freeFakeClient(fakeClient
);
6688 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
6690 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
6694 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
6698 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6699 static int fwriteBulk(FILE *fp
, robj
*obj
) {
6703 /* Avoid the incr/decr ref count business if possible to help
6704 * copy-on-write (we are often in a child process when this function
6706 * Also makes sure that key objects don't get incrRefCount-ed when VM
6708 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
6709 obj
= getDecodedObject(obj
);
6712 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
6713 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
6714 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
6716 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
6717 if (decrrc
) decrRefCount(obj
);
6720 if (decrrc
) decrRefCount(obj
);
6724 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6725 static int fwriteBulkDouble(FILE *fp
, double d
) {
6726 char buf
[128], dbuf
[128];
6728 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
6729 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
6730 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6731 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
6735 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6736 static int fwriteBulkLong(FILE *fp
, long l
) {
6737 char buf
[128], lbuf
[128];
6739 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
6740 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
6741 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6742 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
6746 /* Write a sequence of commands able to fully rebuild the dataset into
6747 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6748 static int rewriteAppendOnlyFile(char *filename
) {
6749 dictIterator
*di
= NULL
;
6754 time_t now
= time(NULL
);
6756 /* Note that we have to use a different temp name here compared to the
6757 * one used by rewriteAppendOnlyFileBackground() function. */
6758 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
6759 fp
= fopen(tmpfile
,"w");
6761 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
6764 for (j
= 0; j
< server
.dbnum
; j
++) {
6765 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
6766 redisDb
*db
= server
.db
+j
;
6768 if (dictSize(d
) == 0) continue;
6769 di
= dictGetIterator(d
);
6775 /* SELECT the new DB */
6776 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
6777 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
6779 /* Iterate this DB writing every entry */
6780 while((de
= dictNext(di
)) != NULL
) {
6785 key
= dictGetEntryKey(de
);
6786 /* If the value for this key is swapped, load a preview in memory.
6787 * We use a "swapped" flag to remember if we need to free the
6788 * value object instead to just increment the ref count anyway
6789 * in order to avoid copy-on-write of pages if we are forked() */
6790 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
6791 key
->storage
== REDIS_VM_SWAPPING
) {
6792 o
= dictGetEntryVal(de
);
6795 o
= vmPreviewObject(key
);
6798 expiretime
= getExpire(db
,key
);
6800 /* Save the key and associated value */
6801 if (o
->type
== REDIS_STRING
) {
6802 /* Emit a SET command */
6803 char cmd
[]="*3\r\n$3\r\nSET\r\n";
6804 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6806 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6807 if (fwriteBulk(fp
,o
) == 0) goto werr
;
6808 } else if (o
->type
== REDIS_LIST
) {
6809 /* Emit the RPUSHes needed to rebuild the list */
6810 list
*list
= o
->ptr
;
6814 listRewind(list
,&li
);
6815 while((ln
= listNext(&li
))) {
6816 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
6817 robj
*eleobj
= listNodeValue(ln
);
6819 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6820 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6821 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6823 } else if (o
->type
== REDIS_SET
) {
6824 /* Emit the SADDs needed to rebuild the set */
6826 dictIterator
*di
= dictGetIterator(set
);
6829 while((de
= dictNext(di
)) != NULL
) {
6830 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
6831 robj
*eleobj
= dictGetEntryKey(de
);
6833 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6834 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6835 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6837 dictReleaseIterator(di
);
6838 } else if (o
->type
== REDIS_ZSET
) {
6839 /* Emit the ZADDs needed to rebuild the sorted set */
6841 dictIterator
*di
= dictGetIterator(zs
->dict
);
6844 while((de
= dictNext(di
)) != NULL
) {
6845 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
6846 robj
*eleobj
= dictGetEntryKey(de
);
6847 double *score
= dictGetEntryVal(de
);
6849 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6850 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6851 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
6852 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6854 dictReleaseIterator(di
);
6856 redisAssert(0 != 0);
6858 /* Save the expire time */
6859 if (expiretime
!= -1) {
6860 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
6861 /* If this key is already expired skip it */
6862 if (expiretime
< now
) continue;
6863 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6864 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6865 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
6867 if (swapped
) decrRefCount(o
);
6869 dictReleaseIterator(di
);
6872 /* Make sure data will not remain on the OS's output buffers */
6877 /* Use RENAME to make sure the DB file is changed atomically only
6878 * if the generate DB file is ok. */
6879 if (rename(tmpfile
,filename
) == -1) {
6880 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
6884 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
6890 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
6891 if (di
) dictReleaseIterator(di
);
6895 /* This is how rewriting of the append only file in background works:
6897 * 1) The user calls BGREWRITEAOF
6898 * 2) Redis calls this function, that forks():
6899 * 2a) the child rewrite the append only file in a temp file.
6900 * 2b) the parent accumulates differences in server.bgrewritebuf.
6901 * 3) When the child finished '2a' exists.
6902 * 4) The parent will trap the exit code, if it's OK, will append the
6903 * data accumulated into server.bgrewritebuf into the temp file, and
6904 * finally will rename(2) the temp file in the actual file name.
6905 * The the new file is reopened as the new append only file. Profit!
6907 static int rewriteAppendOnlyFileBackground(void) {
6910 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
6911 if (server
.vm_enabled
) waitZeroActiveThreads();
6912 if ((childpid
= fork()) == 0) {
6917 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6918 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
6925 if (childpid
== -1) {
6926 redisLog(REDIS_WARNING
,
6927 "Can't rewrite append only file in background: fork: %s",
6931 redisLog(REDIS_NOTICE
,
6932 "Background append only file rewriting started by pid %d",childpid
);
6933 server
.bgrewritechildpid
= childpid
;
6934 /* We set appendseldb to -1 in order to force the next call to the
6935 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6936 * accumulated by the parent into server.bgrewritebuf will start
6937 * with a SELECT statement and it will be safe to merge. */
6938 server
.appendseldb
= -1;
6941 return REDIS_OK
; /* unreached */
6944 static void bgrewriteaofCommand(redisClient
*c
) {
6945 if (server
.bgrewritechildpid
!= -1) {
6946 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6949 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
6950 char *status
= "+Background append only file rewriting started\r\n";
6951 addReplySds(c
,sdsnew(status
));
6953 addReply(c
,shared
.err
);
6957 static void aofRemoveTempFile(pid_t childpid
) {
6960 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
6964 /* Virtual Memory is composed mainly of two subsystems:
6965 * - Blocking Virutal Memory
6966 * - Threaded Virtual Memory I/O
6967 * The two parts are not fully decoupled, but functions are split among two
6968 * different sections of the source code (delimited by comments) in order to
6969 * make more clear what functionality is about the blocking VM and what about
6970 * the threaded (not blocking) VM.
6974 * Redis VM is a blocking VM (one that blocks reading swapped values from
6975 * disk into memory when a value swapped out is needed in memory) that is made
6976 * unblocking by trying to examine the command argument vector in order to
6977 * load in background values that will likely be needed in order to exec
6978 * the command. The command is executed only once all the relevant keys
6979 * are loaded into memory.
6981 * This basically is almost as simple of a blocking VM, but almost as parallel
6982 * as a fully non-blocking VM.
6985 /* =================== Virtual Memory - Blocking Side ====================== */
6986 static void vmInit(void) {
6991 server
.vm_fp
= fopen("/tmp/redisvm","w+b");
6992 if (server
.vm_fp
== NULL
) {
6993 redisLog(REDIS_WARNING
,"Impossible to open the swap file. Exiting.");
6996 server
.vm_fd
= fileno(server
.vm_fp
);
6997 server
.vm_next_page
= 0;
6998 server
.vm_near_pages
= 0;
6999 server
.vm_stats_used_pages
= 0;
7000 server
.vm_stats_swapped_objects
= 0;
7001 server
.vm_stats_swapouts
= 0;
7002 server
.vm_stats_swapins
= 0;
7003 totsize
= server
.vm_pages
*server
.vm_page_size
;
7004 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
7005 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
7006 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
7010 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
7012 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
7013 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
7014 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
7015 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
7016 /* Try to remove the swap file, so the OS will really delete it from the
7017 * file system when Redis exists. */
7018 unlink("/tmp/redisvm");
7020 /* Initialize threaded I/O (used by Virtual Memory) */
7021 server
.io_newjobs
= listCreate();
7022 server
.io_processing
= listCreate();
7023 server
.io_processed
= listCreate();
7024 server
.io_clients
= listCreate();
7025 pthread_mutex_init(&server
.io_mutex
,NULL
);
7026 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
7027 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
7028 server
.io_active_threads
= 0;
7029 if (pipe(pipefds
) == -1) {
7030 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
7034 server
.io_ready_pipe_read
= pipefds
[0];
7035 server
.io_ready_pipe_write
= pipefds
[1];
7036 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
7037 /* LZF requires a lot of stack */
7038 pthread_attr_init(&server
.io_threads_attr
);
7039 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
7040 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
7041 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
7042 /* Listen for events in the threaded I/O pipe */
7043 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
7044 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
7045 oom("creating file event");
7048 /* Mark the page as used */
7049 static void vmMarkPageUsed(off_t page
) {
7050 off_t byte
= page
/8;
7052 server
.vm_bitmap
[byte
] |= 1<<bit
;
7053 redisLog(REDIS_DEBUG
,"Mark used: %lld (byte:%lld bit:%d)\n",
7054 (long long)page
, (long long)byte
, bit
);
7057 /* Mark N contiguous pages as used, with 'page' being the first. */
7058 static void vmMarkPagesUsed(off_t page
, off_t count
) {
7061 for (j
= 0; j
< count
; j
++)
7062 vmMarkPageUsed(page
+j
);
7063 server
.vm_stats_used_pages
+= count
;
7066 /* Mark the page as free */
7067 static void vmMarkPageFree(off_t page
) {
7068 off_t byte
= page
/8;
7070 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
7073 /* Mark N contiguous pages as free, with 'page' being the first. */
7074 static void vmMarkPagesFree(off_t page
, off_t count
) {
7077 for (j
= 0; j
< count
; j
++)
7078 vmMarkPageFree(page
+j
);
7079 server
.vm_stats_used_pages
-= count
;
7082 /* Test if the page is free */
7083 static int vmFreePage(off_t page
) {
7084 off_t byte
= page
/8;
7086 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
7089 /* Find N contiguous free pages storing the first page of the cluster in *first.
7090 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
7091 * REDIS_ERR is returned.
7093 * This function uses a simple algorithm: we try to allocate
7094 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
7095 * again from the start of the swap file searching for free spaces.
7097 * If it looks pretty clear that there are no free pages near our offset
7098 * we try to find less populated places doing a forward jump of
7099 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
7100 * without hurry, and then we jump again and so forth...
7102 * This function can be improved using a free list to avoid to guess
7103 * too much, since we could collect data about freed pages.
7105 * note: I implemented this function just after watching an episode of
7106 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
7108 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
7109 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
7111 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
7112 server
.vm_near_pages
= 0;
7113 server
.vm_next_page
= 0;
7115 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
7116 base
= server
.vm_next_page
;
7118 while(offset
< server
.vm_pages
) {
7119 off_t
this = base
+offset
;
7121 redisLog(REDIS_DEBUG
, "THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
7122 /* If we overflow, restart from page zero */
7123 if (this >= server
.vm_pages
) {
7124 this -= server
.vm_pages
;
7126 /* Just overflowed, what we found on tail is no longer
7127 * interesting, as it's no longer contiguous. */
7131 if (vmFreePage(this)) {
7132 /* This is a free page */
7134 /* Already got N free pages? Return to the caller, with success */
7136 *first
= this-(n
-1);
7137 server
.vm_next_page
= this+1;
7141 /* The current one is not a free page */
7145 /* Fast-forward if the current page is not free and we already
7146 * searched enough near this place. */
7148 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
7149 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
7151 /* Note that even if we rewind after the jump, we are don't need
7152 * to make sure numfree is set to zero as we only jump *if* it
7153 * is set to zero. */
7155 /* Otherwise just check the next page */
7162 /* Write the specified object at the specified page of the swap file */
7163 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
7164 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7165 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7166 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7167 redisLog(REDIS_WARNING
,
7168 "Critical VM problem in vmSwapObjectBlocking(): can't seek: %s",
7172 rdbSaveObject(server
.vm_fp
,o
);
7173 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7177 /* Swap the 'val' object relative to 'key' into disk. Store all the information
7178 * needed to later retrieve the object into the key object.
7179 * If we can't find enough contiguous empty pages to swap the object on disk
7180 * REDIS_ERR is returned. */
7181 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
7182 off_t pages
= rdbSavedObjectPages(val
,NULL
);
7185 assert(key
->storage
== REDIS_VM_MEMORY
);
7186 assert(key
->refcount
== 1);
7187 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
7188 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
7189 key
->vm
.page
= page
;
7190 key
->vm
.usedpages
= pages
;
7191 key
->storage
= REDIS_VM_SWAPPED
;
7192 key
->vtype
= val
->type
;
7193 decrRefCount(val
); /* Deallocate the object from memory. */
7194 vmMarkPagesUsed(page
,pages
);
7195 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
7196 (unsigned char*) key
->ptr
,
7197 (unsigned long long) page
, (unsigned long long) pages
);
7198 server
.vm_stats_swapped_objects
++;
7199 server
.vm_stats_swapouts
++;
7200 fflush(server
.vm_fp
);
7204 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
7207 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7208 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7209 redisLog(REDIS_WARNING
,
7210 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
7214 o
= rdbLoadObject(type
,server
.vm_fp
);
7216 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno
));
7219 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7223 /* Load the value object relative to the 'key' object from swap to memory.
7224 * The newly allocated object is returned.
7226 * If preview is true the unserialized object is returned to the caller but
7227 * no changes are made to the key object, nor the pages are marked as freed */
7228 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
7231 redisAssert(key
->storage
== REDIS_VM_SWAPPED
);
7232 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
7234 key
->storage
= REDIS_VM_MEMORY
;
7235 key
->vm
.atime
= server
.unixtime
;
7236 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7237 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
7238 (unsigned char*) key
->ptr
);
7239 server
.vm_stats_swapped_objects
--;
7241 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
7242 (unsigned char*) key
->ptr
);
7244 server
.vm_stats_swapins
++;
7248 /* Plain object loading, from swap to memory */
7249 static robj
*vmLoadObject(robj
*key
) {
7250 /* If we are loading the object in background, stop it, we
7251 * need to load this object synchronously ASAP. */
7252 if (key
->storage
== REDIS_VM_LOADING
)
7253 vmCancelThreadedIOJob(key
);
7254 return vmGenericLoadObject(key
,0);
7257 /* Just load the value on disk, without to modify the key.
7258 * This is useful when we want to perform some operation on the value
7259 * without to really bring it from swap to memory, like while saving the
7260 * dataset or rewriting the append only log. */
7261 static robj
*vmPreviewObject(robj
*key
) {
7262 return vmGenericLoadObject(key
,1);
7265 /* How a good candidate is this object for swapping?
7266 * The better candidate it is, the greater the returned value.
7268 * Currently we try to perform a fast estimation of the object size in
7269 * memory, and combine it with aging informations.
7271 * Basically swappability = idle-time * log(estimated size)
7273 * Bigger objects are preferred over smaller objects, but not
7274 * proportionally, this is why we use the logarithm. This algorithm is
7275 * just a first try and will probably be tuned later. */
7276 static double computeObjectSwappability(robj
*o
) {
7277 time_t age
= server
.unixtime
- o
->vm
.atime
;
7281 struct dictEntry
*de
;
7284 if (age
<= 0) return 0;
7287 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
7290 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
7295 listNode
*ln
= listFirst(l
);
7297 asize
= sizeof(list
);
7299 robj
*ele
= ln
->value
;
7302 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7303 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7305 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
7310 z
= (o
->type
== REDIS_ZSET
);
7311 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
7313 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
7314 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
7319 de
= dictGetRandomKey(d
);
7320 ele
= dictGetEntryKey(de
);
7321 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7322 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7324 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
7325 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
7329 return (double)asize
*log(1+asize
);
7332 /* Try to swap an object that's a good candidate for swapping.
7333 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
7334 * to swap any object at all.
7336 * If 'usethreaded' is true, Redis will try to swap the object in background
7337 * using I/O threads. */
7338 static int vmSwapOneObject(int usethreads
) {
7340 struct dictEntry
*best
= NULL
;
7341 double best_swappability
= 0;
7342 redisDb
*best_db
= NULL
;
7345 for (j
= 0; j
< server
.dbnum
; j
++) {
7346 redisDb
*db
= server
.db
+j
;
7347 int maxtries
= 1000;
7349 if (dictSize(db
->dict
) == 0) continue;
7350 for (i
= 0; i
< 5; i
++) {
7352 double swappability
;
7354 if (maxtries
) maxtries
--;
7355 de
= dictGetRandomKey(db
->dict
);
7356 key
= dictGetEntryKey(de
);
7357 val
= dictGetEntryVal(de
);
7358 if (key
->storage
!= REDIS_VM_MEMORY
) {
7359 if (maxtries
) i
--; /* don't count this try */
7362 swappability
= computeObjectSwappability(val
);
7363 if (!best
|| swappability
> best_swappability
) {
7365 best_swappability
= swappability
;
7371 redisLog(REDIS_DEBUG
,"No swappable key found!");
7374 key
= dictGetEntryKey(best
);
7375 val
= dictGetEntryVal(best
);
7377 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
7378 key
->ptr
, best_swappability
);
7380 /* Unshare the key if needed */
7381 if (key
->refcount
> 1) {
7382 robj
*newkey
= dupStringObject(key
);
7384 key
= dictGetEntryKey(best
) = newkey
;
7388 vmSwapObjectThreaded(key
,val
,best_db
);
7391 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7392 dictGetEntryVal(best
) = NULL
;
7400 static int vmSwapOneObjectBlocking() {
7401 return vmSwapOneObject(0);
7404 static int vmSwapOneObjectThreaded() {
7405 return vmSwapOneObject(1);
7408 /* Return true if it's safe to swap out objects in a given moment.
7409 * Basically we don't want to swap objects out while there is a BGSAVE
7410 * or a BGAEOREWRITE running in backgroud. */
7411 static int vmCanSwapOut(void) {
7412 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
7415 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
7416 * and was deleted. Otherwise 0 is returned. */
7417 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
7421 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
7422 foundkey
= dictGetEntryKey(de
);
7423 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
7428 /* =================== Virtual Memory - Threaded I/O ======================= */
7430 static void freeIOJob(iojob
*j
) {
7431 if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
7432 j
->type
== REDIS_IOJOB_DO_SWAP
)
7433 decrRefCount(j
->val
);
7434 decrRefCount(j
->key
);
7438 /* Every time a thread finished a Job, it writes a byte into the write side
7439 * of an unix pipe in order to "awake" the main thread, and this function
7441 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
7448 REDIS_NOTUSED(mask
);
7449 REDIS_NOTUSED(privdata
);
7451 /* For every byte we read in the read side of the pipe, there is one
7452 * I/O job completed to process. */
7453 while((retval
= read(fd
,buf
,1)) == 1) {
7457 struct dictEntry
*de
;
7459 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
7460 assert(listLength(server
.io_processed
) != 0);
7462 /* Get the processed element (the oldest one) */
7464 ln
= listFirst(server
.io_processed
);
7466 listDelNode(server
.io_processed
,ln
);
7468 /* If this job is marked as canceled, just ignore it */
7473 /* Post process it in the main thread, as there are things we
7474 * can do just here to avoid race conditions and/or invasive locks */
7475 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
);
7476 de
= dictFind(j
->db
->dict
,j
->key
);
7478 key
= dictGetEntryKey(de
);
7479 if (j
->type
== REDIS_IOJOB_LOAD
) {
7480 /* Key loaded, bring it at home */
7481 key
->storage
= REDIS_VM_MEMORY
;
7482 key
->vm
.atime
= server
.unixtime
;
7483 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7484 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
7485 (unsigned char*) key
->ptr
);
7486 server
.vm_stats_swapped_objects
--;
7487 server
.vm_stats_swapins
++;
7489 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
7490 /* Now we know the amount of pages required to swap this object.
7491 * Let's find some space for it, and queue this task again
7492 * rebranded as REDIS_IOJOB_DO_SWAP. */
7493 if (vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
) {
7494 /* Ooops... no space! */
7497 /* Note that we need to mark this pages as used now,
7498 * if the job will be canceled, we'll mark them as freed
7500 vmMarkPagesUsed(j
->page
,j
->pages
);
7501 j
->type
= REDIS_IOJOB_DO_SWAP
;
7506 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
7509 /* Key swapped. We can finally free some memory. */
7510 if (key
->storage
!= REDIS_VM_SWAPPING
) {
7511 printf("key->storage: %d\n",key
->storage
);
7512 printf("key->name: %s\n",(char*)key
->ptr
);
7513 printf("key->refcount: %d\n",key
->refcount
);
7514 printf("val: %p\n",(void*)j
->val
);
7515 printf("val->type: %d\n",j
->val
->type
);
7516 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
7518 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
7519 val
= dictGetEntryVal(de
);
7520 key
->vm
.page
= j
->page
;
7521 key
->vm
.usedpages
= j
->pages
;
7522 key
->storage
= REDIS_VM_SWAPPED
;
7523 key
->vtype
= j
->val
->type
;
7524 decrRefCount(val
); /* Deallocate the object from memory. */
7525 dictGetEntryVal(de
) = NULL
;
7526 redisLog(REDIS_DEBUG
,
7527 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
7528 (unsigned char*) key
->ptr
,
7529 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
7530 server
.vm_stats_swapped_objects
++;
7531 server
.vm_stats_swapouts
++;
7533 /* Put a few more swap requests in queue if we are still
7535 if (zmalloc_used_memory() > server
.vm_max_memory
) {
7539 more
= listLength(server
.io_newjobs
) <
7540 (unsigned) server
.vm_max_threads
;
7542 /* Don't waste CPU time if swappable objects are rare. */
7543 if (vmSwapOneObjectThreaded() == REDIS_ERR
) break;
7548 if (processed
== REDIS_MAX_COMPLETED_JOBS_PROCESSED
) return;
7550 if (retval
< 0 && errno
!= EAGAIN
) {
7551 redisLog(REDIS_WARNING
,
7552 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
7557 static void lockThreadedIO(void) {
7558 pthread_mutex_lock(&server
.io_mutex
);
7561 static void unlockThreadedIO(void) {
7562 pthread_mutex_unlock(&server
.io_mutex
);
7565 /* Remove the specified object from the threaded I/O queue if still not
7566 * processed, otherwise make sure to flag it as canceled. */
7567 static void vmCancelThreadedIOJob(robj
*o
) {
7569 server
.io_newjobs
, /* 0 */
7570 server
.io_processing
, /* 1 */
7571 server
.io_processed
/* 2 */
7575 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
7578 /* Search for a matching key in one of the queues */
7579 for (i
= 0; i
< 3; i
++) {
7583 listRewind(lists
[i
],&li
);
7584 while ((ln
= listNext(&li
)) != NULL
) {
7585 iojob
*job
= ln
->value
;
7587 if (job
->canceled
) continue; /* Skip this, already canceled. */
7588 if (compareStringObjects(job
->key
,o
) == 0) {
7589 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (LIST ID %d)\n",
7590 (void*)job
, (char*)o
->ptr
, i
);
7591 /* Mark the pages as free since the swap didn't happened
7592 * or happened but is now discarded. */
7593 if (job
->type
== REDIS_IOJOB_DO_SWAP
)
7594 vmMarkPagesFree(job
->page
,job
->pages
);
7595 /* Cancel the job. It depends on the list the job is
7598 case 0: /* io_newjobs */
7599 /* If the job was yet not processed the best thing to do
7600 * is to remove it from the queue at all */
7602 listDelNode(lists
[i
],ln
);
7604 case 1: /* io_processing */
7605 /* Oh Shi- the thread is messing with the Job, and
7606 * probably with the object if this is a
7607 * PREPARE_SWAP or DO_SWAP job. Better to wait for the
7608 * job to move into the next queue... */
7609 if (job
->type
!= REDIS_IOJOB_LOAD
) {
7610 /* Yes, we try again and again until the job
7613 /* But let's wait some time for the I/O thread
7614 * to finish with this job. After all this condition
7615 * should be very rare. */
7622 case 2: /* io_processed */
7623 /* The job was already processed, that's easy...
7624 * just mark it as canceled so that we'll ignore it
7625 * when processing completed jobs. */
7629 /* Finally we have to adjust the storage type of the object
7630 * in order to "UNDO" the operaiton. */
7631 if (o
->storage
== REDIS_VM_LOADING
)
7632 o
->storage
= REDIS_VM_SWAPPED
;
7633 else if (o
->storage
== REDIS_VM_SWAPPING
)
7634 o
->storage
= REDIS_VM_MEMORY
;
7641 assert(1 != 1); /* We should never reach this */
7644 static void *IOThreadEntryPoint(void *arg
) {
7649 pthread_detach(pthread_self());
7651 /* Get a new job to process */
7653 if (listLength(server
.io_newjobs
) == 0) {
7654 /* No new jobs in queue, exit. */
7655 redisLog(REDIS_DEBUG
,"Thread %lld exiting, nothing to do",
7656 (long long) pthread_self());
7657 server
.io_active_threads
--;
7661 ln
= listFirst(server
.io_newjobs
);
7663 listDelNode(server
.io_newjobs
,ln
);
7664 /* Add the job in the processing queue */
7665 j
->thread
= pthread_self();
7666 listAddNodeTail(server
.io_processing
,j
);
7667 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
7669 redisLog(REDIS_DEBUG
,"Thread %lld got a new job (type %d): %p about key '%s'",
7670 (long long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
7672 /* Process the Job */
7673 if (j
->type
== REDIS_IOJOB_LOAD
) {
7674 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
7675 FILE *fp
= fopen("/dev/null","w+");
7676 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
7678 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
7679 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
7683 /* Done: insert the job into the processed queue */
7684 redisLog(REDIS_DEBUG
,"Thread %lld completed the job: %p (key %s)",
7685 (long long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
7687 listDelNode(server
.io_processing
,ln
);
7688 listAddNodeTail(server
.io_processed
,j
);
7691 /* Signal the main thread there is new stuff to process */
7692 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
7694 return NULL
; /* never reached */
7697 static void spawnIOThread(void) {
7700 pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
);
7701 server
.io_active_threads
++;
7704 /* We need to wait for the last thread to exit before we are able to
7705 * fork() in order to BGSAVE or BGREWRITEAOF. */
7706 static void waitZeroActiveThreads(void) {
7709 if (server
.io_active_threads
== 0) {
7714 usleep(10000); /* 10 milliseconds */
7718 /* This function must be called while with threaded IO locked */
7719 static void queueIOJob(iojob
*j
) {
7720 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
7721 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
7722 listAddNodeTail(server
.io_newjobs
,j
);
7723 if (server
.io_active_threads
< server
.vm_max_threads
)
7727 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
7730 assert(key
->storage
== REDIS_VM_MEMORY
);
7731 assert(key
->refcount
== 1);
7733 j
= zmalloc(sizeof(*j
));
7734 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
7736 j
->key
= dupStringObject(key
);
7740 j
->thread
= (pthread_t
) -1;
7741 key
->storage
= REDIS_VM_SWAPPING
;
7749 /* ================================= Debugging ============================== */
7751 static void debugCommand(redisClient
*c
) {
7752 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
7754 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
7755 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
7756 addReply(c
,shared
.err
);
7760 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
7761 addReply(c
,shared
.err
);
7764 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
7765 addReply(c
,shared
.ok
);
7766 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
7768 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
7769 addReply(c
,shared
.err
);
7772 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
7773 addReply(c
,shared
.ok
);
7774 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
7775 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7779 addReply(c
,shared
.nokeyerr
);
7782 key
= dictGetEntryKey(de
);
7783 val
= dictGetEntryVal(de
);
7784 if (server
.vm_enabled
&& (key
->storage
== REDIS_VM_MEMORY
||
7785 key
->storage
== REDIS_VM_SWAPPING
)) {
7786 addReplySds(c
,sdscatprintf(sdsempty(),
7787 "+Key at:%p refcount:%d, value at:%p refcount:%d "
7788 "encoding:%d serializedlength:%lld\r\n",
7789 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
7790 val
->encoding
, rdbSavedObjectLen(val
,NULL
)));
7792 addReplySds(c
,sdscatprintf(sdsempty(),
7793 "+Key at:%p refcount:%d, value swapped at: page %llu "
7794 "using %llu pages\r\n",
7795 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
7796 (unsigned long long) key
->vm
.usedpages
));
7798 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
7799 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7802 if (!server
.vm_enabled
) {
7803 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7807 addReply(c
,shared
.nokeyerr
);
7810 key
= dictGetEntryKey(de
);
7811 val
= dictGetEntryVal(de
);
7812 /* If the key is shared we want to create a copy */
7813 if (key
->refcount
> 1) {
7814 robj
*newkey
= dupStringObject(key
);
7816 key
= dictGetEntryKey(de
) = newkey
;
7819 if (key
->storage
!= REDIS_VM_MEMORY
) {
7820 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
7821 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7822 dictGetEntryVal(de
) = NULL
;
7823 addReply(c
,shared
.ok
);
7825 addReply(c
,shared
.err
);
7828 addReplySds(c
,sdsnew(
7829 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7833 static void _redisAssert(char *estr
, char *file
, int line
) {
7834 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
7835 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
);
7836 #ifdef HAVE_BACKTRACE
7837 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
7842 /* =================================== Main! ================================ */
7845 int linuxOvercommitMemoryValue(void) {
7846 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
7850 if (fgets(buf
,64,fp
) == NULL
) {
7859 void linuxOvercommitMemoryWarning(void) {
7860 if (linuxOvercommitMemoryValue() == 0) {
7861 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.");
7864 #endif /* __linux__ */
7866 static void daemonize(void) {
7870 if (fork() != 0) exit(0); /* parent exits */
7871 setsid(); /* create a new session */
7873 /* Every output goes to /dev/null. If Redis is daemonized but
7874 * the 'logfile' is set to 'stdout' in the configuration file
7875 * it will not log at all. */
7876 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
7877 dup2(fd
, STDIN_FILENO
);
7878 dup2(fd
, STDOUT_FILENO
);
7879 dup2(fd
, STDERR_FILENO
);
7880 if (fd
> STDERR_FILENO
) close(fd
);
7882 /* Try to write the pid file */
7883 fp
= fopen(server
.pidfile
,"w");
7885 fprintf(fp
,"%d\n",getpid());
7890 int main(int argc
, char **argv
) {
7893 resetServerSaveParams();
7894 loadServerConfig(argv
[1]);
7895 } else if (argc
> 2) {
7896 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
7899 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'");
7901 if (server
.daemonize
) daemonize();
7903 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
7905 linuxOvercommitMemoryWarning();
7907 if (server
.appendonly
) {
7908 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
7909 redisLog(REDIS_NOTICE
,"DB loaded from append only file");
7911 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
7912 redisLog(REDIS_NOTICE
,"DB loaded from disk");
7914 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
7916 aeDeleteEventLoop(server
.el
);
7920 /* ============================= Backtrace support ========================= */
7922 #ifdef HAVE_BACKTRACE
7923 static char *findFuncName(void *pointer
, unsigned long *offset
);
7925 static void *getMcontextEip(ucontext_t
*uc
) {
7926 #if defined(__FreeBSD__)
7927 return (void*) uc
->uc_mcontext
.mc_eip
;
7928 #elif defined(__dietlibc__)
7929 return (void*) uc
->uc_mcontext
.eip
;
7930 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
7932 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7934 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7936 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
7937 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
7938 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
7940 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
7942 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
7943 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
7944 #elif defined(__ia64__) /* Linux IA64 */
7945 return (void*) uc
->uc_mcontext
.sc_ip
;
7951 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
7953 char **messages
= NULL
;
7954 int i
, trace_size
= 0;
7955 unsigned long offset
=0;
7956 ucontext_t
*uc
= (ucontext_t
*) secret
;
7958 REDIS_NOTUSED(info
);
7960 redisLog(REDIS_WARNING
,
7961 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
7962 infostring
= genRedisInfoString();
7963 redisLog(REDIS_WARNING
, "%s",infostring
);
7964 /* It's not safe to sdsfree() the returned string under memory
7965 * corruption conditions. Let it leak as we are going to abort */
7967 trace_size
= backtrace(trace
, 100);
7968 /* overwrite sigaction with caller's address */
7969 if (getMcontextEip(uc
) != NULL
) {
7970 trace
[1] = getMcontextEip(uc
);
7972 messages
= backtrace_symbols(trace
, trace_size
);
7974 for (i
=1; i
<trace_size
; ++i
) {
7975 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
7977 p
= strchr(messages
[i
],'+');
7978 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
7979 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
7981 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
7984 /* free(messages); Don't call free() with possibly corrupted memory. */
7988 static void setupSigSegvAction(void) {
7989 struct sigaction act
;
7991 sigemptyset (&act
.sa_mask
);
7992 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
7993 * is used. Otherwise, sa_handler is used */
7994 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
7995 act
.sa_sigaction
= segvHandler
;
7996 sigaction (SIGSEGV
, &act
, NULL
);
7997 sigaction (SIGBUS
, &act
, NULL
);
7998 sigaction (SIGFPE
, &act
, NULL
);
7999 sigaction (SIGILL
, &act
, NULL
);
8000 sigaction (SIGBUS
, &act
, NULL
);
8004 #include "staticsymbols.h"
8005 /* This function try to convert a pointer into a function name. It's used in
8006 * oreder to provide a backtrace under segmentation fault that's able to
8007 * display functions declared as static (otherwise the backtrace is useless). */
8008 static char *findFuncName(void *pointer
, unsigned long *offset
){
8010 unsigned long off
, minoff
= 0;
8012 /* Try to match against the Symbol with the smallest offset */
8013 for (i
=0; symsTable
[i
].pointer
; i
++) {
8014 unsigned long lp
= (unsigned long) pointer
;
8016 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
8017 off
=lp
-symsTable
[i
].pointer
;
8018 if (ret
< 0 || off
< minoff
) {
8024 if (ret
== -1) return NULL
;
8026 return symsTable
[ret
].name
;
8028 #else /* HAVE_BACKTRACE */
8029 static void setupSigSegvAction(void) {
8031 #endif /* HAVE_BACKTRACE */