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.3"
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 *percentage* of completed I/O jobs to process when the
169 * handelr is called. While Virtual Memory I/O operations are performed by
170 * threads, this operations must be processed by the main thread when completed
171 * in order to take effect. */
172 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
175 #define REDIS_CLOSE 1 /* This client connection should be closed ASAP */
176 #define REDIS_SLAVE 2 /* This client is a slave server */
177 #define REDIS_MASTER 4 /* This client is a master server */
178 #define REDIS_MONITOR 8 /* This client is a slave monitor, see MONITOR */
179 #define REDIS_MULTI 16 /* This client is in a MULTI context */
180 #define REDIS_BLOCKED 32 /* The client is waiting in a blocking operation */
181 #define REDIS_IO_WAIT 64 /* The client is waiting for Virtual Memory I/O */
183 /* Slave replication state - slave side */
184 #define REDIS_REPL_NONE 0 /* No active replication */
185 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
186 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
188 /* Slave replication state - from the point of view of master
189 * Note that in SEND_BULK and ONLINE state the slave receives new updates
190 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
191 * to start the next background saving in order to send updates to it. */
192 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
193 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
194 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
195 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
197 /* List related stuff */
201 /* Sort operations */
202 #define REDIS_SORT_GET 0
203 #define REDIS_SORT_ASC 1
204 #define REDIS_SORT_DESC 2
205 #define REDIS_SORTKEY_MAX 1024
208 #define REDIS_DEBUG 0
209 #define REDIS_VERBOSE 1
210 #define REDIS_NOTICE 2
211 #define REDIS_WARNING 3
213 /* Anti-warning macro... */
214 #define REDIS_NOTUSED(V) ((void) V)
216 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
217 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
219 /* Append only defines */
220 #define APPENDFSYNC_NO 0
221 #define APPENDFSYNC_ALWAYS 1
222 #define APPENDFSYNC_EVERYSEC 2
224 /* We can print the stacktrace, so our assert is defined this way: */
225 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),exit(1)))
226 static void _redisAssert(char *estr
, char *file
, int line
);
228 /*================================= Data types ============================== */
230 /* A redis object, that is a type able to hold a string / list / set */
232 /* The VM object structure */
233 struct redisObjectVM
{
234 off_t page
; /* the page at witch the object is stored on disk */
235 off_t usedpages
; /* number of pages used on disk */
236 time_t atime
; /* Last access time */
239 /* The actual Redis Object */
240 typedef struct redisObject
{
243 unsigned char encoding
;
244 unsigned char storage
; /* If this object is a key, where is the value?
245 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
246 unsigned char vtype
; /* If this object is a key, and value is swapped out,
247 * this is the type of the swapped out object. */
249 /* VM fields, this are only allocated if VM is active, otherwise the
250 * object allocation function will just allocate
251 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
252 * Redis without VM active will not have any overhead. */
253 struct redisObjectVM vm
;
256 /* Macro used to initalize a Redis object allocated on the stack.
257 * Note that this macro is taken near the structure definition to make sure
258 * we'll update it when the structure is changed, to avoid bugs like
259 * bug #85 introduced exactly in this way. */
260 #define initStaticStringObject(_var,_ptr) do { \
262 _var.type = REDIS_STRING; \
263 _var.encoding = REDIS_ENCODING_RAW; \
265 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
268 typedef struct redisDb
{
269 dict
*dict
; /* The keyspace for this DB */
270 dict
*expires
; /* Timeout of keys with a timeout set */
271 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
275 /* Client MULTI/EXEC state */
276 typedef struct multiCmd
{
279 struct redisCommand
*cmd
;
282 typedef struct multiState
{
283 multiCmd
*commands
; /* Array of MULTI commands */
284 int count
; /* Total number of MULTI commands */
287 /* With multiplexing we need to take per-clinet state.
288 * Clients are taken in a liked list. */
289 typedef struct redisClient
{
294 robj
**argv
, **mbargv
;
296 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
297 int multibulk
; /* multi bulk command format active */
300 time_t lastinteraction
; /* time of the last interaction, used for timeout */
301 int flags
; /* REDIS_CLOSE | REDIS_SLAVE | REDIS_MONITOR */
303 int slaveseldb
; /* slave selected db, if this client is a slave */
304 int authenticated
; /* when requirepass is non-NULL */
305 int replstate
; /* replication state if this is a slave */
306 int repldbfd
; /* replication DB file descriptor */
307 long repldboff
; /* replication DB file offset */
308 off_t repldbsize
; /* replication DB file size */
309 multiState mstate
; /* MULTI/EXEC state */
310 robj
**blockingkeys
; /* The key we waiting to terminate a blocking
311 * operation such as BLPOP. Otherwise NULL. */
312 int blockingkeysnum
; /* Number of blocking keys */
313 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
314 * is >= blockingto then the operation timed out. */
315 list
*io_keys
; /* Keys this client is waiting to be loaded from the
316 * swap file in order to continue. */
324 /* Global server state structure */
329 dict
*sharingpool
; /* Poll used for object sharing */
330 unsigned int sharingpoolsize
;
331 long long dirty
; /* changes to DB from the last save */
333 list
*slaves
, *monitors
;
334 char neterr
[ANET_ERR_LEN
];
336 int cronloops
; /* number of times the cron function run */
337 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
338 time_t lastsave
; /* Unix time of last save succeeede */
339 /* Fields used only for stats */
340 time_t stat_starttime
; /* server start time */
341 long long stat_numcommands
; /* number of processed commands */
342 long long stat_numconnections
; /* number of connections received */
355 pid_t bgsavechildpid
;
356 pid_t bgrewritechildpid
;
357 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
358 struct saveparam
*saveparams
;
363 char *appendfilename
;
367 /* Replication related */
372 redisClient
*master
; /* client that is master for this slave */
374 unsigned int maxclients
;
375 unsigned long long maxmemory
;
376 unsigned int blockedclients
;
377 /* Sort parameters - qsort_r() is only available under BSD so we
378 * have to take this state global, in order to pass it to sortCompare() */
382 /* Virtual memory configuration */
387 unsigned long long vm_max_memory
;
388 /* Virtual memory state */
391 off_t vm_next_page
; /* Next probably empty page */
392 off_t vm_near_pages
; /* Number of pages allocated sequentially */
393 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
394 time_t unixtime
; /* Unix time sampled every second. */
395 /* Virtual memory I/O threads stuff */
396 /* An I/O thread process an element taken from the io_jobs queue and
397 * put the result of the operation in the io_done list. While the
398 * job is being processed, it's put on io_processing queue. */
399 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
400 list
*io_processing
; /* List of VM I/O jobs being processed */
401 list
*io_processed
; /* List of VM I/O jobs already processed */
402 list
*io_clients
; /* All the clients waiting for SWAP I/O operations */
403 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
404 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
405 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
406 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
407 int io_active_threads
; /* Number of running I/O threads */
408 int vm_max_threads
; /* Max number of I/O threads running at the same time */
409 /* Our main thread is blocked on the event loop, locking for sockets ready
410 * to be read or written, so when a threaded I/O operation is ready to be
411 * processed by the main thread, the I/O thread will use a unix pipe to
412 * awake the main thread. The followings are the two pipe FDs. */
413 int io_ready_pipe_read
;
414 int io_ready_pipe_write
;
415 /* Virtual memory stats */
416 unsigned long long vm_stats_used_pages
;
417 unsigned long long vm_stats_swapped_objects
;
418 unsigned long long vm_stats_swapouts
;
419 unsigned long long vm_stats_swapins
;
423 typedef void redisCommandProc(redisClient
*c
);
424 struct redisCommand
{
426 redisCommandProc
*proc
;
431 struct redisFunctionSym
{
433 unsigned long pointer
;
436 typedef struct _redisSortObject
{
444 typedef struct _redisSortOperation
{
447 } redisSortOperation
;
449 /* ZSETs use a specialized version of Skiplists */
451 typedef struct zskiplistNode
{
452 struct zskiplistNode
**forward
;
453 struct zskiplistNode
*backward
;
458 typedef struct zskiplist
{
459 struct zskiplistNode
*header
, *tail
;
460 unsigned long length
;
464 typedef struct zset
{
469 /* Our shared "common" objects */
471 struct sharedObjectsStruct
{
472 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
473 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
474 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
475 *outofrangeerr
, *plus
,
476 *select0
, *select1
, *select2
, *select3
, *select4
,
477 *select5
, *select6
, *select7
, *select8
, *select9
;
480 /* Global vars that are actally used as constants. The following double
481 * values are used for double on-disk serialization, and are initialized
482 * at runtime to avoid strange compiler optimizations. */
484 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
486 /* VM threaded I/O request message */
487 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
488 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
489 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
490 typedef struct iojon
{
491 int type
; /* Request type, REDIS_IOJOB_* */
492 redisDb
*db
;/* Redis database */
493 robj
*key
; /* This I/O request is about swapping this key */
494 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
495 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
496 off_t page
; /* Swap page where to read/write the object */
497 off_t pages
; /* Swap pages needed to safe object. PREPARE_SWAP return val */
498 int canceled
; /* True if this command was canceled by blocking side of VM */
499 pthread_t thread
; /* ID of the thread processing this entry */
502 /*================================ Prototypes =============================== */
504 static void freeStringObject(robj
*o
);
505 static void freeListObject(robj
*o
);
506 static void freeSetObject(robj
*o
);
507 static void decrRefCount(void *o
);
508 static robj
*createObject(int type
, void *ptr
);
509 static void freeClient(redisClient
*c
);
510 static int rdbLoad(char *filename
);
511 static void addReply(redisClient
*c
, robj
*obj
);
512 static void addReplySds(redisClient
*c
, sds s
);
513 static void incrRefCount(robj
*o
);
514 static int rdbSaveBackground(char *filename
);
515 static robj
*createStringObject(char *ptr
, size_t len
);
516 static robj
*dupStringObject(robj
*o
);
517 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
518 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
519 static int syncWithMaster(void);
520 static robj
*tryObjectSharing(robj
*o
);
521 static int tryObjectEncoding(robj
*o
);
522 static robj
*getDecodedObject(robj
*o
);
523 static int removeExpire(redisDb
*db
, robj
*key
);
524 static int expireIfNeeded(redisDb
*db
, robj
*key
);
525 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
526 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
527 static int deleteKey(redisDb
*db
, robj
*key
);
528 static time_t getExpire(redisDb
*db
, robj
*key
);
529 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
530 static void updateSlavesWaitingBgsave(int bgsaveerr
);
531 static void freeMemoryIfNeeded(void);
532 static int processCommand(redisClient
*c
);
533 static void setupSigSegvAction(void);
534 static void rdbRemoveTempFile(pid_t childpid
);
535 static void aofRemoveTempFile(pid_t childpid
);
536 static size_t stringObjectLen(robj
*o
);
537 static void processInputBuffer(redisClient
*c
);
538 static zskiplist
*zslCreate(void);
539 static void zslFree(zskiplist
*zsl
);
540 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
541 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
542 static void initClientMultiState(redisClient
*c
);
543 static void freeClientMultiState(redisClient
*c
);
544 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
545 static void unblockClientWaitingData(redisClient
*c
);
546 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
547 static void vmInit(void);
548 static void vmMarkPagesFree(off_t page
, off_t count
);
549 static robj
*vmLoadObject(robj
*key
);
550 static robj
*vmPreviewObject(robj
*key
);
551 static int vmSwapOneObjectBlocking(void);
552 static int vmSwapOneObjectThreaded(void);
553 static int vmCanSwapOut(void);
554 static int tryFreeOneObjectFromFreelist(void);
555 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
556 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
557 static void vmCancelThreadedIOJob(robj
*o
);
558 static void lockThreadedIO(void);
559 static void unlockThreadedIO(void);
560 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
561 static void freeIOJob(iojob
*j
);
562 static void queueIOJob(iojob
*j
);
563 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
564 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
565 static void waitEmptyIOJobsQueue(void);
566 static void vmReopenSwapFile(void);
567 static int vmFreePage(off_t page
);
569 static void authCommand(redisClient
*c
);
570 static void pingCommand(redisClient
*c
);
571 static void echoCommand(redisClient
*c
);
572 static void setCommand(redisClient
*c
);
573 static void setnxCommand(redisClient
*c
);
574 static void getCommand(redisClient
*c
);
575 static void delCommand(redisClient
*c
);
576 static void existsCommand(redisClient
*c
);
577 static void incrCommand(redisClient
*c
);
578 static void decrCommand(redisClient
*c
);
579 static void incrbyCommand(redisClient
*c
);
580 static void decrbyCommand(redisClient
*c
);
581 static void selectCommand(redisClient
*c
);
582 static void randomkeyCommand(redisClient
*c
);
583 static void keysCommand(redisClient
*c
);
584 static void dbsizeCommand(redisClient
*c
);
585 static void lastsaveCommand(redisClient
*c
);
586 static void saveCommand(redisClient
*c
);
587 static void bgsaveCommand(redisClient
*c
);
588 static void bgrewriteaofCommand(redisClient
*c
);
589 static void shutdownCommand(redisClient
*c
);
590 static void moveCommand(redisClient
*c
);
591 static void renameCommand(redisClient
*c
);
592 static void renamenxCommand(redisClient
*c
);
593 static void lpushCommand(redisClient
*c
);
594 static void rpushCommand(redisClient
*c
);
595 static void lpopCommand(redisClient
*c
);
596 static void rpopCommand(redisClient
*c
);
597 static void llenCommand(redisClient
*c
);
598 static void lindexCommand(redisClient
*c
);
599 static void lrangeCommand(redisClient
*c
);
600 static void ltrimCommand(redisClient
*c
);
601 static void typeCommand(redisClient
*c
);
602 static void lsetCommand(redisClient
*c
);
603 static void saddCommand(redisClient
*c
);
604 static void sremCommand(redisClient
*c
);
605 static void smoveCommand(redisClient
*c
);
606 static void sismemberCommand(redisClient
*c
);
607 static void scardCommand(redisClient
*c
);
608 static void spopCommand(redisClient
*c
);
609 static void srandmemberCommand(redisClient
*c
);
610 static void sinterCommand(redisClient
*c
);
611 static void sinterstoreCommand(redisClient
*c
);
612 static void sunionCommand(redisClient
*c
);
613 static void sunionstoreCommand(redisClient
*c
);
614 static void sdiffCommand(redisClient
*c
);
615 static void sdiffstoreCommand(redisClient
*c
);
616 static void syncCommand(redisClient
*c
);
617 static void flushdbCommand(redisClient
*c
);
618 static void flushallCommand(redisClient
*c
);
619 static void sortCommand(redisClient
*c
);
620 static void lremCommand(redisClient
*c
);
621 static void rpoplpushcommand(redisClient
*c
);
622 static void infoCommand(redisClient
*c
);
623 static void mgetCommand(redisClient
*c
);
624 static void monitorCommand(redisClient
*c
);
625 static void expireCommand(redisClient
*c
);
626 static void expireatCommand(redisClient
*c
);
627 static void getsetCommand(redisClient
*c
);
628 static void ttlCommand(redisClient
*c
);
629 static void slaveofCommand(redisClient
*c
);
630 static void debugCommand(redisClient
*c
);
631 static void msetCommand(redisClient
*c
);
632 static void msetnxCommand(redisClient
*c
);
633 static void zaddCommand(redisClient
*c
);
634 static void zincrbyCommand(redisClient
*c
);
635 static void zrangeCommand(redisClient
*c
);
636 static void zrangebyscoreCommand(redisClient
*c
);
637 static void zrevrangeCommand(redisClient
*c
);
638 static void zcardCommand(redisClient
*c
);
639 static void zremCommand(redisClient
*c
);
640 static void zscoreCommand(redisClient
*c
);
641 static void zremrangebyscoreCommand(redisClient
*c
);
642 static void multiCommand(redisClient
*c
);
643 static void execCommand(redisClient
*c
);
644 static void blpopCommand(redisClient
*c
);
645 static void brpopCommand(redisClient
*c
);
647 /*================================= Globals ================================= */
650 static struct redisServer server
; /* server global state */
651 static struct redisCommand cmdTable
[] = {
652 {"get",getCommand
,2,REDIS_CMD_INLINE
},
653 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
654 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
655 {"del",delCommand
,-2,REDIS_CMD_INLINE
},
656 {"exists",existsCommand
,2,REDIS_CMD_INLINE
},
657 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
658 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
659 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
},
660 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
661 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
662 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
},
663 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
},
664 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
},
665 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
},
666 {"llen",llenCommand
,2,REDIS_CMD_INLINE
},
667 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
},
668 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
669 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
},
670 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
},
671 {"lrem",lremCommand
,4,REDIS_CMD_BULK
},
672 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
673 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
674 {"srem",sremCommand
,3,REDIS_CMD_BULK
},
675 {"smove",smoveCommand
,4,REDIS_CMD_BULK
},
676 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
},
677 {"scard",scardCommand
,2,REDIS_CMD_INLINE
},
678 {"spop",spopCommand
,2,REDIS_CMD_INLINE
},
679 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
},
680 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
681 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
682 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
683 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
684 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
685 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
686 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
},
687 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
688 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
689 {"zrem",zremCommand
,3,REDIS_CMD_BULK
},
690 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
},
691 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
},
692 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
},
693 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
},
694 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
},
695 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
696 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
697 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
698 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
699 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
700 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
},
701 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
},
702 {"select",selectCommand
,2,REDIS_CMD_INLINE
},
703 {"move",moveCommand
,3,REDIS_CMD_INLINE
},
704 {"rename",renameCommand
,3,REDIS_CMD_INLINE
},
705 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
},
706 {"expire",expireCommand
,3,REDIS_CMD_INLINE
},
707 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
},
708 {"keys",keysCommand
,2,REDIS_CMD_INLINE
},
709 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
},
710 {"auth",authCommand
,2,REDIS_CMD_INLINE
},
711 {"ping",pingCommand
,1,REDIS_CMD_INLINE
},
712 {"echo",echoCommand
,2,REDIS_CMD_BULK
},
713 {"save",saveCommand
,1,REDIS_CMD_INLINE
},
714 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
},
715 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
},
716 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
},
717 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
},
718 {"type",typeCommand
,2,REDIS_CMD_INLINE
},
719 {"multi",multiCommand
,1,REDIS_CMD_INLINE
},
720 {"exec",execCommand
,1,REDIS_CMD_INLINE
},
721 {"sync",syncCommand
,1,REDIS_CMD_INLINE
},
722 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
},
723 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
},
724 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
},
725 {"info",infoCommand
,1,REDIS_CMD_INLINE
},
726 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
},
727 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
},
728 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
},
729 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
},
733 /*============================ Utility functions ============================ */
735 /* Glob-style pattern matching. */
736 int stringmatchlen(const char *pattern
, int patternLen
,
737 const char *string
, int stringLen
, int nocase
)
742 while (pattern
[1] == '*') {
747 return 1; /* match */
749 if (stringmatchlen(pattern
+1, patternLen
-1,
750 string
, stringLen
, nocase
))
751 return 1; /* match */
755 return 0; /* no match */
759 return 0; /* no match */
769 not = pattern
[0] == '^';
776 if (pattern
[0] == '\\') {
779 if (pattern
[0] == string
[0])
781 } else if (pattern
[0] == ']') {
783 } else if (patternLen
== 0) {
787 } else if (pattern
[1] == '-' && patternLen
>= 3) {
788 int start
= pattern
[0];
789 int end
= pattern
[2];
797 start
= tolower(start
);
803 if (c
>= start
&& c
<= end
)
807 if (pattern
[0] == string
[0])
810 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
820 return 0; /* no match */
826 if (patternLen
>= 2) {
833 if (pattern
[0] != string
[0])
834 return 0; /* no match */
836 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
837 return 0; /* no match */
845 if (stringLen
== 0) {
846 while(*pattern
== '*') {
853 if (patternLen
== 0 && stringLen
== 0)
858 static void redisLog(int level
, const char *fmt
, ...) {
862 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
866 if (level
>= server
.verbosity
) {
872 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
873 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
874 vfprintf(fp
, fmt
, ap
);
880 if (server
.logfile
) fclose(fp
);
883 /*====================== Hash table type implementation ==================== */
885 /* This is an hash table type that uses the SDS dynamic strings libary as
886 * keys and radis objects as values (objects can hold SDS strings,
889 static void dictVanillaFree(void *privdata
, void *val
)
891 DICT_NOTUSED(privdata
);
895 static void dictListDestructor(void *privdata
, void *val
)
897 DICT_NOTUSED(privdata
);
898 listRelease((list
*)val
);
901 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
905 DICT_NOTUSED(privdata
);
907 l1
= sdslen((sds
)key1
);
908 l2
= sdslen((sds
)key2
);
909 if (l1
!= l2
) return 0;
910 return memcmp(key1
, key2
, l1
) == 0;
913 static void dictRedisObjectDestructor(void *privdata
, void *val
)
915 DICT_NOTUSED(privdata
);
917 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
921 static int dictObjKeyCompare(void *privdata
, const void *key1
,
924 const robj
*o1
= key1
, *o2
= key2
;
925 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
928 static unsigned int dictObjHash(const void *key
) {
930 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
933 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
936 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
939 o1
= getDecodedObject(o1
);
940 o2
= getDecodedObject(o2
);
941 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
947 static unsigned int dictEncObjHash(const void *key
) {
948 robj
*o
= (robj
*) key
;
950 o
= getDecodedObject(o
);
951 unsigned int hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
956 /* Sets type and expires */
957 static dictType setDictType
= {
958 dictEncObjHash
, /* hash function */
961 dictEncObjKeyCompare
, /* key compare */
962 dictRedisObjectDestructor
, /* key destructor */
963 NULL
/* val destructor */
966 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
967 static dictType zsetDictType
= {
968 dictEncObjHash
, /* hash function */
971 dictEncObjKeyCompare
, /* key compare */
972 dictRedisObjectDestructor
, /* key destructor */
973 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
977 static dictType hashDictType
= {
978 dictObjHash
, /* hash function */
981 dictObjKeyCompare
, /* key compare */
982 dictRedisObjectDestructor
, /* key destructor */
983 dictRedisObjectDestructor
/* val destructor */
987 static dictType keyptrDictType
= {
988 dictObjHash
, /* hash function */
991 dictObjKeyCompare
, /* key compare */
992 dictRedisObjectDestructor
, /* key destructor */
993 NULL
/* val destructor */
996 /* Keylist hash table type has unencoded redis objects as keys and
997 * lists as values. It's used for blocking operations (BLPOP) */
998 static dictType keylistDictType
= {
999 dictObjHash
, /* hash function */
1002 dictObjKeyCompare
, /* key compare */
1003 dictRedisObjectDestructor
, /* key destructor */
1004 dictListDestructor
/* val destructor */
1007 /* ========================= Random utility functions ======================= */
1009 /* Redis generally does not try to recover from out of memory conditions
1010 * when allocating objects or strings, it is not clear if it will be possible
1011 * to report this condition to the client since the networking layer itself
1012 * is based on heap allocation for send buffers, so we simply abort.
1013 * At least the code will be simpler to read... */
1014 static void oom(const char *msg
) {
1015 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1020 /* ====================== Redis server networking stuff ===================== */
1021 static void closeTimedoutClients(void) {
1024 time_t now
= time(NULL
);
1027 listRewind(server
.clients
,&li
);
1028 while ((ln
= listNext(&li
)) != NULL
) {
1029 c
= listNodeValue(ln
);
1030 if (server
.maxidletime
&&
1031 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1032 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1033 (now
- c
->lastinteraction
> server
.maxidletime
))
1035 redisLog(REDIS_VERBOSE
,"Closing idle client");
1037 } else if (c
->flags
& REDIS_BLOCKED
) {
1038 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1039 addReply(c
,shared
.nullmultibulk
);
1040 unblockClientWaitingData(c
);
1046 static int htNeedsResize(dict
*dict
) {
1047 long long size
, used
;
1049 size
= dictSlots(dict
);
1050 used
= dictSize(dict
);
1051 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1052 (used
*100/size
< REDIS_HT_MINFILL
));
1055 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1056 * we resize the hash table to save memory */
1057 static void tryResizeHashTables(void) {
1060 for (j
= 0; j
< server
.dbnum
; j
++) {
1061 if (htNeedsResize(server
.db
[j
].dict
)) {
1062 redisLog(REDIS_VERBOSE
,"The hash table %d is too sparse, resize it...",j
);
1063 dictResize(server
.db
[j
].dict
);
1064 redisLog(REDIS_VERBOSE
,"Hash table %d resized.",j
);
1066 if (htNeedsResize(server
.db
[j
].expires
))
1067 dictResize(server
.db
[j
].expires
);
1071 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1072 void backgroundSaveDoneHandler(int statloc
) {
1073 int exitcode
= WEXITSTATUS(statloc
);
1074 int bysignal
= WIFSIGNALED(statloc
);
1076 if (!bysignal
&& exitcode
== 0) {
1077 redisLog(REDIS_NOTICE
,
1078 "Background saving terminated with success");
1080 server
.lastsave
= time(NULL
);
1081 } else if (!bysignal
&& exitcode
!= 0) {
1082 redisLog(REDIS_WARNING
, "Background saving error");
1084 redisLog(REDIS_WARNING
,
1085 "Background saving terminated by signal");
1086 rdbRemoveTempFile(server
.bgsavechildpid
);
1088 server
.bgsavechildpid
= -1;
1089 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1090 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1091 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1094 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1096 void backgroundRewriteDoneHandler(int statloc
) {
1097 int exitcode
= WEXITSTATUS(statloc
);
1098 int bysignal
= WIFSIGNALED(statloc
);
1100 if (!bysignal
&& exitcode
== 0) {
1104 redisLog(REDIS_NOTICE
,
1105 "Background append only file rewriting terminated with success");
1106 /* Now it's time to flush the differences accumulated by the parent */
1107 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1108 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1110 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1113 /* Flush our data... */
1114 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1115 (signed) sdslen(server
.bgrewritebuf
)) {
1116 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
));
1120 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1121 /* Now our work is to rename the temp file into the stable file. And
1122 * switch the file descriptor used by the server for append only. */
1123 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1124 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1128 /* Mission completed... almost */
1129 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1130 if (server
.appendfd
!= -1) {
1131 /* If append only is actually enabled... */
1132 close(server
.appendfd
);
1133 server
.appendfd
= fd
;
1135 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1136 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1138 /* If append only is disabled we just generate a dump in this
1139 * format. Why not? */
1142 } else if (!bysignal
&& exitcode
!= 0) {
1143 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1145 redisLog(REDIS_WARNING
,
1146 "Background append only file rewriting terminated by signal");
1149 sdsfree(server
.bgrewritebuf
);
1150 server
.bgrewritebuf
= sdsempty();
1151 aofRemoveTempFile(server
.bgrewritechildpid
);
1152 server
.bgrewritechildpid
= -1;
1155 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1156 int j
, loops
= server
.cronloops
++;
1157 REDIS_NOTUSED(eventLoop
);
1159 REDIS_NOTUSED(clientData
);
1161 /* We take a cached value of the unix time in the global state because
1162 * with virtual memory and aging there is to store the current time
1163 * in objects at every object access, and accuracy is not needed.
1164 * To access a global var is faster than calling time(NULL) */
1165 server
.unixtime
= time(NULL
);
1167 /* Show some info about non-empty databases */
1168 for (j
= 0; j
< server
.dbnum
; j
++) {
1169 long long size
, used
, vkeys
;
1171 size
= dictSlots(server
.db
[j
].dict
);
1172 used
= dictSize(server
.db
[j
].dict
);
1173 vkeys
= dictSize(server
.db
[j
].expires
);
1174 if (!(loops
% 5) && (used
|| vkeys
)) {
1175 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1176 /* dictPrintStats(server.dict); */
1180 /* We don't want to resize the hash tables while a bacground saving
1181 * is in progress: the saving child is created using fork() that is
1182 * implemented with a copy-on-write semantic in most modern systems, so
1183 * if we resize the HT while there is the saving child at work actually
1184 * a lot of memory movements in the parent will cause a lot of pages
1186 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1188 /* Show information about connected clients */
1190 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1191 listLength(server
.clients
)-listLength(server
.slaves
),
1192 listLength(server
.slaves
),
1193 zmalloc_used_memory(),
1194 dictSize(server
.sharingpool
));
1197 /* Close connections of timedout clients */
1198 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blockedclients
)
1199 closeTimedoutClients();
1201 /* Check if a background saving or AOF rewrite in progress terminated */
1202 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1206 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1207 if (pid
== server
.bgsavechildpid
) {
1208 backgroundSaveDoneHandler(statloc
);
1210 backgroundRewriteDoneHandler(statloc
);
1214 /* If there is not a background saving in progress check if
1215 * we have to save now */
1216 time_t now
= time(NULL
);
1217 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1218 struct saveparam
*sp
= server
.saveparams
+j
;
1220 if (server
.dirty
>= sp
->changes
&&
1221 now
-server
.lastsave
> sp
->seconds
) {
1222 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1223 sp
->changes
, sp
->seconds
);
1224 rdbSaveBackground(server
.dbfilename
);
1230 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1231 * will use few CPU cycles if there are few expiring keys, otherwise
1232 * it will get more aggressive to avoid that too much memory is used by
1233 * keys that can be removed from the keyspace. */
1234 for (j
= 0; j
< server
.dbnum
; j
++) {
1236 redisDb
*db
= server
.db
+j
;
1238 /* Continue to expire if at the end of the cycle more than 25%
1239 * of the keys were expired. */
1241 long num
= dictSize(db
->expires
);
1242 time_t now
= time(NULL
);
1245 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1246 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1251 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1252 t
= (time_t) dictGetEntryVal(de
);
1254 deleteKey(db
,dictGetEntryKey(de
));
1258 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1261 /* Swap a few keys on disk if we are over the memory limit and VM
1262 * is enbled. Try to free objects from the free list first. */
1263 if (vmCanSwapOut()) {
1264 while (server
.vm_enabled
&& zmalloc_used_memory() >
1265 server
.vm_max_memory
)
1269 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1270 retval
= (server
.vm_max_threads
== 0) ?
1271 vmSwapOneObjectBlocking() :
1272 vmSwapOneObjectThreaded();
1273 if (retval
== REDIS_ERR
&& (loops
% 30) == 0 &&
1274 zmalloc_used_memory() >
1275 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1277 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1279 /* Note that when using threade I/O we free just one object,
1280 * because anyway when the I/O thread in charge to swap this
1281 * object out will finish, the handler of completed jobs
1282 * will try to swap more objects if we are still out of memory. */
1283 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1287 /* Check if we should connect to a MASTER */
1288 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1289 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1290 if (syncWithMaster() == REDIS_OK
) {
1291 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1297 static void createSharedObjects(void) {
1298 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1299 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1300 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1301 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1302 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1303 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1304 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1305 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1306 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1307 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1308 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1309 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1310 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1311 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1312 "-ERR no such key\r\n"));
1313 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1314 "-ERR syntax error\r\n"));
1315 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1316 "-ERR source and destination objects are the same\r\n"));
1317 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1318 "-ERR index out of range\r\n"));
1319 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1320 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1321 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1322 shared
.select0
= createStringObject("select 0\r\n",10);
1323 shared
.select1
= createStringObject("select 1\r\n",10);
1324 shared
.select2
= createStringObject("select 2\r\n",10);
1325 shared
.select3
= createStringObject("select 3\r\n",10);
1326 shared
.select4
= createStringObject("select 4\r\n",10);
1327 shared
.select5
= createStringObject("select 5\r\n",10);
1328 shared
.select6
= createStringObject("select 6\r\n",10);
1329 shared
.select7
= createStringObject("select 7\r\n",10);
1330 shared
.select8
= createStringObject("select 8\r\n",10);
1331 shared
.select9
= createStringObject("select 9\r\n",10);
1334 static void appendServerSaveParams(time_t seconds
, int changes
) {
1335 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1336 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1337 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1338 server
.saveparamslen
++;
1341 static void resetServerSaveParams() {
1342 zfree(server
.saveparams
);
1343 server
.saveparams
= NULL
;
1344 server
.saveparamslen
= 0;
1347 static void initServerConfig() {
1348 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1349 server
.port
= REDIS_SERVERPORT
;
1350 server
.verbosity
= REDIS_VERBOSE
;
1351 server
.maxidletime
= REDIS_MAXIDLETIME
;
1352 server
.saveparams
= NULL
;
1353 server
.logfile
= NULL
; /* NULL = log on standard output */
1354 server
.bindaddr
= NULL
;
1355 server
.glueoutputbuf
= 1;
1356 server
.daemonize
= 0;
1357 server
.appendonly
= 0;
1358 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1359 server
.lastfsync
= time(NULL
);
1360 server
.appendfd
= -1;
1361 server
.appendseldb
= -1; /* Make sure the first time will not match */
1362 server
.pidfile
= "/var/run/redis.pid";
1363 server
.dbfilename
= "dump.rdb";
1364 server
.appendfilename
= "appendonly.aof";
1365 server
.requirepass
= NULL
;
1366 server
.shareobjects
= 0;
1367 server
.rdbcompression
= 1;
1368 server
.sharingpoolsize
= 1024;
1369 server
.maxclients
= 0;
1370 server
.blockedclients
= 0;
1371 server
.maxmemory
= 0;
1372 server
.vm_enabled
= 0;
1373 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
1374 server
.vm_page_size
= 256; /* 256 bytes per page */
1375 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1376 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1377 server
.vm_max_threads
= 4;
1379 resetServerSaveParams();
1381 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1382 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1383 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1384 /* Replication related */
1386 server
.masterauth
= NULL
;
1387 server
.masterhost
= NULL
;
1388 server
.masterport
= 6379;
1389 server
.master
= NULL
;
1390 server
.replstate
= REDIS_REPL_NONE
;
1392 /* Double constants initialization */
1394 R_PosInf
= 1.0/R_Zero
;
1395 R_NegInf
= -1.0/R_Zero
;
1396 R_Nan
= R_Zero
/R_Zero
;
1399 static void initServer() {
1402 signal(SIGHUP
, SIG_IGN
);
1403 signal(SIGPIPE
, SIG_IGN
);
1404 setupSigSegvAction();
1406 server
.devnull
= fopen("/dev/null","w");
1407 if (server
.devnull
== NULL
) {
1408 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1411 server
.clients
= listCreate();
1412 server
.slaves
= listCreate();
1413 server
.monitors
= listCreate();
1414 server
.objfreelist
= listCreate();
1415 createSharedObjects();
1416 server
.el
= aeCreateEventLoop();
1417 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1418 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1419 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1420 if (server
.fd
== -1) {
1421 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1424 for (j
= 0; j
< server
.dbnum
; j
++) {
1425 server
.db
[j
].dict
= dictCreate(&hashDictType
,NULL
);
1426 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1427 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1428 server
.db
[j
].id
= j
;
1430 server
.cronloops
= 0;
1431 server
.bgsavechildpid
= -1;
1432 server
.bgrewritechildpid
= -1;
1433 server
.bgrewritebuf
= sdsempty();
1434 server
.lastsave
= time(NULL
);
1436 server
.stat_numcommands
= 0;
1437 server
.stat_numconnections
= 0;
1438 server
.stat_starttime
= time(NULL
);
1439 server
.unixtime
= time(NULL
);
1440 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1441 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1442 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1444 if (server
.appendonly
) {
1445 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1446 if (server
.appendfd
== -1) {
1447 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1453 if (server
.vm_enabled
) vmInit();
1456 /* Empty the whole database */
1457 static long long emptyDb() {
1459 long long removed
= 0;
1461 for (j
= 0; j
< server
.dbnum
; j
++) {
1462 removed
+= dictSize(server
.db
[j
].dict
);
1463 dictEmpty(server
.db
[j
].dict
);
1464 dictEmpty(server
.db
[j
].expires
);
1469 static int yesnotoi(char *s
) {
1470 if (!strcasecmp(s
,"yes")) return 1;
1471 else if (!strcasecmp(s
,"no")) return 0;
1475 /* I agree, this is a very rudimental way to load a configuration...
1476 will improve later if the config gets more complex */
1477 static void loadServerConfig(char *filename
) {
1479 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1483 if (filename
[0] == '-' && filename
[1] == '\0')
1486 if ((fp
= fopen(filename
,"r")) == NULL
) {
1487 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1492 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1498 line
= sdstrim(line
," \t\r\n");
1500 /* Skip comments and blank lines*/
1501 if (line
[0] == '#' || line
[0] == '\0') {
1506 /* Split into arguments */
1507 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1508 sdstolower(argv
[0]);
1510 /* Execute config directives */
1511 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1512 server
.maxidletime
= atoi(argv
[1]);
1513 if (server
.maxidletime
< 0) {
1514 err
= "Invalid timeout value"; goto loaderr
;
1516 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1517 server
.port
= atoi(argv
[1]);
1518 if (server
.port
< 1 || server
.port
> 65535) {
1519 err
= "Invalid port"; goto loaderr
;
1521 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1522 server
.bindaddr
= zstrdup(argv
[1]);
1523 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1524 int seconds
= atoi(argv
[1]);
1525 int changes
= atoi(argv
[2]);
1526 if (seconds
< 1 || changes
< 0) {
1527 err
= "Invalid save parameters"; goto loaderr
;
1529 appendServerSaveParams(seconds
,changes
);
1530 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1531 if (chdir(argv
[1]) == -1) {
1532 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1533 argv
[1], strerror(errno
));
1536 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1537 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1538 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1539 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1540 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1542 err
= "Invalid log level. Must be one of debug, notice, warning";
1545 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1548 server
.logfile
= zstrdup(argv
[1]);
1549 if (!strcasecmp(server
.logfile
,"stdout")) {
1550 zfree(server
.logfile
);
1551 server
.logfile
= NULL
;
1553 if (server
.logfile
) {
1554 /* Test if we are able to open the file. The server will not
1555 * be able to abort just for this problem later... */
1556 logfp
= fopen(server
.logfile
,"a");
1557 if (logfp
== NULL
) {
1558 err
= sdscatprintf(sdsempty(),
1559 "Can't open the log file: %s", strerror(errno
));
1564 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1565 server
.dbnum
= atoi(argv
[1]);
1566 if (server
.dbnum
< 1) {
1567 err
= "Invalid number of databases"; goto loaderr
;
1569 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1570 server
.maxclients
= atoi(argv
[1]);
1571 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1572 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1573 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1574 server
.masterhost
= sdsnew(argv
[1]);
1575 server
.masterport
= atoi(argv
[2]);
1576 server
.replstate
= REDIS_REPL_CONNECT
;
1577 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1578 server
.masterauth
= zstrdup(argv
[1]);
1579 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1580 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1581 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1583 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1584 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1585 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1587 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1588 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1589 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1591 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1592 server
.sharingpoolsize
= atoi(argv
[1]);
1593 if (server
.sharingpoolsize
< 1) {
1594 err
= "invalid object sharing pool size"; goto loaderr
;
1596 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1597 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1598 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1600 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1601 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1602 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1604 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1605 if (!strcasecmp(argv
[1],"no")) {
1606 server
.appendfsync
= APPENDFSYNC_NO
;
1607 } else if (!strcasecmp(argv
[1],"always")) {
1608 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1609 } else if (!strcasecmp(argv
[1],"everysec")) {
1610 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1612 err
= "argument must be 'no', 'always' or 'everysec'";
1615 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1616 server
.requirepass
= zstrdup(argv
[1]);
1617 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1618 server
.pidfile
= zstrdup(argv
[1]);
1619 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1620 server
.dbfilename
= zstrdup(argv
[1]);
1621 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1622 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1623 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1625 } else if (!strcasecmp(argv
[0],"vm-swap-file") && argc
== 2) {
1626 zfree(server
.vm_swap_file
);
1627 server
.vm_swap_file
= zstrdup(argv
[1]);
1628 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1629 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1630 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1631 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1632 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1633 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1634 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1635 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1637 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1639 for (j
= 0; j
< argc
; j
++)
1644 if (fp
!= stdin
) fclose(fp
);
1648 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1649 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1650 fprintf(stderr
, ">>> '%s'\n", line
);
1651 fprintf(stderr
, "%s\n", err
);
1655 static void freeClientArgv(redisClient
*c
) {
1658 for (j
= 0; j
< c
->argc
; j
++)
1659 decrRefCount(c
->argv
[j
]);
1660 for (j
= 0; j
< c
->mbargc
; j
++)
1661 decrRefCount(c
->mbargv
[j
]);
1666 static void freeClient(redisClient
*c
) {
1669 /* Note that if the client we are freeing is blocked into a blocking
1670 * call, we have to set querybuf to NULL *before* to call
1671 * unblockClientWaitingData() to avoid processInputBuffer() will get
1672 * called. Also it is important to remove the file events after
1673 * this, because this call adds the READABLE event. */
1674 sdsfree(c
->querybuf
);
1676 if (c
->flags
& REDIS_BLOCKED
)
1677 unblockClientWaitingData(c
);
1679 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1680 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1681 listRelease(c
->reply
);
1684 /* Remove from the list of clients */
1685 ln
= listSearchKey(server
.clients
,c
);
1686 redisAssert(ln
!= NULL
);
1687 listDelNode(server
.clients
,ln
);
1688 /* Remove from the list of clients waiting for VM operations */
1689 if (server
.vm_enabled
&& listLength(c
->io_keys
)) {
1690 ln
= listSearchKey(server
.io_clients
,c
);
1691 if (ln
) listDelNode(server
.io_clients
,ln
);
1692 listRelease(c
->io_keys
);
1694 listRelease(c
->io_keys
);
1696 if (c
->flags
& REDIS_SLAVE
) {
1697 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1699 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1700 ln
= listSearchKey(l
,c
);
1701 redisAssert(ln
!= NULL
);
1704 if (c
->flags
& REDIS_MASTER
) {
1705 server
.master
= NULL
;
1706 server
.replstate
= REDIS_REPL_CONNECT
;
1710 freeClientMultiState(c
);
1714 #define GLUEREPLY_UP_TO (1024)
1715 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1717 char buf
[GLUEREPLY_UP_TO
];
1722 listRewind(c
->reply
,&li
);
1723 while((ln
= listNext(&li
))) {
1727 objlen
= sdslen(o
->ptr
);
1728 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1729 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1731 listDelNode(c
->reply
,ln
);
1733 if (copylen
== 0) return;
1737 /* Now the output buffer is empty, add the new single element */
1738 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1739 listAddNodeHead(c
->reply
,o
);
1742 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1743 redisClient
*c
= privdata
;
1744 int nwritten
= 0, totwritten
= 0, objlen
;
1747 REDIS_NOTUSED(mask
);
1749 /* Use writev() if we have enough buffers to send */
1750 if (!server
.glueoutputbuf
&&
1751 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1752 !(c
->flags
& REDIS_MASTER
))
1754 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1758 while(listLength(c
->reply
)) {
1759 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1760 glueReplyBuffersIfNeeded(c
);
1762 o
= listNodeValue(listFirst(c
->reply
));
1763 objlen
= sdslen(o
->ptr
);
1766 listDelNode(c
->reply
,listFirst(c
->reply
));
1770 if (c
->flags
& REDIS_MASTER
) {
1771 /* Don't reply to a master */
1772 nwritten
= objlen
- c
->sentlen
;
1774 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1775 if (nwritten
<= 0) break;
1777 c
->sentlen
+= nwritten
;
1778 totwritten
+= nwritten
;
1779 /* If we fully sent the object on head go to the next one */
1780 if (c
->sentlen
== objlen
) {
1781 listDelNode(c
->reply
,listFirst(c
->reply
));
1784 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1785 * bytes, in a single threaded server it's a good idea to serve
1786 * other clients as well, even if a very large request comes from
1787 * super fast link that is always able to accept data (in real world
1788 * scenario think about 'KEYS *' against the loopback interfae) */
1789 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1791 if (nwritten
== -1) {
1792 if (errno
== EAGAIN
) {
1795 redisLog(REDIS_VERBOSE
,
1796 "Error writing to client: %s", strerror(errno
));
1801 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1802 if (listLength(c
->reply
) == 0) {
1804 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1808 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1810 redisClient
*c
= privdata
;
1811 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1813 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1814 int offset
, ion
= 0;
1816 REDIS_NOTUSED(mask
);
1819 while (listLength(c
->reply
)) {
1820 offset
= c
->sentlen
;
1824 /* fill-in the iov[] array */
1825 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1826 o
= listNodeValue(node
);
1827 objlen
= sdslen(o
->ptr
);
1829 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1832 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1833 break; /* no more iovecs */
1835 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1836 iov
[ion
].iov_len
= objlen
- offset
;
1837 willwrite
+= objlen
- offset
;
1838 offset
= 0; /* just for the first item */
1845 /* write all collected blocks at once */
1846 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1847 if (errno
!= EAGAIN
) {
1848 redisLog(REDIS_VERBOSE
,
1849 "Error writing to client: %s", strerror(errno
));
1856 totwritten
+= nwritten
;
1857 offset
= c
->sentlen
;
1859 /* remove written robjs from c->reply */
1860 while (nwritten
&& listLength(c
->reply
)) {
1861 o
= listNodeValue(listFirst(c
->reply
));
1862 objlen
= sdslen(o
->ptr
);
1864 if(nwritten
>= objlen
- offset
) {
1865 listDelNode(c
->reply
, listFirst(c
->reply
));
1866 nwritten
-= objlen
- offset
;
1870 c
->sentlen
+= nwritten
;
1878 c
->lastinteraction
= time(NULL
);
1880 if (listLength(c
->reply
) == 0) {
1882 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1886 static struct redisCommand
*lookupCommand(char *name
) {
1888 while(cmdTable
[j
].name
!= NULL
) {
1889 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
1895 /* resetClient prepare the client to process the next command */
1896 static void resetClient(redisClient
*c
) {
1902 /* Call() is the core of Redis execution of a command */
1903 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
1906 dirty
= server
.dirty
;
1908 if (server
.appendonly
&& server
.dirty
-dirty
)
1909 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1910 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
1911 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1912 if (listLength(server
.monitors
))
1913 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
1914 server
.stat_numcommands
++;
1917 /* If this function gets called we already read a whole
1918 * command, argments are in the client argv/argc fields.
1919 * processCommand() execute the command or prepare the
1920 * server for a bulk read from the client.
1922 * If 1 is returned the client is still alive and valid and
1923 * and other operations can be performed by the caller. Otherwise
1924 * if 0 is returned the client was destroied (i.e. after QUIT). */
1925 static int processCommand(redisClient
*c
) {
1926 struct redisCommand
*cmd
;
1928 /* Free some memory if needed (maxmemory setting) */
1929 if (server
.maxmemory
) freeMemoryIfNeeded();
1931 /* Handle the multi bulk command type. This is an alternative protocol
1932 * supported by Redis in order to receive commands that are composed of
1933 * multiple binary-safe "bulk" arguments. The latency of processing is
1934 * a bit higher but this allows things like multi-sets, so if this
1935 * protocol is used only for MSET and similar commands this is a big win. */
1936 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
1937 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1938 if (c
->multibulk
<= 0) {
1942 decrRefCount(c
->argv
[c
->argc
-1]);
1946 } else if (c
->multibulk
) {
1947 if (c
->bulklen
== -1) {
1948 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
1949 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
1953 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
1954 decrRefCount(c
->argv
[0]);
1955 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
1957 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
1962 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
1966 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
1967 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
1971 if (c
->multibulk
== 0) {
1975 /* Here we need to swap the multi-bulk argc/argv with the
1976 * normal argc/argv of the client structure. */
1978 c
->argv
= c
->mbargv
;
1979 c
->mbargv
= auxargv
;
1982 c
->argc
= c
->mbargc
;
1983 c
->mbargc
= auxargc
;
1985 /* We need to set bulklen to something different than -1
1986 * in order for the code below to process the command without
1987 * to try to read the last argument of a bulk command as
1988 * a special argument. */
1990 /* continue below and process the command */
1997 /* -- end of multi bulk commands processing -- */
1999 /* The QUIT command is handled as a special case. Normal command
2000 * procs are unable to close the client connection safely */
2001 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2005 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2008 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2009 (char*)c
->argv
[0]->ptr
));
2012 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2013 (c
->argc
< -cmd
->arity
)) {
2015 sdscatprintf(sdsempty(),
2016 "-ERR wrong number of arguments for '%s' command\r\n",
2020 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
2021 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2024 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2025 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2027 decrRefCount(c
->argv
[c
->argc
-1]);
2028 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2030 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2035 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2036 /* It is possible that the bulk read is already in the
2037 * buffer. Check this condition and handle it accordingly.
2038 * This is just a fast path, alternative to call processInputBuffer().
2039 * It's a good idea since the code is small and this condition
2040 * happens most of the times. */
2041 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2042 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2044 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2049 /* Let's try to share objects on the command arguments vector */
2050 if (server
.shareobjects
) {
2052 for(j
= 1; j
< c
->argc
; j
++)
2053 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
2055 /* Let's try to encode the bulk object to save space. */
2056 if (cmd
->flags
& REDIS_CMD_BULK
)
2057 tryObjectEncoding(c
->argv
[c
->argc
-1]);
2059 /* Check if the user is authenticated */
2060 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2061 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2066 /* Exec the command */
2067 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
) {
2068 queueMultiCommand(c
,cmd
);
2069 addReply(c
,shared
.queued
);
2074 /* Prepare the client for the next command */
2075 if (c
->flags
& REDIS_CLOSE
) {
2083 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
2088 /* (args*2)+1 is enough room for args, spaces, newlines */
2089 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
2091 if (argc
<= REDIS_STATIC_ARGS
) {
2094 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
2097 for (j
= 0; j
< argc
; j
++) {
2098 if (j
!= 0) outv
[outc
++] = shared
.space
;
2099 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
2102 lenobj
= createObject(REDIS_STRING
,
2103 sdscatprintf(sdsempty(),"%lu\r\n",
2104 (unsigned long) stringObjectLen(argv
[j
])));
2105 lenobj
->refcount
= 0;
2106 outv
[outc
++] = lenobj
;
2108 outv
[outc
++] = argv
[j
];
2110 outv
[outc
++] = shared
.crlf
;
2112 /* Increment all the refcounts at start and decrement at end in order to
2113 * be sure to free objects if there is no slave in a replication state
2114 * able to be feed with commands */
2115 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2116 listRewind(slaves
,&li
);
2117 while((ln
= listNext(&li
))) {
2118 redisClient
*slave
= ln
->value
;
2120 /* Don't feed slaves that are still waiting for BGSAVE to start */
2121 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2123 /* Feed all the other slaves, MONITORs and so on */
2124 if (slave
->slaveseldb
!= dictid
) {
2128 case 0: selectcmd
= shared
.select0
; break;
2129 case 1: selectcmd
= shared
.select1
; break;
2130 case 2: selectcmd
= shared
.select2
; break;
2131 case 3: selectcmd
= shared
.select3
; break;
2132 case 4: selectcmd
= shared
.select4
; break;
2133 case 5: selectcmd
= shared
.select5
; break;
2134 case 6: selectcmd
= shared
.select6
; break;
2135 case 7: selectcmd
= shared
.select7
; break;
2136 case 8: selectcmd
= shared
.select8
; break;
2137 case 9: selectcmd
= shared
.select9
; break;
2139 selectcmd
= createObject(REDIS_STRING
,
2140 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2141 selectcmd
->refcount
= 0;
2144 addReply(slave
,selectcmd
);
2145 slave
->slaveseldb
= dictid
;
2147 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2149 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2150 if (outv
!= static_outv
) zfree(outv
);
2153 static void processInputBuffer(redisClient
*c
) {
2155 /* Before to process the input buffer, make sure the client is not
2156 * waitig for a blocking operation such as BLPOP. Note that the first
2157 * iteration the client is never blocked, otherwise the processInputBuffer
2158 * would not be called at all, but after the execution of the first commands
2159 * in the input buffer the client may be blocked, and the "goto again"
2160 * will try to reiterate. The following line will make it return asap. */
2161 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2162 if (c
->bulklen
== -1) {
2163 /* Read the first line of the query */
2164 char *p
= strchr(c
->querybuf
,'\n');
2171 query
= c
->querybuf
;
2172 c
->querybuf
= sdsempty();
2173 querylen
= 1+(p
-(query
));
2174 if (sdslen(query
) > querylen
) {
2175 /* leave data after the first line of the query in the buffer */
2176 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2178 *p
= '\0'; /* remove "\n" */
2179 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2180 sdsupdatelen(query
);
2182 /* Now we can split the query in arguments */
2183 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2186 if (c
->argv
) zfree(c
->argv
);
2187 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2189 for (j
= 0; j
< argc
; j
++) {
2190 if (sdslen(argv
[j
])) {
2191 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2199 /* Execute the command. If the client is still valid
2200 * after processCommand() return and there is something
2201 * on the query buffer try to process the next command. */
2202 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2204 /* Nothing to process, argc == 0. Just process the query
2205 * buffer if it's not empty or return to the caller */
2206 if (sdslen(c
->querybuf
)) goto again
;
2209 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2210 redisLog(REDIS_VERBOSE
, "Client protocol error");
2215 /* Bulk read handling. Note that if we are at this point
2216 the client already sent a command terminated with a newline,
2217 we are reading the bulk data that is actually the last
2218 argument of the command. */
2219 int qbl
= sdslen(c
->querybuf
);
2221 if (c
->bulklen
<= qbl
) {
2222 /* Copy everything but the final CRLF as final argument */
2223 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2225 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2226 /* Process the command. If the client is still valid after
2227 * the processing and there is more data in the buffer
2228 * try to parse it. */
2229 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2235 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2236 redisClient
*c
= (redisClient
*) privdata
;
2237 char buf
[REDIS_IOBUF_LEN
];
2240 REDIS_NOTUSED(mask
);
2242 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2244 if (errno
== EAGAIN
) {
2247 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2251 } else if (nread
== 0) {
2252 redisLog(REDIS_VERBOSE
, "Client closed connection");
2257 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2258 c
->lastinteraction
= time(NULL
);
2262 processInputBuffer(c
);
2265 static int selectDb(redisClient
*c
, int id
) {
2266 if (id
< 0 || id
>= server
.dbnum
)
2268 c
->db
= &server
.db
[id
];
2272 static void *dupClientReplyValue(void *o
) {
2273 incrRefCount((robj
*)o
);
2277 static redisClient
*createClient(int fd
) {
2278 redisClient
*c
= zmalloc(sizeof(*c
));
2280 anetNonBlock(NULL
,fd
);
2281 anetTcpNoDelay(NULL
,fd
);
2282 if (!c
) return NULL
;
2285 c
->querybuf
= sdsempty();
2294 c
->lastinteraction
= time(NULL
);
2295 c
->authenticated
= 0;
2296 c
->replstate
= REDIS_REPL_NONE
;
2297 c
->reply
= listCreate();
2298 listSetFreeMethod(c
->reply
,decrRefCount
);
2299 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2300 c
->blockingkeys
= NULL
;
2301 c
->blockingkeysnum
= 0;
2302 c
->io_keys
= listCreate();
2303 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2304 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2305 readQueryFromClient
, c
) == AE_ERR
) {
2309 listAddNodeTail(server
.clients
,c
);
2310 initClientMultiState(c
);
2314 static void addReply(redisClient
*c
, robj
*obj
) {
2315 if (listLength(c
->reply
) == 0 &&
2316 (c
->replstate
== REDIS_REPL_NONE
||
2317 c
->replstate
== REDIS_REPL_ONLINE
) &&
2318 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2319 sendReplyToClient
, c
) == AE_ERR
) return;
2321 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2322 obj
= dupStringObject(obj
);
2323 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2325 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2328 static void addReplySds(redisClient
*c
, sds s
) {
2329 robj
*o
= createObject(REDIS_STRING
,s
);
2334 static void addReplyDouble(redisClient
*c
, double d
) {
2337 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2338 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2339 (unsigned long) strlen(buf
),buf
));
2342 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2345 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2346 len
= sdslen(obj
->ptr
);
2348 long n
= (long)obj
->ptr
;
2350 /* Compute how many bytes will take this integer as a radix 10 string */
2356 while((n
= n
/10) != 0) {
2360 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2363 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2368 REDIS_NOTUSED(mask
);
2369 REDIS_NOTUSED(privdata
);
2371 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2372 if (cfd
== AE_ERR
) {
2373 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2376 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2377 if ((c
= createClient(cfd
)) == NULL
) {
2378 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2379 close(cfd
); /* May be already closed, just ingore errors */
2382 /* If maxclient directive is set and this is one client more... close the
2383 * connection. Note that we create the client instead to check before
2384 * for this condition, since now the socket is already set in nonblocking
2385 * mode and we can send an error for free using the Kernel I/O */
2386 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2387 char *err
= "-ERR max number of clients reached\r\n";
2389 /* That's a best effort error message, don't check write errors */
2390 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2391 /* Nothing to do, Just to avoid the warning... */
2396 server
.stat_numconnections
++;
2399 /* ======================= Redis objects implementation ===================== */
2401 static robj
*createObject(int type
, void *ptr
) {
2404 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2405 if (listLength(server
.objfreelist
)) {
2406 listNode
*head
= listFirst(server
.objfreelist
);
2407 o
= listNodeValue(head
);
2408 listDelNode(server
.objfreelist
,head
);
2409 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2411 if (server
.vm_enabled
) {
2412 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2413 o
= zmalloc(sizeof(*o
));
2415 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2419 o
->encoding
= REDIS_ENCODING_RAW
;
2422 if (server
.vm_enabled
) {
2423 /* Note that this code may run in the context of an I/O thread
2424 * and accessing to server.unixtime in theory is an error
2425 * (no locks). But in practice this is safe, and even if we read
2426 * garbage Redis will not fail, as it's just a statistical info */
2427 o
->vm
.atime
= server
.unixtime
;
2428 o
->storage
= REDIS_VM_MEMORY
;
2433 static robj
*createStringObject(char *ptr
, size_t len
) {
2434 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2437 static robj
*dupStringObject(robj
*o
) {
2438 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2439 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2442 static robj
*createListObject(void) {
2443 list
*l
= listCreate();
2445 listSetFreeMethod(l
,decrRefCount
);
2446 return createObject(REDIS_LIST
,l
);
2449 static robj
*createSetObject(void) {
2450 dict
*d
= dictCreate(&setDictType
,NULL
);
2451 return createObject(REDIS_SET
,d
);
2454 static robj
*createZsetObject(void) {
2455 zset
*zs
= zmalloc(sizeof(*zs
));
2457 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2458 zs
->zsl
= zslCreate();
2459 return createObject(REDIS_ZSET
,zs
);
2462 static void freeStringObject(robj
*o
) {
2463 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2468 static void freeListObject(robj
*o
) {
2469 listRelease((list
*) o
->ptr
);
2472 static void freeSetObject(robj
*o
) {
2473 dictRelease((dict
*) o
->ptr
);
2476 static void freeZsetObject(robj
*o
) {
2479 dictRelease(zs
->dict
);
2484 static void freeHashObject(robj
*o
) {
2485 dictRelease((dict
*) o
->ptr
);
2488 static void incrRefCount(robj
*o
) {
2489 redisAssert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2493 static void decrRefCount(void *obj
) {
2496 /* Object is a key of a swapped out value, or in the process of being
2498 if (server
.vm_enabled
&&
2499 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
2501 if (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
) {
2502 redisAssert(o
->refcount
== 1);
2504 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
2505 redisAssert(o
->type
== REDIS_STRING
);
2506 freeStringObject(o
);
2507 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2508 pthread_mutex_lock(&server
.obj_freelist_mutex
);
2509 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2510 !listAddNodeHead(server
.objfreelist
,o
))
2512 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2513 server
.vm_stats_swapped_objects
--;
2516 /* Object is in memory, or in the process of being swapped out. */
2517 if (--(o
->refcount
) == 0) {
2518 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
2519 vmCancelThreadedIOJob(obj
);
2521 case REDIS_STRING
: freeStringObject(o
); break;
2522 case REDIS_LIST
: freeListObject(o
); break;
2523 case REDIS_SET
: freeSetObject(o
); break;
2524 case REDIS_ZSET
: freeZsetObject(o
); break;
2525 case REDIS_HASH
: freeHashObject(o
); break;
2526 default: redisAssert(0 != 0); break;
2528 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2529 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2530 !listAddNodeHead(server
.objfreelist
,o
))
2532 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2536 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2537 dictEntry
*de
= dictFind(db
->dict
,key
);
2539 robj
*key
= dictGetEntryKey(de
);
2540 robj
*val
= dictGetEntryVal(de
);
2542 if (server
.vm_enabled
) {
2543 if (key
->storage
== REDIS_VM_MEMORY
||
2544 key
->storage
== REDIS_VM_SWAPPING
)
2546 /* If we were swapping the object out, stop it, this key
2548 if (key
->storage
== REDIS_VM_SWAPPING
)
2549 vmCancelThreadedIOJob(key
);
2550 /* Update the access time of the key for the aging algorithm. */
2551 key
->vm
.atime
= server
.unixtime
;
2553 /* Our value was swapped on disk. Bring it at home. */
2554 redisAssert(val
== NULL
);
2555 val
= vmLoadObject(key
);
2556 dictGetEntryVal(de
) = val
;
2565 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2566 expireIfNeeded(db
,key
);
2567 return lookupKey(db
,key
);
2570 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2571 deleteIfVolatile(db
,key
);
2572 return lookupKey(db
,key
);
2575 static int deleteKey(redisDb
*db
, robj
*key
) {
2578 /* We need to protect key from destruction: after the first dictDelete()
2579 * it may happen that 'key' is no longer valid if we don't increment
2580 * it's count. This may happen when we get the object reference directly
2581 * from the hash table with dictRandomKey() or dict iterators */
2583 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2584 retval
= dictDelete(db
->dict
,key
);
2587 return retval
== DICT_OK
;
2590 /* Try to share an object against the shared objects pool */
2591 static robj
*tryObjectSharing(robj
*o
) {
2592 struct dictEntry
*de
;
2595 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2597 redisAssert(o
->type
== REDIS_STRING
);
2598 de
= dictFind(server
.sharingpool
,o
);
2600 robj
*shared
= dictGetEntryKey(de
);
2602 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2603 dictGetEntryVal(de
) = (void*) c
;
2604 incrRefCount(shared
);
2608 /* Here we are using a stream algorihtm: Every time an object is
2609 * shared we increment its count, everytime there is a miss we
2610 * recrement the counter of a random object. If this object reaches
2611 * zero we remove the object and put the current object instead. */
2612 if (dictSize(server
.sharingpool
) >=
2613 server
.sharingpoolsize
) {
2614 de
= dictGetRandomKey(server
.sharingpool
);
2615 redisAssert(de
!= NULL
);
2616 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2617 dictGetEntryVal(de
) = (void*) c
;
2619 dictDelete(server
.sharingpool
,de
->key
);
2622 c
= 0; /* If the pool is empty we want to add this object */
2627 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2628 redisAssert(retval
== DICT_OK
);
2635 /* Check if the nul-terminated string 's' can be represented by a long
2636 * (that is, is a number that fits into long without any other space or
2637 * character before or after the digits).
2639 * If so, the function returns REDIS_OK and *longval is set to the value
2640 * of the number. Otherwise REDIS_ERR is returned */
2641 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2642 char buf
[32], *endptr
;
2646 value
= strtol(s
, &endptr
, 10);
2647 if (endptr
[0] != '\0') return REDIS_ERR
;
2648 slen
= snprintf(buf
,32,"%ld",value
);
2650 /* If the number converted back into a string is not identical
2651 * then it's not possible to encode the string as integer */
2652 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2653 if (longval
) *longval
= value
;
2657 /* Try to encode a string object in order to save space */
2658 static int tryObjectEncoding(robj
*o
) {
2662 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2663 return REDIS_ERR
; /* Already encoded */
2665 /* It's not save to encode shared objects: shared objects can be shared
2666 * everywhere in the "object space" of Redis. Encoded objects can only
2667 * appear as "values" (and not, for instance, as keys) */
2668 if (o
->refcount
> 1) return REDIS_ERR
;
2670 /* Currently we try to encode only strings */
2671 redisAssert(o
->type
== REDIS_STRING
);
2673 /* Check if we can represent this string as a long integer */
2674 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2676 /* Ok, this object can be encoded */
2677 o
->encoding
= REDIS_ENCODING_INT
;
2679 o
->ptr
= (void*) value
;
2683 /* Get a decoded version of an encoded object (returned as a new object).
2684 * If the object is already raw-encoded just increment the ref count. */
2685 static robj
*getDecodedObject(robj
*o
) {
2688 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2692 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2695 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2696 dec
= createStringObject(buf
,strlen(buf
));
2699 redisAssert(1 != 1);
2703 /* Compare two string objects via strcmp() or alike.
2704 * Note that the objects may be integer-encoded. In such a case we
2705 * use snprintf() to get a string representation of the numbers on the stack
2706 * and compare the strings, it's much faster than calling getDecodedObject().
2708 * Important note: if objects are not integer encoded, but binary-safe strings,
2709 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2711 static int compareStringObjects(robj
*a
, robj
*b
) {
2712 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2713 char bufa
[128], bufb
[128], *astr
, *bstr
;
2716 if (a
== b
) return 0;
2717 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2718 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2724 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2725 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2731 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2734 static size_t stringObjectLen(robj
*o
) {
2735 redisAssert(o
->type
== REDIS_STRING
);
2736 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2737 return sdslen(o
->ptr
);
2741 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2745 /*============================ RDB saving/loading =========================== */
2747 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2748 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2752 static int rdbSaveTime(FILE *fp
, time_t t
) {
2753 int32_t t32
= (int32_t) t
;
2754 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2758 /* check rdbLoadLen() comments for more info */
2759 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2760 unsigned char buf
[2];
2763 /* Save a 6 bit len */
2764 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2765 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2766 } else if (len
< (1<<14)) {
2767 /* Save a 14 bit len */
2768 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2770 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2772 /* Save a 32 bit len */
2773 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2774 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2776 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2781 /* String objects in the form "2391" "-100" without any space and with a
2782 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2783 * encoded as integers to save space */
2784 static int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
2786 char *endptr
, buf
[32];
2788 /* Check if it's possible to encode this value as a number */
2789 value
= strtoll(s
, &endptr
, 10);
2790 if (endptr
[0] != '\0') return 0;
2791 snprintf(buf
,32,"%lld",value
);
2793 /* If the number converted back into a string is not identical
2794 * then it's not possible to encode the string as integer */
2795 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
2797 /* Finally check if it fits in our ranges */
2798 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2799 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2800 enc
[1] = value
&0xFF;
2802 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2803 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2804 enc
[1] = value
&0xFF;
2805 enc
[2] = (value
>>8)&0xFF;
2807 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2808 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2809 enc
[1] = value
&0xFF;
2810 enc
[2] = (value
>>8)&0xFF;
2811 enc
[3] = (value
>>16)&0xFF;
2812 enc
[4] = (value
>>24)&0xFF;
2819 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
2820 unsigned int comprlen
, outlen
;
2824 /* We require at least four bytes compression for this to be worth it */
2825 outlen
= sdslen(obj
->ptr
)-4;
2826 if (outlen
<= 0) return 0;
2827 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2828 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
2829 if (comprlen
== 0) {
2833 /* Data compressed! Let's save it on disk */
2834 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
2835 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
2836 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
2837 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
2838 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
2847 /* Save a string objet as [len][data] on disk. If the object is a string
2848 * representation of an integer value we try to safe it in a special form */
2849 static int rdbSaveStringObjectRaw(FILE *fp
, robj
*obj
) {
2853 len
= sdslen(obj
->ptr
);
2855 /* Try integer encoding */
2857 unsigned char buf
[5];
2858 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
2859 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
2864 /* Try LZF compression - under 20 bytes it's unable to compress even
2865 * aaaaaaaaaaaaaaaaaa so skip it */
2866 if (server
.rdbcompression
&& len
> 20) {
2869 retval
= rdbSaveLzfStringObject(fp
,obj
);
2870 if (retval
== -1) return -1;
2871 if (retval
> 0) return 0;
2872 /* retval == 0 means data can't be compressed, save the old way */
2875 /* Store verbatim */
2876 if (rdbSaveLen(fp
,len
) == -1) return -1;
2877 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
2881 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
2882 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
2885 /* Avoid incr/decr ref count business when possible.
2886 * This plays well with copy-on-write given that we are probably
2887 * in a child process (BGSAVE). Also this makes sure key objects
2888 * of swapped objects are not incRefCount-ed (an assert does not allow
2889 * this in order to avoid bugs) */
2890 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
2891 obj
= getDecodedObject(obj
);
2892 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2895 retval
= rdbSaveStringObjectRaw(fp
,obj
);
2900 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
2901 * 8 bit integer specifing the length of the representation.
2902 * This 8 bit integer has special values in order to specify the following
2908 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
2909 unsigned char buf
[128];
2915 } else if (!isfinite(val
)) {
2917 buf
[0] = (val
< 0) ? 255 : 254;
2919 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
2920 buf
[0] = strlen((char*)buf
+1);
2923 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
2927 /* Save a Redis object. */
2928 static int rdbSaveObject(FILE *fp
, robj
*o
) {
2929 if (o
->type
== REDIS_STRING
) {
2930 /* Save a string value */
2931 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
2932 } else if (o
->type
== REDIS_LIST
) {
2933 /* Save a list value */
2934 list
*list
= o
->ptr
;
2938 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
2939 listRewind(list
,&li
);
2940 while((ln
= listNext(&li
))) {
2941 robj
*eleobj
= listNodeValue(ln
);
2943 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2945 } else if (o
->type
== REDIS_SET
) {
2946 /* Save a set value */
2948 dictIterator
*di
= dictGetIterator(set
);
2951 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
2952 while((de
= dictNext(di
)) != NULL
) {
2953 robj
*eleobj
= dictGetEntryKey(de
);
2955 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2957 dictReleaseIterator(di
);
2958 } else if (o
->type
== REDIS_ZSET
) {
2959 /* Save a set value */
2961 dictIterator
*di
= dictGetIterator(zs
->dict
);
2964 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
2965 while((de
= dictNext(di
)) != NULL
) {
2966 robj
*eleobj
= dictGetEntryKey(de
);
2967 double *score
= dictGetEntryVal(de
);
2969 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
2970 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
2972 dictReleaseIterator(di
);
2974 redisAssert(0 != 0);
2979 /* Return the length the object will have on disk if saved with
2980 * the rdbSaveObject() function. Currently we use a trick to get
2981 * this length with very little changes to the code. In the future
2982 * we could switch to a faster solution. */
2983 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
2984 if (fp
== NULL
) fp
= server
.devnull
;
2986 assert(rdbSaveObject(fp
,o
) != 1);
2990 /* Return the number of pages required to save this object in the swap file */
2991 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
2992 off_t bytes
= rdbSavedObjectLen(o
,fp
);
2994 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
2997 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
2998 static int rdbSave(char *filename
) {
2999 dictIterator
*di
= NULL
;
3004 time_t now
= time(NULL
);
3006 /* Wait for I/O therads to terminate, just in case this is a
3007 * foreground-saving, to avoid seeking the swap file descriptor at the
3009 if (server
.vm_enabled
)
3010 waitEmptyIOJobsQueue();
3012 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3013 fp
= fopen(tmpfile
,"w");
3015 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3018 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3019 for (j
= 0; j
< server
.dbnum
; j
++) {
3020 redisDb
*db
= server
.db
+j
;
3022 if (dictSize(d
) == 0) continue;
3023 di
= dictGetIterator(d
);
3029 /* Write the SELECT DB opcode */
3030 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3031 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3033 /* Iterate this DB writing every entry */
3034 while((de
= dictNext(di
)) != NULL
) {
3035 robj
*key
= dictGetEntryKey(de
);
3036 robj
*o
= dictGetEntryVal(de
);
3037 time_t expiretime
= getExpire(db
,key
);
3039 /* Save the expire time */
3040 if (expiretime
!= -1) {
3041 /* If this key is already expired skip it */
3042 if (expiretime
< now
) continue;
3043 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3044 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3046 /* Save the key and associated value. This requires special
3047 * handling if the value is swapped out. */
3048 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3049 key
->storage
== REDIS_VM_SWAPPING
) {
3050 /* Save type, key, value */
3051 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3052 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3053 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3055 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3057 /* Get a preview of the object in memory */
3058 po
= vmPreviewObject(key
);
3059 /* Save type, key, value */
3060 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3061 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3062 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3063 /* Remove the loaded object from memory */
3067 dictReleaseIterator(di
);
3070 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3072 /* Make sure data will not remain on the OS's output buffers */
3077 /* Use RENAME to make sure the DB file is changed atomically only
3078 * if the generate DB file is ok. */
3079 if (rename(tmpfile
,filename
) == -1) {
3080 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3084 redisLog(REDIS_NOTICE
,"DB saved on disk");
3086 server
.lastsave
= time(NULL
);
3092 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3093 if (di
) dictReleaseIterator(di
);
3097 static int rdbSaveBackground(char *filename
) {
3100 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3101 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
3102 if ((childpid
= fork()) == 0) {
3104 if (server
.vm_enabled
) vmReopenSwapFile();
3106 if (rdbSave(filename
) == REDIS_OK
) {
3113 if (childpid
== -1) {
3114 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3118 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3119 server
.bgsavechildpid
= childpid
;
3122 return REDIS_OK
; /* unreached */
3125 static void rdbRemoveTempFile(pid_t childpid
) {
3128 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3132 static int rdbLoadType(FILE *fp
) {
3134 if (fread(&type
,1,1,fp
) == 0) return -1;
3138 static time_t rdbLoadTime(FILE *fp
) {
3140 if (fread(&t32
,4,1,fp
) == 0) return -1;
3141 return (time_t) t32
;
3144 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3145 * of this file for a description of how this are stored on disk.
3147 * isencoded is set to 1 if the readed length is not actually a length but
3148 * an "encoding type", check the above comments for more info */
3149 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3150 unsigned char buf
[2];
3154 if (isencoded
) *isencoded
= 0;
3155 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3156 type
= (buf
[0]&0xC0)>>6;
3157 if (type
== REDIS_RDB_6BITLEN
) {
3158 /* Read a 6 bit len */
3160 } else if (type
== REDIS_RDB_ENCVAL
) {
3161 /* Read a 6 bit len encoding type */
3162 if (isencoded
) *isencoded
= 1;
3164 } else if (type
== REDIS_RDB_14BITLEN
) {
3165 /* Read a 14 bit len */
3166 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3167 return ((buf
[0]&0x3F)<<8)|buf
[1];
3169 /* Read a 32 bit len */
3170 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3175 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
3176 unsigned char enc
[4];
3179 if (enctype
== REDIS_RDB_ENC_INT8
) {
3180 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3181 val
= (signed char)enc
[0];
3182 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3184 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3185 v
= enc
[0]|(enc
[1]<<8);
3187 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3189 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3190 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3193 val
= 0; /* anti-warning */
3196 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3199 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3200 unsigned int len
, clen
;
3201 unsigned char *c
= NULL
;
3204 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3205 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3206 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3207 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3208 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3209 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3211 return createObject(REDIS_STRING
,val
);
3218 static robj
*rdbLoadStringObject(FILE*fp
) {
3223 len
= rdbLoadLen(fp
,&isencoded
);
3226 case REDIS_RDB_ENC_INT8
:
3227 case REDIS_RDB_ENC_INT16
:
3228 case REDIS_RDB_ENC_INT32
:
3229 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3230 case REDIS_RDB_ENC_LZF
:
3231 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3237 if (len
== REDIS_RDB_LENERR
) return NULL
;
3238 val
= sdsnewlen(NULL
,len
);
3239 if (len
&& fread(val
,len
,1,fp
) == 0) {
3243 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3246 /* For information about double serialization check rdbSaveDoubleValue() */
3247 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3251 if (fread(&len
,1,1,fp
) == 0) return -1;
3253 case 255: *val
= R_NegInf
; return 0;
3254 case 254: *val
= R_PosInf
; return 0;
3255 case 253: *val
= R_Nan
; return 0;
3257 if (fread(buf
,len
,1,fp
) == 0) return -1;
3259 sscanf(buf
, "%lg", val
);
3264 /* Load a Redis object of the specified type from the specified file.
3265 * On success a newly allocated object is returned, otherwise NULL. */
3266 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3269 if (type
== REDIS_STRING
) {
3270 /* Read string value */
3271 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3272 tryObjectEncoding(o
);
3273 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3274 /* Read list/set value */
3277 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3278 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3279 /* Load every single element of the list/set */
3283 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3284 tryObjectEncoding(ele
);
3285 if (type
== REDIS_LIST
) {
3286 listAddNodeTail((list
*)o
->ptr
,ele
);
3288 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3291 } else if (type
== REDIS_ZSET
) {
3292 /* Read list/set value */
3296 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3297 o
= createZsetObject();
3299 /* Load every single element of the list/set */
3302 double *score
= zmalloc(sizeof(double));
3304 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3305 tryObjectEncoding(ele
);
3306 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3307 dictAdd(zs
->dict
,ele
,score
);
3308 zslInsert(zs
->zsl
,*score
,ele
);
3309 incrRefCount(ele
); /* added to skiplist */
3312 redisAssert(0 != 0);
3317 static int rdbLoad(char *filename
) {
3319 robj
*keyobj
= NULL
;
3321 int type
, retval
, rdbver
;
3322 dict
*d
= server
.db
[0].dict
;
3323 redisDb
*db
= server
.db
+0;
3325 time_t expiretime
= -1, now
= time(NULL
);
3326 long long loadedkeys
= 0;
3328 fp
= fopen(filename
,"r");
3329 if (!fp
) return REDIS_ERR
;
3330 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3332 if (memcmp(buf
,"REDIS",5) != 0) {
3334 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3337 rdbver
= atoi(buf
+5);
3340 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3347 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3348 if (type
== REDIS_EXPIRETIME
) {
3349 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3350 /* We read the time so we need to read the object type again */
3351 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3353 if (type
== REDIS_EOF
) break;
3354 /* Handle SELECT DB opcode as a special case */
3355 if (type
== REDIS_SELECTDB
) {
3356 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3358 if (dbid
>= (unsigned)server
.dbnum
) {
3359 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3362 db
= server
.db
+dbid
;
3367 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3369 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3370 /* Add the new object in the hash table */
3371 retval
= dictAdd(d
,keyobj
,o
);
3372 if (retval
== DICT_ERR
) {
3373 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3376 /* Set the expire time if needed */
3377 if (expiretime
!= -1) {
3378 setExpire(db
,keyobj
,expiretime
);
3379 /* Delete this key if already expired */
3380 if (expiretime
< now
) deleteKey(db
,keyobj
);
3384 /* Handle swapping while loading big datasets when VM is on */
3386 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
3387 while (zmalloc_used_memory() > server
.vm_max_memory
) {
3388 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
3395 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3396 if (keyobj
) decrRefCount(keyobj
);
3397 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3399 return REDIS_ERR
; /* Just to avoid warning */
3402 /*================================== Commands =============================== */
3404 static void authCommand(redisClient
*c
) {
3405 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3406 c
->authenticated
= 1;
3407 addReply(c
,shared
.ok
);
3409 c
->authenticated
= 0;
3410 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3414 static void pingCommand(redisClient
*c
) {
3415 addReply(c
,shared
.pong
);
3418 static void echoCommand(redisClient
*c
) {
3419 addReplyBulkLen(c
,c
->argv
[1]);
3420 addReply(c
,c
->argv
[1]);
3421 addReply(c
,shared
.crlf
);
3424 /*=================================== Strings =============================== */
3426 static void setGenericCommand(redisClient
*c
, int nx
) {
3429 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3430 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3431 if (retval
== DICT_ERR
) {
3433 /* If the key is about a swapped value, we want a new key object
3434 * to overwrite the old. So we delete the old key in the database.
3435 * This will also make sure that swap pages about the old object
3436 * will be marked as free. */
3437 if (deleteIfSwapped(c
->db
,c
->argv
[1]))
3438 incrRefCount(c
->argv
[1]);
3439 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3440 incrRefCount(c
->argv
[2]);
3442 addReply(c
,shared
.czero
);
3446 incrRefCount(c
->argv
[1]);
3447 incrRefCount(c
->argv
[2]);
3450 removeExpire(c
->db
,c
->argv
[1]);
3451 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3454 static void setCommand(redisClient
*c
) {
3455 setGenericCommand(c
,0);
3458 static void setnxCommand(redisClient
*c
) {
3459 setGenericCommand(c
,1);
3462 static int getGenericCommand(redisClient
*c
) {
3463 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3466 addReply(c
,shared
.nullbulk
);
3469 if (o
->type
!= REDIS_STRING
) {
3470 addReply(c
,shared
.wrongtypeerr
);
3473 addReplyBulkLen(c
,o
);
3475 addReply(c
,shared
.crlf
);
3481 static void getCommand(redisClient
*c
) {
3482 getGenericCommand(c
);
3485 static void getsetCommand(redisClient
*c
) {
3486 if (getGenericCommand(c
) == REDIS_ERR
) return;
3487 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3488 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3490 incrRefCount(c
->argv
[1]);
3492 incrRefCount(c
->argv
[2]);
3494 removeExpire(c
->db
,c
->argv
[1]);
3497 static void mgetCommand(redisClient
*c
) {
3500 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3501 for (j
= 1; j
< c
->argc
; j
++) {
3502 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3504 addReply(c
,shared
.nullbulk
);
3506 if (o
->type
!= REDIS_STRING
) {
3507 addReply(c
,shared
.nullbulk
);
3509 addReplyBulkLen(c
,o
);
3511 addReply(c
,shared
.crlf
);
3517 static void msetGenericCommand(redisClient
*c
, int nx
) {
3518 int j
, busykeys
= 0;
3520 if ((c
->argc
% 2) == 0) {
3521 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3524 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3525 * set nothing at all if at least one already key exists. */
3527 for (j
= 1; j
< c
->argc
; j
+= 2) {
3528 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3534 addReply(c
, shared
.czero
);
3538 for (j
= 1; j
< c
->argc
; j
+= 2) {
3541 tryObjectEncoding(c
->argv
[j
+1]);
3542 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3543 if (retval
== DICT_ERR
) {
3544 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3545 incrRefCount(c
->argv
[j
+1]);
3547 incrRefCount(c
->argv
[j
]);
3548 incrRefCount(c
->argv
[j
+1]);
3550 removeExpire(c
->db
,c
->argv
[j
]);
3552 server
.dirty
+= (c
->argc
-1)/2;
3553 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3556 static void msetCommand(redisClient
*c
) {
3557 msetGenericCommand(c
,0);
3560 static void msetnxCommand(redisClient
*c
) {
3561 msetGenericCommand(c
,1);
3564 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3569 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3573 if (o
->type
!= REDIS_STRING
) {
3578 if (o
->encoding
== REDIS_ENCODING_RAW
)
3579 value
= strtoll(o
->ptr
, &eptr
, 10);
3580 else if (o
->encoding
== REDIS_ENCODING_INT
)
3581 value
= (long)o
->ptr
;
3583 redisAssert(1 != 1);
3588 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3589 tryObjectEncoding(o
);
3590 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3591 if (retval
== DICT_ERR
) {
3592 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3593 removeExpire(c
->db
,c
->argv
[1]);
3595 incrRefCount(c
->argv
[1]);
3598 addReply(c
,shared
.colon
);
3600 addReply(c
,shared
.crlf
);
3603 static void incrCommand(redisClient
*c
) {
3604 incrDecrCommand(c
,1);
3607 static void decrCommand(redisClient
*c
) {
3608 incrDecrCommand(c
,-1);
3611 static void incrbyCommand(redisClient
*c
) {
3612 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3613 incrDecrCommand(c
,incr
);
3616 static void decrbyCommand(redisClient
*c
) {
3617 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3618 incrDecrCommand(c
,-incr
);
3621 /* ========================= Type agnostic commands ========================= */
3623 static void delCommand(redisClient
*c
) {
3626 for (j
= 1; j
< c
->argc
; j
++) {
3627 if (deleteKey(c
->db
,c
->argv
[j
])) {
3634 addReply(c
,shared
.czero
);
3637 addReply(c
,shared
.cone
);
3640 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3645 static void existsCommand(redisClient
*c
) {
3646 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3649 static void selectCommand(redisClient
*c
) {
3650 int id
= atoi(c
->argv
[1]->ptr
);
3652 if (selectDb(c
,id
) == REDIS_ERR
) {
3653 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3655 addReply(c
,shared
.ok
);
3659 static void randomkeyCommand(redisClient
*c
) {
3663 de
= dictGetRandomKey(c
->db
->dict
);
3664 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3667 addReply(c
,shared
.plus
);
3668 addReply(c
,shared
.crlf
);
3670 addReply(c
,shared
.plus
);
3671 addReply(c
,dictGetEntryKey(de
));
3672 addReply(c
,shared
.crlf
);
3676 static void keysCommand(redisClient
*c
) {
3679 sds pattern
= c
->argv
[1]->ptr
;
3680 int plen
= sdslen(pattern
);
3681 unsigned long numkeys
= 0, keyslen
= 0;
3682 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
3684 di
= dictGetIterator(c
->db
->dict
);
3686 decrRefCount(lenobj
);
3687 while((de
= dictNext(di
)) != NULL
) {
3688 robj
*keyobj
= dictGetEntryKey(de
);
3690 sds key
= keyobj
->ptr
;
3691 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
3692 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
3693 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
3695 addReply(c
,shared
.space
);
3698 keyslen
+= sdslen(key
);
3702 dictReleaseIterator(di
);
3703 lenobj
->ptr
= sdscatprintf(sdsempty(),"$%lu\r\n",keyslen
+(numkeys
? (numkeys
-1) : 0));
3704 addReply(c
,shared
.crlf
);
3707 static void dbsizeCommand(redisClient
*c
) {
3709 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
3712 static void lastsaveCommand(redisClient
*c
) {
3714 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
3717 static void typeCommand(redisClient
*c
) {
3721 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3726 case REDIS_STRING
: type
= "+string"; break;
3727 case REDIS_LIST
: type
= "+list"; break;
3728 case REDIS_SET
: type
= "+set"; break;
3729 case REDIS_ZSET
: type
= "+zset"; break;
3730 default: type
= "unknown"; break;
3733 addReplySds(c
,sdsnew(type
));
3734 addReply(c
,shared
.crlf
);
3737 static void saveCommand(redisClient
*c
) {
3738 if (server
.bgsavechildpid
!= -1) {
3739 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
3742 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3743 addReply(c
,shared
.ok
);
3745 addReply(c
,shared
.err
);
3749 static void bgsaveCommand(redisClient
*c
) {
3750 if (server
.bgsavechildpid
!= -1) {
3751 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
3754 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
3755 char *status
= "+Background saving started\r\n";
3756 addReplySds(c
,sdsnew(status
));
3758 addReply(c
,shared
.err
);
3762 static void shutdownCommand(redisClient
*c
) {
3763 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
3764 /* Kill the saving child if there is a background saving in progress.
3765 We want to avoid race conditions, for instance our saving child may
3766 overwrite the synchronous saving did by SHUTDOWN. */
3767 if (server
.bgsavechildpid
!= -1) {
3768 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
3769 kill(server
.bgsavechildpid
,SIGKILL
);
3770 rdbRemoveTempFile(server
.bgsavechildpid
);
3772 if (server
.appendonly
) {
3773 /* Append only file: fsync() the AOF and exit */
3774 fsync(server
.appendfd
);
3775 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
3778 /* Snapshotting. Perform a SYNC SAVE and exit */
3779 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3780 if (server
.daemonize
)
3781 unlink(server
.pidfile
);
3782 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
3783 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
3784 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
3787 /* Ooops.. error saving! The best we can do is to continue operating.
3788 * Note that if there was a background saving process, in the next
3789 * cron() Redis will be notified that the background saving aborted,
3790 * handling special stuff like slaves pending for synchronization... */
3791 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
3792 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
3797 static void renameGenericCommand(redisClient
*c
, int nx
) {
3800 /* To use the same key as src and dst is probably an error */
3801 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
3802 addReply(c
,shared
.sameobjecterr
);
3806 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3808 addReply(c
,shared
.nokeyerr
);
3812 deleteIfVolatile(c
->db
,c
->argv
[2]);
3813 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
3816 addReply(c
,shared
.czero
);
3819 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
3821 incrRefCount(c
->argv
[2]);
3823 deleteKey(c
->db
,c
->argv
[1]);
3825 addReply(c
,nx
? shared
.cone
: shared
.ok
);
3828 static void renameCommand(redisClient
*c
) {
3829 renameGenericCommand(c
,0);
3832 static void renamenxCommand(redisClient
*c
) {
3833 renameGenericCommand(c
,1);
3836 static void moveCommand(redisClient
*c
) {
3841 /* Obtain source and target DB pointers */
3844 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
3845 addReply(c
,shared
.outofrangeerr
);
3849 selectDb(c
,srcid
); /* Back to the source DB */
3851 /* If the user is moving using as target the same
3852 * DB as the source DB it is probably an error. */
3854 addReply(c
,shared
.sameobjecterr
);
3858 /* Check if the element exists and get a reference */
3859 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3861 addReply(c
,shared
.czero
);
3865 /* Try to add the element to the target DB */
3866 deleteIfVolatile(dst
,c
->argv
[1]);
3867 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
3868 addReply(c
,shared
.czero
);
3871 incrRefCount(c
->argv
[1]);
3874 /* OK! key moved, free the entry in the source DB */
3875 deleteKey(src
,c
->argv
[1]);
3877 addReply(c
,shared
.cone
);
3880 /* =================================== Lists ================================ */
3881 static void pushGenericCommand(redisClient
*c
, int where
) {
3885 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3887 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3888 addReply(c
,shared
.ok
);
3891 lobj
= createListObject();
3893 if (where
== REDIS_HEAD
) {
3894 listAddNodeHead(list
,c
->argv
[2]);
3896 listAddNodeTail(list
,c
->argv
[2]);
3898 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
3899 incrRefCount(c
->argv
[1]);
3900 incrRefCount(c
->argv
[2]);
3902 if (lobj
->type
!= REDIS_LIST
) {
3903 addReply(c
,shared
.wrongtypeerr
);
3906 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
3907 addReply(c
,shared
.ok
);
3911 if (where
== REDIS_HEAD
) {
3912 listAddNodeHead(list
,c
->argv
[2]);
3914 listAddNodeTail(list
,c
->argv
[2]);
3916 incrRefCount(c
->argv
[2]);
3919 addReply(c
,shared
.ok
);
3922 static void lpushCommand(redisClient
*c
) {
3923 pushGenericCommand(c
,REDIS_HEAD
);
3926 static void rpushCommand(redisClient
*c
) {
3927 pushGenericCommand(c
,REDIS_TAIL
);
3930 static void llenCommand(redisClient
*c
) {
3934 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3936 addReply(c
,shared
.czero
);
3939 if (o
->type
!= REDIS_LIST
) {
3940 addReply(c
,shared
.wrongtypeerr
);
3943 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
3948 static void lindexCommand(redisClient
*c
) {
3950 int index
= atoi(c
->argv
[2]->ptr
);
3952 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3954 addReply(c
,shared
.nullbulk
);
3956 if (o
->type
!= REDIS_LIST
) {
3957 addReply(c
,shared
.wrongtypeerr
);
3959 list
*list
= o
->ptr
;
3962 ln
= listIndex(list
, index
);
3964 addReply(c
,shared
.nullbulk
);
3966 robj
*ele
= listNodeValue(ln
);
3967 addReplyBulkLen(c
,ele
);
3969 addReply(c
,shared
.crlf
);
3975 static void lsetCommand(redisClient
*c
) {
3977 int index
= atoi(c
->argv
[2]->ptr
);
3979 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3981 addReply(c
,shared
.nokeyerr
);
3983 if (o
->type
!= REDIS_LIST
) {
3984 addReply(c
,shared
.wrongtypeerr
);
3986 list
*list
= o
->ptr
;
3989 ln
= listIndex(list
, index
);
3991 addReply(c
,shared
.outofrangeerr
);
3993 robj
*ele
= listNodeValue(ln
);
3996 listNodeValue(ln
) = c
->argv
[3];
3997 incrRefCount(c
->argv
[3]);
3998 addReply(c
,shared
.ok
);
4005 static void popGenericCommand(redisClient
*c
, int where
) {
4008 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4010 addReply(c
,shared
.nullbulk
);
4012 if (o
->type
!= REDIS_LIST
) {
4013 addReply(c
,shared
.wrongtypeerr
);
4015 list
*list
= o
->ptr
;
4018 if (where
== REDIS_HEAD
)
4019 ln
= listFirst(list
);
4021 ln
= listLast(list
);
4024 addReply(c
,shared
.nullbulk
);
4026 robj
*ele
= listNodeValue(ln
);
4027 addReplyBulkLen(c
,ele
);
4029 addReply(c
,shared
.crlf
);
4030 listDelNode(list
,ln
);
4037 static void lpopCommand(redisClient
*c
) {
4038 popGenericCommand(c
,REDIS_HEAD
);
4041 static void rpopCommand(redisClient
*c
) {
4042 popGenericCommand(c
,REDIS_TAIL
);
4045 static void lrangeCommand(redisClient
*c
) {
4047 int start
= atoi(c
->argv
[2]->ptr
);
4048 int end
= atoi(c
->argv
[3]->ptr
);
4050 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4052 addReply(c
,shared
.nullmultibulk
);
4054 if (o
->type
!= REDIS_LIST
) {
4055 addReply(c
,shared
.wrongtypeerr
);
4057 list
*list
= o
->ptr
;
4059 int llen
= listLength(list
);
4063 /* convert negative indexes */
4064 if (start
< 0) start
= llen
+start
;
4065 if (end
< 0) end
= llen
+end
;
4066 if (start
< 0) start
= 0;
4067 if (end
< 0) end
= 0;
4069 /* indexes sanity checks */
4070 if (start
> end
|| start
>= llen
) {
4071 /* Out of range start or start > end result in empty list */
4072 addReply(c
,shared
.emptymultibulk
);
4075 if (end
>= llen
) end
= llen
-1;
4076 rangelen
= (end
-start
)+1;
4078 /* Return the result in form of a multi-bulk reply */
4079 ln
= listIndex(list
, start
);
4080 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4081 for (j
= 0; j
< rangelen
; j
++) {
4082 ele
= listNodeValue(ln
);
4083 addReplyBulkLen(c
,ele
);
4085 addReply(c
,shared
.crlf
);
4092 static void ltrimCommand(redisClient
*c
) {
4094 int start
= atoi(c
->argv
[2]->ptr
);
4095 int end
= atoi(c
->argv
[3]->ptr
);
4097 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4099 addReply(c
,shared
.ok
);
4101 if (o
->type
!= REDIS_LIST
) {
4102 addReply(c
,shared
.wrongtypeerr
);
4104 list
*list
= o
->ptr
;
4106 int llen
= listLength(list
);
4107 int j
, ltrim
, rtrim
;
4109 /* convert negative indexes */
4110 if (start
< 0) start
= llen
+start
;
4111 if (end
< 0) end
= llen
+end
;
4112 if (start
< 0) start
= 0;
4113 if (end
< 0) end
= 0;
4115 /* indexes sanity checks */
4116 if (start
> end
|| start
>= llen
) {
4117 /* Out of range start or start > end result in empty list */
4121 if (end
>= llen
) end
= llen
-1;
4126 /* Remove list elements to perform the trim */
4127 for (j
= 0; j
< ltrim
; j
++) {
4128 ln
= listFirst(list
);
4129 listDelNode(list
,ln
);
4131 for (j
= 0; j
< rtrim
; j
++) {
4132 ln
= listLast(list
);
4133 listDelNode(list
,ln
);
4136 addReply(c
,shared
.ok
);
4141 static void lremCommand(redisClient
*c
) {
4144 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4146 addReply(c
,shared
.czero
);
4148 if (o
->type
!= REDIS_LIST
) {
4149 addReply(c
,shared
.wrongtypeerr
);
4151 list
*list
= o
->ptr
;
4152 listNode
*ln
, *next
;
4153 int toremove
= atoi(c
->argv
[2]->ptr
);
4158 toremove
= -toremove
;
4161 ln
= fromtail
? list
->tail
: list
->head
;
4163 robj
*ele
= listNodeValue(ln
);
4165 next
= fromtail
? ln
->prev
: ln
->next
;
4166 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
4167 listDelNode(list
,ln
);
4170 if (toremove
&& removed
== toremove
) break;
4174 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4179 /* This is the semantic of this command:
4180 * RPOPLPUSH srclist dstlist:
4181 * IF LLEN(srclist) > 0
4182 * element = RPOP srclist
4183 * LPUSH dstlist element
4190 * The idea is to be able to get an element from a list in a reliable way
4191 * since the element is not just returned but pushed against another list
4192 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4194 static void rpoplpushcommand(redisClient
*c
) {
4197 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4199 addReply(c
,shared
.nullbulk
);
4201 if (sobj
->type
!= REDIS_LIST
) {
4202 addReply(c
,shared
.wrongtypeerr
);
4204 list
*srclist
= sobj
->ptr
;
4205 listNode
*ln
= listLast(srclist
);
4208 addReply(c
,shared
.nullbulk
);
4210 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4211 robj
*ele
= listNodeValue(ln
);
4214 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4215 addReply(c
,shared
.wrongtypeerr
);
4219 /* Add the element to the target list (unless it's directly
4220 * passed to some BLPOP-ing client */
4221 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4223 /* Create the list if the key does not exist */
4224 dobj
= createListObject();
4225 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4226 incrRefCount(c
->argv
[2]);
4228 dstlist
= dobj
->ptr
;
4229 listAddNodeHead(dstlist
,ele
);
4233 /* Send the element to the client as reply as well */
4234 addReplyBulkLen(c
,ele
);
4236 addReply(c
,shared
.crlf
);
4238 /* Finally remove the element from the source list */
4239 listDelNode(srclist
,ln
);
4247 /* ==================================== Sets ================================ */
4249 static void saddCommand(redisClient
*c
) {
4252 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4254 set
= createSetObject();
4255 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4256 incrRefCount(c
->argv
[1]);
4258 if (set
->type
!= REDIS_SET
) {
4259 addReply(c
,shared
.wrongtypeerr
);
4263 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4264 incrRefCount(c
->argv
[2]);
4266 addReply(c
,shared
.cone
);
4268 addReply(c
,shared
.czero
);
4272 static void sremCommand(redisClient
*c
) {
4275 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4277 addReply(c
,shared
.czero
);
4279 if (set
->type
!= REDIS_SET
) {
4280 addReply(c
,shared
.wrongtypeerr
);
4283 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4285 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4286 addReply(c
,shared
.cone
);
4288 addReply(c
,shared
.czero
);
4293 static void smoveCommand(redisClient
*c
) {
4294 robj
*srcset
, *dstset
;
4296 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4297 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4299 /* If the source key does not exist return 0, if it's of the wrong type
4301 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4302 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4305 /* Error if the destination key is not a set as well */
4306 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4307 addReply(c
,shared
.wrongtypeerr
);
4310 /* Remove the element from the source set */
4311 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4312 /* Key not found in the src set! return zero */
4313 addReply(c
,shared
.czero
);
4317 /* Add the element to the destination set */
4319 dstset
= createSetObject();
4320 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4321 incrRefCount(c
->argv
[2]);
4323 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4324 incrRefCount(c
->argv
[3]);
4325 addReply(c
,shared
.cone
);
4328 static void sismemberCommand(redisClient
*c
) {
4331 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4333 addReply(c
,shared
.czero
);
4335 if (set
->type
!= REDIS_SET
) {
4336 addReply(c
,shared
.wrongtypeerr
);
4339 if (dictFind(set
->ptr
,c
->argv
[2]))
4340 addReply(c
,shared
.cone
);
4342 addReply(c
,shared
.czero
);
4346 static void scardCommand(redisClient
*c
) {
4350 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4352 addReply(c
,shared
.czero
);
4355 if (o
->type
!= REDIS_SET
) {
4356 addReply(c
,shared
.wrongtypeerr
);
4359 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4365 static void spopCommand(redisClient
*c
) {
4369 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4371 addReply(c
,shared
.nullbulk
);
4373 if (set
->type
!= REDIS_SET
) {
4374 addReply(c
,shared
.wrongtypeerr
);
4377 de
= dictGetRandomKey(set
->ptr
);
4379 addReply(c
,shared
.nullbulk
);
4381 robj
*ele
= dictGetEntryKey(de
);
4383 addReplyBulkLen(c
,ele
);
4385 addReply(c
,shared
.crlf
);
4386 dictDelete(set
->ptr
,ele
);
4387 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4393 static void srandmemberCommand(redisClient
*c
) {
4397 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4399 addReply(c
,shared
.nullbulk
);
4401 if (set
->type
!= REDIS_SET
) {
4402 addReply(c
,shared
.wrongtypeerr
);
4405 de
= dictGetRandomKey(set
->ptr
);
4407 addReply(c
,shared
.nullbulk
);
4409 robj
*ele
= dictGetEntryKey(de
);
4411 addReplyBulkLen(c
,ele
);
4413 addReply(c
,shared
.crlf
);
4418 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4419 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4421 return dictSize(*d1
)-dictSize(*d2
);
4424 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4425 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4428 robj
*lenobj
= NULL
, *dstset
= NULL
;
4429 unsigned long j
, cardinality
= 0;
4431 for (j
= 0; j
< setsnum
; j
++) {
4435 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4436 lookupKeyRead(c
->db
,setskeys
[j
]);
4440 if (deleteKey(c
->db
,dstkey
))
4442 addReply(c
,shared
.czero
);
4444 addReply(c
,shared
.nullmultibulk
);
4448 if (setobj
->type
!= REDIS_SET
) {
4450 addReply(c
,shared
.wrongtypeerr
);
4453 dv
[j
] = setobj
->ptr
;
4455 /* Sort sets from the smallest to largest, this will improve our
4456 * algorithm's performace */
4457 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4459 /* The first thing we should output is the total number of elements...
4460 * since this is a multi-bulk write, but at this stage we don't know
4461 * the intersection set size, so we use a trick, append an empty object
4462 * to the output list and save the pointer to later modify it with the
4465 lenobj
= createObject(REDIS_STRING
,NULL
);
4467 decrRefCount(lenobj
);
4469 /* If we have a target key where to store the resulting set
4470 * create this key with an empty set inside */
4471 dstset
= createSetObject();
4474 /* Iterate all the elements of the first (smallest) set, and test
4475 * the element against all the other sets, if at least one set does
4476 * not include the element it is discarded */
4477 di
= dictGetIterator(dv
[0]);
4479 while((de
= dictNext(di
)) != NULL
) {
4482 for (j
= 1; j
< setsnum
; j
++)
4483 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4485 continue; /* at least one set does not contain the member */
4486 ele
= dictGetEntryKey(de
);
4488 addReplyBulkLen(c
,ele
);
4490 addReply(c
,shared
.crlf
);
4493 dictAdd(dstset
->ptr
,ele
,NULL
);
4497 dictReleaseIterator(di
);
4500 /* Store the resulting set into the target */
4501 deleteKey(c
->db
,dstkey
);
4502 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4503 incrRefCount(dstkey
);
4507 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4509 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4510 dictSize((dict
*)dstset
->ptr
)));
4516 static void sinterCommand(redisClient
*c
) {
4517 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4520 static void sinterstoreCommand(redisClient
*c
) {
4521 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4524 #define REDIS_OP_UNION 0
4525 #define REDIS_OP_DIFF 1
4527 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4528 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4531 robj
*dstset
= NULL
;
4532 int j
, cardinality
= 0;
4534 for (j
= 0; j
< setsnum
; j
++) {
4538 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4539 lookupKeyRead(c
->db
,setskeys
[j
]);
4544 if (setobj
->type
!= REDIS_SET
) {
4546 addReply(c
,shared
.wrongtypeerr
);
4549 dv
[j
] = setobj
->ptr
;
4552 /* We need a temp set object to store our union. If the dstkey
4553 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4554 * this set object will be the resulting object to set into the target key*/
4555 dstset
= createSetObject();
4557 /* Iterate all the elements of all the sets, add every element a single
4558 * time to the result set */
4559 for (j
= 0; j
< setsnum
; j
++) {
4560 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4561 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4563 di
= dictGetIterator(dv
[j
]);
4565 while((de
= dictNext(di
)) != NULL
) {
4568 /* dictAdd will not add the same element multiple times */
4569 ele
= dictGetEntryKey(de
);
4570 if (op
== REDIS_OP_UNION
|| j
== 0) {
4571 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4575 } else if (op
== REDIS_OP_DIFF
) {
4576 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4581 dictReleaseIterator(di
);
4583 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4586 /* Output the content of the resulting set, if not in STORE mode */
4588 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4589 di
= dictGetIterator(dstset
->ptr
);
4590 while((de
= dictNext(di
)) != NULL
) {
4593 ele
= dictGetEntryKey(de
);
4594 addReplyBulkLen(c
,ele
);
4596 addReply(c
,shared
.crlf
);
4598 dictReleaseIterator(di
);
4600 /* If we have a target key where to store the resulting set
4601 * create this key with the result set inside */
4602 deleteKey(c
->db
,dstkey
);
4603 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4604 incrRefCount(dstkey
);
4609 decrRefCount(dstset
);
4611 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4612 dictSize((dict
*)dstset
->ptr
)));
4618 static void sunionCommand(redisClient
*c
) {
4619 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4622 static void sunionstoreCommand(redisClient
*c
) {
4623 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4626 static void sdiffCommand(redisClient
*c
) {
4627 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4630 static void sdiffstoreCommand(redisClient
*c
) {
4631 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4634 /* ==================================== ZSets =============================== */
4636 /* ZSETs are ordered sets using two data structures to hold the same elements
4637 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4640 * The elements are added to an hash table mapping Redis objects to scores.
4641 * At the same time the elements are added to a skip list mapping scores
4642 * to Redis objects (so objects are sorted by scores in this "view"). */
4644 /* This skiplist implementation is almost a C translation of the original
4645 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4646 * Alternative to Balanced Trees", modified in three ways:
4647 * a) this implementation allows for repeated values.
4648 * b) the comparison is not just by key (our 'score') but by satellite data.
4649 * c) there is a back pointer, so it's a doubly linked list with the back
4650 * pointers being only at "level 1". This allows to traverse the list
4651 * from tail to head, useful for ZREVRANGE. */
4653 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4654 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4656 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4662 static zskiplist
*zslCreate(void) {
4666 zsl
= zmalloc(sizeof(*zsl
));
4669 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4670 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++)
4671 zsl
->header
->forward
[j
] = NULL
;
4672 zsl
->header
->backward
= NULL
;
4677 static void zslFreeNode(zskiplistNode
*node
) {
4678 decrRefCount(node
->obj
);
4679 zfree(node
->forward
);
4683 static void zslFree(zskiplist
*zsl
) {
4684 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4686 zfree(zsl
->header
->forward
);
4689 next
= node
->forward
[0];
4696 static int zslRandomLevel(void) {
4698 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
4703 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
4704 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4708 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4709 while (x
->forward
[i
] &&
4710 (x
->forward
[i
]->score
< score
||
4711 (x
->forward
[i
]->score
== score
&&
4712 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4716 /* we assume the key is not already inside, since we allow duplicated
4717 * scores, and the re-insertion of score and redis object should never
4718 * happpen since the caller of zslInsert() should test in the hash table
4719 * if the element is already inside or not. */
4720 level
= zslRandomLevel();
4721 if (level
> zsl
->level
) {
4722 for (i
= zsl
->level
; i
< level
; i
++)
4723 update
[i
] = zsl
->header
;
4726 x
= zslCreateNode(level
,score
,obj
);
4727 for (i
= 0; i
< level
; i
++) {
4728 x
->forward
[i
] = update
[i
]->forward
[i
];
4729 update
[i
]->forward
[i
] = x
;
4731 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
4733 x
->forward
[0]->backward
= x
;
4739 /* Delete an element with matching score/object from the skiplist. */
4740 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
4741 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4745 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4746 while (x
->forward
[i
] &&
4747 (x
->forward
[i
]->score
< score
||
4748 (x
->forward
[i
]->score
== score
&&
4749 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
4753 /* We may have multiple elements with the same score, what we need
4754 * is to find the element with both the right score and object. */
4756 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
4757 for (i
= 0; i
< zsl
->level
; i
++) {
4758 if (update
[i
]->forward
[i
] != x
) break;
4759 update
[i
]->forward
[i
] = x
->forward
[i
];
4761 if (x
->forward
[0]) {
4762 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4765 zsl
->tail
= x
->backward
;
4768 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4773 return 0; /* not found */
4775 return 0; /* not found */
4778 /* Delete all the elements with score between min and max from the skiplist.
4779 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
4780 * Note that this function takes the reference to the hash table view of the
4781 * sorted set, in order to remove the elements from the hash table too. */
4782 static unsigned long zslDeleteRange(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
4783 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4784 unsigned long removed
= 0;
4788 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4789 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
4793 /* We may have multiple elements with the same score, what we need
4794 * is to find the element with both the right score and object. */
4796 while (x
&& x
->score
<= max
) {
4797 zskiplistNode
*next
;
4799 for (i
= 0; i
< zsl
->level
; i
++) {
4800 if (update
[i
]->forward
[i
] != x
) break;
4801 update
[i
]->forward
[i
] = x
->forward
[i
];
4803 if (x
->forward
[0]) {
4804 x
->forward
[0]->backward
= (x
->backward
== zsl
->header
) ?
4807 zsl
->tail
= x
->backward
;
4809 next
= x
->forward
[0];
4810 dictDelete(dict
,x
->obj
);
4812 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
4818 return removed
; /* not found */
4821 /* Find the first node having a score equal or greater than the specified one.
4822 * Returns NULL if there is no match. */
4823 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
4828 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4829 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
4832 /* We may have multiple elements with the same score, what we need
4833 * is to find the element with both the right score and object. */
4834 return x
->forward
[0];
4837 /* The actual Z-commands implementations */
4839 /* This generic command implements both ZADD and ZINCRBY.
4840 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
4841 * the increment if the operation is a ZINCRBY (doincrement == 1). */
4842 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
4847 zsetobj
= lookupKeyWrite(c
->db
,key
);
4848 if (zsetobj
== NULL
) {
4849 zsetobj
= createZsetObject();
4850 dictAdd(c
->db
->dict
,key
,zsetobj
);
4853 if (zsetobj
->type
!= REDIS_ZSET
) {
4854 addReply(c
,shared
.wrongtypeerr
);
4860 /* Ok now since we implement both ZADD and ZINCRBY here the code
4861 * needs to handle the two different conditions. It's all about setting
4862 * '*score', that is, the new score to set, to the right value. */
4863 score
= zmalloc(sizeof(double));
4867 /* Read the old score. If the element was not present starts from 0 */
4868 de
= dictFind(zs
->dict
,ele
);
4870 double *oldscore
= dictGetEntryVal(de
);
4871 *score
= *oldscore
+ scoreval
;
4879 /* What follows is a simple remove and re-insert operation that is common
4880 * to both ZADD and ZINCRBY... */
4881 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
4882 /* case 1: New element */
4883 incrRefCount(ele
); /* added to hash */
4884 zslInsert(zs
->zsl
,*score
,ele
);
4885 incrRefCount(ele
); /* added to skiplist */
4888 addReplyDouble(c
,*score
);
4890 addReply(c
,shared
.cone
);
4895 /* case 2: Score update operation */
4896 de
= dictFind(zs
->dict
,ele
);
4897 redisAssert(de
!= NULL
);
4898 oldscore
= dictGetEntryVal(de
);
4899 if (*score
!= *oldscore
) {
4902 /* Remove and insert the element in the skip list with new score */
4903 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
4904 redisAssert(deleted
!= 0);
4905 zslInsert(zs
->zsl
,*score
,ele
);
4907 /* Update the score in the hash table */
4908 dictReplace(zs
->dict
,ele
,score
);
4914 addReplyDouble(c
,*score
);
4916 addReply(c
,shared
.czero
);
4920 static void zaddCommand(redisClient
*c
) {
4923 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4924 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
4927 static void zincrbyCommand(redisClient
*c
) {
4930 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
4931 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
4934 static void zremCommand(redisClient
*c
) {
4938 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4939 if (zsetobj
== NULL
) {
4940 addReply(c
,shared
.czero
);
4946 if (zsetobj
->type
!= REDIS_ZSET
) {
4947 addReply(c
,shared
.wrongtypeerr
);
4951 de
= dictFind(zs
->dict
,c
->argv
[2]);
4953 addReply(c
,shared
.czero
);
4956 /* Delete from the skiplist */
4957 oldscore
= dictGetEntryVal(de
);
4958 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
4959 redisAssert(deleted
!= 0);
4961 /* Delete from the hash table */
4962 dictDelete(zs
->dict
,c
->argv
[2]);
4963 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4965 addReply(c
,shared
.cone
);
4969 static void zremrangebyscoreCommand(redisClient
*c
) {
4970 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
4971 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
4975 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4976 if (zsetobj
== NULL
) {
4977 addReply(c
,shared
.czero
);
4981 if (zsetobj
->type
!= REDIS_ZSET
) {
4982 addReply(c
,shared
.wrongtypeerr
);
4986 deleted
= zslDeleteRange(zs
->zsl
,min
,max
,zs
->dict
);
4987 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
4988 server
.dirty
+= deleted
;
4989 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
4993 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
4995 int start
= atoi(c
->argv
[2]->ptr
);
4996 int end
= atoi(c
->argv
[3]->ptr
);
4999 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
5001 } else if (c
->argc
>= 5) {
5002 addReply(c
,shared
.syntaxerr
);
5006 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5008 addReply(c
,shared
.nullmultibulk
);
5010 if (o
->type
!= REDIS_ZSET
) {
5011 addReply(c
,shared
.wrongtypeerr
);
5013 zset
*zsetobj
= o
->ptr
;
5014 zskiplist
*zsl
= zsetobj
->zsl
;
5017 int llen
= zsl
->length
;
5021 /* convert negative indexes */
5022 if (start
< 0) start
= llen
+start
;
5023 if (end
< 0) end
= llen
+end
;
5024 if (start
< 0) start
= 0;
5025 if (end
< 0) end
= 0;
5027 /* indexes sanity checks */
5028 if (start
> end
|| start
>= llen
) {
5029 /* Out of range start or start > end result in empty list */
5030 addReply(c
,shared
.emptymultibulk
);
5033 if (end
>= llen
) end
= llen
-1;
5034 rangelen
= (end
-start
)+1;
5036 /* Return the result in form of a multi-bulk reply */
5042 ln
= zsl
->header
->forward
[0];
5044 ln
= ln
->forward
[0];
5047 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
5048 withscores
? (rangelen
*2) : rangelen
));
5049 for (j
= 0; j
< rangelen
; j
++) {
5051 addReplyBulkLen(c
,ele
);
5053 addReply(c
,shared
.crlf
);
5055 addReplyDouble(c
,ln
->score
);
5056 ln
= reverse
? ln
->backward
: ln
->forward
[0];
5062 static void zrangeCommand(redisClient
*c
) {
5063 zrangeGenericCommand(c
,0);
5066 static void zrevrangeCommand(redisClient
*c
) {
5067 zrangeGenericCommand(c
,1);
5070 static void zrangebyscoreCommand(redisClient
*c
) {
5072 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
5073 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
5074 int offset
= 0, limit
= -1;
5076 if (c
->argc
!= 4 && c
->argc
!= 7) {
5078 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5080 } else if (c
->argc
== 7 && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
5081 addReply(c
,shared
.syntaxerr
);
5083 } else if (c
->argc
== 7) {
5084 offset
= atoi(c
->argv
[5]->ptr
);
5085 limit
= atoi(c
->argv
[6]->ptr
);
5086 if (offset
< 0) offset
= 0;
5089 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5091 addReply(c
,shared
.nullmultibulk
);
5093 if (o
->type
!= REDIS_ZSET
) {
5094 addReply(c
,shared
.wrongtypeerr
);
5096 zset
*zsetobj
= o
->ptr
;
5097 zskiplist
*zsl
= zsetobj
->zsl
;
5100 unsigned int rangelen
= 0;
5102 /* Get the first node with the score >= min */
5103 ln
= zslFirstWithScore(zsl
,min
);
5105 /* No element matching the speciifed interval */
5106 addReply(c
,shared
.emptymultibulk
);
5110 /* We don't know in advance how many matching elements there
5111 * are in the list, so we push this object that will represent
5112 * the multi-bulk length in the output buffer, and will "fix"
5114 lenobj
= createObject(REDIS_STRING
,NULL
);
5116 decrRefCount(lenobj
);
5118 while(ln
&& ln
->score
<= max
) {
5121 ln
= ln
->forward
[0];
5124 if (limit
== 0) break;
5126 addReplyBulkLen(c
,ele
);
5128 addReply(c
,shared
.crlf
);
5129 ln
= ln
->forward
[0];
5131 if (limit
> 0) limit
--;
5133 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",rangelen
);
5138 static void zcardCommand(redisClient
*c
) {
5142 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5144 addReply(c
,shared
.czero
);
5147 if (o
->type
!= REDIS_ZSET
) {
5148 addReply(c
,shared
.wrongtypeerr
);
5151 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
5156 static void zscoreCommand(redisClient
*c
) {
5160 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5162 addReply(c
,shared
.nullbulk
);
5165 if (o
->type
!= REDIS_ZSET
) {
5166 addReply(c
,shared
.wrongtypeerr
);
5171 de
= dictFind(zs
->dict
,c
->argv
[2]);
5173 addReply(c
,shared
.nullbulk
);
5175 double *score
= dictGetEntryVal(de
);
5177 addReplyDouble(c
,*score
);
5183 /* ========================= Non type-specific commands ==================== */
5185 static void flushdbCommand(redisClient
*c
) {
5186 server
.dirty
+= dictSize(c
->db
->dict
);
5187 dictEmpty(c
->db
->dict
);
5188 dictEmpty(c
->db
->expires
);
5189 addReply(c
,shared
.ok
);
5192 static void flushallCommand(redisClient
*c
) {
5193 server
.dirty
+= emptyDb();
5194 addReply(c
,shared
.ok
);
5195 rdbSave(server
.dbfilename
);
5199 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
5200 redisSortOperation
*so
= zmalloc(sizeof(*so
));
5202 so
->pattern
= pattern
;
5206 /* Return the value associated to the key with a name obtained
5207 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5208 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
5212 int prefixlen
, sublen
, postfixlen
;
5213 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5217 char buf
[REDIS_SORTKEY_MAX
+1];
5220 /* If the pattern is "#" return the substitution object itself in order
5221 * to implement the "SORT ... GET #" feature. */
5222 spat
= pattern
->ptr
;
5223 if (spat
[0] == '#' && spat
[1] == '\0') {
5227 /* The substitution object may be specially encoded. If so we create
5228 * a decoded object on the fly. Otherwise getDecodedObject will just
5229 * increment the ref count, that we'll decrement later. */
5230 subst
= getDecodedObject(subst
);
5233 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
5234 p
= strchr(spat
,'*');
5236 decrRefCount(subst
);
5241 sublen
= sdslen(ssub
);
5242 postfixlen
= sdslen(spat
)-(prefixlen
+1);
5243 memcpy(keyname
.buf
,spat
,prefixlen
);
5244 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
5245 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
5246 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
5247 keyname
.len
= prefixlen
+sublen
+postfixlen
;
5249 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
5250 decrRefCount(subst
);
5252 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5253 return lookupKeyRead(db
,&keyobj
);
5256 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5257 * the additional parameter is not standard but a BSD-specific we have to
5258 * pass sorting parameters via the global 'server' structure */
5259 static int sortCompare(const void *s1
, const void *s2
) {
5260 const redisSortObject
*so1
= s1
, *so2
= s2
;
5263 if (!server
.sort_alpha
) {
5264 /* Numeric sorting. Here it's trivial as we precomputed scores */
5265 if (so1
->u
.score
> so2
->u
.score
) {
5267 } else if (so1
->u
.score
< so2
->u
.score
) {
5273 /* Alphanumeric sorting */
5274 if (server
.sort_bypattern
) {
5275 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
5276 /* At least one compare object is NULL */
5277 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
5279 else if (so1
->u
.cmpobj
== NULL
)
5284 /* We have both the objects, use strcoll */
5285 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
5288 /* Compare elements directly */
5291 dec1
= getDecodedObject(so1
->obj
);
5292 dec2
= getDecodedObject(so2
->obj
);
5293 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
5298 return server
.sort_desc
? -cmp
: cmp
;
5301 /* The SORT command is the most complex command in Redis. Warning: this code
5302 * is optimized for speed and a bit less for readability */
5303 static void sortCommand(redisClient
*c
) {
5306 int desc
= 0, alpha
= 0;
5307 int limit_start
= 0, limit_count
= -1, start
, end
;
5308 int j
, dontsort
= 0, vectorlen
;
5309 int getop
= 0; /* GET operation counter */
5310 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
5311 redisSortObject
*vector
; /* Resulting vector to sort */
5313 /* Lookup the key to sort. It must be of the right types */
5314 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
5315 if (sortval
== NULL
) {
5316 addReply(c
,shared
.nullmultibulk
);
5319 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
5320 sortval
->type
!= REDIS_ZSET
)
5322 addReply(c
,shared
.wrongtypeerr
);
5326 /* Create a list of operations to perform for every sorted element.
5327 * Operations can be GET/DEL/INCR/DECR */
5328 operations
= listCreate();
5329 listSetFreeMethod(operations
,zfree
);
5332 /* Now we need to protect sortval incrementing its count, in the future
5333 * SORT may have options able to overwrite/delete keys during the sorting
5334 * and the sorted key itself may get destroied */
5335 incrRefCount(sortval
);
5337 /* The SORT command has an SQL-alike syntax, parse it */
5338 while(j
< c
->argc
) {
5339 int leftargs
= c
->argc
-j
-1;
5340 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
5342 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
5344 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
5346 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
5347 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
5348 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
5350 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
5351 storekey
= c
->argv
[j
+1];
5353 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
5354 sortby
= c
->argv
[j
+1];
5355 /* If the BY pattern does not contain '*', i.e. it is constant,
5356 * we don't need to sort nor to lookup the weight keys. */
5357 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
5359 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
5360 listAddNodeTail(operations
,createSortOperation(
5361 REDIS_SORT_GET
,c
->argv
[j
+1]));
5365 decrRefCount(sortval
);
5366 listRelease(operations
);
5367 addReply(c
,shared
.syntaxerr
);
5373 /* Load the sorting vector with all the objects to sort */
5374 switch(sortval
->type
) {
5375 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
5376 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
5377 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
5378 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
5380 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
5383 if (sortval
->type
== REDIS_LIST
) {
5384 list
*list
= sortval
->ptr
;
5388 listRewind(list
,&li
);
5389 while((ln
= listNext(&li
))) {
5390 robj
*ele
= ln
->value
;
5391 vector
[j
].obj
= ele
;
5392 vector
[j
].u
.score
= 0;
5393 vector
[j
].u
.cmpobj
= NULL
;
5401 if (sortval
->type
== REDIS_SET
) {
5404 zset
*zs
= sortval
->ptr
;
5408 di
= dictGetIterator(set
);
5409 while((setele
= dictNext(di
)) != NULL
) {
5410 vector
[j
].obj
= dictGetEntryKey(setele
);
5411 vector
[j
].u
.score
= 0;
5412 vector
[j
].u
.cmpobj
= NULL
;
5415 dictReleaseIterator(di
);
5417 redisAssert(j
== vectorlen
);
5419 /* Now it's time to load the right scores in the sorting vector */
5420 if (dontsort
== 0) {
5421 for (j
= 0; j
< vectorlen
; j
++) {
5425 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
5426 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
5428 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
5430 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
5431 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
5433 /* Don't need to decode the object if it's
5434 * integer-encoded (the only encoding supported) so
5435 * far. We can just cast it */
5436 if (byval
->encoding
== REDIS_ENCODING_INT
) {
5437 vector
[j
].u
.score
= (long)byval
->ptr
;
5439 redisAssert(1 != 1);
5444 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
5445 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
5447 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
5448 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
5450 redisAssert(1 != 1);
5457 /* We are ready to sort the vector... perform a bit of sanity check
5458 * on the LIMIT option too. We'll use a partial version of quicksort. */
5459 start
= (limit_start
< 0) ? 0 : limit_start
;
5460 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
5461 if (start
>= vectorlen
) {
5462 start
= vectorlen
-1;
5465 if (end
>= vectorlen
) end
= vectorlen
-1;
5467 if (dontsort
== 0) {
5468 server
.sort_desc
= desc
;
5469 server
.sort_alpha
= alpha
;
5470 server
.sort_bypattern
= sortby
? 1 : 0;
5471 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
5472 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
5474 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
5477 /* Send command output to the output buffer, performing the specified
5478 * GET/DEL/INCR/DECR operations if any. */
5479 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
5480 if (storekey
== NULL
) {
5481 /* STORE option not specified, sent the sorting result to client */
5482 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
5483 for (j
= start
; j
<= end
; j
++) {
5488 addReplyBulkLen(c
,vector
[j
].obj
);
5489 addReply(c
,vector
[j
].obj
);
5490 addReply(c
,shared
.crlf
);
5492 listRewind(operations
,&li
);
5493 while((ln
= listNext(&li
))) {
5494 redisSortOperation
*sop
= ln
->value
;
5495 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5498 if (sop
->type
== REDIS_SORT_GET
) {
5499 if (!val
|| val
->type
!= REDIS_STRING
) {
5500 addReply(c
,shared
.nullbulk
);
5502 addReplyBulkLen(c
,val
);
5504 addReply(c
,shared
.crlf
);
5507 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5512 robj
*listObject
= createListObject();
5513 list
*listPtr
= (list
*) listObject
->ptr
;
5515 /* STORE option specified, set the sorting result as a List object */
5516 for (j
= start
; j
<= end
; j
++) {
5521 listAddNodeTail(listPtr
,vector
[j
].obj
);
5522 incrRefCount(vector
[j
].obj
);
5524 listRewind(operations
,&li
);
5525 while((ln
= listNext(&li
))) {
5526 redisSortOperation
*sop
= ln
->value
;
5527 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5530 if (sop
->type
== REDIS_SORT_GET
) {
5531 if (!val
|| val
->type
!= REDIS_STRING
) {
5532 listAddNodeTail(listPtr
,createStringObject("",0));
5534 listAddNodeTail(listPtr
,val
);
5538 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
5542 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
5543 incrRefCount(storekey
);
5545 /* Note: we add 1 because the DB is dirty anyway since even if the
5546 * SORT result is empty a new key is set and maybe the old content
5548 server
.dirty
+= 1+outputlen
;
5549 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
5553 decrRefCount(sortval
);
5554 listRelease(operations
);
5555 for (j
= 0; j
< vectorlen
; j
++) {
5556 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
5557 decrRefCount(vector
[j
].u
.cmpobj
);
5562 /* Convert an amount of bytes into a human readable string in the form
5563 * of 100B, 2G, 100M, 4K, and so forth. */
5564 static void bytesToHuman(char *s
, unsigned long long n
) {
5569 sprintf(s
,"%lluB",n
);
5571 } else if (n
< (1024*1024)) {
5572 d
= (double)n
/(1024);
5573 sprintf(s
,"%.2fK",d
);
5574 } else if (n
< (1024LL*1024*1024)) {
5575 d
= (double)n
/(1024*1024);
5576 sprintf(s
,"%.2fM",d
);
5577 } else if (n
< (1024LL*1024*1024*1024)) {
5578 d
= (double)n
/(1024LL*1024*1024);
5579 sprintf(s
,"%.2fG",d
);
5583 /* Create the string returned by the INFO command. This is decoupled
5584 * by the INFO command itself as we need to report the same information
5585 * on memory corruption problems. */
5586 static sds
genRedisInfoString(void) {
5588 time_t uptime
= time(NULL
)-server
.stat_starttime
;
5592 bytesToHuman(hmem
,zmalloc_used_memory());
5593 info
= sdscatprintf(sdsempty(),
5594 "redis_version:%s\r\n"
5596 "multiplexing_api:%s\r\n"
5597 "process_id:%ld\r\n"
5598 "uptime_in_seconds:%ld\r\n"
5599 "uptime_in_days:%ld\r\n"
5600 "connected_clients:%d\r\n"
5601 "connected_slaves:%d\r\n"
5602 "blocked_clients:%d\r\n"
5603 "used_memory:%zu\r\n"
5604 "used_memory_human:%s\r\n"
5605 "changes_since_last_save:%lld\r\n"
5606 "bgsave_in_progress:%d\r\n"
5607 "last_save_time:%ld\r\n"
5608 "bgrewriteaof_in_progress:%d\r\n"
5609 "total_connections_received:%lld\r\n"
5610 "total_commands_processed:%lld\r\n"
5614 (sizeof(long) == 8) ? "64" : "32",
5619 listLength(server
.clients
)-listLength(server
.slaves
),
5620 listLength(server
.slaves
),
5621 server
.blockedclients
,
5622 zmalloc_used_memory(),
5625 server
.bgsavechildpid
!= -1,
5627 server
.bgrewritechildpid
!= -1,
5628 server
.stat_numconnections
,
5629 server
.stat_numcommands
,
5630 server
.vm_enabled
!= 0,
5631 server
.masterhost
== NULL
? "master" : "slave"
5633 if (server
.masterhost
) {
5634 info
= sdscatprintf(info
,
5635 "master_host:%s\r\n"
5636 "master_port:%d\r\n"
5637 "master_link_status:%s\r\n"
5638 "master_last_io_seconds_ago:%d\r\n"
5641 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
5643 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
5646 if (server
.vm_enabled
) {
5648 info
= sdscatprintf(info
,
5649 "vm_conf_max_memory:%llu\r\n"
5650 "vm_conf_page_size:%llu\r\n"
5651 "vm_conf_pages:%llu\r\n"
5652 "vm_stats_used_pages:%llu\r\n"
5653 "vm_stats_swapped_objects:%llu\r\n"
5654 "vm_stats_swappin_count:%llu\r\n"
5655 "vm_stats_swappout_count:%llu\r\n"
5656 "vm_stats_io_newjobs_len:%lu\r\n"
5657 "vm_stats_io_processing_len:%lu\r\n"
5658 "vm_stats_io_processed_len:%lu\r\n"
5659 "vm_stats_io_waiting_clients:%lu\r\n"
5660 "vm_stats_io_active_threads:%lu\r\n"
5661 ,(unsigned long long) server
.vm_max_memory
,
5662 (unsigned long long) server
.vm_page_size
,
5663 (unsigned long long) server
.vm_pages
,
5664 (unsigned long long) server
.vm_stats_used_pages
,
5665 (unsigned long long) server
.vm_stats_swapped_objects
,
5666 (unsigned long long) server
.vm_stats_swapins
,
5667 (unsigned long long) server
.vm_stats_swapouts
,
5668 (unsigned long) listLength(server
.io_newjobs
),
5669 (unsigned long) listLength(server
.io_processing
),
5670 (unsigned long) listLength(server
.io_processed
),
5671 (unsigned long) listLength(server
.io_clients
),
5672 (unsigned long) server
.io_active_threads
5676 for (j
= 0; j
< server
.dbnum
; j
++) {
5677 long long keys
, vkeys
;
5679 keys
= dictSize(server
.db
[j
].dict
);
5680 vkeys
= dictSize(server
.db
[j
].expires
);
5681 if (keys
|| vkeys
) {
5682 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
5689 static void infoCommand(redisClient
*c
) {
5690 sds info
= genRedisInfoString();
5691 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
5692 (unsigned long)sdslen(info
)));
5693 addReplySds(c
,info
);
5694 addReply(c
,shared
.crlf
);
5697 static void monitorCommand(redisClient
*c
) {
5698 /* ignore MONITOR if aleady slave or in monitor mode */
5699 if (c
->flags
& REDIS_SLAVE
) return;
5701 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
5703 listAddNodeTail(server
.monitors
,c
);
5704 addReply(c
,shared
.ok
);
5707 /* ================================= Expire ================================= */
5708 static int removeExpire(redisDb
*db
, robj
*key
) {
5709 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
5716 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
5717 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
5725 /* Return the expire time of the specified key, or -1 if no expire
5726 * is associated with this key (i.e. the key is non volatile) */
5727 static time_t getExpire(redisDb
*db
, robj
*key
) {
5730 /* No expire? return ASAP */
5731 if (dictSize(db
->expires
) == 0 ||
5732 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
5734 return (time_t) dictGetEntryVal(de
);
5737 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
5741 /* No expire? return ASAP */
5742 if (dictSize(db
->expires
) == 0 ||
5743 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5745 /* Lookup the expire */
5746 when
= (time_t) dictGetEntryVal(de
);
5747 if (time(NULL
) <= when
) return 0;
5749 /* Delete the key */
5750 dictDelete(db
->expires
,key
);
5751 return dictDelete(db
->dict
,key
) == DICT_OK
;
5754 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
5757 /* No expire? return ASAP */
5758 if (dictSize(db
->expires
) == 0 ||
5759 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
5761 /* Delete the key */
5763 dictDelete(db
->expires
,key
);
5764 return dictDelete(db
->dict
,key
) == DICT_OK
;
5767 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
5770 de
= dictFind(c
->db
->dict
,key
);
5772 addReply(c
,shared
.czero
);
5776 if (deleteKey(c
->db
,key
)) server
.dirty
++;
5777 addReply(c
, shared
.cone
);
5780 time_t when
= time(NULL
)+seconds
;
5781 if (setExpire(c
->db
,key
,when
)) {
5782 addReply(c
,shared
.cone
);
5785 addReply(c
,shared
.czero
);
5791 static void expireCommand(redisClient
*c
) {
5792 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
5795 static void expireatCommand(redisClient
*c
) {
5796 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
5799 static void ttlCommand(redisClient
*c
) {
5803 expire
= getExpire(c
->db
,c
->argv
[1]);
5805 ttl
= (int) (expire
-time(NULL
));
5806 if (ttl
< 0) ttl
= -1;
5808 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
5811 /* ================================ MULTI/EXEC ============================== */
5813 /* Client state initialization for MULTI/EXEC */
5814 static void initClientMultiState(redisClient
*c
) {
5815 c
->mstate
.commands
= NULL
;
5816 c
->mstate
.count
= 0;
5819 /* Release all the resources associated with MULTI/EXEC state */
5820 static void freeClientMultiState(redisClient
*c
) {
5823 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5825 multiCmd
*mc
= c
->mstate
.commands
+j
;
5827 for (i
= 0; i
< mc
->argc
; i
++)
5828 decrRefCount(mc
->argv
[i
]);
5831 zfree(c
->mstate
.commands
);
5834 /* Add a new command into the MULTI commands queue */
5835 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
5839 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
5840 sizeof(multiCmd
)*(c
->mstate
.count
+1));
5841 mc
= c
->mstate
.commands
+c
->mstate
.count
;
5844 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
5845 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
5846 for (j
= 0; j
< c
->argc
; j
++)
5847 incrRefCount(mc
->argv
[j
]);
5851 static void multiCommand(redisClient
*c
) {
5852 c
->flags
|= REDIS_MULTI
;
5853 addReply(c
,shared
.ok
);
5856 static void execCommand(redisClient
*c
) {
5861 if (!(c
->flags
& REDIS_MULTI
)) {
5862 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
5866 orig_argv
= c
->argv
;
5867 orig_argc
= c
->argc
;
5868 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
5869 for (j
= 0; j
< c
->mstate
.count
; j
++) {
5870 c
->argc
= c
->mstate
.commands
[j
].argc
;
5871 c
->argv
= c
->mstate
.commands
[j
].argv
;
5872 call(c
,c
->mstate
.commands
[j
].cmd
);
5874 c
->argv
= orig_argv
;
5875 c
->argc
= orig_argc
;
5876 freeClientMultiState(c
);
5877 initClientMultiState(c
);
5878 c
->flags
&= (~REDIS_MULTI
);
5881 /* =========================== Blocking Operations ========================= */
5883 /* Currently Redis blocking operations support is limited to list POP ops,
5884 * so the current implementation is not fully generic, but it is also not
5885 * completely specific so it will not require a rewrite to support new
5886 * kind of blocking operations in the future.
5888 * Still it's important to note that list blocking operations can be already
5889 * used as a notification mechanism in order to implement other blocking
5890 * operations at application level, so there must be a very strong evidence
5891 * of usefulness and generality before new blocking operations are implemented.
5893 * This is how the current blocking POP works, we use BLPOP as example:
5894 * - If the user calls BLPOP and the key exists and contains a non empty list
5895 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
5896 * if there is not to block.
5897 * - If instead BLPOP is called and the key does not exists or the list is
5898 * empty we need to block. In order to do so we remove the notification for
5899 * new data to read in the client socket (so that we'll not serve new
5900 * requests if the blocking request is not served). Also we put the client
5901 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
5902 * blocking for this keys.
5903 * - If a PUSH operation against a key with blocked clients waiting is
5904 * performed, we serve the first in the list: basically instead to push
5905 * the new element inside the list we return it to the (first / oldest)
5906 * blocking client, unblock the client, and remove it form the list.
5908 * The above comment and the source code should be enough in order to understand
5909 * the implementation and modify / fix it later.
5912 /* Set a client in blocking mode for the specified key, with the specified
5914 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
5919 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
5920 c
->blockingkeysnum
= numkeys
;
5921 c
->blockingto
= timeout
;
5922 for (j
= 0; j
< numkeys
; j
++) {
5923 /* Add the key in the client structure, to map clients -> keys */
5924 c
->blockingkeys
[j
] = keys
[j
];
5925 incrRefCount(keys
[j
]);
5927 /* And in the other "side", to map keys -> clients */
5928 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
5932 /* For every key we take a list of clients blocked for it */
5934 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
5935 incrRefCount(keys
[j
]);
5936 assert(retval
== DICT_OK
);
5938 l
= dictGetEntryVal(de
);
5940 listAddNodeTail(l
,c
);
5942 /* Mark the client as a blocked client */
5943 c
->flags
|= REDIS_BLOCKED
;
5944 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
5945 server
.blockedclients
++;
5948 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
5949 static void unblockClientWaitingData(redisClient
*c
) {
5954 assert(c
->blockingkeys
!= NULL
);
5955 /* The client may wait for multiple keys, so unblock it for every key. */
5956 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
5957 /* Remove this client from the list of clients waiting for this key. */
5958 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5960 l
= dictGetEntryVal(de
);
5961 listDelNode(l
,listSearchKey(l
,c
));
5962 /* If the list is empty we need to remove it to avoid wasting memory */
5963 if (listLength(l
) == 0)
5964 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
5965 decrRefCount(c
->blockingkeys
[j
]);
5967 /* Cleanup the client structure */
5968 zfree(c
->blockingkeys
);
5969 c
->blockingkeys
= NULL
;
5970 c
->flags
&= (~REDIS_BLOCKED
);
5971 server
.blockedclients
--;
5972 /* Ok now we are ready to get read events from socket, note that we
5973 * can't trap errors here as it's possible that unblockClientWaitingDatas() is
5974 * called from freeClient() itself, and the only thing we can do
5975 * if we failed to register the READABLE event is to kill the client.
5976 * Still the following function should never fail in the real world as
5977 * we are sure the file descriptor is sane, and we exit on out of mem. */
5978 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
, readQueryFromClient
, c
);
5979 /* As a final step we want to process data if there is some command waiting
5980 * in the input buffer. Note that this is safe even if
5981 * unblockClientWaitingData() gets called from freeClient() because
5982 * freeClient() will be smart enough to call this function
5983 * *after* c->querybuf was set to NULL. */
5984 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
5987 /* This should be called from any function PUSHing into lists.
5988 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
5989 * 'ele' is the element pushed.
5991 * If the function returns 0 there was no client waiting for a list push
5994 * If the function returns 1 there was a client waiting for a list push
5995 * against this key, the element was passed to this client thus it's not
5996 * needed to actually add it to the list and the caller should return asap. */
5997 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
5998 struct dictEntry
*de
;
5999 redisClient
*receiver
;
6003 de
= dictFind(c
->db
->blockingkeys
,key
);
6004 if (de
== NULL
) return 0;
6005 l
= dictGetEntryVal(de
);
6008 receiver
= ln
->value
;
6010 addReplySds(receiver
,sdsnew("*2\r\n"));
6011 addReplyBulkLen(receiver
,key
);
6012 addReply(receiver
,key
);
6013 addReply(receiver
,shared
.crlf
);
6014 addReplyBulkLen(receiver
,ele
);
6015 addReply(receiver
,ele
);
6016 addReply(receiver
,shared
.crlf
);
6017 unblockClientWaitingData(receiver
);
6021 /* Blocking RPOP/LPOP */
6022 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
6027 for (j
= 1; j
< c
->argc
-1; j
++) {
6028 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
6030 if (o
->type
!= REDIS_LIST
) {
6031 addReply(c
,shared
.wrongtypeerr
);
6034 list
*list
= o
->ptr
;
6035 if (listLength(list
) != 0) {
6036 /* If the list contains elements fall back to the usual
6037 * non-blocking POP operation */
6038 robj
*argv
[2], **orig_argv
;
6041 /* We need to alter the command arguments before to call
6042 * popGenericCommand() as the command takes a single key. */
6043 orig_argv
= c
->argv
;
6044 orig_argc
= c
->argc
;
6045 argv
[1] = c
->argv
[j
];
6049 /* Also the return value is different, we need to output
6050 * the multi bulk reply header and the key name. The
6051 * "real" command will add the last element (the value)
6052 * for us. If this souds like an hack to you it's just
6053 * because it is... */
6054 addReplySds(c
,sdsnew("*2\r\n"));
6055 addReplyBulkLen(c
,argv
[1]);
6056 addReply(c
,argv
[1]);
6057 addReply(c
,shared
.crlf
);
6058 popGenericCommand(c
,where
);
6060 /* Fix the client structure with the original stuff */
6061 c
->argv
= orig_argv
;
6062 c
->argc
= orig_argc
;
6068 /* If the list is empty or the key does not exists we must block */
6069 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
6070 if (timeout
> 0) timeout
+= time(NULL
);
6071 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
6074 static void blpopCommand(redisClient
*c
) {
6075 blockingPopGenericCommand(c
,REDIS_HEAD
);
6078 static void brpopCommand(redisClient
*c
) {
6079 blockingPopGenericCommand(c
,REDIS_TAIL
);
6082 /* =============================== Replication ============================= */
6084 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6085 ssize_t nwritten
, ret
= size
;
6086 time_t start
= time(NULL
);
6090 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
6091 nwritten
= write(fd
,ptr
,size
);
6092 if (nwritten
== -1) return -1;
6096 if ((time(NULL
)-start
) > timeout
) {
6104 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6105 ssize_t nread
, totread
= 0;
6106 time_t start
= time(NULL
);
6110 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
6111 nread
= read(fd
,ptr
,size
);
6112 if (nread
== -1) return -1;
6117 if ((time(NULL
)-start
) > timeout
) {
6125 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6132 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
6135 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
6146 static void syncCommand(redisClient
*c
) {
6147 /* ignore SYNC if aleady slave or in monitor mode */
6148 if (c
->flags
& REDIS_SLAVE
) return;
6150 /* SYNC can't be issued when the server has pending data to send to
6151 * the client about already issued commands. We need a fresh reply
6152 * buffer registering the differences between the BGSAVE and the current
6153 * dataset, so that we can copy to other slaves if needed. */
6154 if (listLength(c
->reply
) != 0) {
6155 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
6159 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
6160 /* Here we need to check if there is a background saving operation
6161 * in progress, or if it is required to start one */
6162 if (server
.bgsavechildpid
!= -1) {
6163 /* Ok a background save is in progress. Let's check if it is a good
6164 * one for replication, i.e. if there is another slave that is
6165 * registering differences since the server forked to save */
6170 listRewind(server
.slaves
,&li
);
6171 while((ln
= listNext(&li
))) {
6173 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
6176 /* Perfect, the server is already registering differences for
6177 * another slave. Set the right state, and copy the buffer. */
6178 listRelease(c
->reply
);
6179 c
->reply
= listDup(slave
->reply
);
6180 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6181 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
6183 /* No way, we need to wait for the next BGSAVE in order to
6184 * register differences */
6185 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6186 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
6189 /* Ok we don't have a BGSAVE in progress, let's start one */
6190 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
6191 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6192 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
6193 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
6196 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6199 c
->flags
|= REDIS_SLAVE
;
6201 listAddNodeTail(server
.slaves
,c
);
6205 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
6206 redisClient
*slave
= privdata
;
6208 REDIS_NOTUSED(mask
);
6209 char buf
[REDIS_IOBUF_LEN
];
6210 ssize_t nwritten
, buflen
;
6212 if (slave
->repldboff
== 0) {
6213 /* Write the bulk write count before to transfer the DB. In theory here
6214 * we don't know how much room there is in the output buffer of the
6215 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
6216 * operations) will never be smaller than the few bytes we need. */
6219 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
6221 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
6229 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
6230 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
6232 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
6233 (buflen
== 0) ? "premature EOF" : strerror(errno
));
6237 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
6238 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
6243 slave
->repldboff
+= nwritten
;
6244 if (slave
->repldboff
== slave
->repldbsize
) {
6245 close(slave
->repldbfd
);
6246 slave
->repldbfd
= -1;
6247 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6248 slave
->replstate
= REDIS_REPL_ONLINE
;
6249 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
6250 sendReplyToClient
, slave
) == AE_ERR
) {
6254 addReplySds(slave
,sdsempty());
6255 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
6259 /* This function is called at the end of every backgrond saving.
6260 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
6261 * otherwise REDIS_ERR is passed to the function.
6263 * The goal of this function is to handle slaves waiting for a successful
6264 * background saving in order to perform non-blocking synchronization. */
6265 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
6267 int startbgsave
= 0;
6270 listRewind(server
.slaves
,&li
);
6271 while((ln
= listNext(&li
))) {
6272 redisClient
*slave
= ln
->value
;
6274 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
6276 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6277 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
6278 struct redis_stat buf
;
6280 if (bgsaveerr
!= REDIS_OK
) {
6282 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
6285 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
6286 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
6288 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
6291 slave
->repldboff
= 0;
6292 slave
->repldbsize
= buf
.st_size
;
6293 slave
->replstate
= REDIS_REPL_SEND_BULK
;
6294 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6295 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
6302 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6305 listRewind(server
.slaves
,&li
);
6306 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
6307 while((ln
= listNext(&li
))) {
6308 redisClient
*slave
= ln
->value
;
6310 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
6317 static int syncWithMaster(void) {
6318 char buf
[1024], tmpfile
[256], authcmd
[1024];
6320 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
6324 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
6329 /* AUTH with the master if required. */
6330 if(server
.masterauth
) {
6331 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
6332 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
6334 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
6338 /* Read the AUTH result. */
6339 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6341 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
6345 if (buf
[0] != '+') {
6347 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
6352 /* Issue the SYNC command */
6353 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
6355 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
6359 /* Read the bulk write count */
6360 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6362 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
6366 if (buf
[0] != '$') {
6368 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6371 dumpsize
= atoi(buf
+1);
6372 redisLog(REDIS_NOTICE
,"Receiving %d bytes data dump from MASTER",dumpsize
);
6373 /* Read the bulk write data on a temp file */
6374 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
6375 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
6378 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
6382 int nread
, nwritten
;
6384 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
6386 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
6392 nwritten
= write(dfd
,buf
,nread
);
6393 if (nwritten
== -1) {
6394 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
6402 if (rename(tmpfile
,server
.dbfilename
) == -1) {
6403 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
6409 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6410 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
6414 server
.master
= createClient(fd
);
6415 server
.master
->flags
|= REDIS_MASTER
;
6416 server
.master
->authenticated
= 1;
6417 server
.replstate
= REDIS_REPL_CONNECTED
;
6421 static void slaveofCommand(redisClient
*c
) {
6422 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
6423 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
6424 if (server
.masterhost
) {
6425 sdsfree(server
.masterhost
);
6426 server
.masterhost
= NULL
;
6427 if (server
.master
) freeClient(server
.master
);
6428 server
.replstate
= REDIS_REPL_NONE
;
6429 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
6432 sdsfree(server
.masterhost
);
6433 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
6434 server
.masterport
= atoi(c
->argv
[2]->ptr
);
6435 if (server
.master
) freeClient(server
.master
);
6436 server
.replstate
= REDIS_REPL_CONNECT
;
6437 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
6438 server
.masterhost
, server
.masterport
);
6440 addReply(c
,shared
.ok
);
6443 /* ============================ Maxmemory directive ======================== */
6445 /* Try to free one object form the pre-allocated objects free list.
6446 * This is useful under low mem conditions as by default we take 1 million
6447 * free objects allocated. On success REDIS_OK is returned, otherwise
6449 static int tryFreeOneObjectFromFreelist(void) {
6452 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
6453 if (listLength(server
.objfreelist
)) {
6454 listNode
*head
= listFirst(server
.objfreelist
);
6455 o
= listNodeValue(head
);
6456 listDelNode(server
.objfreelist
,head
);
6457 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6461 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6466 /* This function gets called when 'maxmemory' is set on the config file to limit
6467 * the max memory used by the server, and we are out of memory.
6468 * This function will try to, in order:
6470 * - Free objects from the free list
6471 * - Try to remove keys with an EXPIRE set
6473 * It is not possible to free enough memory to reach used-memory < maxmemory
6474 * the server will start refusing commands that will enlarge even more the
6477 static void freeMemoryIfNeeded(void) {
6478 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
6479 int j
, k
, freed
= 0;
6481 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
6482 for (j
= 0; j
< server
.dbnum
; j
++) {
6484 robj
*minkey
= NULL
;
6485 struct dictEntry
*de
;
6487 if (dictSize(server
.db
[j
].expires
)) {
6489 /* From a sample of three keys drop the one nearest to
6490 * the natural expire */
6491 for (k
= 0; k
< 3; k
++) {
6494 de
= dictGetRandomKey(server
.db
[j
].expires
);
6495 t
= (time_t) dictGetEntryVal(de
);
6496 if (minttl
== -1 || t
< minttl
) {
6497 minkey
= dictGetEntryKey(de
);
6501 deleteKey(server
.db
+j
,minkey
);
6504 if (!freed
) return; /* nothing to free... */
6508 /* ============================== Append Only file ========================== */
6510 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
6511 sds buf
= sdsempty();
6517 /* The DB this command was targetting is not the same as the last command
6518 * we appendend. To issue a SELECT command is needed. */
6519 if (dictid
!= server
.appendseldb
) {
6522 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
6523 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
6524 (unsigned long)strlen(seldb
),seldb
);
6525 server
.appendseldb
= dictid
;
6528 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
6529 * EXPIREs into EXPIREATs calls */
6530 if (cmd
->proc
== expireCommand
) {
6533 tmpargv
[0] = createStringObject("EXPIREAT",8);
6534 tmpargv
[1] = argv
[1];
6535 incrRefCount(argv
[1]);
6536 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
6537 tmpargv
[2] = createObject(REDIS_STRING
,
6538 sdscatprintf(sdsempty(),"%ld",when
));
6542 /* Append the actual command */
6543 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
6544 for (j
= 0; j
< argc
; j
++) {
6547 o
= getDecodedObject(o
);
6548 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
6549 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
6550 buf
= sdscatlen(buf
,"\r\n",2);
6554 /* Free the objects from the modified argv for EXPIREAT */
6555 if (cmd
->proc
== expireCommand
) {
6556 for (j
= 0; j
< 3; j
++)
6557 decrRefCount(argv
[j
]);
6560 /* We want to perform a single write. This should be guaranteed atomic
6561 * at least if the filesystem we are writing is a real physical one.
6562 * While this will save us against the server being killed I don't think
6563 * there is much to do about the whole server stopping for power problems
6565 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
6566 if (nwritten
!= (signed)sdslen(buf
)) {
6567 /* Ooops, we are in troubles. The best thing to do for now is
6568 * to simply exit instead to give the illusion that everything is
6569 * working as expected. */
6570 if (nwritten
== -1) {
6571 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
6573 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
6577 /* If a background append only file rewriting is in progress we want to
6578 * accumulate the differences between the child DB and the current one
6579 * in a buffer, so that when the child process will do its work we
6580 * can append the differences to the new append only file. */
6581 if (server
.bgrewritechildpid
!= -1)
6582 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
6586 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
6587 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
6588 now
-server
.lastfsync
> 1))
6590 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
6591 server
.lastfsync
= now
;
6595 /* In Redis commands are always executed in the context of a client, so in
6596 * order to load the append only file we need to create a fake client. */
6597 static struct redisClient
*createFakeClient(void) {
6598 struct redisClient
*c
= zmalloc(sizeof(*c
));
6602 c
->querybuf
= sdsempty();
6606 /* We set the fake client as a slave waiting for the synchronization
6607 * so that Redis will not try to send replies to this client. */
6608 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6609 c
->reply
= listCreate();
6610 listSetFreeMethod(c
->reply
,decrRefCount
);
6611 listSetDupMethod(c
->reply
,dupClientReplyValue
);
6615 static void freeFakeClient(struct redisClient
*c
) {
6616 sdsfree(c
->querybuf
);
6617 listRelease(c
->reply
);
6621 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
6622 * error (the append only file is zero-length) REDIS_ERR is returned. On
6623 * fatal error an error message is logged and the program exists. */
6624 int loadAppendOnlyFile(char *filename
) {
6625 struct redisClient
*fakeClient
;
6626 FILE *fp
= fopen(filename
,"r");
6627 struct redis_stat sb
;
6628 unsigned long long loadedkeys
= 0;
6630 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
6634 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
6638 fakeClient
= createFakeClient();
6645 struct redisCommand
*cmd
;
6647 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
6653 if (buf
[0] != '*') goto fmterr
;
6655 argv
= zmalloc(sizeof(robj
*)*argc
);
6656 for (j
= 0; j
< argc
; j
++) {
6657 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
6658 if (buf
[0] != '$') goto fmterr
;
6659 len
= strtol(buf
+1,NULL
,10);
6660 argsds
= sdsnewlen(NULL
,len
);
6661 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
6662 argv
[j
] = createObject(REDIS_STRING
,argsds
);
6663 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
6666 /* Command lookup */
6667 cmd
= lookupCommand(argv
[0]->ptr
);
6669 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
6672 /* Try object sharing and encoding */
6673 if (server
.shareobjects
) {
6675 for(j
= 1; j
< argc
; j
++)
6676 argv
[j
] = tryObjectSharing(argv
[j
]);
6678 if (cmd
->flags
& REDIS_CMD_BULK
)
6679 tryObjectEncoding(argv
[argc
-1]);
6680 /* Run the command in the context of a fake client */
6681 fakeClient
->argc
= argc
;
6682 fakeClient
->argv
= argv
;
6683 cmd
->proc(fakeClient
);
6684 /* Discard the reply objects list from the fake client */
6685 while(listLength(fakeClient
->reply
))
6686 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
6687 /* Clean up, ready for the next command */
6688 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
6690 /* Handle swapping while loading big datasets when VM is on */
6692 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
6693 while (zmalloc_used_memory() > server
.vm_max_memory
) {
6694 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
6699 freeFakeClient(fakeClient
);
6704 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
6706 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
6710 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
6714 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
6715 static int fwriteBulk(FILE *fp
, robj
*obj
) {
6719 /* Avoid the incr/decr ref count business if possible to help
6720 * copy-on-write (we are often in a child process when this function
6722 * Also makes sure that key objects don't get incrRefCount-ed when VM
6724 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
6725 obj
= getDecodedObject(obj
);
6728 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
6729 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
6730 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
6732 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
6733 if (decrrc
) decrRefCount(obj
);
6736 if (decrrc
) decrRefCount(obj
);
6740 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
6741 static int fwriteBulkDouble(FILE *fp
, double d
) {
6742 char buf
[128], dbuf
[128];
6744 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
6745 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
6746 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6747 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
6751 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
6752 static int fwriteBulkLong(FILE *fp
, long l
) {
6753 char buf
[128], lbuf
[128];
6755 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
6756 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
6757 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
6758 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
6762 /* Write a sequence of commands able to fully rebuild the dataset into
6763 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
6764 static int rewriteAppendOnlyFile(char *filename
) {
6765 dictIterator
*di
= NULL
;
6770 time_t now
= time(NULL
);
6772 /* Note that we have to use a different temp name here compared to the
6773 * one used by rewriteAppendOnlyFileBackground() function. */
6774 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
6775 fp
= fopen(tmpfile
,"w");
6777 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
6780 for (j
= 0; j
< server
.dbnum
; j
++) {
6781 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
6782 redisDb
*db
= server
.db
+j
;
6784 if (dictSize(d
) == 0) continue;
6785 di
= dictGetIterator(d
);
6791 /* SELECT the new DB */
6792 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
6793 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
6795 /* Iterate this DB writing every entry */
6796 while((de
= dictNext(di
)) != NULL
) {
6801 key
= dictGetEntryKey(de
);
6802 /* If the value for this key is swapped, load a preview in memory.
6803 * We use a "swapped" flag to remember if we need to free the
6804 * value object instead to just increment the ref count anyway
6805 * in order to avoid copy-on-write of pages if we are forked() */
6806 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
6807 key
->storage
== REDIS_VM_SWAPPING
) {
6808 o
= dictGetEntryVal(de
);
6811 o
= vmPreviewObject(key
);
6814 expiretime
= getExpire(db
,key
);
6816 /* Save the key and associated value */
6817 if (o
->type
== REDIS_STRING
) {
6818 /* Emit a SET command */
6819 char cmd
[]="*3\r\n$3\r\nSET\r\n";
6820 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6822 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6823 if (fwriteBulk(fp
,o
) == 0) goto werr
;
6824 } else if (o
->type
== REDIS_LIST
) {
6825 /* Emit the RPUSHes needed to rebuild the list */
6826 list
*list
= o
->ptr
;
6830 listRewind(list
,&li
);
6831 while((ln
= listNext(&li
))) {
6832 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
6833 robj
*eleobj
= listNodeValue(ln
);
6835 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6836 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6837 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6839 } else if (o
->type
== REDIS_SET
) {
6840 /* Emit the SADDs needed to rebuild the set */
6842 dictIterator
*di
= dictGetIterator(set
);
6845 while((de
= dictNext(di
)) != NULL
) {
6846 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
6847 robj
*eleobj
= dictGetEntryKey(de
);
6849 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6850 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6851 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6853 dictReleaseIterator(di
);
6854 } else if (o
->type
== REDIS_ZSET
) {
6855 /* Emit the ZADDs needed to rebuild the sorted set */
6857 dictIterator
*di
= dictGetIterator(zs
->dict
);
6860 while((de
= dictNext(di
)) != NULL
) {
6861 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
6862 robj
*eleobj
= dictGetEntryKey(de
);
6863 double *score
= dictGetEntryVal(de
);
6865 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6866 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6867 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
6868 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
6870 dictReleaseIterator(di
);
6872 redisAssert(0 != 0);
6874 /* Save the expire time */
6875 if (expiretime
!= -1) {
6876 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
6877 /* If this key is already expired skip it */
6878 if (expiretime
< now
) continue;
6879 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
6880 if (fwriteBulk(fp
,key
) == 0) goto werr
;
6881 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
6883 if (swapped
) decrRefCount(o
);
6885 dictReleaseIterator(di
);
6888 /* Make sure data will not remain on the OS's output buffers */
6893 /* Use RENAME to make sure the DB file is changed atomically only
6894 * if the generate DB file is ok. */
6895 if (rename(tmpfile
,filename
) == -1) {
6896 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
6900 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
6906 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
6907 if (di
) dictReleaseIterator(di
);
6911 /* This is how rewriting of the append only file in background works:
6913 * 1) The user calls BGREWRITEAOF
6914 * 2) Redis calls this function, that forks():
6915 * 2a) the child rewrite the append only file in a temp file.
6916 * 2b) the parent accumulates differences in server.bgrewritebuf.
6917 * 3) When the child finished '2a' exists.
6918 * 4) The parent will trap the exit code, if it's OK, will append the
6919 * data accumulated into server.bgrewritebuf into the temp file, and
6920 * finally will rename(2) the temp file in the actual file name.
6921 * The the new file is reopened as the new append only file. Profit!
6923 static int rewriteAppendOnlyFileBackground(void) {
6926 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
6927 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
6928 if ((childpid
= fork()) == 0) {
6932 if (server
.vm_enabled
) vmReopenSwapFile();
6934 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
6935 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
6942 if (childpid
== -1) {
6943 redisLog(REDIS_WARNING
,
6944 "Can't rewrite append only file in background: fork: %s",
6948 redisLog(REDIS_NOTICE
,
6949 "Background append only file rewriting started by pid %d",childpid
);
6950 server
.bgrewritechildpid
= childpid
;
6951 /* We set appendseldb to -1 in order to force the next call to the
6952 * feedAppendOnlyFile() to issue a SELECT command, so the differences
6953 * accumulated by the parent into server.bgrewritebuf will start
6954 * with a SELECT statement and it will be safe to merge. */
6955 server
.appendseldb
= -1;
6958 return REDIS_OK
; /* unreached */
6961 static void bgrewriteaofCommand(redisClient
*c
) {
6962 if (server
.bgrewritechildpid
!= -1) {
6963 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
6966 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
6967 char *status
= "+Background append only file rewriting started\r\n";
6968 addReplySds(c
,sdsnew(status
));
6970 addReply(c
,shared
.err
);
6974 static void aofRemoveTempFile(pid_t childpid
) {
6977 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
6981 /* Virtual Memory is composed mainly of two subsystems:
6982 * - Blocking Virutal Memory
6983 * - Threaded Virtual Memory I/O
6984 * The two parts are not fully decoupled, but functions are split among two
6985 * different sections of the source code (delimited by comments) in order to
6986 * make more clear what functionality is about the blocking VM and what about
6987 * the threaded (not blocking) VM.
6991 * Redis VM is a blocking VM (one that blocks reading swapped values from
6992 * disk into memory when a value swapped out is needed in memory) that is made
6993 * unblocking by trying to examine the command argument vector in order to
6994 * load in background values that will likely be needed in order to exec
6995 * the command. The command is executed only once all the relevant keys
6996 * are loaded into memory.
6998 * This basically is almost as simple of a blocking VM, but almost as parallel
6999 * as a fully non-blocking VM.
7002 /* =================== Virtual Memory - Blocking Side ====================== */
7004 /* substitute the first occurrence of '%p' with the process pid in the
7005 * swap file name. */
7006 static void expandVmSwapFilename(void) {
7007 char *p
= strstr(server
.vm_swap_file
,"%p");
7013 new = sdscat(new,server
.vm_swap_file
);
7014 new = sdscatprintf(new,"%ld",(long) getpid());
7015 new = sdscat(new,p
+2);
7016 zfree(server
.vm_swap_file
);
7017 server
.vm_swap_file
= new;
7020 static void vmInit(void) {
7025 if (server
.vm_max_threads
!= 0)
7026 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
7028 expandVmSwapFilename();
7029 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
7030 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
7031 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
7033 if (server
.vm_fp
== NULL
) {
7034 redisLog(REDIS_WARNING
,
7035 "Impossible to open the swap file: %s. Exiting.",
7039 server
.vm_fd
= fileno(server
.vm_fp
);
7040 server
.vm_next_page
= 0;
7041 server
.vm_near_pages
= 0;
7042 server
.vm_stats_used_pages
= 0;
7043 server
.vm_stats_swapped_objects
= 0;
7044 server
.vm_stats_swapouts
= 0;
7045 server
.vm_stats_swapins
= 0;
7046 totsize
= server
.vm_pages
*server
.vm_page_size
;
7047 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
7048 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
7049 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
7053 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
7055 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
7056 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
7057 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
7058 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
7060 /* Initialize threaded I/O (used by Virtual Memory) */
7061 server
.io_newjobs
= listCreate();
7062 server
.io_processing
= listCreate();
7063 server
.io_processed
= listCreate();
7064 server
.io_clients
= listCreate();
7065 pthread_mutex_init(&server
.io_mutex
,NULL
);
7066 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
7067 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
7068 server
.io_active_threads
= 0;
7069 if (pipe(pipefds
) == -1) {
7070 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
7074 server
.io_ready_pipe_read
= pipefds
[0];
7075 server
.io_ready_pipe_write
= pipefds
[1];
7076 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
7077 /* LZF requires a lot of stack */
7078 pthread_attr_init(&server
.io_threads_attr
);
7079 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
7080 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
7081 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
7082 /* Listen for events in the threaded I/O pipe */
7083 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
7084 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
7085 oom("creating file event");
7088 /* Mark the page as used */
7089 static void vmMarkPageUsed(off_t page
) {
7090 off_t byte
= page
/8;
7092 redisAssert(vmFreePage(page
) == 1);
7093 server
.vm_bitmap
[byte
] |= 1<<bit
;
7094 redisLog(REDIS_DEBUG
,"Mark used: %lld (byte:%lld bit:%d)\n",
7095 (long long)page
, (long long)byte
, bit
);
7098 /* Mark N contiguous pages as used, with 'page' being the first. */
7099 static void vmMarkPagesUsed(off_t page
, off_t count
) {
7102 for (j
= 0; j
< count
; j
++)
7103 vmMarkPageUsed(page
+j
);
7104 server
.vm_stats_used_pages
+= count
;
7107 /* Mark the page as free */
7108 static void vmMarkPageFree(off_t page
) {
7109 off_t byte
= page
/8;
7111 redisAssert(vmFreePage(page
) == 0);
7112 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
7113 redisLog(REDIS_DEBUG
,"Mark free: %lld (byte:%lld bit:%d)\n",
7114 (long long)page
, (long long)byte
, bit
);
7117 /* Mark N contiguous pages as free, with 'page' being the first. */
7118 static void vmMarkPagesFree(off_t page
, off_t count
) {
7121 for (j
= 0; j
< count
; j
++)
7122 vmMarkPageFree(page
+j
);
7123 server
.vm_stats_used_pages
-= count
;
7124 if (server
.vm_stats_used_pages
> 100000000) {
7129 /* Test if the page is free */
7130 static int vmFreePage(off_t page
) {
7131 off_t byte
= page
/8;
7133 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
7136 /* Find N contiguous free pages storing the first page of the cluster in *first.
7137 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
7138 * REDIS_ERR is returned.
7140 * This function uses a simple algorithm: we try to allocate
7141 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
7142 * again from the start of the swap file searching for free spaces.
7144 * If it looks pretty clear that there are no free pages near our offset
7145 * we try to find less populated places doing a forward jump of
7146 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
7147 * without hurry, and then we jump again and so forth...
7149 * This function can be improved using a free list to avoid to guess
7150 * too much, since we could collect data about freed pages.
7152 * note: I implemented this function just after watching an episode of
7153 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
7155 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
7156 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
7158 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
7159 server
.vm_near_pages
= 0;
7160 server
.vm_next_page
= 0;
7162 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
7163 base
= server
.vm_next_page
;
7165 while(offset
< server
.vm_pages
) {
7166 off_t
this = base
+offset
;
7168 /* If we overflow, restart from page zero */
7169 if (this >= server
.vm_pages
) {
7170 this -= server
.vm_pages
;
7172 /* Just overflowed, what we found on tail is no longer
7173 * interesting, as it's no longer contiguous. */
7177 redisLog(REDIS_DEBUG
, "THIS: %lld (%c)\n", (long long) this, vmFreePage(this) ? 'F' : 'X');
7178 if (vmFreePage(this)) {
7179 /* This is a free page */
7181 /* Already got N free pages? Return to the caller, with success */
7183 *first
= this-(n
-1);
7184 server
.vm_next_page
= this+1;
7188 /* The current one is not a free page */
7192 /* Fast-forward if the current page is not free and we already
7193 * searched enough near this place. */
7195 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
7196 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
7198 /* Note that even if we rewind after the jump, we are don't need
7199 * to make sure numfree is set to zero as we only jump *if* it
7200 * is set to zero. */
7202 /* Otherwise just check the next page */
7209 /* Write the specified object at the specified page of the swap file */
7210 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
7211 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7212 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7213 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7214 redisLog(REDIS_WARNING
,
7215 "Critical VM problem in vmSwapObjectBlocking(): can't seek: %s",
7219 rdbSaveObject(server
.vm_fp
,o
);
7220 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7224 /* Swap the 'val' object relative to 'key' into disk. Store all the information
7225 * needed to later retrieve the object into the key object.
7226 * If we can't find enough contiguous empty pages to swap the object on disk
7227 * REDIS_ERR is returned. */
7228 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
7229 off_t pages
= rdbSavedObjectPages(val
,NULL
);
7232 assert(key
->storage
== REDIS_VM_MEMORY
);
7233 assert(key
->refcount
== 1);
7234 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
7235 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
7236 key
->vm
.page
= page
;
7237 key
->vm
.usedpages
= pages
;
7238 key
->storage
= REDIS_VM_SWAPPED
;
7239 key
->vtype
= val
->type
;
7240 decrRefCount(val
); /* Deallocate the object from memory. */
7241 vmMarkPagesUsed(page
,pages
);
7242 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
7243 (unsigned char*) key
->ptr
,
7244 (unsigned long long) page
, (unsigned long long) pages
);
7245 server
.vm_stats_swapped_objects
++;
7246 server
.vm_stats_swapouts
++;
7247 fflush(server
.vm_fp
);
7251 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
7254 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7255 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7256 redisLog(REDIS_WARNING
,
7257 "Unrecoverable VM problem in vmLoadObject(): can't seek: %s",
7261 o
= rdbLoadObject(type
,server
.vm_fp
);
7263 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmLoadObject(): can't load object from swap file: %s", strerror(errno
));
7266 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7270 /* Load the value object relative to the 'key' object from swap to memory.
7271 * The newly allocated object is returned.
7273 * If preview is true the unserialized object is returned to the caller but
7274 * no changes are made to the key object, nor the pages are marked as freed */
7275 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
7278 redisAssert(key
->storage
== REDIS_VM_SWAPPED
);
7279 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
7281 key
->storage
= REDIS_VM_MEMORY
;
7282 key
->vm
.atime
= server
.unixtime
;
7283 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7284 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
7285 (unsigned char*) key
->ptr
);
7286 server
.vm_stats_swapped_objects
--;
7288 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
7289 (unsigned char*) key
->ptr
);
7291 server
.vm_stats_swapins
++;
7295 /* Plain object loading, from swap to memory */
7296 static robj
*vmLoadObject(robj
*key
) {
7297 /* If we are loading the object in background, stop it, we
7298 * need to load this object synchronously ASAP. */
7299 if (key
->storage
== REDIS_VM_LOADING
)
7300 vmCancelThreadedIOJob(key
);
7301 return vmGenericLoadObject(key
,0);
7304 /* Just load the value on disk, without to modify the key.
7305 * This is useful when we want to perform some operation on the value
7306 * without to really bring it from swap to memory, like while saving the
7307 * dataset or rewriting the append only log. */
7308 static robj
*vmPreviewObject(robj
*key
) {
7309 return vmGenericLoadObject(key
,1);
7312 /* How a good candidate is this object for swapping?
7313 * The better candidate it is, the greater the returned value.
7315 * Currently we try to perform a fast estimation of the object size in
7316 * memory, and combine it with aging informations.
7318 * Basically swappability = idle-time * log(estimated size)
7320 * Bigger objects are preferred over smaller objects, but not
7321 * proportionally, this is why we use the logarithm. This algorithm is
7322 * just a first try and will probably be tuned later. */
7323 static double computeObjectSwappability(robj
*o
) {
7324 time_t age
= server
.unixtime
- o
->vm
.atime
;
7328 struct dictEntry
*de
;
7331 if (age
<= 0) return 0;
7334 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
7337 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
7342 listNode
*ln
= listFirst(l
);
7344 asize
= sizeof(list
);
7346 robj
*ele
= ln
->value
;
7349 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7350 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7352 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
7357 z
= (o
->type
== REDIS_ZSET
);
7358 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
7360 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
7361 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
7366 de
= dictGetRandomKey(d
);
7367 ele
= dictGetEntryKey(de
);
7368 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7369 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7371 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
7372 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
7376 return (double)asize
*log(1+asize
);
7379 /* Try to swap an object that's a good candidate for swapping.
7380 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
7381 * to swap any object at all.
7383 * If 'usethreaded' is true, Redis will try to swap the object in background
7384 * using I/O threads. */
7385 static int vmSwapOneObject(int usethreads
) {
7387 struct dictEntry
*best
= NULL
;
7388 double best_swappability
= 0;
7389 redisDb
*best_db
= NULL
;
7392 for (j
= 0; j
< server
.dbnum
; j
++) {
7393 redisDb
*db
= server
.db
+j
;
7394 /* Why maxtries is set to 100?
7395 * Because this way (usually) we'll find 1 object even if just 1% - 2%
7396 * are swappable objects */
7399 if (dictSize(db
->dict
) == 0) continue;
7400 for (i
= 0; i
< 5; i
++) {
7402 double swappability
;
7404 if (maxtries
) maxtries
--;
7405 de
= dictGetRandomKey(db
->dict
);
7406 key
= dictGetEntryKey(de
);
7407 val
= dictGetEntryVal(de
);
7408 /* Only swap objects that are currently in memory.
7410 * Also don't swap shared objects if threaded VM is on, as we
7411 * try to ensure that the main thread does not touch the
7412 * object while the I/O thread is using it, but we can't
7413 * control other keys without adding additional mutex. */
7414 if (key
->storage
!= REDIS_VM_MEMORY
||
7415 (server
.vm_max_threads
!= 0 && val
->refcount
!= 1)) {
7416 if (maxtries
) i
--; /* don't count this try */
7419 swappability
= computeObjectSwappability(val
);
7420 if (!best
|| swappability
> best_swappability
) {
7422 best_swappability
= swappability
;
7428 redisLog(REDIS_DEBUG
,"No swappable key found!");
7431 key
= dictGetEntryKey(best
);
7432 val
= dictGetEntryVal(best
);
7434 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
7435 key
->ptr
, best_swappability
);
7437 /* Unshare the key if needed */
7438 if (key
->refcount
> 1) {
7439 robj
*newkey
= dupStringObject(key
);
7441 key
= dictGetEntryKey(best
) = newkey
;
7445 vmSwapObjectThreaded(key
,val
,best_db
);
7448 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7449 dictGetEntryVal(best
) = NULL
;
7457 static int vmSwapOneObjectBlocking() {
7458 return vmSwapOneObject(0);
7461 static int vmSwapOneObjectThreaded() {
7462 return vmSwapOneObject(1);
7465 /* Return true if it's safe to swap out objects in a given moment.
7466 * Basically we don't want to swap objects out while there is a BGSAVE
7467 * or a BGAEOREWRITE running in backgroud. */
7468 static int vmCanSwapOut(void) {
7469 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
7472 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
7473 * and was deleted. Otherwise 0 is returned. */
7474 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
7478 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
7479 foundkey
= dictGetEntryKey(de
);
7480 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
7485 /* =================== Virtual Memory - Threaded I/O ======================= */
7487 static void freeIOJob(iojob
*j
) {
7488 if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
7489 j
->type
== REDIS_IOJOB_DO_SWAP
)
7490 decrRefCount(j
->val
);
7491 decrRefCount(j
->key
);
7495 /* Every time a thread finished a Job, it writes a byte into the write side
7496 * of an unix pipe in order to "awake" the main thread, and this function
7498 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
7502 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
7504 REDIS_NOTUSED(mask
);
7505 REDIS_NOTUSED(privdata
);
7507 /* For every byte we read in the read side of the pipe, there is one
7508 * I/O job completed to process. */
7509 while((retval
= read(fd
,buf
,1)) == 1) {
7513 struct dictEntry
*de
;
7515 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
7517 /* Get the processed element (the oldest one) */
7519 assert(listLength(server
.io_processed
) != 0);
7520 if (toprocess
== -1) {
7521 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
7522 if (toprocess
<= 0) toprocess
= 1;
7524 ln
= listFirst(server
.io_processed
);
7526 listDelNode(server
.io_processed
,ln
);
7528 /* If this job is marked as canceled, just ignore it */
7533 /* Post process it in the main thread, as there are things we
7534 * can do just here to avoid race conditions and/or invasive locks */
7535 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
);
7536 de
= dictFind(j
->db
->dict
,j
->key
);
7538 key
= dictGetEntryKey(de
);
7539 if (j
->type
== REDIS_IOJOB_LOAD
) {
7540 /* Key loaded, bring it at home */
7541 key
->storage
= REDIS_VM_MEMORY
;
7542 key
->vm
.atime
= server
.unixtime
;
7543 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7544 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
7545 (unsigned char*) key
->ptr
);
7546 server
.vm_stats_swapped_objects
--;
7547 server
.vm_stats_swapins
++;
7549 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
7550 /* Now we know the amount of pages required to swap this object.
7551 * Let's find some space for it, and queue this task again
7552 * rebranded as REDIS_IOJOB_DO_SWAP. */
7553 if (!vmCanSwapOut() ||
7554 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
7556 /* Ooops... no space or we can't swap as there is
7557 * a fork()ed Redis trying to save stuff on disk. */
7559 key
->storage
= REDIS_VM_MEMORY
; /* undo operation */
7561 /* Note that we need to mark this pages as used now,
7562 * if the job will be canceled, we'll mark them as freed
7564 vmMarkPagesUsed(j
->page
,j
->pages
);
7565 j
->type
= REDIS_IOJOB_DO_SWAP
;
7570 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
7573 /* Key swapped. We can finally free some memory. */
7574 if (key
->storage
!= REDIS_VM_SWAPPING
) {
7575 printf("key->storage: %d\n",key
->storage
);
7576 printf("key->name: %s\n",(char*)key
->ptr
);
7577 printf("key->refcount: %d\n",key
->refcount
);
7578 printf("val: %p\n",(void*)j
->val
);
7579 printf("val->type: %d\n",j
->val
->type
);
7580 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
7582 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
7583 val
= dictGetEntryVal(de
);
7584 key
->vm
.page
= j
->page
;
7585 key
->vm
.usedpages
= j
->pages
;
7586 key
->storage
= REDIS_VM_SWAPPED
;
7587 key
->vtype
= j
->val
->type
;
7588 decrRefCount(val
); /* Deallocate the object from memory. */
7589 dictGetEntryVal(de
) = NULL
;
7590 redisLog(REDIS_DEBUG
,
7591 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
7592 (unsigned char*) key
->ptr
,
7593 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
7594 server
.vm_stats_swapped_objects
++;
7595 server
.vm_stats_swapouts
++;
7597 /* Put a few more swap requests in queue if we are still
7599 if (trytoswap
&& vmCanSwapOut() &&
7600 zmalloc_used_memory() > server
.vm_max_memory
)
7605 more
= listLength(server
.io_newjobs
) <
7606 (unsigned) server
.vm_max_threads
;
7608 /* Don't waste CPU time if swappable objects are rare. */
7609 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
7617 if (processed
== toprocess
) return;
7619 if (retval
< 0 && errno
!= EAGAIN
) {
7620 redisLog(REDIS_WARNING
,
7621 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
7626 static void lockThreadedIO(void) {
7627 pthread_mutex_lock(&server
.io_mutex
);
7630 static void unlockThreadedIO(void) {
7631 pthread_mutex_unlock(&server
.io_mutex
);
7634 /* Remove the specified object from the threaded I/O queue if still not
7635 * processed, otherwise make sure to flag it as canceled. */
7636 static void vmCancelThreadedIOJob(robj
*o
) {
7638 server
.io_newjobs
, /* 0 */
7639 server
.io_processing
, /* 1 */
7640 server
.io_processed
/* 2 */
7644 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
7647 /* Search for a matching key in one of the queues */
7648 for (i
= 0; i
< 3; i
++) {
7652 listRewind(lists
[i
],&li
);
7653 while ((ln
= listNext(&li
)) != NULL
) {
7654 iojob
*job
= ln
->value
;
7656 if (job
->canceled
) continue; /* Skip this, already canceled. */
7657 if (compareStringObjects(job
->key
,o
) == 0) {
7658 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
7659 (void*)job
, (char*)o
->ptr
, job
->type
, i
);
7660 /* Mark the pages as free since the swap didn't happened
7661 * or happened but is now discarded. */
7662 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
7663 vmMarkPagesFree(job
->page
,job
->pages
);
7664 /* Cancel the job. It depends on the list the job is
7667 case 0: /* io_newjobs */
7668 /* If the job was yet not processed the best thing to do
7669 * is to remove it from the queue at all */
7671 listDelNode(lists
[i
],ln
);
7673 case 1: /* io_processing */
7674 /* Oh Shi- the thread is messing with the Job, and
7675 * probably with the object if this is a
7676 * PREPARE_SWAP or DO_SWAP job. Better to wait for the
7677 * job to move into the next queue... */
7678 if (job
->type
!= REDIS_IOJOB_LOAD
) {
7679 /* Yes, we try again and again until the job
7682 /* But let's wait some time for the I/O thread
7683 * to finish with this job. After all this condition
7684 * should be very rare. */
7691 case 2: /* io_processed */
7692 /* The job was already processed, that's easy...
7693 * just mark it as canceled so that we'll ignore it
7694 * when processing completed jobs. */
7698 /* Finally we have to adjust the storage type of the object
7699 * in order to "UNDO" the operaiton. */
7700 if (o
->storage
== REDIS_VM_LOADING
)
7701 o
->storage
= REDIS_VM_SWAPPED
;
7702 else if (o
->storage
== REDIS_VM_SWAPPING
)
7703 o
->storage
= REDIS_VM_MEMORY
;
7710 assert(1 != 1); /* We should never reach this */
7713 static void *IOThreadEntryPoint(void *arg
) {
7718 pthread_detach(pthread_self());
7720 /* Get a new job to process */
7722 if (listLength(server
.io_newjobs
) == 0) {
7723 /* No new jobs in queue, exit. */
7724 redisLog(REDIS_DEBUG
,"Thread %lld exiting, nothing to do",
7725 (long long) pthread_self());
7726 server
.io_active_threads
--;
7730 ln
= listFirst(server
.io_newjobs
);
7732 listDelNode(server
.io_newjobs
,ln
);
7733 /* Add the job in the processing queue */
7734 j
->thread
= pthread_self();
7735 listAddNodeTail(server
.io_processing
,j
);
7736 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
7738 redisLog(REDIS_DEBUG
,"Thread %lld got a new job (type %d): %p about key '%s'",
7739 (long long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
7741 /* Process the Job */
7742 if (j
->type
== REDIS_IOJOB_LOAD
) {
7743 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
7744 FILE *fp
= fopen("/dev/null","w+");
7745 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
7747 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
7748 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
7752 /* Done: insert the job into the processed queue */
7753 redisLog(REDIS_DEBUG
,"Thread %lld completed the job: %p (key %s)",
7754 (long long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
7756 listDelNode(server
.io_processing
,ln
);
7757 listAddNodeTail(server
.io_processed
,j
);
7760 /* Signal the main thread there is new stuff to process */
7761 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
7763 return NULL
; /* never reached */
7766 static void spawnIOThread(void) {
7769 pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
);
7770 server
.io_active_threads
++;
7773 /* We need to wait for the last thread to exit before we are able to
7774 * fork() in order to BGSAVE or BGREWRITEAOF. */
7775 static void waitEmptyIOJobsQueue(void) {
7777 int io_processed_len
;
7780 if (listLength(server
.io_newjobs
) == 0 &&
7781 listLength(server
.io_processing
) == 0 &&
7782 server
.io_active_threads
== 0)
7787 /* While waiting for empty jobs queue condition we post-process some
7788 * finshed job, as I/O threads may be hanging trying to write against
7789 * the io_ready_pipe_write FD but there are so much pending jobs that
7791 io_processed_len
= listLength(server
.io_processed
);
7793 if (io_processed_len
) {
7794 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,NULL
,0);
7795 usleep(1000); /* 1 millisecond */
7797 usleep(10000); /* 10 milliseconds */
7802 static void vmReopenSwapFile(void) {
7803 fclose(server
.vm_fp
);
7804 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
7805 if (server
.vm_fp
== NULL
) {
7806 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
7807 server
.vm_swap_file
);
7810 server
.vm_fd
= fileno(server
.vm_fp
);
7813 /* This function must be called while with threaded IO locked */
7814 static void queueIOJob(iojob
*j
) {
7815 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
7816 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
7817 listAddNodeTail(server
.io_newjobs
,j
);
7818 if (server
.io_active_threads
< server
.vm_max_threads
)
7822 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
7825 assert(key
->storage
== REDIS_VM_MEMORY
);
7826 assert(key
->refcount
== 1);
7828 j
= zmalloc(sizeof(*j
));
7829 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
7831 j
->key
= dupStringObject(key
);
7835 j
->thread
= (pthread_t
) -1;
7836 key
->storage
= REDIS_VM_SWAPPING
;
7844 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
7846 /* Is this client attempting to run a command against swapped keys?
7847 * If so, block it ASAP, load the keys in background, then resume it.4
7849 * The improtat thing about this function is that it can fail! If keys will
7850 * still be swapped when the client is resumed, a few of key lookups will
7851 * just block loading keys from disk. */
7853 static void blockClientOnSwappedKeys(redisClient
*c
) {
7857 /* ================================= Debugging ============================== */
7859 static void debugCommand(redisClient
*c
) {
7860 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
7862 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
7863 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
7864 addReply(c
,shared
.err
);
7868 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
7869 addReply(c
,shared
.err
);
7872 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
7873 addReply(c
,shared
.ok
);
7874 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
7876 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
7877 addReply(c
,shared
.err
);
7880 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
7881 addReply(c
,shared
.ok
);
7882 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
7883 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7887 addReply(c
,shared
.nokeyerr
);
7890 key
= dictGetEntryKey(de
);
7891 val
= dictGetEntryVal(de
);
7892 if (server
.vm_enabled
&& (key
->storage
== REDIS_VM_MEMORY
||
7893 key
->storage
== REDIS_VM_SWAPPING
)) {
7894 addReplySds(c
,sdscatprintf(sdsempty(),
7895 "+Key at:%p refcount:%d, value at:%p refcount:%d "
7896 "encoding:%d serializedlength:%lld\r\n",
7897 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
7898 val
->encoding
, (long long) rdbSavedObjectLen(val
,NULL
)));
7900 addReplySds(c
,sdscatprintf(sdsempty(),
7901 "+Key at:%p refcount:%d, value swapped at: page %llu "
7902 "using %llu pages\r\n",
7903 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
7904 (unsigned long long) key
->vm
.usedpages
));
7906 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
7907 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
7910 if (!server
.vm_enabled
) {
7911 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
7915 addReply(c
,shared
.nokeyerr
);
7918 key
= dictGetEntryKey(de
);
7919 val
= dictGetEntryVal(de
);
7920 /* If the key is shared we want to create a copy */
7921 if (key
->refcount
> 1) {
7922 robj
*newkey
= dupStringObject(key
);
7924 key
= dictGetEntryKey(de
) = newkey
;
7927 if (key
->storage
!= REDIS_VM_MEMORY
) {
7928 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
7929 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7930 dictGetEntryVal(de
) = NULL
;
7931 addReply(c
,shared
.ok
);
7933 addReply(c
,shared
.err
);
7936 addReplySds(c
,sdsnew(
7937 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
7941 static void _redisAssert(char *estr
, char *file
, int line
) {
7942 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
7943 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
);
7944 #ifdef HAVE_BACKTRACE
7945 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
7950 /* =================================== Main! ================================ */
7953 int linuxOvercommitMemoryValue(void) {
7954 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
7958 if (fgets(buf
,64,fp
) == NULL
) {
7967 void linuxOvercommitMemoryWarning(void) {
7968 if (linuxOvercommitMemoryValue() == 0) {
7969 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.");
7972 #endif /* __linux__ */
7974 static void daemonize(void) {
7978 if (fork() != 0) exit(0); /* parent exits */
7979 setsid(); /* create a new session */
7981 /* Every output goes to /dev/null. If Redis is daemonized but
7982 * the 'logfile' is set to 'stdout' in the configuration file
7983 * it will not log at all. */
7984 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
7985 dup2(fd
, STDIN_FILENO
);
7986 dup2(fd
, STDOUT_FILENO
);
7987 dup2(fd
, STDERR_FILENO
);
7988 if (fd
> STDERR_FILENO
) close(fd
);
7990 /* Try to write the pid file */
7991 fp
= fopen(server
.pidfile
,"w");
7993 fprintf(fp
,"%d\n",getpid());
7998 int main(int argc
, char **argv
) {
8001 resetServerSaveParams();
8002 loadServerConfig(argv
[1]);
8003 } else if (argc
> 2) {
8004 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
8007 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'");
8009 if (server
.daemonize
) daemonize();
8011 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
8013 linuxOvercommitMemoryWarning();
8015 if (server
.appendonly
) {
8016 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
8017 redisLog(REDIS_NOTICE
,"DB loaded from append only file");
8019 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
8020 redisLog(REDIS_NOTICE
,"DB loaded from disk");
8022 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
8024 aeDeleteEventLoop(server
.el
);
8028 /* ============================= Backtrace support ========================= */
8030 #ifdef HAVE_BACKTRACE
8031 static char *findFuncName(void *pointer
, unsigned long *offset
);
8033 static void *getMcontextEip(ucontext_t
*uc
) {
8034 #if defined(__FreeBSD__)
8035 return (void*) uc
->uc_mcontext
.mc_eip
;
8036 #elif defined(__dietlibc__)
8037 return (void*) uc
->uc_mcontext
.eip
;
8038 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
8040 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
8042 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
8044 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
8045 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
8046 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
8048 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
8050 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
8051 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
8052 #elif defined(__ia64__) /* Linux IA64 */
8053 return (void*) uc
->uc_mcontext
.sc_ip
;
8059 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
8061 char **messages
= NULL
;
8062 int i
, trace_size
= 0;
8063 unsigned long offset
=0;
8064 ucontext_t
*uc
= (ucontext_t
*) secret
;
8066 REDIS_NOTUSED(info
);
8068 redisLog(REDIS_WARNING
,
8069 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
8070 infostring
= genRedisInfoString();
8071 redisLog(REDIS_WARNING
, "%s",infostring
);
8072 /* It's not safe to sdsfree() the returned string under memory
8073 * corruption conditions. Let it leak as we are going to abort */
8075 trace_size
= backtrace(trace
, 100);
8076 /* overwrite sigaction with caller's address */
8077 if (getMcontextEip(uc
) != NULL
) {
8078 trace
[1] = getMcontextEip(uc
);
8080 messages
= backtrace_symbols(trace
, trace_size
);
8082 for (i
=1; i
<trace_size
; ++i
) {
8083 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
8085 p
= strchr(messages
[i
],'+');
8086 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
8087 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
8089 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
8092 /* free(messages); Don't call free() with possibly corrupted memory. */
8096 static void setupSigSegvAction(void) {
8097 struct sigaction act
;
8099 sigemptyset (&act
.sa_mask
);
8100 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
8101 * is used. Otherwise, sa_handler is used */
8102 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
8103 act
.sa_sigaction
= segvHandler
;
8104 sigaction (SIGSEGV
, &act
, NULL
);
8105 sigaction (SIGBUS
, &act
, NULL
);
8106 sigaction (SIGFPE
, &act
, NULL
);
8107 sigaction (SIGILL
, &act
, NULL
);
8108 sigaction (SIGBUS
, &act
, NULL
);
8112 #include "staticsymbols.h"
8113 /* This function try to convert a pointer into a function name. It's used in
8114 * oreder to provide a backtrace under segmentation fault that's able to
8115 * display functions declared as static (otherwise the backtrace is useless). */
8116 static char *findFuncName(void *pointer
, unsigned long *offset
){
8118 unsigned long off
, minoff
= 0;
8120 /* Try to match against the Symbol with the smallest offset */
8121 for (i
=0; symsTable
[i
].pointer
; i
++) {
8122 unsigned long lp
= (unsigned long) pointer
;
8124 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
8125 off
=lp
-symsTable
[i
].pointer
;
8126 if (ret
< 0 || off
< minoff
) {
8132 if (ret
== -1) return NULL
;
8134 return symsTable
[ret
].name
;
8136 #else /* HAVE_BACKTRACE */
8137 static void setupSigSegvAction(void) {
8139 #endif /* HAVE_BACKTRACE */