2 * Copyright (c) 2009-2010, 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.4"
40 #define __USE_POSIX199309
47 #endif /* HAVE_BACKTRACE */
55 #include <arpa/inet.h>
59 #include <sys/resource.h>
66 #include "solarisfixes.h"
70 #include "ae.h" /* Event driven programming library */
71 #include "sds.h" /* Dynamic safe strings */
72 #include "anet.h" /* Networking the easy way */
73 #include "dict.h" /* Hash tables */
74 #include "adlist.h" /* Linked lists */
75 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
76 #include "lzf.h" /* LZF compression library */
77 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
84 /* Static server configuration */
85 #define REDIS_SERVERPORT 6379 /* TCP port */
86 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
87 #define REDIS_IOBUF_LEN 1024
88 #define REDIS_LOADBUF_LEN 1024
89 #define REDIS_STATIC_ARGS 4
90 #define REDIS_DEFAULT_DBNUM 16
91 #define REDIS_CONFIGLINE_MAX 1024
92 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
93 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
94 #define REDIS_EXPIRELOOKUPS_PER_CRON 100 /* try to expire 100 keys/second */
95 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
96 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
98 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
99 #define REDIS_WRITEV_THRESHOLD 3
100 /* Max number of iovecs used for each writev call */
101 #define REDIS_WRITEV_IOVEC_COUNT 256
103 /* Hash table parameters */
104 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
107 #define REDIS_CMD_BULK 1 /* Bulk write command */
108 #define REDIS_CMD_INLINE 2 /* Inline command */
109 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
110 this flags will return an error when the 'maxmemory' option is set in the
111 config file and the server is using more than maxmemory bytes of memory.
112 In short this commands are denied on low memory conditions. */
113 #define REDIS_CMD_DENYOOM 4
116 #define REDIS_STRING 0
122 /* Objects encoding. Some kind of objects like Strings and Hashes can be
123 * internally represented in multiple ways. The 'encoding' field of the object
124 * is set to one of this fields for this object. */
125 #define REDIS_ENCODING_RAW 0 /* Raw representation */
126 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
127 #define REDIS_ENCODING_ZIPMAP 2 /* Encoded as zipmap */
128 #define REDIS_ENCODING_HT 3 /* Encoded as an hash table */
130 /* Object types only used for dumping to disk */
131 #define REDIS_EXPIRETIME 253
132 #define REDIS_SELECTDB 254
133 #define REDIS_EOF 255
135 /* Defines related to the dump file format. To store 32 bits lengths for short
136 * keys requires a lot of space, so we check the most significant 2 bits of
137 * the first byte to interpreter the length:
139 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
140 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
141 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
142 * 11|000000 this means: specially encoded object will follow. The six bits
143 * number specify the kind of object that follows.
144 * See the REDIS_RDB_ENC_* defines.
146 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
147 * values, will fit inside. */
148 #define REDIS_RDB_6BITLEN 0
149 #define REDIS_RDB_14BITLEN 1
150 #define REDIS_RDB_32BITLEN 2
151 #define REDIS_RDB_ENCVAL 3
152 #define REDIS_RDB_LENERR UINT_MAX
154 /* When a length of a string object stored on disk has the first two bits
155 * set, the remaining two bits specify a special encoding for the object
156 * accordingly to the following defines: */
157 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
158 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
159 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
160 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
162 /* Virtual memory object->where field. */
163 #define REDIS_VM_MEMORY 0 /* The object is on memory */
164 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
165 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
166 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
168 /* Virtual memory static configuration stuff.
169 * Check vmFindContiguousPages() to know more about this magic numbers. */
170 #define REDIS_VM_MAX_NEAR_PAGES 65536
171 #define REDIS_VM_MAX_RANDOM_JUMP 4096
172 #define REDIS_VM_MAX_THREADS 32
173 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
174 /* The following is the *percentage* of completed I/O jobs to process when the
175 * handelr is called. While Virtual Memory I/O operations are performed by
176 * threads, this operations must be processed by the main thread when completed
177 * in order to take effect. */
178 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
181 #define REDIS_SLAVE 1 /* This client is a slave server */
182 #define REDIS_MASTER 2 /* This client is a master server */
183 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
184 #define REDIS_MULTI 8 /* This client is in a MULTI context */
185 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
186 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
188 /* Slave replication state - slave side */
189 #define REDIS_REPL_NONE 0 /* No active replication */
190 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
191 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
193 /* Slave replication state - from the point of view of master
194 * Note that in SEND_BULK and ONLINE state the slave receives new updates
195 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
196 * to start the next background saving in order to send updates to it. */
197 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
198 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
199 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
200 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
202 /* List related stuff */
206 /* Sort operations */
207 #define REDIS_SORT_GET 0
208 #define REDIS_SORT_ASC 1
209 #define REDIS_SORT_DESC 2
210 #define REDIS_SORTKEY_MAX 1024
213 #define REDIS_DEBUG 0
214 #define REDIS_VERBOSE 1
215 #define REDIS_NOTICE 2
216 #define REDIS_WARNING 3
218 /* Anti-warning macro... */
219 #define REDIS_NOTUSED(V) ((void) V)
221 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
222 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
224 /* Append only defines */
225 #define APPENDFSYNC_NO 0
226 #define APPENDFSYNC_ALWAYS 1
227 #define APPENDFSYNC_EVERYSEC 2
229 /* Hashes related defaults */
230 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
231 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
233 /* We can print the stacktrace, so our assert is defined this way: */
234 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
235 static void _redisAssert(char *estr
, char *file
, int line
);
237 /*================================= Data types ============================== */
239 /* A redis object, that is a type able to hold a string / list / set */
241 /* The VM object structure */
242 struct redisObjectVM
{
243 off_t page
; /* the page at witch the object is stored on disk */
244 off_t usedpages
; /* number of pages used on disk */
245 time_t atime
; /* Last access time */
248 /* The actual Redis Object */
249 typedef struct redisObject
{
252 unsigned char encoding
;
253 unsigned char storage
; /* If this object is a key, where is the value?
254 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
255 unsigned char vtype
; /* If this object is a key, and value is swapped out,
256 * this is the type of the swapped out object. */
258 /* VM fields, this are only allocated if VM is active, otherwise the
259 * object allocation function will just allocate
260 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
261 * Redis without VM active will not have any overhead. */
262 struct redisObjectVM vm
;
265 /* Macro used to initalize a Redis object allocated on the stack.
266 * Note that this macro is taken near the structure definition to make sure
267 * we'll update it when the structure is changed, to avoid bugs like
268 * bug #85 introduced exactly in this way. */
269 #define initStaticStringObject(_var,_ptr) do { \
271 _var.type = REDIS_STRING; \
272 _var.encoding = REDIS_ENCODING_RAW; \
274 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
277 typedef struct redisDb
{
278 dict
*dict
; /* The keyspace for this DB */
279 dict
*expires
; /* Timeout of keys with a timeout set */
280 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
281 dict
*io_keys
; /* Keys with clients waiting for VM I/O */
285 /* Client MULTI/EXEC state */
286 typedef struct multiCmd
{
289 struct redisCommand
*cmd
;
292 typedef struct multiState
{
293 multiCmd
*commands
; /* Array of MULTI commands */
294 int count
; /* Total number of MULTI commands */
297 /* With multiplexing we need to take per-clinet state.
298 * Clients are taken in a liked list. */
299 typedef struct redisClient
{
304 robj
**argv
, **mbargv
;
306 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
307 int multibulk
; /* multi bulk command format active */
310 time_t lastinteraction
; /* time of the last interaction, used for timeout */
311 int flags
; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
312 int slaveseldb
; /* slave selected db, if this client is a slave */
313 int authenticated
; /* when requirepass is non-NULL */
314 int replstate
; /* replication state if this is a slave */
315 int repldbfd
; /* replication DB file descriptor */
316 long repldboff
; /* replication DB file offset */
317 off_t repldbsize
; /* replication DB file size */
318 multiState mstate
; /* MULTI/EXEC state */
319 robj
**blockingkeys
; /* The key we are waiting to terminate a blocking
320 * operation such as BLPOP. Otherwise NULL. */
321 int blockingkeysnum
; /* Number of blocking keys */
322 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
323 * is >= blockingto then the operation timed out. */
324 list
*io_keys
; /* Keys this client is waiting to be loaded from the
325 * swap file in order to continue. */
333 /* Global server state structure */
338 dict
*sharingpool
; /* Poll used for object sharing */
339 unsigned int sharingpoolsize
;
340 long long dirty
; /* changes to DB from the last save */
342 list
*slaves
, *monitors
;
343 char neterr
[ANET_ERR_LEN
];
345 int cronloops
; /* number of times the cron function run */
346 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
347 time_t lastsave
; /* Unix time of last save succeeede */
348 /* Fields used only for stats */
349 time_t stat_starttime
; /* server start time */
350 long long stat_numcommands
; /* number of processed commands */
351 long long stat_numconnections
; /* number of connections received */
364 pid_t bgsavechildpid
;
365 pid_t bgrewritechildpid
;
366 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
367 struct saveparam
*saveparams
;
372 char *appendfilename
;
376 /* Replication related */
381 redisClient
*master
; /* client that is master for this slave */
383 unsigned int maxclients
;
384 unsigned long long maxmemory
;
385 unsigned int blpop_blocked_clients
;
386 unsigned int vm_blocked_clients
;
387 /* Sort parameters - qsort_r() is only available under BSD so we
388 * have to take this state global, in order to pass it to sortCompare() */
392 /* Virtual memory configuration */
397 unsigned long long vm_max_memory
;
399 size_t hash_max_zipmap_entries
;
400 size_t hash_max_zipmap_value
;
401 /* Virtual memory state */
404 off_t vm_next_page
; /* Next probably empty page */
405 off_t vm_near_pages
; /* Number of pages allocated sequentially */
406 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
407 time_t unixtime
; /* Unix time sampled every second. */
408 /* Virtual memory I/O threads stuff */
409 /* An I/O thread process an element taken from the io_jobs queue and
410 * put the result of the operation in the io_done list. While the
411 * job is being processed, it's put on io_processing queue. */
412 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
413 list
*io_processing
; /* List of VM I/O jobs being processed */
414 list
*io_processed
; /* List of VM I/O jobs already processed */
415 list
*io_ready_clients
; /* Clients ready to be unblocked. All keys loaded */
416 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
417 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
418 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
419 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
420 int io_active_threads
; /* Number of running I/O threads */
421 int vm_max_threads
; /* Max number of I/O threads running at the same time */
422 /* Our main thread is blocked on the event loop, locking for sockets ready
423 * to be read or written, so when a threaded I/O operation is ready to be
424 * processed by the main thread, the I/O thread will use a unix pipe to
425 * awake the main thread. The followings are the two pipe FDs. */
426 int io_ready_pipe_read
;
427 int io_ready_pipe_write
;
428 /* Virtual memory stats */
429 unsigned long long vm_stats_used_pages
;
430 unsigned long long vm_stats_swapped_objects
;
431 unsigned long long vm_stats_swapouts
;
432 unsigned long long vm_stats_swapins
;
436 typedef void redisCommandProc(redisClient
*c
);
437 struct redisCommand
{
439 redisCommandProc
*proc
;
442 /* What keys should be loaded in background when calling this command? */
443 int vm_firstkey
; /* The first argument that's a key (0 = no keys) */
444 int vm_lastkey
; /* THe last argument that's a key */
445 int vm_keystep
; /* The step between first and last key */
448 struct redisFunctionSym
{
450 unsigned long pointer
;
453 typedef struct _redisSortObject
{
461 typedef struct _redisSortOperation
{
464 } redisSortOperation
;
466 /* ZSETs use a specialized version of Skiplists */
468 typedef struct zskiplistNode
{
469 struct zskiplistNode
**forward
;
470 struct zskiplistNode
*backward
;
476 typedef struct zskiplist
{
477 struct zskiplistNode
*header
, *tail
;
478 unsigned long length
;
482 typedef struct zset
{
487 /* Our shared "common" objects */
489 struct sharedObjectsStruct
{
490 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
491 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
492 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
493 *outofrangeerr
, *plus
,
494 *select0
, *select1
, *select2
, *select3
, *select4
,
495 *select5
, *select6
, *select7
, *select8
, *select9
;
498 /* Global vars that are actally used as constants. The following double
499 * values are used for double on-disk serialization, and are initialized
500 * at runtime to avoid strange compiler optimizations. */
502 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
504 /* VM threaded I/O request message */
505 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
506 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
507 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
508 typedef struct iojob
{
509 int type
; /* Request type, REDIS_IOJOB_* */
510 redisDb
*db
;/* Redis database */
511 robj
*key
; /* This I/O request is about swapping this key */
512 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
513 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
514 off_t page
; /* Swap page where to read/write the object */
515 off_t pages
; /* Swap pages needed to safe object. PREPARE_SWAP return val */
516 int canceled
; /* True if this command was canceled by blocking side of VM */
517 pthread_t thread
; /* ID of the thread processing this entry */
520 /*================================ Prototypes =============================== */
522 static void freeStringObject(robj
*o
);
523 static void freeListObject(robj
*o
);
524 static void freeSetObject(robj
*o
);
525 static void decrRefCount(void *o
);
526 static robj
*createObject(int type
, void *ptr
);
527 static void freeClient(redisClient
*c
);
528 static int rdbLoad(char *filename
);
529 static void addReply(redisClient
*c
, robj
*obj
);
530 static void addReplySds(redisClient
*c
, sds s
);
531 static void incrRefCount(robj
*o
);
532 static int rdbSaveBackground(char *filename
);
533 static robj
*createStringObject(char *ptr
, size_t len
);
534 static robj
*dupStringObject(robj
*o
);
535 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
536 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
537 static int syncWithMaster(void);
538 static robj
*tryObjectSharing(robj
*o
);
539 static int tryObjectEncoding(robj
*o
);
540 static robj
*getDecodedObject(robj
*o
);
541 static int removeExpire(redisDb
*db
, robj
*key
);
542 static int expireIfNeeded(redisDb
*db
, robj
*key
);
543 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
544 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
545 static int deleteKey(redisDb
*db
, robj
*key
);
546 static time_t getExpire(redisDb
*db
, robj
*key
);
547 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
548 static void updateSlavesWaitingBgsave(int bgsaveerr
);
549 static void freeMemoryIfNeeded(void);
550 static int processCommand(redisClient
*c
);
551 static void setupSigSegvAction(void);
552 static void rdbRemoveTempFile(pid_t childpid
);
553 static void aofRemoveTempFile(pid_t childpid
);
554 static size_t stringObjectLen(robj
*o
);
555 static void processInputBuffer(redisClient
*c
);
556 static zskiplist
*zslCreate(void);
557 static void zslFree(zskiplist
*zsl
);
558 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
559 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
560 static void initClientMultiState(redisClient
*c
);
561 static void freeClientMultiState(redisClient
*c
);
562 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
563 static void unblockClientWaitingData(redisClient
*c
);
564 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
565 static void vmInit(void);
566 static void vmMarkPagesFree(off_t page
, off_t count
);
567 static robj
*vmLoadObject(robj
*key
);
568 static robj
*vmPreviewObject(robj
*key
);
569 static int vmSwapOneObjectBlocking(void);
570 static int vmSwapOneObjectThreaded(void);
571 static int vmCanSwapOut(void);
572 static int tryFreeOneObjectFromFreelist(void);
573 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
574 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
575 static void vmCancelThreadedIOJob(robj
*o
);
576 static void lockThreadedIO(void);
577 static void unlockThreadedIO(void);
578 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
579 static void freeIOJob(iojob
*j
);
580 static void queueIOJob(iojob
*j
);
581 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
582 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
583 static void waitEmptyIOJobsQueue(void);
584 static void vmReopenSwapFile(void);
585 static int vmFreePage(off_t page
);
586 static int blockClientOnSwappedKeys(struct redisCommand
*cmd
, redisClient
*c
);
587 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
);
588 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
);
589 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
590 static struct redisCommand
*lookupCommand(char *name
);
591 static void call(redisClient
*c
, struct redisCommand
*cmd
);
592 static void resetClient(redisClient
*c
);
594 static void authCommand(redisClient
*c
);
595 static void pingCommand(redisClient
*c
);
596 static void echoCommand(redisClient
*c
);
597 static void setCommand(redisClient
*c
);
598 static void setnxCommand(redisClient
*c
);
599 static void getCommand(redisClient
*c
);
600 static void delCommand(redisClient
*c
);
601 static void existsCommand(redisClient
*c
);
602 static void incrCommand(redisClient
*c
);
603 static void decrCommand(redisClient
*c
);
604 static void incrbyCommand(redisClient
*c
);
605 static void decrbyCommand(redisClient
*c
);
606 static void selectCommand(redisClient
*c
);
607 static void randomkeyCommand(redisClient
*c
);
608 static void keysCommand(redisClient
*c
);
609 static void dbsizeCommand(redisClient
*c
);
610 static void lastsaveCommand(redisClient
*c
);
611 static void saveCommand(redisClient
*c
);
612 static void bgsaveCommand(redisClient
*c
);
613 static void bgrewriteaofCommand(redisClient
*c
);
614 static void shutdownCommand(redisClient
*c
);
615 static void moveCommand(redisClient
*c
);
616 static void renameCommand(redisClient
*c
);
617 static void renamenxCommand(redisClient
*c
);
618 static void lpushCommand(redisClient
*c
);
619 static void rpushCommand(redisClient
*c
);
620 static void lpopCommand(redisClient
*c
);
621 static void rpopCommand(redisClient
*c
);
622 static void llenCommand(redisClient
*c
);
623 static void lindexCommand(redisClient
*c
);
624 static void lrangeCommand(redisClient
*c
);
625 static void ltrimCommand(redisClient
*c
);
626 static void typeCommand(redisClient
*c
);
627 static void lsetCommand(redisClient
*c
);
628 static void saddCommand(redisClient
*c
);
629 static void sremCommand(redisClient
*c
);
630 static void smoveCommand(redisClient
*c
);
631 static void sismemberCommand(redisClient
*c
);
632 static void scardCommand(redisClient
*c
);
633 static void spopCommand(redisClient
*c
);
634 static void srandmemberCommand(redisClient
*c
);
635 static void sinterCommand(redisClient
*c
);
636 static void sinterstoreCommand(redisClient
*c
);
637 static void sunionCommand(redisClient
*c
);
638 static void sunionstoreCommand(redisClient
*c
);
639 static void sdiffCommand(redisClient
*c
);
640 static void sdiffstoreCommand(redisClient
*c
);
641 static void syncCommand(redisClient
*c
);
642 static void flushdbCommand(redisClient
*c
);
643 static void flushallCommand(redisClient
*c
);
644 static void sortCommand(redisClient
*c
);
645 static void lremCommand(redisClient
*c
);
646 static void rpoplpushcommand(redisClient
*c
);
647 static void infoCommand(redisClient
*c
);
648 static void mgetCommand(redisClient
*c
);
649 static void monitorCommand(redisClient
*c
);
650 static void expireCommand(redisClient
*c
);
651 static void expireatCommand(redisClient
*c
);
652 static void getsetCommand(redisClient
*c
);
653 static void ttlCommand(redisClient
*c
);
654 static void slaveofCommand(redisClient
*c
);
655 static void debugCommand(redisClient
*c
);
656 static void msetCommand(redisClient
*c
);
657 static void msetnxCommand(redisClient
*c
);
658 static void zaddCommand(redisClient
*c
);
659 static void zincrbyCommand(redisClient
*c
);
660 static void zrangeCommand(redisClient
*c
);
661 static void zrangebyscoreCommand(redisClient
*c
);
662 static void zcountCommand(redisClient
*c
);
663 static void zrevrangeCommand(redisClient
*c
);
664 static void zcardCommand(redisClient
*c
);
665 static void zremCommand(redisClient
*c
);
666 static void zscoreCommand(redisClient
*c
);
667 static void zremrangebyscoreCommand(redisClient
*c
);
668 static void multiCommand(redisClient
*c
);
669 static void execCommand(redisClient
*c
);
670 static void discardCommand(redisClient
*c
);
671 static void blpopCommand(redisClient
*c
);
672 static void brpopCommand(redisClient
*c
);
673 static void appendCommand(redisClient
*c
);
674 static void substrCommand(redisClient
*c
);
675 static void zrankCommand(redisClient
*c
);
676 static void hsetCommand(redisClient
*c
);
677 static void hgetCommand(redisClient
*c
);
679 /*================================= Globals ================================= */
682 static struct redisServer server
; /* server global state */
683 static struct redisCommand cmdTable
[] = {
684 {"get",getCommand
,2,REDIS_CMD_INLINE
,1,1,1},
685 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,0,0,0},
686 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,0,0,0},
687 {"append",appendCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
688 {"substr",substrCommand
,4,REDIS_CMD_INLINE
,1,1,1},
689 {"del",delCommand
,-2,REDIS_CMD_INLINE
,0,0,0},
690 {"exists",existsCommand
,2,REDIS_CMD_INLINE
,1,1,1},
691 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1},
692 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1},
693 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
,1,-1,1},
694 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
695 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
696 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
,1,1,1},
697 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
,1,1,1},
698 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
,1,1,1},
699 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
,1,1,1},
700 {"llen",llenCommand
,2,REDIS_CMD_INLINE
,1,1,1},
701 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
,1,1,1},
702 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
703 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
,1,1,1},
704 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
,1,1,1},
705 {"lrem",lremCommand
,4,REDIS_CMD_BULK
,1,1,1},
706 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,2,1},
707 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
708 {"srem",sremCommand
,3,REDIS_CMD_BULK
,1,1,1},
709 {"smove",smoveCommand
,4,REDIS_CMD_BULK
,1,2,1},
710 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
,1,1,1},
711 {"scard",scardCommand
,2,REDIS_CMD_INLINE
,1,1,1},
712 {"spop",spopCommand
,2,REDIS_CMD_INLINE
,1,1,1},
713 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
,1,1,1},
714 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,-1,1},
715 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,2,-1,1},
716 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,-1,1},
717 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,2,-1,1},
718 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,-1,1},
719 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,2,-1,1},
720 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
,1,1,1},
721 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
722 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
723 {"zrem",zremCommand
,3,REDIS_CMD_BULK
,1,1,1},
724 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
,1,1,1},
725 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
,1,1,1},
726 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
,1,1,1},
727 {"zcount",zcountCommand
,4,REDIS_CMD_INLINE
,1,1,1},
728 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
,1,1,1},
729 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
,1,1,1},
730 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
731 {"zrank",zrankCommand
,3,REDIS_CMD_INLINE
,1,1,1},
732 {"hset",hsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
733 {"hget",hgetCommand
,3,REDIS_CMD_BULK
,1,1,1},
734 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1},
735 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1},
736 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,1,1},
737 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,-1,2},
738 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,1,-1,2},
739 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
,0,0,0},
740 {"select",selectCommand
,2,REDIS_CMD_INLINE
,0,0,0},
741 {"move",moveCommand
,3,REDIS_CMD_INLINE
,1,1,1},
742 {"rename",renameCommand
,3,REDIS_CMD_INLINE
,1,1,1},
743 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
,1,1,1},
744 {"expire",expireCommand
,3,REDIS_CMD_INLINE
,0,0,0},
745 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
,0,0,0},
746 {"keys",keysCommand
,2,REDIS_CMD_INLINE
,0,0,0},
747 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
,0,0,0},
748 {"auth",authCommand
,2,REDIS_CMD_INLINE
,0,0,0},
749 {"ping",pingCommand
,1,REDIS_CMD_INLINE
,0,0,0},
750 {"echo",echoCommand
,2,REDIS_CMD_BULK
,0,0,0},
751 {"save",saveCommand
,1,REDIS_CMD_INLINE
,0,0,0},
752 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
,0,0,0},
753 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
,0,0,0},
754 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
,0,0,0},
755 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
,0,0,0},
756 {"type",typeCommand
,2,REDIS_CMD_INLINE
,1,1,1},
757 {"multi",multiCommand
,1,REDIS_CMD_INLINE
,0,0,0},
758 {"exec",execCommand
,1,REDIS_CMD_INLINE
,0,0,0},
759 {"discard",discardCommand
,1,REDIS_CMD_INLINE
,0,0,0},
760 {"sync",syncCommand
,1,REDIS_CMD_INLINE
,0,0,0},
761 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
,0,0,0},
762 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
,0,0,0},
763 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,1,1,1},
764 {"info",infoCommand
,1,REDIS_CMD_INLINE
,0,0,0},
765 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
,0,0,0},
766 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
,1,1,1},
767 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
,0,0,0},
768 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
,0,0,0},
769 {NULL
,NULL
,0,0,0,0,0}
772 /*============================ Utility functions ============================ */
774 /* Glob-style pattern matching. */
775 int stringmatchlen(const char *pattern
, int patternLen
,
776 const char *string
, int stringLen
, int nocase
)
781 while (pattern
[1] == '*') {
786 return 1; /* match */
788 if (stringmatchlen(pattern
+1, patternLen
-1,
789 string
, stringLen
, nocase
))
790 return 1; /* match */
794 return 0; /* no match */
798 return 0; /* no match */
808 not = pattern
[0] == '^';
815 if (pattern
[0] == '\\') {
818 if (pattern
[0] == string
[0])
820 } else if (pattern
[0] == ']') {
822 } else if (patternLen
== 0) {
826 } else if (pattern
[1] == '-' && patternLen
>= 3) {
827 int start
= pattern
[0];
828 int end
= pattern
[2];
836 start
= tolower(start
);
842 if (c
>= start
&& c
<= end
)
846 if (pattern
[0] == string
[0])
849 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
859 return 0; /* no match */
865 if (patternLen
>= 2) {
872 if (pattern
[0] != string
[0])
873 return 0; /* no match */
875 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
876 return 0; /* no match */
884 if (stringLen
== 0) {
885 while(*pattern
== '*') {
892 if (patternLen
== 0 && stringLen
== 0)
897 static void redisLog(int level
, const char *fmt
, ...) {
901 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
905 if (level
>= server
.verbosity
) {
911 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
912 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
913 vfprintf(fp
, fmt
, ap
);
919 if (server
.logfile
) fclose(fp
);
922 /*====================== Hash table type implementation ==================== */
924 /* This is an hash table type that uses the SDS dynamic strings libary as
925 * keys and radis objects as values (objects can hold SDS strings,
928 static void dictVanillaFree(void *privdata
, void *val
)
930 DICT_NOTUSED(privdata
);
934 static void dictListDestructor(void *privdata
, void *val
)
936 DICT_NOTUSED(privdata
);
937 listRelease((list
*)val
);
940 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
944 DICT_NOTUSED(privdata
);
946 l1
= sdslen((sds
)key1
);
947 l2
= sdslen((sds
)key2
);
948 if (l1
!= l2
) return 0;
949 return memcmp(key1
, key2
, l1
) == 0;
952 static void dictRedisObjectDestructor(void *privdata
, void *val
)
954 DICT_NOTUSED(privdata
);
956 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
960 static int dictObjKeyCompare(void *privdata
, const void *key1
,
963 const robj
*o1
= key1
, *o2
= key2
;
964 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
967 static unsigned int dictObjHash(const void *key
) {
969 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
972 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
975 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
978 o1
= getDecodedObject(o1
);
979 o2
= getDecodedObject(o2
);
980 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
986 static unsigned int dictEncObjHash(const void *key
) {
987 robj
*o
= (robj
*) key
;
989 if (o
->encoding
== REDIS_ENCODING_RAW
) {
990 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
992 if (o
->encoding
== REDIS_ENCODING_INT
) {
996 len
= snprintf(buf
,32,"%ld",(long)o
->ptr
);
997 return dictGenHashFunction((unsigned char*)buf
, len
);
1001 o
= getDecodedObject(o
);
1002 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1009 /* Sets type and expires */
1010 static dictType setDictType
= {
1011 dictEncObjHash
, /* hash function */
1014 dictEncObjKeyCompare
, /* key compare */
1015 dictRedisObjectDestructor
, /* key destructor */
1016 NULL
/* val destructor */
1019 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1020 static dictType zsetDictType
= {
1021 dictEncObjHash
, /* hash function */
1024 dictEncObjKeyCompare
, /* key compare */
1025 dictRedisObjectDestructor
, /* key destructor */
1026 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
1030 static dictType dbDictType
= {
1031 dictObjHash
, /* hash function */
1034 dictObjKeyCompare
, /* key compare */
1035 dictRedisObjectDestructor
, /* key destructor */
1036 dictRedisObjectDestructor
/* val destructor */
1040 static dictType keyptrDictType
= {
1041 dictObjHash
, /* hash function */
1044 dictObjKeyCompare
, /* key compare */
1045 dictRedisObjectDestructor
, /* key destructor */
1046 NULL
/* val destructor */
1049 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1050 static dictType hashDictType
= {
1051 dictEncObjHash
, /* hash function */
1054 dictEncObjKeyCompare
, /* key compare */
1055 dictRedisObjectDestructor
, /* key destructor */
1056 dictRedisObjectDestructor
/* val destructor */
1059 /* Keylist hash table type has unencoded redis objects as keys and
1060 * lists as values. It's used for blocking operations (BLPOP) and to
1061 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1062 static dictType keylistDictType
= {
1063 dictObjHash
, /* hash function */
1066 dictObjKeyCompare
, /* key compare */
1067 dictRedisObjectDestructor
, /* key destructor */
1068 dictListDestructor
/* val destructor */
1071 /* ========================= Random utility functions ======================= */
1073 /* Redis generally does not try to recover from out of memory conditions
1074 * when allocating objects or strings, it is not clear if it will be possible
1075 * to report this condition to the client since the networking layer itself
1076 * is based on heap allocation for send buffers, so we simply abort.
1077 * At least the code will be simpler to read... */
1078 static void oom(const char *msg
) {
1079 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1084 /* ====================== Redis server networking stuff ===================== */
1085 static void closeTimedoutClients(void) {
1088 time_t now
= time(NULL
);
1091 listRewind(server
.clients
,&li
);
1092 while ((ln
= listNext(&li
)) != NULL
) {
1093 c
= listNodeValue(ln
);
1094 if (server
.maxidletime
&&
1095 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1096 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1097 (now
- c
->lastinteraction
> server
.maxidletime
))
1099 redisLog(REDIS_VERBOSE
,"Closing idle client");
1101 } else if (c
->flags
& REDIS_BLOCKED
) {
1102 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1103 addReply(c
,shared
.nullmultibulk
);
1104 unblockClientWaitingData(c
);
1110 static int htNeedsResize(dict
*dict
) {
1111 long long size
, used
;
1113 size
= dictSlots(dict
);
1114 used
= dictSize(dict
);
1115 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1116 (used
*100/size
< REDIS_HT_MINFILL
));
1119 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1120 * we resize the hash table to save memory */
1121 static void tryResizeHashTables(void) {
1124 for (j
= 0; j
< server
.dbnum
; j
++) {
1125 if (htNeedsResize(server
.db
[j
].dict
)) {
1126 redisLog(REDIS_VERBOSE
,"The hash table %d is too sparse, resize it...",j
);
1127 dictResize(server
.db
[j
].dict
);
1128 redisLog(REDIS_VERBOSE
,"Hash table %d resized.",j
);
1130 if (htNeedsResize(server
.db
[j
].expires
))
1131 dictResize(server
.db
[j
].expires
);
1135 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1136 void backgroundSaveDoneHandler(int statloc
) {
1137 int exitcode
= WEXITSTATUS(statloc
);
1138 int bysignal
= WIFSIGNALED(statloc
);
1140 if (!bysignal
&& exitcode
== 0) {
1141 redisLog(REDIS_NOTICE
,
1142 "Background saving terminated with success");
1144 server
.lastsave
= time(NULL
);
1145 } else if (!bysignal
&& exitcode
!= 0) {
1146 redisLog(REDIS_WARNING
, "Background saving error");
1148 redisLog(REDIS_WARNING
,
1149 "Background saving terminated by signal");
1150 rdbRemoveTempFile(server
.bgsavechildpid
);
1152 server
.bgsavechildpid
= -1;
1153 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1154 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1155 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1158 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1160 void backgroundRewriteDoneHandler(int statloc
) {
1161 int exitcode
= WEXITSTATUS(statloc
);
1162 int bysignal
= WIFSIGNALED(statloc
);
1164 if (!bysignal
&& exitcode
== 0) {
1168 redisLog(REDIS_NOTICE
,
1169 "Background append only file rewriting terminated with success");
1170 /* Now it's time to flush the differences accumulated by the parent */
1171 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1172 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1174 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1177 /* Flush our data... */
1178 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1179 (signed) sdslen(server
.bgrewritebuf
)) {
1180 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
));
1184 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1185 /* Now our work is to rename the temp file into the stable file. And
1186 * switch the file descriptor used by the server for append only. */
1187 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1188 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1192 /* Mission completed... almost */
1193 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1194 if (server
.appendfd
!= -1) {
1195 /* If append only is actually enabled... */
1196 close(server
.appendfd
);
1197 server
.appendfd
= fd
;
1199 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1200 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1202 /* If append only is disabled we just generate a dump in this
1203 * format. Why not? */
1206 } else if (!bysignal
&& exitcode
!= 0) {
1207 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1209 redisLog(REDIS_WARNING
,
1210 "Background append only file rewriting terminated by signal");
1213 sdsfree(server
.bgrewritebuf
);
1214 server
.bgrewritebuf
= sdsempty();
1215 aofRemoveTempFile(server
.bgrewritechildpid
);
1216 server
.bgrewritechildpid
= -1;
1219 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1220 int j
, loops
= server
.cronloops
++;
1221 REDIS_NOTUSED(eventLoop
);
1223 REDIS_NOTUSED(clientData
);
1225 /* We take a cached value of the unix time in the global state because
1226 * with virtual memory and aging there is to store the current time
1227 * in objects at every object access, and accuracy is not needed.
1228 * To access a global var is faster than calling time(NULL) */
1229 server
.unixtime
= time(NULL
);
1231 /* Show some info about non-empty databases */
1232 for (j
= 0; j
< server
.dbnum
; j
++) {
1233 long long size
, used
, vkeys
;
1235 size
= dictSlots(server
.db
[j
].dict
);
1236 used
= dictSize(server
.db
[j
].dict
);
1237 vkeys
= dictSize(server
.db
[j
].expires
);
1238 if (!(loops
% 5) && (used
|| vkeys
)) {
1239 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1240 /* dictPrintStats(server.dict); */
1244 /* We don't want to resize the hash tables while a bacground saving
1245 * is in progress: the saving child is created using fork() that is
1246 * implemented with a copy-on-write semantic in most modern systems, so
1247 * if we resize the HT while there is the saving child at work actually
1248 * a lot of memory movements in the parent will cause a lot of pages
1250 if (server
.bgsavechildpid
== -1) tryResizeHashTables();
1252 /* Show information about connected clients */
1254 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1255 listLength(server
.clients
)-listLength(server
.slaves
),
1256 listLength(server
.slaves
),
1257 zmalloc_used_memory(),
1258 dictSize(server
.sharingpool
));
1261 /* Close connections of timedout clients */
1262 if ((server
.maxidletime
&& !(loops
% 10)) || server
.blpop_blocked_clients
)
1263 closeTimedoutClients();
1265 /* Check if a background saving or AOF rewrite in progress terminated */
1266 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1270 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1271 if (pid
== server
.bgsavechildpid
) {
1272 backgroundSaveDoneHandler(statloc
);
1274 backgroundRewriteDoneHandler(statloc
);
1278 /* If there is not a background saving in progress check if
1279 * we have to save now */
1280 time_t now
= time(NULL
);
1281 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1282 struct saveparam
*sp
= server
.saveparams
+j
;
1284 if (server
.dirty
>= sp
->changes
&&
1285 now
-server
.lastsave
> sp
->seconds
) {
1286 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1287 sp
->changes
, sp
->seconds
);
1288 rdbSaveBackground(server
.dbfilename
);
1294 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1295 * will use few CPU cycles if there are few expiring keys, otherwise
1296 * it will get more aggressive to avoid that too much memory is used by
1297 * keys that can be removed from the keyspace. */
1298 for (j
= 0; j
< server
.dbnum
; j
++) {
1300 redisDb
*db
= server
.db
+j
;
1302 /* Continue to expire if at the end of the cycle more than 25%
1303 * of the keys were expired. */
1305 long num
= dictSize(db
->expires
);
1306 time_t now
= time(NULL
);
1309 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1310 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1315 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1316 t
= (time_t) dictGetEntryVal(de
);
1318 deleteKey(db
,dictGetEntryKey(de
));
1322 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1325 /* Swap a few keys on disk if we are over the memory limit and VM
1326 * is enbled. Try to free objects from the free list first. */
1327 if (vmCanSwapOut()) {
1328 while (server
.vm_enabled
&& zmalloc_used_memory() >
1329 server
.vm_max_memory
)
1333 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1334 retval
= (server
.vm_max_threads
== 0) ?
1335 vmSwapOneObjectBlocking() :
1336 vmSwapOneObjectThreaded();
1337 if (retval
== REDIS_ERR
&& (loops
% 30) == 0 &&
1338 zmalloc_used_memory() >
1339 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1341 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1343 /* Note that when using threade I/O we free just one object,
1344 * because anyway when the I/O thread in charge to swap this
1345 * object out will finish, the handler of completed jobs
1346 * will try to swap more objects if we are still out of memory. */
1347 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1351 /* Check if we should connect to a MASTER */
1352 if (server
.replstate
== REDIS_REPL_CONNECT
) {
1353 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1354 if (syncWithMaster() == REDIS_OK
) {
1355 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1361 /* This function gets called every time Redis is entering the
1362 * main loop of the event driven library, that is, before to sleep
1363 * for ready file descriptors. */
1364 static void beforeSleep(struct aeEventLoop
*eventLoop
) {
1365 REDIS_NOTUSED(eventLoop
);
1367 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
1371 listRewind(server
.io_ready_clients
,&li
);
1372 while((ln
= listNext(&li
))) {
1373 redisClient
*c
= ln
->value
;
1374 struct redisCommand
*cmd
;
1376 /* Resume the client. */
1377 listDelNode(server
.io_ready_clients
,ln
);
1378 c
->flags
&= (~REDIS_IO_WAIT
);
1379 server
.vm_blocked_clients
--;
1380 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1381 readQueryFromClient
, c
);
1382 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1383 assert(cmd
!= NULL
);
1386 /* There may be more data to process in the input buffer. */
1387 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
1388 processInputBuffer(c
);
1393 static void createSharedObjects(void) {
1394 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1395 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1396 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1397 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1398 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1399 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1400 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1401 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1402 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1403 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1404 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1405 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1406 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1407 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1408 "-ERR no such key\r\n"));
1409 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1410 "-ERR syntax error\r\n"));
1411 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1412 "-ERR source and destination objects are the same\r\n"));
1413 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1414 "-ERR index out of range\r\n"));
1415 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1416 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1417 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1418 shared
.select0
= createStringObject("select 0\r\n",10);
1419 shared
.select1
= createStringObject("select 1\r\n",10);
1420 shared
.select2
= createStringObject("select 2\r\n",10);
1421 shared
.select3
= createStringObject("select 3\r\n",10);
1422 shared
.select4
= createStringObject("select 4\r\n",10);
1423 shared
.select5
= createStringObject("select 5\r\n",10);
1424 shared
.select6
= createStringObject("select 6\r\n",10);
1425 shared
.select7
= createStringObject("select 7\r\n",10);
1426 shared
.select8
= createStringObject("select 8\r\n",10);
1427 shared
.select9
= createStringObject("select 9\r\n",10);
1430 static void appendServerSaveParams(time_t seconds
, int changes
) {
1431 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1432 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1433 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1434 server
.saveparamslen
++;
1437 static void resetServerSaveParams() {
1438 zfree(server
.saveparams
);
1439 server
.saveparams
= NULL
;
1440 server
.saveparamslen
= 0;
1443 static void initServerConfig() {
1444 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1445 server
.port
= REDIS_SERVERPORT
;
1446 server
.verbosity
= REDIS_VERBOSE
;
1447 server
.maxidletime
= REDIS_MAXIDLETIME
;
1448 server
.saveparams
= NULL
;
1449 server
.logfile
= NULL
; /* NULL = log on standard output */
1450 server
.bindaddr
= NULL
;
1451 server
.glueoutputbuf
= 1;
1452 server
.daemonize
= 0;
1453 server
.appendonly
= 0;
1454 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1455 server
.lastfsync
= time(NULL
);
1456 server
.appendfd
= -1;
1457 server
.appendseldb
= -1; /* Make sure the first time will not match */
1458 server
.pidfile
= "/var/run/redis.pid";
1459 server
.dbfilename
= "dump.rdb";
1460 server
.appendfilename
= "appendonly.aof";
1461 server
.requirepass
= NULL
;
1462 server
.shareobjects
= 0;
1463 server
.rdbcompression
= 1;
1464 server
.sharingpoolsize
= 1024;
1465 server
.maxclients
= 0;
1466 server
.blpop_blocked_clients
= 0;
1467 server
.maxmemory
= 0;
1468 server
.vm_enabled
= 0;
1469 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
1470 server
.vm_page_size
= 256; /* 256 bytes per page */
1471 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1472 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1473 server
.vm_max_threads
= 4;
1474 server
.vm_blocked_clients
= 0;
1475 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
1476 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
1478 resetServerSaveParams();
1480 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1481 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1482 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1483 /* Replication related */
1485 server
.masterauth
= NULL
;
1486 server
.masterhost
= NULL
;
1487 server
.masterport
= 6379;
1488 server
.master
= NULL
;
1489 server
.replstate
= REDIS_REPL_NONE
;
1491 /* Double constants initialization */
1493 R_PosInf
= 1.0/R_Zero
;
1494 R_NegInf
= -1.0/R_Zero
;
1495 R_Nan
= R_Zero
/R_Zero
;
1498 static void initServer() {
1501 signal(SIGHUP
, SIG_IGN
);
1502 signal(SIGPIPE
, SIG_IGN
);
1503 setupSigSegvAction();
1505 server
.devnull
= fopen("/dev/null","w");
1506 if (server
.devnull
== NULL
) {
1507 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1510 server
.clients
= listCreate();
1511 server
.slaves
= listCreate();
1512 server
.monitors
= listCreate();
1513 server
.objfreelist
= listCreate();
1514 createSharedObjects();
1515 server
.el
= aeCreateEventLoop();
1516 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1517 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1518 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1519 if (server
.fd
== -1) {
1520 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1523 for (j
= 0; j
< server
.dbnum
; j
++) {
1524 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
1525 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1526 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1527 if (server
.vm_enabled
)
1528 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
1529 server
.db
[j
].id
= j
;
1531 server
.cronloops
= 0;
1532 server
.bgsavechildpid
= -1;
1533 server
.bgrewritechildpid
= -1;
1534 server
.bgrewritebuf
= sdsempty();
1535 server
.lastsave
= time(NULL
);
1537 server
.stat_numcommands
= 0;
1538 server
.stat_numconnections
= 0;
1539 server
.stat_starttime
= time(NULL
);
1540 server
.unixtime
= time(NULL
);
1541 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1542 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1543 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1545 if (server
.appendonly
) {
1546 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1547 if (server
.appendfd
== -1) {
1548 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1554 if (server
.vm_enabled
) vmInit();
1557 /* Empty the whole database */
1558 static long long emptyDb() {
1560 long long removed
= 0;
1562 for (j
= 0; j
< server
.dbnum
; j
++) {
1563 removed
+= dictSize(server
.db
[j
].dict
);
1564 dictEmpty(server
.db
[j
].dict
);
1565 dictEmpty(server
.db
[j
].expires
);
1570 static int yesnotoi(char *s
) {
1571 if (!strcasecmp(s
,"yes")) return 1;
1572 else if (!strcasecmp(s
,"no")) return 0;
1576 /* I agree, this is a very rudimental way to load a configuration...
1577 will improve later if the config gets more complex */
1578 static void loadServerConfig(char *filename
) {
1580 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1584 if (filename
[0] == '-' && filename
[1] == '\0')
1587 if ((fp
= fopen(filename
,"r")) == NULL
) {
1588 redisLog(REDIS_WARNING
,"Fatal error, can't open config file");
1593 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1599 line
= sdstrim(line
," \t\r\n");
1601 /* Skip comments and blank lines*/
1602 if (line
[0] == '#' || line
[0] == '\0') {
1607 /* Split into arguments */
1608 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1609 sdstolower(argv
[0]);
1611 /* Execute config directives */
1612 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1613 server
.maxidletime
= atoi(argv
[1]);
1614 if (server
.maxidletime
< 0) {
1615 err
= "Invalid timeout value"; goto loaderr
;
1617 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1618 server
.port
= atoi(argv
[1]);
1619 if (server
.port
< 1 || server
.port
> 65535) {
1620 err
= "Invalid port"; goto loaderr
;
1622 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1623 server
.bindaddr
= zstrdup(argv
[1]);
1624 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1625 int seconds
= atoi(argv
[1]);
1626 int changes
= atoi(argv
[2]);
1627 if (seconds
< 1 || changes
< 0) {
1628 err
= "Invalid save parameters"; goto loaderr
;
1630 appendServerSaveParams(seconds
,changes
);
1631 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1632 if (chdir(argv
[1]) == -1) {
1633 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1634 argv
[1], strerror(errno
));
1637 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1638 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1639 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1640 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1641 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1643 err
= "Invalid log level. Must be one of debug, notice, warning";
1646 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1649 server
.logfile
= zstrdup(argv
[1]);
1650 if (!strcasecmp(server
.logfile
,"stdout")) {
1651 zfree(server
.logfile
);
1652 server
.logfile
= NULL
;
1654 if (server
.logfile
) {
1655 /* Test if we are able to open the file. The server will not
1656 * be able to abort just for this problem later... */
1657 logfp
= fopen(server
.logfile
,"a");
1658 if (logfp
== NULL
) {
1659 err
= sdscatprintf(sdsempty(),
1660 "Can't open the log file: %s", strerror(errno
));
1665 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1666 server
.dbnum
= atoi(argv
[1]);
1667 if (server
.dbnum
< 1) {
1668 err
= "Invalid number of databases"; goto loaderr
;
1670 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1671 server
.maxclients
= atoi(argv
[1]);
1672 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1673 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1674 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1675 server
.masterhost
= sdsnew(argv
[1]);
1676 server
.masterport
= atoi(argv
[2]);
1677 server
.replstate
= REDIS_REPL_CONNECT
;
1678 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1679 server
.masterauth
= zstrdup(argv
[1]);
1680 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1681 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1682 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1684 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1685 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1686 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1688 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1689 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1690 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1692 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1693 server
.sharingpoolsize
= atoi(argv
[1]);
1694 if (server
.sharingpoolsize
< 1) {
1695 err
= "invalid object sharing pool size"; goto loaderr
;
1697 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1698 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1699 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1701 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1702 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1703 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1705 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1706 if (!strcasecmp(argv
[1],"no")) {
1707 server
.appendfsync
= APPENDFSYNC_NO
;
1708 } else if (!strcasecmp(argv
[1],"always")) {
1709 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1710 } else if (!strcasecmp(argv
[1],"everysec")) {
1711 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1713 err
= "argument must be 'no', 'always' or 'everysec'";
1716 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1717 server
.requirepass
= zstrdup(argv
[1]);
1718 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1719 server
.pidfile
= zstrdup(argv
[1]);
1720 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1721 server
.dbfilename
= zstrdup(argv
[1]);
1722 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1723 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1724 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1726 } else if (!strcasecmp(argv
[0],"vm-swap-file") && argc
== 2) {
1727 zfree(server
.vm_swap_file
);
1728 server
.vm_swap_file
= zstrdup(argv
[1]);
1729 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1730 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1731 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1732 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1733 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1734 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1735 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1736 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1737 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-entries") && argc
== 2){
1738 server
.hash_max_zipmap_entries
= strtol(argv
[1], NULL
, 10);
1739 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-value") && argc
== 2){
1740 server
.hash_max_zipmap_value
= strtol(argv
[1], NULL
, 10);
1741 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1742 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1744 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1746 for (j
= 0; j
< argc
; j
++)
1751 if (fp
!= stdin
) fclose(fp
);
1755 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1756 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1757 fprintf(stderr
, ">>> '%s'\n", line
);
1758 fprintf(stderr
, "%s\n", err
);
1762 static void freeClientArgv(redisClient
*c
) {
1765 for (j
= 0; j
< c
->argc
; j
++)
1766 decrRefCount(c
->argv
[j
]);
1767 for (j
= 0; j
< c
->mbargc
; j
++)
1768 decrRefCount(c
->mbargv
[j
]);
1773 static void freeClient(redisClient
*c
) {
1776 /* Note that if the client we are freeing is blocked into a blocking
1777 * call, we have to set querybuf to NULL *before* to call
1778 * unblockClientWaitingData() to avoid processInputBuffer() will get
1779 * called. Also it is important to remove the file events after
1780 * this, because this call adds the READABLE event. */
1781 sdsfree(c
->querybuf
);
1783 if (c
->flags
& REDIS_BLOCKED
)
1784 unblockClientWaitingData(c
);
1786 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1787 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1788 listRelease(c
->reply
);
1791 /* Remove from the list of clients */
1792 ln
= listSearchKey(server
.clients
,c
);
1793 redisAssert(ln
!= NULL
);
1794 listDelNode(server
.clients
,ln
);
1795 /* Remove from the list of clients waiting for swapped keys */
1796 if (c
->flags
& REDIS_IO_WAIT
&& listLength(c
->io_keys
) == 0) {
1797 ln
= listSearchKey(server
.io_ready_clients
,c
);
1799 listDelNode(server
.io_ready_clients
,ln
);
1800 server
.vm_blocked_clients
--;
1803 while (server
.vm_enabled
&& listLength(c
->io_keys
)) {
1804 ln
= listFirst(c
->io_keys
);
1805 dontWaitForSwappedKey(c
,ln
->value
);
1807 listRelease(c
->io_keys
);
1809 if (c
->flags
& REDIS_SLAVE
) {
1810 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1812 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1813 ln
= listSearchKey(l
,c
);
1814 redisAssert(ln
!= NULL
);
1817 if (c
->flags
& REDIS_MASTER
) {
1818 server
.master
= NULL
;
1819 server
.replstate
= REDIS_REPL_CONNECT
;
1823 freeClientMultiState(c
);
1827 #define GLUEREPLY_UP_TO (1024)
1828 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1830 char buf
[GLUEREPLY_UP_TO
];
1835 listRewind(c
->reply
,&li
);
1836 while((ln
= listNext(&li
))) {
1840 objlen
= sdslen(o
->ptr
);
1841 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1842 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1844 listDelNode(c
->reply
,ln
);
1846 if (copylen
== 0) return;
1850 /* Now the output buffer is empty, add the new single element */
1851 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1852 listAddNodeHead(c
->reply
,o
);
1855 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1856 redisClient
*c
= privdata
;
1857 int nwritten
= 0, totwritten
= 0, objlen
;
1860 REDIS_NOTUSED(mask
);
1862 /* Use writev() if we have enough buffers to send */
1863 if (!server
.glueoutputbuf
&&
1864 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1865 !(c
->flags
& REDIS_MASTER
))
1867 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1871 while(listLength(c
->reply
)) {
1872 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1873 glueReplyBuffersIfNeeded(c
);
1875 o
= listNodeValue(listFirst(c
->reply
));
1876 objlen
= sdslen(o
->ptr
);
1879 listDelNode(c
->reply
,listFirst(c
->reply
));
1883 if (c
->flags
& REDIS_MASTER
) {
1884 /* Don't reply to a master */
1885 nwritten
= objlen
- c
->sentlen
;
1887 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1888 if (nwritten
<= 0) break;
1890 c
->sentlen
+= nwritten
;
1891 totwritten
+= nwritten
;
1892 /* If we fully sent the object on head go to the next one */
1893 if (c
->sentlen
== objlen
) {
1894 listDelNode(c
->reply
,listFirst(c
->reply
));
1897 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1898 * bytes, in a single threaded server it's a good idea to serve
1899 * other clients as well, even if a very large request comes from
1900 * super fast link that is always able to accept data (in real world
1901 * scenario think about 'KEYS *' against the loopback interfae) */
1902 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1904 if (nwritten
== -1) {
1905 if (errno
== EAGAIN
) {
1908 redisLog(REDIS_VERBOSE
,
1909 "Error writing to client: %s", strerror(errno
));
1914 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1915 if (listLength(c
->reply
) == 0) {
1917 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1921 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1923 redisClient
*c
= privdata
;
1924 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1926 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1927 int offset
, ion
= 0;
1929 REDIS_NOTUSED(mask
);
1932 while (listLength(c
->reply
)) {
1933 offset
= c
->sentlen
;
1937 /* fill-in the iov[] array */
1938 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1939 o
= listNodeValue(node
);
1940 objlen
= sdslen(o
->ptr
);
1942 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1945 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1946 break; /* no more iovecs */
1948 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1949 iov
[ion
].iov_len
= objlen
- offset
;
1950 willwrite
+= objlen
- offset
;
1951 offset
= 0; /* just for the first item */
1958 /* write all collected blocks at once */
1959 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
1960 if (errno
!= EAGAIN
) {
1961 redisLog(REDIS_VERBOSE
,
1962 "Error writing to client: %s", strerror(errno
));
1969 totwritten
+= nwritten
;
1970 offset
= c
->sentlen
;
1972 /* remove written robjs from c->reply */
1973 while (nwritten
&& listLength(c
->reply
)) {
1974 o
= listNodeValue(listFirst(c
->reply
));
1975 objlen
= sdslen(o
->ptr
);
1977 if(nwritten
>= objlen
- offset
) {
1978 listDelNode(c
->reply
, listFirst(c
->reply
));
1979 nwritten
-= objlen
- offset
;
1983 c
->sentlen
+= nwritten
;
1991 c
->lastinteraction
= time(NULL
);
1993 if (listLength(c
->reply
) == 0) {
1995 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1999 static struct redisCommand
*lookupCommand(char *name
) {
2001 while(cmdTable
[j
].name
!= NULL
) {
2002 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
2008 /* resetClient prepare the client to process the next command */
2009 static void resetClient(redisClient
*c
) {
2015 /* Call() is the core of Redis execution of a command */
2016 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
2019 dirty
= server
.dirty
;
2021 if (server
.appendonly
&& server
.dirty
-dirty
)
2022 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2023 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
2024 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2025 if (listLength(server
.monitors
))
2026 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2027 server
.stat_numcommands
++;
2030 /* If this function gets called we already read a whole
2031 * command, argments are in the client argv/argc fields.
2032 * processCommand() execute the command or prepare the
2033 * server for a bulk read from the client.
2035 * If 1 is returned the client is still alive and valid and
2036 * and other operations can be performed by the caller. Otherwise
2037 * if 0 is returned the client was destroied (i.e. after QUIT). */
2038 static int processCommand(redisClient
*c
) {
2039 struct redisCommand
*cmd
;
2041 /* Free some memory if needed (maxmemory setting) */
2042 if (server
.maxmemory
) freeMemoryIfNeeded();
2044 /* Handle the multi bulk command type. This is an alternative protocol
2045 * supported by Redis in order to receive commands that are composed of
2046 * multiple binary-safe "bulk" arguments. The latency of processing is
2047 * a bit higher but this allows things like multi-sets, so if this
2048 * protocol is used only for MSET and similar commands this is a big win. */
2049 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
2050 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2051 if (c
->multibulk
<= 0) {
2055 decrRefCount(c
->argv
[c
->argc
-1]);
2059 } else if (c
->multibulk
) {
2060 if (c
->bulklen
== -1) {
2061 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
2062 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
2066 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2067 decrRefCount(c
->argv
[0]);
2068 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2070 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2075 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2079 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
2080 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
2084 if (c
->multibulk
== 0) {
2088 /* Here we need to swap the multi-bulk argc/argv with the
2089 * normal argc/argv of the client structure. */
2091 c
->argv
= c
->mbargv
;
2092 c
->mbargv
= auxargv
;
2095 c
->argc
= c
->mbargc
;
2096 c
->mbargc
= auxargc
;
2098 /* We need to set bulklen to something different than -1
2099 * in order for the code below to process the command without
2100 * to try to read the last argument of a bulk command as
2101 * a special argument. */
2103 /* continue below and process the command */
2110 /* -- end of multi bulk commands processing -- */
2112 /* The QUIT command is handled as a special case. Normal command
2113 * procs are unable to close the client connection safely */
2114 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2119 /* Now lookup the command and check ASAP about trivial error conditions
2120 * such wrong arity, bad command name and so forth. */
2121 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2124 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2125 (char*)c
->argv
[0]->ptr
));
2128 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2129 (c
->argc
< -cmd
->arity
)) {
2131 sdscatprintf(sdsempty(),
2132 "-ERR wrong number of arguments for '%s' command\r\n",
2136 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
2137 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2140 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2141 /* This is a bulk command, we have to read the last argument yet. */
2142 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2144 decrRefCount(c
->argv
[c
->argc
-1]);
2145 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2147 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2152 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2153 /* It is possible that the bulk read is already in the
2154 * buffer. Check this condition and handle it accordingly.
2155 * This is just a fast path, alternative to call processInputBuffer().
2156 * It's a good idea since the code is small and this condition
2157 * happens most of the times. */
2158 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2159 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2161 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2163 /* Otherwise return... there is to read the last argument
2164 * from the socket. */
2168 /* Let's try to share objects on the command arguments vector */
2169 if (server
.shareobjects
) {
2171 for(j
= 1; j
< c
->argc
; j
++)
2172 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
2174 /* Let's try to encode the bulk object to save space. */
2175 if (cmd
->flags
& REDIS_CMD_BULK
)
2176 tryObjectEncoding(c
->argv
[c
->argc
-1]);
2178 /* Check if the user is authenticated */
2179 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2180 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2185 /* Exec the command */
2186 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
) {
2187 queueMultiCommand(c
,cmd
);
2188 addReply(c
,shared
.queued
);
2190 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
2191 blockClientOnSwappedKeys(cmd
,c
)) return 1;
2195 /* Prepare the client for the next command */
2200 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
2205 /* (args*2)+1 is enough room for args, spaces, newlines */
2206 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
2208 if (argc
<= REDIS_STATIC_ARGS
) {
2211 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
2214 for (j
= 0; j
< argc
; j
++) {
2215 if (j
!= 0) outv
[outc
++] = shared
.space
;
2216 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
2219 lenobj
= createObject(REDIS_STRING
,
2220 sdscatprintf(sdsempty(),"%lu\r\n",
2221 (unsigned long) stringObjectLen(argv
[j
])));
2222 lenobj
->refcount
= 0;
2223 outv
[outc
++] = lenobj
;
2225 outv
[outc
++] = argv
[j
];
2227 outv
[outc
++] = shared
.crlf
;
2229 /* Increment all the refcounts at start and decrement at end in order to
2230 * be sure to free objects if there is no slave in a replication state
2231 * able to be feed with commands */
2232 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2233 listRewind(slaves
,&li
);
2234 while((ln
= listNext(&li
))) {
2235 redisClient
*slave
= ln
->value
;
2237 /* Don't feed slaves that are still waiting for BGSAVE to start */
2238 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2240 /* Feed all the other slaves, MONITORs and so on */
2241 if (slave
->slaveseldb
!= dictid
) {
2245 case 0: selectcmd
= shared
.select0
; break;
2246 case 1: selectcmd
= shared
.select1
; break;
2247 case 2: selectcmd
= shared
.select2
; break;
2248 case 3: selectcmd
= shared
.select3
; break;
2249 case 4: selectcmd
= shared
.select4
; break;
2250 case 5: selectcmd
= shared
.select5
; break;
2251 case 6: selectcmd
= shared
.select6
; break;
2252 case 7: selectcmd
= shared
.select7
; break;
2253 case 8: selectcmd
= shared
.select8
; break;
2254 case 9: selectcmd
= shared
.select9
; break;
2256 selectcmd
= createObject(REDIS_STRING
,
2257 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2258 selectcmd
->refcount
= 0;
2261 addReply(slave
,selectcmd
);
2262 slave
->slaveseldb
= dictid
;
2264 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2266 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2267 if (outv
!= static_outv
) zfree(outv
);
2270 static void processInputBuffer(redisClient
*c
) {
2272 /* Before to process the input buffer, make sure the client is not
2273 * waitig for a blocking operation such as BLPOP. Note that the first
2274 * iteration the client is never blocked, otherwise the processInputBuffer
2275 * would not be called at all, but after the execution of the first commands
2276 * in the input buffer the client may be blocked, and the "goto again"
2277 * will try to reiterate. The following line will make it return asap. */
2278 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2279 if (c
->bulklen
== -1) {
2280 /* Read the first line of the query */
2281 char *p
= strchr(c
->querybuf
,'\n');
2288 query
= c
->querybuf
;
2289 c
->querybuf
= sdsempty();
2290 querylen
= 1+(p
-(query
));
2291 if (sdslen(query
) > querylen
) {
2292 /* leave data after the first line of the query in the buffer */
2293 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2295 *p
= '\0'; /* remove "\n" */
2296 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2297 sdsupdatelen(query
);
2299 /* Now we can split the query in arguments */
2300 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2303 if (c
->argv
) zfree(c
->argv
);
2304 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2306 for (j
= 0; j
< argc
; j
++) {
2307 if (sdslen(argv
[j
])) {
2308 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2316 /* Execute the command. If the client is still valid
2317 * after processCommand() return and there is something
2318 * on the query buffer try to process the next command. */
2319 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2321 /* Nothing to process, argc == 0. Just process the query
2322 * buffer if it's not empty or return to the caller */
2323 if (sdslen(c
->querybuf
)) goto again
;
2326 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2327 redisLog(REDIS_VERBOSE
, "Client protocol error");
2332 /* Bulk read handling. Note that if we are at this point
2333 the client already sent a command terminated with a newline,
2334 we are reading the bulk data that is actually the last
2335 argument of the command. */
2336 int qbl
= sdslen(c
->querybuf
);
2338 if (c
->bulklen
<= qbl
) {
2339 /* Copy everything but the final CRLF as final argument */
2340 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2342 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2343 /* Process the command. If the client is still valid after
2344 * the processing and there is more data in the buffer
2345 * try to parse it. */
2346 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2352 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2353 redisClient
*c
= (redisClient
*) privdata
;
2354 char buf
[REDIS_IOBUF_LEN
];
2357 REDIS_NOTUSED(mask
);
2359 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2361 if (errno
== EAGAIN
) {
2364 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2368 } else if (nread
== 0) {
2369 redisLog(REDIS_VERBOSE
, "Client closed connection");
2374 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2375 c
->lastinteraction
= time(NULL
);
2379 if (!(c
->flags
& REDIS_BLOCKED
))
2380 processInputBuffer(c
);
2383 static int selectDb(redisClient
*c
, int id
) {
2384 if (id
< 0 || id
>= server
.dbnum
)
2386 c
->db
= &server
.db
[id
];
2390 static void *dupClientReplyValue(void *o
) {
2391 incrRefCount((robj
*)o
);
2395 static redisClient
*createClient(int fd
) {
2396 redisClient
*c
= zmalloc(sizeof(*c
));
2398 anetNonBlock(NULL
,fd
);
2399 anetTcpNoDelay(NULL
,fd
);
2400 if (!c
) return NULL
;
2403 c
->querybuf
= sdsempty();
2412 c
->lastinteraction
= time(NULL
);
2413 c
->authenticated
= 0;
2414 c
->replstate
= REDIS_REPL_NONE
;
2415 c
->reply
= listCreate();
2416 listSetFreeMethod(c
->reply
,decrRefCount
);
2417 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2418 c
->blockingkeys
= NULL
;
2419 c
->blockingkeysnum
= 0;
2420 c
->io_keys
= listCreate();
2421 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2422 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2423 readQueryFromClient
, c
) == AE_ERR
) {
2427 listAddNodeTail(server
.clients
,c
);
2428 initClientMultiState(c
);
2432 static void addReply(redisClient
*c
, robj
*obj
) {
2433 if (listLength(c
->reply
) == 0 &&
2434 (c
->replstate
== REDIS_REPL_NONE
||
2435 c
->replstate
== REDIS_REPL_ONLINE
) &&
2436 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2437 sendReplyToClient
, c
) == AE_ERR
) return;
2439 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2440 obj
= dupStringObject(obj
);
2441 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2443 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2446 static void addReplySds(redisClient
*c
, sds s
) {
2447 robj
*o
= createObject(REDIS_STRING
,s
);
2452 static void addReplyDouble(redisClient
*c
, double d
) {
2455 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2456 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2457 (unsigned long) strlen(buf
),buf
));
2460 static void addReplyLong(redisClient
*c
, long l
) {
2464 len
= snprintf(buf
,sizeof(buf
),":%ld\r\n",l
);
2465 addReplySds(c
,sdsnewlen(buf
,len
));
2468 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2471 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2472 len
= sdslen(obj
->ptr
);
2474 long n
= (long)obj
->ptr
;
2476 /* Compute how many bytes will take this integer as a radix 10 string */
2482 while((n
= n
/10) != 0) {
2486 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2489 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2494 REDIS_NOTUSED(mask
);
2495 REDIS_NOTUSED(privdata
);
2497 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2498 if (cfd
== AE_ERR
) {
2499 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2502 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2503 if ((c
= createClient(cfd
)) == NULL
) {
2504 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2505 close(cfd
); /* May be already closed, just ingore errors */
2508 /* If maxclient directive is set and this is one client more... close the
2509 * connection. Note that we create the client instead to check before
2510 * for this condition, since now the socket is already set in nonblocking
2511 * mode and we can send an error for free using the Kernel I/O */
2512 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2513 char *err
= "-ERR max number of clients reached\r\n";
2515 /* That's a best effort error message, don't check write errors */
2516 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2517 /* Nothing to do, Just to avoid the warning... */
2522 server
.stat_numconnections
++;
2525 /* ======================= Redis objects implementation ===================== */
2527 static robj
*createObject(int type
, void *ptr
) {
2530 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2531 if (listLength(server
.objfreelist
)) {
2532 listNode
*head
= listFirst(server
.objfreelist
);
2533 o
= listNodeValue(head
);
2534 listDelNode(server
.objfreelist
,head
);
2535 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2537 if (server
.vm_enabled
) {
2538 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2539 o
= zmalloc(sizeof(*o
));
2541 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2545 o
->encoding
= REDIS_ENCODING_RAW
;
2548 if (server
.vm_enabled
) {
2549 /* Note that this code may run in the context of an I/O thread
2550 * and accessing to server.unixtime in theory is an error
2551 * (no locks). But in practice this is safe, and even if we read
2552 * garbage Redis will not fail, as it's just a statistical info */
2553 o
->vm
.atime
= server
.unixtime
;
2554 o
->storage
= REDIS_VM_MEMORY
;
2559 static robj
*createStringObject(char *ptr
, size_t len
) {
2560 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2563 static robj
*dupStringObject(robj
*o
) {
2564 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2565 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2568 static robj
*createListObject(void) {
2569 list
*l
= listCreate();
2571 listSetFreeMethod(l
,decrRefCount
);
2572 return createObject(REDIS_LIST
,l
);
2575 static robj
*createSetObject(void) {
2576 dict
*d
= dictCreate(&setDictType
,NULL
);
2577 return createObject(REDIS_SET
,d
);
2580 static robj
*createHashObject(void) {
2581 /* All the Hashes start as zipmaps. Will be automatically converted
2582 * into hash tables if there are enough elements or big elements
2584 unsigned char *zm
= zipmapNew();
2585 robj
*o
= createObject(REDIS_HASH
,zm
);
2586 o
->encoding
= REDIS_ENCODING_ZIPMAP
;
2590 static robj
*createZsetObject(void) {
2591 zset
*zs
= zmalloc(sizeof(*zs
));
2593 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2594 zs
->zsl
= zslCreate();
2595 return createObject(REDIS_ZSET
,zs
);
2598 static void freeStringObject(robj
*o
) {
2599 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2604 static void freeListObject(robj
*o
) {
2605 listRelease((list
*) o
->ptr
);
2608 static void freeSetObject(robj
*o
) {
2609 dictRelease((dict
*) o
->ptr
);
2612 static void freeZsetObject(robj
*o
) {
2615 dictRelease(zs
->dict
);
2620 static void freeHashObject(robj
*o
) {
2621 switch (o
->encoding
) {
2622 case REDIS_ENCODING_HT
:
2623 dictRelease((dict
*) o
->ptr
);
2625 case REDIS_ENCODING_ZIPMAP
:
2634 static void incrRefCount(robj
*o
) {
2635 redisAssert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2639 static void decrRefCount(void *obj
) {
2642 /* Object is a key of a swapped out value, or in the process of being
2644 if (server
.vm_enabled
&&
2645 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
2647 if (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
) {
2648 redisAssert(o
->refcount
== 1);
2650 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
2651 redisAssert(o
->type
== REDIS_STRING
);
2652 freeStringObject(o
);
2653 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2654 pthread_mutex_lock(&server
.obj_freelist_mutex
);
2655 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2656 !listAddNodeHead(server
.objfreelist
,o
))
2658 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2659 server
.vm_stats_swapped_objects
--;
2662 /* Object is in memory, or in the process of being swapped out. */
2663 if (--(o
->refcount
) == 0) {
2664 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
2665 vmCancelThreadedIOJob(obj
);
2667 case REDIS_STRING
: freeStringObject(o
); break;
2668 case REDIS_LIST
: freeListObject(o
); break;
2669 case REDIS_SET
: freeSetObject(o
); break;
2670 case REDIS_ZSET
: freeZsetObject(o
); break;
2671 case REDIS_HASH
: freeHashObject(o
); break;
2672 default: redisAssert(0 != 0); break;
2674 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2675 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2676 !listAddNodeHead(server
.objfreelist
,o
))
2678 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2682 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2683 dictEntry
*de
= dictFind(db
->dict
,key
);
2685 robj
*key
= dictGetEntryKey(de
);
2686 robj
*val
= dictGetEntryVal(de
);
2688 if (server
.vm_enabled
) {
2689 if (key
->storage
== REDIS_VM_MEMORY
||
2690 key
->storage
== REDIS_VM_SWAPPING
)
2692 /* If we were swapping the object out, stop it, this key
2694 if (key
->storage
== REDIS_VM_SWAPPING
)
2695 vmCancelThreadedIOJob(key
);
2696 /* Update the access time of the key for the aging algorithm. */
2697 key
->vm
.atime
= server
.unixtime
;
2699 int notify
= (key
->storage
== REDIS_VM_LOADING
);
2701 /* Our value was swapped on disk. Bring it at home. */
2702 redisAssert(val
== NULL
);
2703 val
= vmLoadObject(key
);
2704 dictGetEntryVal(de
) = val
;
2706 /* Clients blocked by the VM subsystem may be waiting for
2708 if (notify
) handleClientsBlockedOnSwappedKey(db
,key
);
2717 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2718 expireIfNeeded(db
,key
);
2719 return lookupKey(db
,key
);
2722 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2723 deleteIfVolatile(db
,key
);
2724 return lookupKey(db
,key
);
2727 static int deleteKey(redisDb
*db
, robj
*key
) {
2730 /* We need to protect key from destruction: after the first dictDelete()
2731 * it may happen that 'key' is no longer valid if we don't increment
2732 * it's count. This may happen when we get the object reference directly
2733 * from the hash table with dictRandomKey() or dict iterators */
2735 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2736 retval
= dictDelete(db
->dict
,key
);
2739 return retval
== DICT_OK
;
2742 /* Try to share an object against the shared objects pool */
2743 static robj
*tryObjectSharing(robj
*o
) {
2744 struct dictEntry
*de
;
2747 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2749 redisAssert(o
->type
== REDIS_STRING
);
2750 de
= dictFind(server
.sharingpool
,o
);
2752 robj
*shared
= dictGetEntryKey(de
);
2754 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2755 dictGetEntryVal(de
) = (void*) c
;
2756 incrRefCount(shared
);
2760 /* Here we are using a stream algorihtm: Every time an object is
2761 * shared we increment its count, everytime there is a miss we
2762 * recrement the counter of a random object. If this object reaches
2763 * zero we remove the object and put the current object instead. */
2764 if (dictSize(server
.sharingpool
) >=
2765 server
.sharingpoolsize
) {
2766 de
= dictGetRandomKey(server
.sharingpool
);
2767 redisAssert(de
!= NULL
);
2768 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2769 dictGetEntryVal(de
) = (void*) c
;
2771 dictDelete(server
.sharingpool
,de
->key
);
2774 c
= 0; /* If the pool is empty we want to add this object */
2779 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2780 redisAssert(retval
== DICT_OK
);
2787 /* Check if the nul-terminated string 's' can be represented by a long
2788 * (that is, is a number that fits into long without any other space or
2789 * character before or after the digits).
2791 * If so, the function returns REDIS_OK and *longval is set to the value
2792 * of the number. Otherwise REDIS_ERR is returned */
2793 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2794 char buf
[32], *endptr
;
2798 value
= strtol(s
, &endptr
, 10);
2799 if (endptr
[0] != '\0') return REDIS_ERR
;
2800 slen
= snprintf(buf
,32,"%ld",value
);
2802 /* If the number converted back into a string is not identical
2803 * then it's not possible to encode the string as integer */
2804 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2805 if (longval
) *longval
= value
;
2809 /* Try to encode a string object in order to save space */
2810 static int tryObjectEncoding(robj
*o
) {
2814 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2815 return REDIS_ERR
; /* Already encoded */
2817 /* It's not save to encode shared objects: shared objects can be shared
2818 * everywhere in the "object space" of Redis. Encoded objects can only
2819 * appear as "values" (and not, for instance, as keys) */
2820 if (o
->refcount
> 1) return REDIS_ERR
;
2822 /* Currently we try to encode only strings */
2823 redisAssert(o
->type
== REDIS_STRING
);
2825 /* Check if we can represent this string as a long integer */
2826 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2828 /* Ok, this object can be encoded */
2829 o
->encoding
= REDIS_ENCODING_INT
;
2831 o
->ptr
= (void*) value
;
2835 /* Get a decoded version of an encoded object (returned as a new object).
2836 * If the object is already raw-encoded just increment the ref count. */
2837 static robj
*getDecodedObject(robj
*o
) {
2840 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2844 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2847 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2848 dec
= createStringObject(buf
,strlen(buf
));
2851 redisAssert(1 != 1);
2855 /* Compare two string objects via strcmp() or alike.
2856 * Note that the objects may be integer-encoded. In such a case we
2857 * use snprintf() to get a string representation of the numbers on the stack
2858 * and compare the strings, it's much faster than calling getDecodedObject().
2860 * Important note: if objects are not integer encoded, but binary-safe strings,
2861 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2863 static int compareStringObjects(robj
*a
, robj
*b
) {
2864 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2865 char bufa
[128], bufb
[128], *astr
, *bstr
;
2868 if (a
== b
) return 0;
2869 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2870 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2876 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2877 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2883 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2886 static size_t stringObjectLen(robj
*o
) {
2887 redisAssert(o
->type
== REDIS_STRING
);
2888 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2889 return sdslen(o
->ptr
);
2893 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2897 /*============================ RDB saving/loading =========================== */
2899 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2900 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2904 static int rdbSaveTime(FILE *fp
, time_t t
) {
2905 int32_t t32
= (int32_t) t
;
2906 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
2910 /* check rdbLoadLen() comments for more info */
2911 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
2912 unsigned char buf
[2];
2915 /* Save a 6 bit len */
2916 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
2917 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2918 } else if (len
< (1<<14)) {
2919 /* Save a 14 bit len */
2920 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
2922 if (fwrite(buf
,2,1,fp
) == 0) return -1;
2924 /* Save a 32 bit len */
2925 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
2926 if (fwrite(buf
,1,1,fp
) == 0) return -1;
2928 if (fwrite(&len
,4,1,fp
) == 0) return -1;
2933 /* String objects in the form "2391" "-100" without any space and with a
2934 * range of values that can fit in an 8, 16 or 32 bit signed value can be
2935 * encoded as integers to save space */
2936 static int rdbTryIntegerEncoding(sds s
, unsigned char *enc
) {
2938 char *endptr
, buf
[32];
2940 /* Check if it's possible to encode this value as a number */
2941 value
= strtoll(s
, &endptr
, 10);
2942 if (endptr
[0] != '\0') return 0;
2943 snprintf(buf
,32,"%lld",value
);
2945 /* If the number converted back into a string is not identical
2946 * then it's not possible to encode the string as integer */
2947 if (strlen(buf
) != sdslen(s
) || memcmp(buf
,s
,sdslen(s
))) return 0;
2949 /* Finally check if it fits in our ranges */
2950 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
2951 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
2952 enc
[1] = value
&0xFF;
2954 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
2955 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
2956 enc
[1] = value
&0xFF;
2957 enc
[2] = (value
>>8)&0xFF;
2959 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
2960 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
2961 enc
[1] = value
&0xFF;
2962 enc
[2] = (value
>>8)&0xFF;
2963 enc
[3] = (value
>>16)&0xFF;
2964 enc
[4] = (value
>>24)&0xFF;
2971 static int rdbSaveLzfStringObject(FILE *fp
, robj
*obj
) {
2972 unsigned int comprlen
, outlen
;
2976 /* We require at least four bytes compression for this to be worth it */
2977 outlen
= sdslen(obj
->ptr
)-4;
2978 if (outlen
<= 0) return 0;
2979 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
2980 comprlen
= lzf_compress(obj
->ptr
, sdslen(obj
->ptr
), out
, outlen
);
2981 if (comprlen
== 0) {
2985 /* Data compressed! Let's save it on disk */
2986 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
2987 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
2988 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
2989 if (rdbSaveLen(fp
,sdslen(obj
->ptr
)) == -1) goto writeerr
;
2990 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
2999 /* Save a string objet as [len][data] on disk. If the object is a string
3000 * representation of an integer value we try to safe it in a special form */
3001 static int rdbSaveStringObjectRaw(FILE *fp
, robj
*obj
) {
3005 len
= sdslen(obj
->ptr
);
3007 /* Try integer encoding */
3009 unsigned char buf
[5];
3010 if ((enclen
= rdbTryIntegerEncoding(obj
->ptr
,buf
)) > 0) {
3011 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3016 /* Try LZF compression - under 20 bytes it's unable to compress even
3017 * aaaaaaaaaaaaaaaaaa so skip it */
3018 if (server
.rdbcompression
&& len
> 20) {
3021 retval
= rdbSaveLzfStringObject(fp
,obj
);
3022 if (retval
== -1) return -1;
3023 if (retval
> 0) return 0;
3024 /* retval == 0 means data can't be compressed, save the old way */
3027 /* Store verbatim */
3028 if (rdbSaveLen(fp
,len
) == -1) return -1;
3029 if (len
&& fwrite(obj
->ptr
,len
,1,fp
) == 0) return -1;
3033 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3034 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
3037 /* Avoid incr/decr ref count business when possible.
3038 * This plays well with copy-on-write given that we are probably
3039 * in a child process (BGSAVE). Also this makes sure key objects
3040 * of swapped objects are not incRefCount-ed (an assert does not allow
3041 * this in order to avoid bugs) */
3042 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
3043 obj
= getDecodedObject(obj
);
3044 retval
= rdbSaveStringObjectRaw(fp
,obj
);
3047 retval
= rdbSaveStringObjectRaw(fp
,obj
);
3052 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3053 * 8 bit integer specifing the length of the representation.
3054 * This 8 bit integer has special values in order to specify the following
3060 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
3061 unsigned char buf
[128];
3067 } else if (!isfinite(val
)) {
3069 buf
[0] = (val
< 0) ? 255 : 254;
3071 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
3072 buf
[0] = strlen((char*)buf
+1);
3075 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
3079 /* Save a Redis object. */
3080 static int rdbSaveObject(FILE *fp
, robj
*o
) {
3081 if (o
->type
== REDIS_STRING
) {
3082 /* Save a string value */
3083 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
3084 } else if (o
->type
== REDIS_LIST
) {
3085 /* Save a list value */
3086 list
*list
= o
->ptr
;
3090 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
3091 listRewind(list
,&li
);
3092 while((ln
= listNext(&li
))) {
3093 robj
*eleobj
= listNodeValue(ln
);
3095 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3097 } else if (o
->type
== REDIS_SET
) {
3098 /* Save a set value */
3100 dictIterator
*di
= dictGetIterator(set
);
3103 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
3104 while((de
= dictNext(di
)) != NULL
) {
3105 robj
*eleobj
= dictGetEntryKey(de
);
3107 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3109 dictReleaseIterator(di
);
3110 } else if (o
->type
== REDIS_ZSET
) {
3111 /* Save a set value */
3113 dictIterator
*di
= dictGetIterator(zs
->dict
);
3116 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
3117 while((de
= dictNext(di
)) != NULL
) {
3118 robj
*eleobj
= dictGetEntryKey(de
);
3119 double *score
= dictGetEntryVal(de
);
3121 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3122 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
3124 dictReleaseIterator(di
);
3126 redisAssert(0 != 0);
3131 /* Return the length the object will have on disk if saved with
3132 * the rdbSaveObject() function. Currently we use a trick to get
3133 * this length with very little changes to the code. In the future
3134 * we could switch to a faster solution. */
3135 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
3136 if (fp
== NULL
) fp
= server
.devnull
;
3138 assert(rdbSaveObject(fp
,o
) != 1);
3142 /* Return the number of pages required to save this object in the swap file */
3143 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
3144 off_t bytes
= rdbSavedObjectLen(o
,fp
);
3146 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
3149 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3150 static int rdbSave(char *filename
) {
3151 dictIterator
*di
= NULL
;
3156 time_t now
= time(NULL
);
3158 /* Wait for I/O therads to terminate, just in case this is a
3159 * foreground-saving, to avoid seeking the swap file descriptor at the
3161 if (server
.vm_enabled
)
3162 waitEmptyIOJobsQueue();
3164 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3165 fp
= fopen(tmpfile
,"w");
3167 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3170 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3171 for (j
= 0; j
< server
.dbnum
; j
++) {
3172 redisDb
*db
= server
.db
+j
;
3174 if (dictSize(d
) == 0) continue;
3175 di
= dictGetIterator(d
);
3181 /* Write the SELECT DB opcode */
3182 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3183 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3185 /* Iterate this DB writing every entry */
3186 while((de
= dictNext(di
)) != NULL
) {
3187 robj
*key
= dictGetEntryKey(de
);
3188 robj
*o
= dictGetEntryVal(de
);
3189 time_t expiretime
= getExpire(db
,key
);
3191 /* Save the expire time */
3192 if (expiretime
!= -1) {
3193 /* If this key is already expired skip it */
3194 if (expiretime
< now
) continue;
3195 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3196 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3198 /* Save the key and associated value. This requires special
3199 * handling if the value is swapped out. */
3200 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3201 key
->storage
== REDIS_VM_SWAPPING
) {
3202 /* Save type, key, value */
3203 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3204 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3205 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3207 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3209 /* Get a preview of the object in memory */
3210 po
= vmPreviewObject(key
);
3211 /* Save type, key, value */
3212 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3213 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3214 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3215 /* Remove the loaded object from memory */
3219 dictReleaseIterator(di
);
3222 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3224 /* Make sure data will not remain on the OS's output buffers */
3229 /* Use RENAME to make sure the DB file is changed atomically only
3230 * if the generate DB file is ok. */
3231 if (rename(tmpfile
,filename
) == -1) {
3232 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3236 redisLog(REDIS_NOTICE
,"DB saved on disk");
3238 server
.lastsave
= time(NULL
);
3244 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3245 if (di
) dictReleaseIterator(di
);
3249 static int rdbSaveBackground(char *filename
) {
3252 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3253 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
3254 if ((childpid
= fork()) == 0) {
3256 if (server
.vm_enabled
) vmReopenSwapFile();
3258 if (rdbSave(filename
) == REDIS_OK
) {
3265 if (childpid
== -1) {
3266 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3270 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3271 server
.bgsavechildpid
= childpid
;
3274 return REDIS_OK
; /* unreached */
3277 static void rdbRemoveTempFile(pid_t childpid
) {
3280 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3284 static int rdbLoadType(FILE *fp
) {
3286 if (fread(&type
,1,1,fp
) == 0) return -1;
3290 static time_t rdbLoadTime(FILE *fp
) {
3292 if (fread(&t32
,4,1,fp
) == 0) return -1;
3293 return (time_t) t32
;
3296 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3297 * of this file for a description of how this are stored on disk.
3299 * isencoded is set to 1 if the readed length is not actually a length but
3300 * an "encoding type", check the above comments for more info */
3301 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3302 unsigned char buf
[2];
3306 if (isencoded
) *isencoded
= 0;
3307 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3308 type
= (buf
[0]&0xC0)>>6;
3309 if (type
== REDIS_RDB_6BITLEN
) {
3310 /* Read a 6 bit len */
3312 } else if (type
== REDIS_RDB_ENCVAL
) {
3313 /* Read a 6 bit len encoding type */
3314 if (isencoded
) *isencoded
= 1;
3316 } else if (type
== REDIS_RDB_14BITLEN
) {
3317 /* Read a 14 bit len */
3318 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3319 return ((buf
[0]&0x3F)<<8)|buf
[1];
3321 /* Read a 32 bit len */
3322 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3327 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
3328 unsigned char enc
[4];
3331 if (enctype
== REDIS_RDB_ENC_INT8
) {
3332 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3333 val
= (signed char)enc
[0];
3334 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3336 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3337 v
= enc
[0]|(enc
[1]<<8);
3339 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3341 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3342 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3345 val
= 0; /* anti-warning */
3348 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3351 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3352 unsigned int len
, clen
;
3353 unsigned char *c
= NULL
;
3356 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3357 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3358 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3359 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3360 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3361 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3363 return createObject(REDIS_STRING
,val
);
3370 static robj
*rdbLoadStringObject(FILE*fp
) {
3375 len
= rdbLoadLen(fp
,&isencoded
);
3378 case REDIS_RDB_ENC_INT8
:
3379 case REDIS_RDB_ENC_INT16
:
3380 case REDIS_RDB_ENC_INT32
:
3381 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3382 case REDIS_RDB_ENC_LZF
:
3383 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3389 if (len
== REDIS_RDB_LENERR
) return NULL
;
3390 val
= sdsnewlen(NULL
,len
);
3391 if (len
&& fread(val
,len
,1,fp
) == 0) {
3395 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3398 /* For information about double serialization check rdbSaveDoubleValue() */
3399 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3403 if (fread(&len
,1,1,fp
) == 0) return -1;
3405 case 255: *val
= R_NegInf
; return 0;
3406 case 254: *val
= R_PosInf
; return 0;
3407 case 253: *val
= R_Nan
; return 0;
3409 if (fread(buf
,len
,1,fp
) == 0) return -1;
3411 sscanf(buf
, "%lg", val
);
3416 /* Load a Redis object of the specified type from the specified file.
3417 * On success a newly allocated object is returned, otherwise NULL. */
3418 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3421 if (type
== REDIS_STRING
) {
3422 /* Read string value */
3423 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3424 tryObjectEncoding(o
);
3425 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3426 /* Read list/set value */
3429 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3430 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3431 /* It's faster to expand the dict to the right size asap in order
3432 * to avoid rehashing */
3433 if (type
== REDIS_SET
&& listlen
> DICT_HT_INITIAL_SIZE
)
3434 dictExpand(o
->ptr
,listlen
);
3435 /* Load every single element of the list/set */
3439 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3440 tryObjectEncoding(ele
);
3441 if (type
== REDIS_LIST
) {
3442 listAddNodeTail((list
*)o
->ptr
,ele
);
3444 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3447 } else if (type
== REDIS_ZSET
) {
3448 /* Read list/set value */
3452 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3453 o
= createZsetObject();
3455 /* Load every single element of the list/set */
3458 double *score
= zmalloc(sizeof(double));
3460 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3461 tryObjectEncoding(ele
);
3462 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3463 dictAdd(zs
->dict
,ele
,score
);
3464 zslInsert(zs
->zsl
,*score
,ele
);
3465 incrRefCount(ele
); /* added to skiplist */
3468 redisAssert(0 != 0);
3473 static int rdbLoad(char *filename
) {
3475 robj
*keyobj
= NULL
;
3477 int type
, retval
, rdbver
;
3478 dict
*d
= server
.db
[0].dict
;
3479 redisDb
*db
= server
.db
+0;
3481 time_t expiretime
= -1, now
= time(NULL
);
3482 long long loadedkeys
= 0;
3484 fp
= fopen(filename
,"r");
3485 if (!fp
) return REDIS_ERR
;
3486 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3488 if (memcmp(buf
,"REDIS",5) != 0) {
3490 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3493 rdbver
= atoi(buf
+5);
3496 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3503 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3504 if (type
== REDIS_EXPIRETIME
) {
3505 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3506 /* We read the time so we need to read the object type again */
3507 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3509 if (type
== REDIS_EOF
) break;
3510 /* Handle SELECT DB opcode as a special case */
3511 if (type
== REDIS_SELECTDB
) {
3512 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3514 if (dbid
>= (unsigned)server
.dbnum
) {
3515 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3518 db
= server
.db
+dbid
;
3523 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3525 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3526 /* Add the new object in the hash table */
3527 retval
= dictAdd(d
,keyobj
,o
);
3528 if (retval
== DICT_ERR
) {
3529 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3532 /* Set the expire time if needed */
3533 if (expiretime
!= -1) {
3534 setExpire(db
,keyobj
,expiretime
);
3535 /* Delete this key if already expired */
3536 if (expiretime
< now
) deleteKey(db
,keyobj
);
3540 /* Handle swapping while loading big datasets when VM is on */
3542 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
3543 while (zmalloc_used_memory() > server
.vm_max_memory
) {
3544 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
3551 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3552 if (keyobj
) decrRefCount(keyobj
);
3553 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3555 return REDIS_ERR
; /* Just to avoid warning */
3558 /*================================== Commands =============================== */
3560 static void authCommand(redisClient
*c
) {
3561 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3562 c
->authenticated
= 1;
3563 addReply(c
,shared
.ok
);
3565 c
->authenticated
= 0;
3566 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3570 static void pingCommand(redisClient
*c
) {
3571 addReply(c
,shared
.pong
);
3574 static void echoCommand(redisClient
*c
) {
3575 addReplyBulkLen(c
,c
->argv
[1]);
3576 addReply(c
,c
->argv
[1]);
3577 addReply(c
,shared
.crlf
);
3580 /*=================================== Strings =============================== */
3582 static void setGenericCommand(redisClient
*c
, int nx
) {
3585 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3586 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3587 if (retval
== DICT_ERR
) {
3589 /* If the key is about a swapped value, we want a new key object
3590 * to overwrite the old. So we delete the old key in the database.
3591 * This will also make sure that swap pages about the old object
3592 * will be marked as free. */
3593 if (server
.vm_enabled
&& deleteIfSwapped(c
->db
,c
->argv
[1]))
3594 incrRefCount(c
->argv
[1]);
3595 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3596 incrRefCount(c
->argv
[2]);
3598 addReply(c
,shared
.czero
);
3602 incrRefCount(c
->argv
[1]);
3603 incrRefCount(c
->argv
[2]);
3606 removeExpire(c
->db
,c
->argv
[1]);
3607 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3610 static void setCommand(redisClient
*c
) {
3611 setGenericCommand(c
,0);
3614 static void setnxCommand(redisClient
*c
) {
3615 setGenericCommand(c
,1);
3618 static int getGenericCommand(redisClient
*c
) {
3619 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3622 addReply(c
,shared
.nullbulk
);
3625 if (o
->type
!= REDIS_STRING
) {
3626 addReply(c
,shared
.wrongtypeerr
);
3629 addReplyBulkLen(c
,o
);
3631 addReply(c
,shared
.crlf
);
3637 static void getCommand(redisClient
*c
) {
3638 getGenericCommand(c
);
3641 static void getsetCommand(redisClient
*c
) {
3642 if (getGenericCommand(c
) == REDIS_ERR
) return;
3643 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3644 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3646 incrRefCount(c
->argv
[1]);
3648 incrRefCount(c
->argv
[2]);
3650 removeExpire(c
->db
,c
->argv
[1]);
3653 static void mgetCommand(redisClient
*c
) {
3656 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3657 for (j
= 1; j
< c
->argc
; j
++) {
3658 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3660 addReply(c
,shared
.nullbulk
);
3662 if (o
->type
!= REDIS_STRING
) {
3663 addReply(c
,shared
.nullbulk
);
3665 addReplyBulkLen(c
,o
);
3667 addReply(c
,shared
.crlf
);
3673 static void msetGenericCommand(redisClient
*c
, int nx
) {
3674 int j
, busykeys
= 0;
3676 if ((c
->argc
% 2) == 0) {
3677 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3680 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3681 * set nothing at all if at least one already key exists. */
3683 for (j
= 1; j
< c
->argc
; j
+= 2) {
3684 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3690 addReply(c
, shared
.czero
);
3694 for (j
= 1; j
< c
->argc
; j
+= 2) {
3697 tryObjectEncoding(c
->argv
[j
+1]);
3698 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3699 if (retval
== DICT_ERR
) {
3700 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3701 incrRefCount(c
->argv
[j
+1]);
3703 incrRefCount(c
->argv
[j
]);
3704 incrRefCount(c
->argv
[j
+1]);
3706 removeExpire(c
->db
,c
->argv
[j
]);
3708 server
.dirty
+= (c
->argc
-1)/2;
3709 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3712 static void msetCommand(redisClient
*c
) {
3713 msetGenericCommand(c
,0);
3716 static void msetnxCommand(redisClient
*c
) {
3717 msetGenericCommand(c
,1);
3720 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3725 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3729 if (o
->type
!= REDIS_STRING
) {
3734 if (o
->encoding
== REDIS_ENCODING_RAW
)
3735 value
= strtoll(o
->ptr
, &eptr
, 10);
3736 else if (o
->encoding
== REDIS_ENCODING_INT
)
3737 value
= (long)o
->ptr
;
3739 redisAssert(1 != 1);
3744 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3745 tryObjectEncoding(o
);
3746 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3747 if (retval
== DICT_ERR
) {
3748 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3749 removeExpire(c
->db
,c
->argv
[1]);
3751 incrRefCount(c
->argv
[1]);
3754 addReply(c
,shared
.colon
);
3756 addReply(c
,shared
.crlf
);
3759 static void incrCommand(redisClient
*c
) {
3760 incrDecrCommand(c
,1);
3763 static void decrCommand(redisClient
*c
) {
3764 incrDecrCommand(c
,-1);
3767 static void incrbyCommand(redisClient
*c
) {
3768 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3769 incrDecrCommand(c
,incr
);
3772 static void decrbyCommand(redisClient
*c
) {
3773 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3774 incrDecrCommand(c
,-incr
);
3777 static void appendCommand(redisClient
*c
) {
3782 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3784 /* Create the key */
3785 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3786 incrRefCount(c
->argv
[1]);
3787 incrRefCount(c
->argv
[2]);
3788 totlen
= stringObjectLen(c
->argv
[2]);
3792 de
= dictFind(c
->db
->dict
,c
->argv
[1]);
3795 o
= dictGetEntryVal(de
);
3796 if (o
->type
!= REDIS_STRING
) {
3797 addReply(c
,shared
.wrongtypeerr
);
3800 /* If the object is specially encoded or shared we have to make
3802 if (o
->refcount
!= 1 || o
->encoding
!= REDIS_ENCODING_RAW
) {
3803 robj
*decoded
= getDecodedObject(o
);
3805 o
= createStringObject(decoded
->ptr
, sdslen(decoded
->ptr
));
3806 decrRefCount(decoded
);
3807 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3810 if (c
->argv
[2]->encoding
== REDIS_ENCODING_RAW
) {
3811 o
->ptr
= sdscatlen(o
->ptr
,
3812 c
->argv
[2]->ptr
, sdslen(c
->argv
[2]->ptr
));
3814 o
->ptr
= sdscatprintf(o
->ptr
, "%ld",
3815 (unsigned long) c
->argv
[2]->ptr
);
3817 totlen
= sdslen(o
->ptr
);
3820 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen
));
3823 static void substrCommand(redisClient
*c
) {
3825 long start
= atoi(c
->argv
[2]->ptr
);
3826 long end
= atoi(c
->argv
[3]->ptr
);
3828 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3830 addReply(c
,shared
.nullbulk
);
3832 if (o
->type
!= REDIS_STRING
) {
3833 addReply(c
,shared
.wrongtypeerr
);
3835 size_t rangelen
, strlen
;
3838 o
= getDecodedObject(o
);
3839 strlen
= sdslen(o
->ptr
);
3841 /* convert negative indexes */
3842 if (start
< 0) start
= strlen
+start
;
3843 if (end
< 0) end
= strlen
+end
;
3844 if (start
< 0) start
= 0;
3845 if (end
< 0) end
= 0;
3847 /* indexes sanity checks */
3848 if (start
> end
|| (size_t)start
>= strlen
) {
3849 /* Out of range start or start > end result in null reply */
3850 addReply(c
,shared
.nullbulk
);
3854 if ((size_t)end
>= strlen
) end
= strlen
-1;
3855 rangelen
= (end
-start
)+1;
3857 /* Return the result */
3858 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",rangelen
));
3859 range
= sdsnewlen((char*)o
->ptr
+start
,rangelen
);
3860 addReplySds(c
,range
);
3861 addReply(c
,shared
.crlf
);
3867 /* ========================= Type agnostic commands ========================= */
3869 static void delCommand(redisClient
*c
) {
3872 for (j
= 1; j
< c
->argc
; j
++) {
3873 if (deleteKey(c
->db
,c
->argv
[j
])) {
3880 addReply(c
,shared
.czero
);
3883 addReply(c
,shared
.cone
);
3886 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",deleted
));
3891 static void existsCommand(redisClient
*c
) {
3892 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
3895 static void selectCommand(redisClient
*c
) {
3896 int id
= atoi(c
->argv
[1]->ptr
);
3898 if (selectDb(c
,id
) == REDIS_ERR
) {
3899 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
3901 addReply(c
,shared
.ok
);
3905 static void randomkeyCommand(redisClient
*c
) {
3909 de
= dictGetRandomKey(c
->db
->dict
);
3910 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
3913 addReply(c
,shared
.plus
);
3914 addReply(c
,shared
.crlf
);
3916 addReply(c
,shared
.plus
);
3917 addReply(c
,dictGetEntryKey(de
));
3918 addReply(c
,shared
.crlf
);
3922 static void keysCommand(redisClient
*c
) {
3925 sds pattern
= c
->argv
[1]->ptr
;
3926 int plen
= sdslen(pattern
);
3927 unsigned long numkeys
= 0;
3928 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
3930 di
= dictGetIterator(c
->db
->dict
);
3932 decrRefCount(lenobj
);
3933 while((de
= dictNext(di
)) != NULL
) {
3934 robj
*keyobj
= dictGetEntryKey(de
);
3936 sds key
= keyobj
->ptr
;
3937 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
3938 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
3939 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
3940 addReplyBulkLen(c
,keyobj
);
3942 addReply(c
,shared
.crlf
);
3947 dictReleaseIterator(di
);
3948 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",numkeys
);
3951 static void dbsizeCommand(redisClient
*c
) {
3953 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
3956 static void lastsaveCommand(redisClient
*c
) {
3958 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
3961 static void typeCommand(redisClient
*c
) {
3965 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
3970 case REDIS_STRING
: type
= "+string"; break;
3971 case REDIS_LIST
: type
= "+list"; break;
3972 case REDIS_SET
: type
= "+set"; break;
3973 case REDIS_ZSET
: type
= "+zset"; break;
3974 default: type
= "unknown"; break;
3977 addReplySds(c
,sdsnew(type
));
3978 addReply(c
,shared
.crlf
);
3981 static void saveCommand(redisClient
*c
) {
3982 if (server
.bgsavechildpid
!= -1) {
3983 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
3986 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
3987 addReply(c
,shared
.ok
);
3989 addReply(c
,shared
.err
);
3993 static void bgsaveCommand(redisClient
*c
) {
3994 if (server
.bgsavechildpid
!= -1) {
3995 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
3998 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
3999 char *status
= "+Background saving started\r\n";
4000 addReplySds(c
,sdsnew(status
));
4002 addReply(c
,shared
.err
);
4006 static void shutdownCommand(redisClient
*c
) {
4007 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
4008 /* Kill the saving child if there is a background saving in progress.
4009 We want to avoid race conditions, for instance our saving child may
4010 overwrite the synchronous saving did by SHUTDOWN. */
4011 if (server
.bgsavechildpid
!= -1) {
4012 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
4013 kill(server
.bgsavechildpid
,SIGKILL
);
4014 rdbRemoveTempFile(server
.bgsavechildpid
);
4016 if (server
.appendonly
) {
4017 /* Append only file: fsync() the AOF and exit */
4018 fsync(server
.appendfd
);
4019 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
4022 /* Snapshotting. Perform a SYNC SAVE and exit */
4023 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4024 if (server
.daemonize
)
4025 unlink(server
.pidfile
);
4026 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
4027 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
4028 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
4031 /* Ooops.. error saving! The best we can do is to continue operating.
4032 * Note that if there was a background saving process, in the next
4033 * cron() Redis will be notified that the background saving aborted,
4034 * handling special stuff like slaves pending for synchronization... */
4035 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
4036 addReplySds(c
,sdsnew("-ERR can't quit, problems saving the DB\r\n"));
4041 static void renameGenericCommand(redisClient
*c
, int nx
) {
4044 /* To use the same key as src and dst is probably an error */
4045 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
4046 addReply(c
,shared
.sameobjecterr
);
4050 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4052 addReply(c
,shared
.nokeyerr
);
4056 deleteIfVolatile(c
->db
,c
->argv
[2]);
4057 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
4060 addReply(c
,shared
.czero
);
4063 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
4065 incrRefCount(c
->argv
[2]);
4067 deleteKey(c
->db
,c
->argv
[1]);
4069 addReply(c
,nx
? shared
.cone
: shared
.ok
);
4072 static void renameCommand(redisClient
*c
) {
4073 renameGenericCommand(c
,0);
4076 static void renamenxCommand(redisClient
*c
) {
4077 renameGenericCommand(c
,1);
4080 static void moveCommand(redisClient
*c
) {
4085 /* Obtain source and target DB pointers */
4088 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
4089 addReply(c
,shared
.outofrangeerr
);
4093 selectDb(c
,srcid
); /* Back to the source DB */
4095 /* If the user is moving using as target the same
4096 * DB as the source DB it is probably an error. */
4098 addReply(c
,shared
.sameobjecterr
);
4102 /* Check if the element exists and get a reference */
4103 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4105 addReply(c
,shared
.czero
);
4109 /* Try to add the element to the target DB */
4110 deleteIfVolatile(dst
,c
->argv
[1]);
4111 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
4112 addReply(c
,shared
.czero
);
4115 incrRefCount(c
->argv
[1]);
4118 /* OK! key moved, free the entry in the source DB */
4119 deleteKey(src
,c
->argv
[1]);
4121 addReply(c
,shared
.cone
);
4124 /* =================================== Lists ================================ */
4125 static void pushGenericCommand(redisClient
*c
, int where
) {
4129 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4131 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4132 addReply(c
,shared
.cone
);
4135 lobj
= createListObject();
4137 if (where
== REDIS_HEAD
) {
4138 listAddNodeHead(list
,c
->argv
[2]);
4140 listAddNodeTail(list
,c
->argv
[2]);
4142 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
4143 incrRefCount(c
->argv
[1]);
4144 incrRefCount(c
->argv
[2]);
4146 if (lobj
->type
!= REDIS_LIST
) {
4147 addReply(c
,shared
.wrongtypeerr
);
4150 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4151 addReply(c
,shared
.cone
);
4155 if (where
== REDIS_HEAD
) {
4156 listAddNodeHead(list
,c
->argv
[2]);
4158 listAddNodeTail(list
,c
->argv
[2]);
4160 incrRefCount(c
->argv
[2]);
4163 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(list
)));
4166 static void lpushCommand(redisClient
*c
) {
4167 pushGenericCommand(c
,REDIS_HEAD
);
4170 static void rpushCommand(redisClient
*c
) {
4171 pushGenericCommand(c
,REDIS_TAIL
);
4174 static void llenCommand(redisClient
*c
) {
4178 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4180 addReply(c
,shared
.czero
);
4183 if (o
->type
!= REDIS_LIST
) {
4184 addReply(c
,shared
.wrongtypeerr
);
4187 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(l
)));
4192 static void lindexCommand(redisClient
*c
) {
4194 int index
= atoi(c
->argv
[2]->ptr
);
4196 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4198 addReply(c
,shared
.nullbulk
);
4200 if (o
->type
!= REDIS_LIST
) {
4201 addReply(c
,shared
.wrongtypeerr
);
4203 list
*list
= o
->ptr
;
4206 ln
= listIndex(list
, index
);
4208 addReply(c
,shared
.nullbulk
);
4210 robj
*ele
= listNodeValue(ln
);
4211 addReplyBulkLen(c
,ele
);
4213 addReply(c
,shared
.crlf
);
4219 static void lsetCommand(redisClient
*c
) {
4221 int index
= atoi(c
->argv
[2]->ptr
);
4223 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4225 addReply(c
,shared
.nokeyerr
);
4227 if (o
->type
!= REDIS_LIST
) {
4228 addReply(c
,shared
.wrongtypeerr
);
4230 list
*list
= o
->ptr
;
4233 ln
= listIndex(list
, index
);
4235 addReply(c
,shared
.outofrangeerr
);
4237 robj
*ele
= listNodeValue(ln
);
4240 listNodeValue(ln
) = c
->argv
[3];
4241 incrRefCount(c
->argv
[3]);
4242 addReply(c
,shared
.ok
);
4249 static void popGenericCommand(redisClient
*c
, int where
) {
4252 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4254 addReply(c
,shared
.nullbulk
);
4256 if (o
->type
!= REDIS_LIST
) {
4257 addReply(c
,shared
.wrongtypeerr
);
4259 list
*list
= o
->ptr
;
4262 if (where
== REDIS_HEAD
)
4263 ln
= listFirst(list
);
4265 ln
= listLast(list
);
4268 addReply(c
,shared
.nullbulk
);
4270 robj
*ele
= listNodeValue(ln
);
4271 addReplyBulkLen(c
,ele
);
4273 addReply(c
,shared
.crlf
);
4274 listDelNode(list
,ln
);
4281 static void lpopCommand(redisClient
*c
) {
4282 popGenericCommand(c
,REDIS_HEAD
);
4285 static void rpopCommand(redisClient
*c
) {
4286 popGenericCommand(c
,REDIS_TAIL
);
4289 static void lrangeCommand(redisClient
*c
) {
4291 int start
= atoi(c
->argv
[2]->ptr
);
4292 int end
= atoi(c
->argv
[3]->ptr
);
4294 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4296 addReply(c
,shared
.nullmultibulk
);
4298 if (o
->type
!= REDIS_LIST
) {
4299 addReply(c
,shared
.wrongtypeerr
);
4301 list
*list
= o
->ptr
;
4303 int llen
= listLength(list
);
4307 /* convert negative indexes */
4308 if (start
< 0) start
= llen
+start
;
4309 if (end
< 0) end
= llen
+end
;
4310 if (start
< 0) start
= 0;
4311 if (end
< 0) end
= 0;
4313 /* indexes sanity checks */
4314 if (start
> end
|| start
>= llen
) {
4315 /* Out of range start or start > end result in empty list */
4316 addReply(c
,shared
.emptymultibulk
);
4319 if (end
>= llen
) end
= llen
-1;
4320 rangelen
= (end
-start
)+1;
4322 /* Return the result in form of a multi-bulk reply */
4323 ln
= listIndex(list
, start
);
4324 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4325 for (j
= 0; j
< rangelen
; j
++) {
4326 ele
= listNodeValue(ln
);
4327 addReplyBulkLen(c
,ele
);
4329 addReply(c
,shared
.crlf
);
4336 static void ltrimCommand(redisClient
*c
) {
4338 int start
= atoi(c
->argv
[2]->ptr
);
4339 int end
= atoi(c
->argv
[3]->ptr
);
4341 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4343 addReply(c
,shared
.ok
);
4345 if (o
->type
!= REDIS_LIST
) {
4346 addReply(c
,shared
.wrongtypeerr
);
4348 list
*list
= o
->ptr
;
4350 int llen
= listLength(list
);
4351 int j
, ltrim
, rtrim
;
4353 /* convert negative indexes */
4354 if (start
< 0) start
= llen
+start
;
4355 if (end
< 0) end
= llen
+end
;
4356 if (start
< 0) start
= 0;
4357 if (end
< 0) end
= 0;
4359 /* indexes sanity checks */
4360 if (start
> end
|| start
>= llen
) {
4361 /* Out of range start or start > end result in empty list */
4365 if (end
>= llen
) end
= llen
-1;
4370 /* Remove list elements to perform the trim */
4371 for (j
= 0; j
< ltrim
; j
++) {
4372 ln
= listFirst(list
);
4373 listDelNode(list
,ln
);
4375 for (j
= 0; j
< rtrim
; j
++) {
4376 ln
= listLast(list
);
4377 listDelNode(list
,ln
);
4380 addReply(c
,shared
.ok
);
4385 static void lremCommand(redisClient
*c
) {
4388 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4390 addReply(c
,shared
.czero
);
4392 if (o
->type
!= REDIS_LIST
) {
4393 addReply(c
,shared
.wrongtypeerr
);
4395 list
*list
= o
->ptr
;
4396 listNode
*ln
, *next
;
4397 int toremove
= atoi(c
->argv
[2]->ptr
);
4402 toremove
= -toremove
;
4405 ln
= fromtail
? list
->tail
: list
->head
;
4407 robj
*ele
= listNodeValue(ln
);
4409 next
= fromtail
? ln
->prev
: ln
->next
;
4410 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
4411 listDelNode(list
,ln
);
4414 if (toremove
&& removed
== toremove
) break;
4418 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4423 /* This is the semantic of this command:
4424 * RPOPLPUSH srclist dstlist:
4425 * IF LLEN(srclist) > 0
4426 * element = RPOP srclist
4427 * LPUSH dstlist element
4434 * The idea is to be able to get an element from a list in a reliable way
4435 * since the element is not just returned but pushed against another list
4436 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4438 static void rpoplpushcommand(redisClient
*c
) {
4441 sobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4443 addReply(c
,shared
.nullbulk
);
4445 if (sobj
->type
!= REDIS_LIST
) {
4446 addReply(c
,shared
.wrongtypeerr
);
4448 list
*srclist
= sobj
->ptr
;
4449 listNode
*ln
= listLast(srclist
);
4452 addReply(c
,shared
.nullbulk
);
4454 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4455 robj
*ele
= listNodeValue(ln
);
4458 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4459 addReply(c
,shared
.wrongtypeerr
);
4463 /* Add the element to the target list (unless it's directly
4464 * passed to some BLPOP-ing client */
4465 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4467 /* Create the list if the key does not exist */
4468 dobj
= createListObject();
4469 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4470 incrRefCount(c
->argv
[2]);
4472 dstlist
= dobj
->ptr
;
4473 listAddNodeHead(dstlist
,ele
);
4477 /* Send the element to the client as reply as well */
4478 addReplyBulkLen(c
,ele
);
4480 addReply(c
,shared
.crlf
);
4482 /* Finally remove the element from the source list */
4483 listDelNode(srclist
,ln
);
4491 /* ==================================== Sets ================================ */
4493 static void saddCommand(redisClient
*c
) {
4496 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4498 set
= createSetObject();
4499 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4500 incrRefCount(c
->argv
[1]);
4502 if (set
->type
!= REDIS_SET
) {
4503 addReply(c
,shared
.wrongtypeerr
);
4507 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4508 incrRefCount(c
->argv
[2]);
4510 addReply(c
,shared
.cone
);
4512 addReply(c
,shared
.czero
);
4516 static void sremCommand(redisClient
*c
) {
4519 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4521 addReply(c
,shared
.czero
);
4523 if (set
->type
!= REDIS_SET
) {
4524 addReply(c
,shared
.wrongtypeerr
);
4527 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4529 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4530 addReply(c
,shared
.cone
);
4532 addReply(c
,shared
.czero
);
4537 static void smoveCommand(redisClient
*c
) {
4538 robj
*srcset
, *dstset
;
4540 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4541 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4543 /* If the source key does not exist return 0, if it's of the wrong type
4545 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4546 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4549 /* Error if the destination key is not a set as well */
4550 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4551 addReply(c
,shared
.wrongtypeerr
);
4554 /* Remove the element from the source set */
4555 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4556 /* Key not found in the src set! return zero */
4557 addReply(c
,shared
.czero
);
4561 /* Add the element to the destination set */
4563 dstset
= createSetObject();
4564 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4565 incrRefCount(c
->argv
[2]);
4567 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4568 incrRefCount(c
->argv
[3]);
4569 addReply(c
,shared
.cone
);
4572 static void sismemberCommand(redisClient
*c
) {
4575 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4577 addReply(c
,shared
.czero
);
4579 if (set
->type
!= REDIS_SET
) {
4580 addReply(c
,shared
.wrongtypeerr
);
4583 if (dictFind(set
->ptr
,c
->argv
[2]))
4584 addReply(c
,shared
.cone
);
4586 addReply(c
,shared
.czero
);
4590 static void scardCommand(redisClient
*c
) {
4594 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4596 addReply(c
,shared
.czero
);
4599 if (o
->type
!= REDIS_SET
) {
4600 addReply(c
,shared
.wrongtypeerr
);
4603 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4609 static void spopCommand(redisClient
*c
) {
4613 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4615 addReply(c
,shared
.nullbulk
);
4617 if (set
->type
!= REDIS_SET
) {
4618 addReply(c
,shared
.wrongtypeerr
);
4621 de
= dictGetRandomKey(set
->ptr
);
4623 addReply(c
,shared
.nullbulk
);
4625 robj
*ele
= dictGetEntryKey(de
);
4627 addReplyBulkLen(c
,ele
);
4629 addReply(c
,shared
.crlf
);
4630 dictDelete(set
->ptr
,ele
);
4631 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4637 static void srandmemberCommand(redisClient
*c
) {
4641 set
= lookupKeyRead(c
->db
,c
->argv
[1]);
4643 addReply(c
,shared
.nullbulk
);
4645 if (set
->type
!= REDIS_SET
) {
4646 addReply(c
,shared
.wrongtypeerr
);
4649 de
= dictGetRandomKey(set
->ptr
);
4651 addReply(c
,shared
.nullbulk
);
4653 robj
*ele
= dictGetEntryKey(de
);
4655 addReplyBulkLen(c
,ele
);
4657 addReply(c
,shared
.crlf
);
4662 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4663 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4665 return dictSize(*d1
)-dictSize(*d2
);
4668 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4669 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4672 robj
*lenobj
= NULL
, *dstset
= NULL
;
4673 unsigned long j
, cardinality
= 0;
4675 for (j
= 0; j
< setsnum
; j
++) {
4679 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4680 lookupKeyRead(c
->db
,setskeys
[j
]);
4684 if (deleteKey(c
->db
,dstkey
))
4686 addReply(c
,shared
.czero
);
4688 addReply(c
,shared
.nullmultibulk
);
4692 if (setobj
->type
!= REDIS_SET
) {
4694 addReply(c
,shared
.wrongtypeerr
);
4697 dv
[j
] = setobj
->ptr
;
4699 /* Sort sets from the smallest to largest, this will improve our
4700 * algorithm's performace */
4701 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4703 /* The first thing we should output is the total number of elements...
4704 * since this is a multi-bulk write, but at this stage we don't know
4705 * the intersection set size, so we use a trick, append an empty object
4706 * to the output list and save the pointer to later modify it with the
4709 lenobj
= createObject(REDIS_STRING
,NULL
);
4711 decrRefCount(lenobj
);
4713 /* If we have a target key where to store the resulting set
4714 * create this key with an empty set inside */
4715 dstset
= createSetObject();
4718 /* Iterate all the elements of the first (smallest) set, and test
4719 * the element against all the other sets, if at least one set does
4720 * not include the element it is discarded */
4721 di
= dictGetIterator(dv
[0]);
4723 while((de
= dictNext(di
)) != NULL
) {
4726 for (j
= 1; j
< setsnum
; j
++)
4727 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4729 continue; /* at least one set does not contain the member */
4730 ele
= dictGetEntryKey(de
);
4732 addReplyBulkLen(c
,ele
);
4734 addReply(c
,shared
.crlf
);
4737 dictAdd(dstset
->ptr
,ele
,NULL
);
4741 dictReleaseIterator(di
);
4744 /* Store the resulting set into the target */
4745 deleteKey(c
->db
,dstkey
);
4746 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4747 incrRefCount(dstkey
);
4751 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4753 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4754 dictSize((dict
*)dstset
->ptr
)));
4760 static void sinterCommand(redisClient
*c
) {
4761 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4764 static void sinterstoreCommand(redisClient
*c
) {
4765 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4768 #define REDIS_OP_UNION 0
4769 #define REDIS_OP_DIFF 1
4771 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4772 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4775 robj
*dstset
= NULL
;
4776 int j
, cardinality
= 0;
4778 for (j
= 0; j
< setsnum
; j
++) {
4782 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4783 lookupKeyRead(c
->db
,setskeys
[j
]);
4788 if (setobj
->type
!= REDIS_SET
) {
4790 addReply(c
,shared
.wrongtypeerr
);
4793 dv
[j
] = setobj
->ptr
;
4796 /* We need a temp set object to store our union. If the dstkey
4797 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4798 * this set object will be the resulting object to set into the target key*/
4799 dstset
= createSetObject();
4801 /* Iterate all the elements of all the sets, add every element a single
4802 * time to the result set */
4803 for (j
= 0; j
< setsnum
; j
++) {
4804 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4805 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4807 di
= dictGetIterator(dv
[j
]);
4809 while((de
= dictNext(di
)) != NULL
) {
4812 /* dictAdd will not add the same element multiple times */
4813 ele
= dictGetEntryKey(de
);
4814 if (op
== REDIS_OP_UNION
|| j
== 0) {
4815 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4819 } else if (op
== REDIS_OP_DIFF
) {
4820 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4825 dictReleaseIterator(di
);
4827 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break; /* result set is empty */
4830 /* Output the content of the resulting set, if not in STORE mode */
4832 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4833 di
= dictGetIterator(dstset
->ptr
);
4834 while((de
= dictNext(di
)) != NULL
) {
4837 ele
= dictGetEntryKey(de
);
4838 addReplyBulkLen(c
,ele
);
4840 addReply(c
,shared
.crlf
);
4842 dictReleaseIterator(di
);
4844 /* If we have a target key where to store the resulting set
4845 * create this key with the result set inside */
4846 deleteKey(c
->db
,dstkey
);
4847 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4848 incrRefCount(dstkey
);
4853 decrRefCount(dstset
);
4855 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",
4856 dictSize((dict
*)dstset
->ptr
)));
4862 static void sunionCommand(redisClient
*c
) {
4863 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4866 static void sunionstoreCommand(redisClient
*c
) {
4867 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4870 static void sdiffCommand(redisClient
*c
) {
4871 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4874 static void sdiffstoreCommand(redisClient
*c
) {
4875 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4878 /* ==================================== ZSets =============================== */
4880 /* ZSETs are ordered sets using two data structures to hold the same elements
4881 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4884 * The elements are added to an hash table mapping Redis objects to scores.
4885 * At the same time the elements are added to a skip list mapping scores
4886 * to Redis objects (so objects are sorted by scores in this "view"). */
4888 /* This skiplist implementation is almost a C translation of the original
4889 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4890 * Alternative to Balanced Trees", modified in three ways:
4891 * a) this implementation allows for repeated values.
4892 * b) the comparison is not just by key (our 'score') but by satellite data.
4893 * c) there is a back pointer, so it's a doubly linked list with the back
4894 * pointers being only at "level 1". This allows to traverse the list
4895 * from tail to head, useful for ZREVRANGE. */
4897 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4898 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4900 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4902 zn
->span
= zmalloc(sizeof(unsigned int) * (level
- 1));
4908 static zskiplist
*zslCreate(void) {
4912 zsl
= zmalloc(sizeof(*zsl
));
4915 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4916 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
4917 zsl
->header
->forward
[j
] = NULL
;
4919 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
4920 if (j
< ZSKIPLIST_MAXLEVEL
-1)
4921 zsl
->header
->span
[j
] = 0;
4923 zsl
->header
->backward
= NULL
;
4928 static void zslFreeNode(zskiplistNode
*node
) {
4929 decrRefCount(node
->obj
);
4930 zfree(node
->forward
);
4935 static void zslFree(zskiplist
*zsl
) {
4936 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4938 zfree(zsl
->header
->forward
);
4939 zfree(zsl
->header
->span
);
4942 next
= node
->forward
[0];
4949 static int zslRandomLevel(void) {
4951 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
4956 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
4957 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
4958 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
4962 for (i
= zsl
->level
-1; i
>= 0; i
--) {
4963 /* store rank that is crossed to reach the insert position */
4964 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
4966 while (x
->forward
[i
] &&
4967 (x
->forward
[i
]->score
< score
||
4968 (x
->forward
[i
]->score
== score
&&
4969 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0))) {
4970 rank
[i
] += i
> 0 ? x
->span
[i
-1] : 1;
4975 /* we assume the key is not already inside, since we allow duplicated
4976 * scores, and the re-insertion of score and redis object should never
4977 * happpen since the caller of zslInsert() should test in the hash table
4978 * if the element is already inside or not. */
4979 level
= zslRandomLevel();
4980 if (level
> zsl
->level
) {
4981 for (i
= zsl
->level
; i
< level
; i
++) {
4983 update
[i
] = zsl
->header
;
4984 update
[i
]->span
[i
-1] = zsl
->length
;
4988 x
= zslCreateNode(level
,score
,obj
);
4989 for (i
= 0; i
< level
; i
++) {
4990 x
->forward
[i
] = update
[i
]->forward
[i
];
4991 update
[i
]->forward
[i
] = x
;
4993 /* update span covered by update[i] as x is inserted here */
4995 x
->span
[i
-1] = update
[i
]->span
[i
-1] - (rank
[0] - rank
[i
]);
4996 update
[i
]->span
[i
-1] = (rank
[0] - rank
[i
]) + 1;
5000 /* increment span for untouched levels */
5001 for (i
= level
; i
< zsl
->level
; i
++) {
5002 update
[i
]->span
[i
-1]++;
5005 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
5007 x
->forward
[0]->backward
= x
;
5013 /* Delete an element with matching score/object from the skiplist. */
5014 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
5015 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5019 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5020 while (x
->forward
[i
] &&
5021 (x
->forward
[i
]->score
< score
||
5022 (x
->forward
[i
]->score
== score
&&
5023 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
5027 /* We may have multiple elements with the same score, what we need
5028 * is to find the element with both the right score and object. */
5030 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
5031 for (i
= 0; i
< zsl
->level
; i
++) {
5032 if (update
[i
]->forward
[i
] == x
) {
5034 update
[i
]->span
[i
-1] += x
->span
[i
-1] - 1;
5036 update
[i
]->forward
[i
] = x
->forward
[i
];
5038 /* invariant: i > 0, because update[0]->forward[0]
5039 * is always equal to x */
5040 update
[i
]->span
[i
-1] -= 1;
5043 if (x
->forward
[0]) {
5044 x
->forward
[0]->backward
= x
->backward
;
5046 zsl
->tail
= x
->backward
;
5049 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
5054 return 0; /* not found */
5056 return 0; /* not found */
5059 /* Delete all the elements with score between min and max from the skiplist.
5060 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5061 * Note that this function takes the reference to the hash table view of the
5062 * sorted set, in order to remove the elements from the hash table too. */
5063 static unsigned long zslDeleteRange(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
5064 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5065 unsigned long removed
= 0;
5069 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5070 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
5074 /* We may have multiple elements with the same score, what we need
5075 * is to find the element with both the right score and object. */
5077 while (x
&& x
->score
<= max
) {
5078 zskiplistNode
*next
;
5080 for (i
= 0; i
< zsl
->level
; i
++) {
5081 if (update
[i
]->forward
[i
] == x
) {
5083 update
[i
]->span
[i
-1] += x
->span
[i
-1] - 1;
5085 update
[i
]->forward
[i
] = x
->forward
[i
];
5087 /* invariant: i > 0, because update[0]->forward[0]
5088 * is always equal to x */
5089 update
[i
]->span
[i
-1] -= 1;
5092 if (x
->forward
[0]) {
5093 x
->forward
[0]->backward
= x
->backward
;
5095 zsl
->tail
= x
->backward
;
5097 next
= x
->forward
[0];
5098 dictDelete(dict
,x
->obj
);
5100 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
5106 return removed
; /* not found */
5109 /* Find the first node having a score equal or greater than the specified one.
5110 * Returns NULL if there is no match. */
5111 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
5116 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5117 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
5120 /* We may have multiple elements with the same score, what we need
5121 * is to find the element with both the right score and object. */
5122 return x
->forward
[0];
5125 /* Find the rank for an element by both score and key.
5126 * Returns 0 when the element cannot be found, rank otherwise.
5127 * Note that the rank is 1-based due to the span of zsl->header to the
5129 static unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
5131 unsigned long rank
= 0;
5135 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5136 while (x
->forward
[i
] &&
5137 (x
->forward
[i
]->score
< score
||
5138 (x
->forward
[i
]->score
== score
&&
5139 compareStringObjects(x
->forward
[i
]->obj
,o
) <= 0))) {
5140 rank
+= i
> 0 ? x
->span
[i
-1] : 1;
5144 /* x might be equal to zsl->header, so test if obj is non-NULL */
5145 if (x
->obj
&& compareStringObjects(x
->obj
,o
) == 0) {
5152 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5153 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
5155 unsigned long traversed
= 0;
5159 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5160 while (x
->forward
[i
] && (traversed
+ (i
> 0 ? x
->span
[i
-1] : 1)) <= rank
) {
5161 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5165 if (traversed
== rank
) {
5172 /* The actual Z-commands implementations */
5174 /* This generic command implements both ZADD and ZINCRBY.
5175 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5176 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5177 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
5182 zsetobj
= lookupKeyWrite(c
->db
,key
);
5183 if (zsetobj
== NULL
) {
5184 zsetobj
= createZsetObject();
5185 dictAdd(c
->db
->dict
,key
,zsetobj
);
5188 if (zsetobj
->type
!= REDIS_ZSET
) {
5189 addReply(c
,shared
.wrongtypeerr
);
5195 /* Ok now since we implement both ZADD and ZINCRBY here the code
5196 * needs to handle the two different conditions. It's all about setting
5197 * '*score', that is, the new score to set, to the right value. */
5198 score
= zmalloc(sizeof(double));
5202 /* Read the old score. If the element was not present starts from 0 */
5203 de
= dictFind(zs
->dict
,ele
);
5205 double *oldscore
= dictGetEntryVal(de
);
5206 *score
= *oldscore
+ scoreval
;
5214 /* What follows is a simple remove and re-insert operation that is common
5215 * to both ZADD and ZINCRBY... */
5216 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
5217 /* case 1: New element */
5218 incrRefCount(ele
); /* added to hash */
5219 zslInsert(zs
->zsl
,*score
,ele
);
5220 incrRefCount(ele
); /* added to skiplist */
5223 addReplyDouble(c
,*score
);
5225 addReply(c
,shared
.cone
);
5230 /* case 2: Score update operation */
5231 de
= dictFind(zs
->dict
,ele
);
5232 redisAssert(de
!= NULL
);
5233 oldscore
= dictGetEntryVal(de
);
5234 if (*score
!= *oldscore
) {
5237 /* Remove and insert the element in the skip list with new score */
5238 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
5239 redisAssert(deleted
!= 0);
5240 zslInsert(zs
->zsl
,*score
,ele
);
5242 /* Update the score in the hash table */
5243 dictReplace(zs
->dict
,ele
,score
);
5249 addReplyDouble(c
,*score
);
5251 addReply(c
,shared
.czero
);
5255 static void zaddCommand(redisClient
*c
) {
5258 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
5259 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
5262 static void zincrbyCommand(redisClient
*c
) {
5265 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
5266 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
5269 static void zremCommand(redisClient
*c
) {
5273 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5274 if (zsetobj
== NULL
) {
5275 addReply(c
,shared
.czero
);
5281 if (zsetobj
->type
!= REDIS_ZSET
) {
5282 addReply(c
,shared
.wrongtypeerr
);
5286 de
= dictFind(zs
->dict
,c
->argv
[2]);
5288 addReply(c
,shared
.czero
);
5291 /* Delete from the skiplist */
5292 oldscore
= dictGetEntryVal(de
);
5293 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
5294 redisAssert(deleted
!= 0);
5296 /* Delete from the hash table */
5297 dictDelete(zs
->dict
,c
->argv
[2]);
5298 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5300 addReply(c
,shared
.cone
);
5304 static void zremrangebyscoreCommand(redisClient
*c
) {
5305 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
5306 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
5310 zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5311 if (zsetobj
== NULL
) {
5312 addReply(c
,shared
.czero
);
5316 if (zsetobj
->type
!= REDIS_ZSET
) {
5317 addReply(c
,shared
.wrongtypeerr
);
5321 deleted
= zslDeleteRange(zs
->zsl
,min
,max
,zs
->dict
);
5322 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5323 server
.dirty
+= deleted
;
5324 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",deleted
));
5328 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
5330 int start
= atoi(c
->argv
[2]->ptr
);
5331 int end
= atoi(c
->argv
[3]->ptr
);
5334 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
5336 } else if (c
->argc
>= 5) {
5337 addReply(c
,shared
.syntaxerr
);
5341 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5343 addReply(c
,shared
.nullmultibulk
);
5345 if (o
->type
!= REDIS_ZSET
) {
5346 addReply(c
,shared
.wrongtypeerr
);
5348 zset
*zsetobj
= o
->ptr
;
5349 zskiplist
*zsl
= zsetobj
->zsl
;
5352 int llen
= zsl
->length
;
5356 /* convert negative indexes */
5357 if (start
< 0) start
= llen
+start
;
5358 if (end
< 0) end
= llen
+end
;
5359 if (start
< 0) start
= 0;
5360 if (end
< 0) end
= 0;
5362 /* indexes sanity checks */
5363 if (start
> end
|| start
>= llen
) {
5364 /* Out of range start or start > end result in empty list */
5365 addReply(c
,shared
.emptymultibulk
);
5368 if (end
>= llen
) end
= llen
-1;
5369 rangelen
= (end
-start
)+1;
5371 /* check if starting point is trivial, before searching
5372 * the element in log(N) time */
5374 ln
= start
== 0 ? zsl
->tail
: zslGetElementByRank(zsl
, llen
- start
);
5376 ln
= start
== 0 ? zsl
->header
->forward
[0] : zslGetElementByRank(zsl
, start
+ 1);
5379 /* Return the result in form of a multi-bulk reply */
5380 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
5381 withscores
? (rangelen
*2) : rangelen
));
5382 for (j
= 0; j
< rangelen
; j
++) {
5384 addReplyBulkLen(c
,ele
);
5386 addReply(c
,shared
.crlf
);
5388 addReplyDouble(c
,ln
->score
);
5389 ln
= reverse
? ln
->backward
: ln
->forward
[0];
5395 static void zrangeCommand(redisClient
*c
) {
5396 zrangeGenericCommand(c
,0);
5399 static void zrevrangeCommand(redisClient
*c
) {
5400 zrangeGenericCommand(c
,1);
5403 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
5404 * If justcount is non-zero, just the count is returned. */
5405 static void genericZrangebyscoreCommand(redisClient
*c
, int justcount
) {
5408 int minex
= 0, maxex
= 0; /* are min or max exclusive? */
5409 int offset
= 0, limit
= -1;
5413 /* Parse the min-max interval. If one of the values is prefixed
5414 * by the "(" character, it's considered "open". For instance
5415 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
5416 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
5417 if (((char*)c
->argv
[2]->ptr
)[0] == '(') {
5418 min
= strtod((char*)c
->argv
[2]->ptr
+1,NULL
);
5421 min
= strtod(c
->argv
[2]->ptr
,NULL
);
5423 if (((char*)c
->argv
[3]->ptr
)[0] == '(') {
5424 max
= strtod((char*)c
->argv
[3]->ptr
+1,NULL
);
5427 max
= strtod(c
->argv
[3]->ptr
,NULL
);
5430 /* Parse "WITHSCORES": note that if the command was called with
5431 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
5432 * enter the following paths to parse WITHSCORES and LIMIT. */
5433 if (c
->argc
== 5 || c
->argc
== 8) {
5434 if (strcasecmp(c
->argv
[c
->argc
-1]->ptr
,"withscores") == 0)
5439 if (c
->argc
!= (4 + withscores
) && c
->argc
!= (7 + withscores
))
5443 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5448 if (c
->argc
== (7 + withscores
) && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
5449 addReply(c
,shared
.syntaxerr
);
5451 } else if (c
->argc
== (7 + withscores
)) {
5452 offset
= atoi(c
->argv
[5]->ptr
);
5453 limit
= atoi(c
->argv
[6]->ptr
);
5454 if (offset
< 0) offset
= 0;
5457 /* Ok, lookup the key and get the range */
5458 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5460 addReply(c
,justcount
? shared
.czero
: shared
.nullmultibulk
);
5462 if (o
->type
!= REDIS_ZSET
) {
5463 addReply(c
,shared
.wrongtypeerr
);
5465 zset
*zsetobj
= o
->ptr
;
5466 zskiplist
*zsl
= zsetobj
->zsl
;
5468 robj
*ele
, *lenobj
= NULL
;
5469 unsigned long rangelen
= 0;
5471 /* Get the first node with the score >= min, or with
5472 * score > min if 'minex' is true. */
5473 ln
= zslFirstWithScore(zsl
,min
);
5474 while (minex
&& ln
&& ln
->score
== min
) ln
= ln
->forward
[0];
5477 /* No element matching the speciifed interval */
5478 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
5482 /* We don't know in advance how many matching elements there
5483 * are in the list, so we push this object that will represent
5484 * the multi-bulk length in the output buffer, and will "fix"
5487 lenobj
= createObject(REDIS_STRING
,NULL
);
5489 decrRefCount(lenobj
);
5492 while(ln
&& (maxex
? (ln
->score
< max
) : (ln
->score
<= max
))) {
5495 ln
= ln
->forward
[0];
5498 if (limit
== 0) break;
5501 addReplyBulkLen(c
,ele
);
5503 addReply(c
,shared
.crlf
);
5505 addReplyDouble(c
,ln
->score
);
5507 ln
= ln
->forward
[0];
5509 if (limit
> 0) limit
--;
5512 addReplyLong(c
,(long)rangelen
);
5514 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",
5515 withscores
? (rangelen
*2) : rangelen
);
5521 static void zrangebyscoreCommand(redisClient
*c
) {
5522 genericZrangebyscoreCommand(c
,0);
5525 static void zcountCommand(redisClient
*c
) {
5526 genericZrangebyscoreCommand(c
,1);
5529 static void zcardCommand(redisClient
*c
) {
5533 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5535 addReply(c
,shared
.czero
);
5538 if (o
->type
!= REDIS_ZSET
) {
5539 addReply(c
,shared
.wrongtypeerr
);
5542 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",zs
->zsl
->length
));
5547 static void zscoreCommand(redisClient
*c
) {
5551 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5553 addReply(c
,shared
.nullbulk
);
5556 if (o
->type
!= REDIS_ZSET
) {
5557 addReply(c
,shared
.wrongtypeerr
);
5562 de
= dictFind(zs
->dict
,c
->argv
[2]);
5564 addReply(c
,shared
.nullbulk
);
5566 double *score
= dictGetEntryVal(de
);
5568 addReplyDouble(c
,*score
);
5574 static void zrankCommand(redisClient
*c
) {
5576 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5578 addReply(c
,shared
.nullbulk
);
5581 if (o
->type
!= REDIS_ZSET
) {
5582 addReply(c
,shared
.wrongtypeerr
);
5585 zskiplist
*zsl
= zs
->zsl
;
5589 de
= dictFind(zs
->dict
,c
->argv
[2]);
5591 addReply(c
,shared
.nullbulk
);
5595 double *score
= dictGetEntryVal(de
);
5596 rank
= zslGetRank(zsl
, *score
, c
->argv
[2]);
5598 addReplyLong(c
, rank
-1);
5600 addReply(c
,shared
.nullbulk
);
5605 /* =================================== Hashes =============================== */
5606 static void hsetCommand(redisClient
*c
) {
5608 robj
*o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5611 o
= createHashObject();
5612 dictAdd(c
->db
->dict
,c
->argv
[1],o
);
5613 incrRefCount(c
->argv
[1]);
5615 if (o
->type
!= REDIS_HASH
) {
5616 addReply(c
,shared
.wrongtypeerr
);
5620 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
5621 unsigned char *zm
= o
->ptr
;
5623 zm
= zipmapSet(zm
,c
->argv
[2]->ptr
,sdslen(c
->argv
[2]->ptr
),
5624 c
->argv
[3]->ptr
,sdslen(c
->argv
[3]->ptr
),&update
);
5627 if (dictAdd(o
->ptr
,c
->argv
[2],c
->argv
[3]) == DICT_OK
) {
5628 incrRefCount(c
->argv
[2]);
5632 incrRefCount(c
->argv
[3]);
5635 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",update
== 0));
5638 static void hgetCommand(redisClient
*c
) {
5639 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5642 addReply(c
,shared
.nullbulk
);
5645 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
5646 unsigned char *zm
= o
->ptr
;
5650 if (zipmapGet(zm
,c
->argv
[2]->ptr
,sdslen(c
->argv
[2]->ptr
), &val
,&vlen
)) {
5651 addReplySds(c
,sdscatprintf(sdsempty(),"$%u\r\n", vlen
));
5652 addReplySds(c
,sdsnewlen(val
,vlen
));
5653 addReply(c
,shared
.crlf
);
5656 addReply(c
,shared
.nullbulk
);
5660 struct dictEntry
*de
;
5662 de
= dictFind(o
->ptr
,c
->argv
[2]);
5664 addReply(c
,shared
.nullbulk
);
5666 robj
*e
= dictGetEntryVal(de
);
5668 addReplyBulkLen(c
,e
);
5670 addReply(c
,shared
.crlf
);
5676 /* ========================= Non type-specific commands ==================== */
5678 static void flushdbCommand(redisClient
*c
) {
5679 server
.dirty
+= dictSize(c
->db
->dict
);
5680 dictEmpty(c
->db
->dict
);
5681 dictEmpty(c
->db
->expires
);
5682 addReply(c
,shared
.ok
);
5685 static void flushallCommand(redisClient
*c
) {
5686 server
.dirty
+= emptyDb();
5687 addReply(c
,shared
.ok
);
5688 rdbSave(server
.dbfilename
);
5692 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
5693 redisSortOperation
*so
= zmalloc(sizeof(*so
));
5695 so
->pattern
= pattern
;
5699 /* Return the value associated to the key with a name obtained
5700 * substituting the first occurence of '*' in 'pattern' with 'subst' */
5701 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
5705 int prefixlen
, sublen
, postfixlen
;
5706 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
5710 char buf
[REDIS_SORTKEY_MAX
+1];
5713 /* If the pattern is "#" return the substitution object itself in order
5714 * to implement the "SORT ... GET #" feature. */
5715 spat
= pattern
->ptr
;
5716 if (spat
[0] == '#' && spat
[1] == '\0') {
5720 /* The substitution object may be specially encoded. If so we create
5721 * a decoded object on the fly. Otherwise getDecodedObject will just
5722 * increment the ref count, that we'll decrement later. */
5723 subst
= getDecodedObject(subst
);
5726 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
5727 p
= strchr(spat
,'*');
5729 decrRefCount(subst
);
5734 sublen
= sdslen(ssub
);
5735 postfixlen
= sdslen(spat
)-(prefixlen
+1);
5736 memcpy(keyname
.buf
,spat
,prefixlen
);
5737 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
5738 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
5739 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
5740 keyname
.len
= prefixlen
+sublen
+postfixlen
;
5742 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
5743 decrRefCount(subst
);
5745 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
5746 return lookupKeyRead(db
,&keyobj
);
5749 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
5750 * the additional parameter is not standard but a BSD-specific we have to
5751 * pass sorting parameters via the global 'server' structure */
5752 static int sortCompare(const void *s1
, const void *s2
) {
5753 const redisSortObject
*so1
= s1
, *so2
= s2
;
5756 if (!server
.sort_alpha
) {
5757 /* Numeric sorting. Here it's trivial as we precomputed scores */
5758 if (so1
->u
.score
> so2
->u
.score
) {
5760 } else if (so1
->u
.score
< so2
->u
.score
) {
5766 /* Alphanumeric sorting */
5767 if (server
.sort_bypattern
) {
5768 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
5769 /* At least one compare object is NULL */
5770 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
5772 else if (so1
->u
.cmpobj
== NULL
)
5777 /* We have both the objects, use strcoll */
5778 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
5781 /* Compare elements directly */
5784 dec1
= getDecodedObject(so1
->obj
);
5785 dec2
= getDecodedObject(so2
->obj
);
5786 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
5791 return server
.sort_desc
? -cmp
: cmp
;
5794 /* The SORT command is the most complex command in Redis. Warning: this code
5795 * is optimized for speed and a bit less for readability */
5796 static void sortCommand(redisClient
*c
) {
5799 int desc
= 0, alpha
= 0;
5800 int limit_start
= 0, limit_count
= -1, start
, end
;
5801 int j
, dontsort
= 0, vectorlen
;
5802 int getop
= 0; /* GET operation counter */
5803 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
5804 redisSortObject
*vector
; /* Resulting vector to sort */
5806 /* Lookup the key to sort. It must be of the right types */
5807 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
5808 if (sortval
== NULL
) {
5809 addReply(c
,shared
.nullmultibulk
);
5812 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
5813 sortval
->type
!= REDIS_ZSET
)
5815 addReply(c
,shared
.wrongtypeerr
);
5819 /* Create a list of operations to perform for every sorted element.
5820 * Operations can be GET/DEL/INCR/DECR */
5821 operations
= listCreate();
5822 listSetFreeMethod(operations
,zfree
);
5825 /* Now we need to protect sortval incrementing its count, in the future
5826 * SORT may have options able to overwrite/delete keys during the sorting
5827 * and the sorted key itself may get destroied */
5828 incrRefCount(sortval
);
5830 /* The SORT command has an SQL-alike syntax, parse it */
5831 while(j
< c
->argc
) {
5832 int leftargs
= c
->argc
-j
-1;
5833 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
5835 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
5837 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
5839 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
5840 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
5841 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
5843 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
5844 storekey
= c
->argv
[j
+1];
5846 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
5847 sortby
= c
->argv
[j
+1];
5848 /* If the BY pattern does not contain '*', i.e. it is constant,
5849 * we don't need to sort nor to lookup the weight keys. */
5850 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
5852 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
5853 listAddNodeTail(operations
,createSortOperation(
5854 REDIS_SORT_GET
,c
->argv
[j
+1]));
5858 decrRefCount(sortval
);
5859 listRelease(operations
);
5860 addReply(c
,shared
.syntaxerr
);
5866 /* Load the sorting vector with all the objects to sort */
5867 switch(sortval
->type
) {
5868 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
5869 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
5870 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
5871 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
5873 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
5876 if (sortval
->type
== REDIS_LIST
) {
5877 list
*list
= sortval
->ptr
;
5881 listRewind(list
,&li
);
5882 while((ln
= listNext(&li
))) {
5883 robj
*ele
= ln
->value
;
5884 vector
[j
].obj
= ele
;
5885 vector
[j
].u
.score
= 0;
5886 vector
[j
].u
.cmpobj
= NULL
;
5894 if (sortval
->type
== REDIS_SET
) {
5897 zset
*zs
= sortval
->ptr
;
5901 di
= dictGetIterator(set
);
5902 while((setele
= dictNext(di
)) != NULL
) {
5903 vector
[j
].obj
= dictGetEntryKey(setele
);
5904 vector
[j
].u
.score
= 0;
5905 vector
[j
].u
.cmpobj
= NULL
;
5908 dictReleaseIterator(di
);
5910 redisAssert(j
== vectorlen
);
5912 /* Now it's time to load the right scores in the sorting vector */
5913 if (dontsort
== 0) {
5914 for (j
= 0; j
< vectorlen
; j
++) {
5918 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
5919 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
5921 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
5923 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
5924 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
5926 /* Don't need to decode the object if it's
5927 * integer-encoded (the only encoding supported) so
5928 * far. We can just cast it */
5929 if (byval
->encoding
== REDIS_ENCODING_INT
) {
5930 vector
[j
].u
.score
= (long)byval
->ptr
;
5932 redisAssert(1 != 1);
5937 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
5938 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
5940 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
5941 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
5943 redisAssert(1 != 1);
5950 /* We are ready to sort the vector... perform a bit of sanity check
5951 * on the LIMIT option too. We'll use a partial version of quicksort. */
5952 start
= (limit_start
< 0) ? 0 : limit_start
;
5953 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
5954 if (start
>= vectorlen
) {
5955 start
= vectorlen
-1;
5958 if (end
>= vectorlen
) end
= vectorlen
-1;
5960 if (dontsort
== 0) {
5961 server
.sort_desc
= desc
;
5962 server
.sort_alpha
= alpha
;
5963 server
.sort_bypattern
= sortby
? 1 : 0;
5964 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
5965 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
5967 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
5970 /* Send command output to the output buffer, performing the specified
5971 * GET/DEL/INCR/DECR operations if any. */
5972 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
5973 if (storekey
== NULL
) {
5974 /* STORE option not specified, sent the sorting result to client */
5975 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
5976 for (j
= start
; j
<= end
; j
++) {
5981 addReplyBulkLen(c
,vector
[j
].obj
);
5982 addReply(c
,vector
[j
].obj
);
5983 addReply(c
,shared
.crlf
);
5985 listRewind(operations
,&li
);
5986 while((ln
= listNext(&li
))) {
5987 redisSortOperation
*sop
= ln
->value
;
5988 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
5991 if (sop
->type
== REDIS_SORT_GET
) {
5992 if (!val
|| val
->type
!= REDIS_STRING
) {
5993 addReply(c
,shared
.nullbulk
);
5995 addReplyBulkLen(c
,val
);
5997 addReply(c
,shared
.crlf
);
6000 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
6005 robj
*listObject
= createListObject();
6006 list
*listPtr
= (list
*) listObject
->ptr
;
6008 /* STORE option specified, set the sorting result as a List object */
6009 for (j
= start
; j
<= end
; j
++) {
6014 listAddNodeTail(listPtr
,vector
[j
].obj
);
6015 incrRefCount(vector
[j
].obj
);
6017 listRewind(operations
,&li
);
6018 while((ln
= listNext(&li
))) {
6019 redisSortOperation
*sop
= ln
->value
;
6020 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
6023 if (sop
->type
== REDIS_SORT_GET
) {
6024 if (!val
|| val
->type
!= REDIS_STRING
) {
6025 listAddNodeTail(listPtr
,createStringObject("",0));
6027 listAddNodeTail(listPtr
,val
);
6031 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
6035 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
6036 incrRefCount(storekey
);
6038 /* Note: we add 1 because the DB is dirty anyway since even if the
6039 * SORT result is empty a new key is set and maybe the old content
6041 server
.dirty
+= 1+outputlen
;
6042 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
6046 decrRefCount(sortval
);
6047 listRelease(operations
);
6048 for (j
= 0; j
< vectorlen
; j
++) {
6049 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
6050 decrRefCount(vector
[j
].u
.cmpobj
);
6055 /* Convert an amount of bytes into a human readable string in the form
6056 * of 100B, 2G, 100M, 4K, and so forth. */
6057 static void bytesToHuman(char *s
, unsigned long long n
) {
6062 sprintf(s
,"%lluB",n
);
6064 } else if (n
< (1024*1024)) {
6065 d
= (double)n
/(1024);
6066 sprintf(s
,"%.2fK",d
);
6067 } else if (n
< (1024LL*1024*1024)) {
6068 d
= (double)n
/(1024*1024);
6069 sprintf(s
,"%.2fM",d
);
6070 } else if (n
< (1024LL*1024*1024*1024)) {
6071 d
= (double)n
/(1024LL*1024*1024);
6072 sprintf(s
,"%.2fG",d
);
6076 /* Create the string returned by the INFO command. This is decoupled
6077 * by the INFO command itself as we need to report the same information
6078 * on memory corruption problems. */
6079 static sds
genRedisInfoString(void) {
6081 time_t uptime
= time(NULL
)-server
.stat_starttime
;
6085 bytesToHuman(hmem
,zmalloc_used_memory());
6086 info
= sdscatprintf(sdsempty(),
6087 "redis_version:%s\r\n"
6089 "multiplexing_api:%s\r\n"
6090 "process_id:%ld\r\n"
6091 "uptime_in_seconds:%ld\r\n"
6092 "uptime_in_days:%ld\r\n"
6093 "connected_clients:%d\r\n"
6094 "connected_slaves:%d\r\n"
6095 "blocked_clients:%d\r\n"
6096 "used_memory:%zu\r\n"
6097 "used_memory_human:%s\r\n"
6098 "changes_since_last_save:%lld\r\n"
6099 "bgsave_in_progress:%d\r\n"
6100 "last_save_time:%ld\r\n"
6101 "bgrewriteaof_in_progress:%d\r\n"
6102 "total_connections_received:%lld\r\n"
6103 "total_commands_processed:%lld\r\n"
6107 (sizeof(long) == 8) ? "64" : "32",
6112 listLength(server
.clients
)-listLength(server
.slaves
),
6113 listLength(server
.slaves
),
6114 server
.blpop_blocked_clients
,
6115 zmalloc_used_memory(),
6118 server
.bgsavechildpid
!= -1,
6120 server
.bgrewritechildpid
!= -1,
6121 server
.stat_numconnections
,
6122 server
.stat_numcommands
,
6123 server
.vm_enabled
!= 0,
6124 server
.masterhost
== NULL
? "master" : "slave"
6126 if (server
.masterhost
) {
6127 info
= sdscatprintf(info
,
6128 "master_host:%s\r\n"
6129 "master_port:%d\r\n"
6130 "master_link_status:%s\r\n"
6131 "master_last_io_seconds_ago:%d\r\n"
6134 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
6136 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
6139 if (server
.vm_enabled
) {
6141 info
= sdscatprintf(info
,
6142 "vm_conf_max_memory:%llu\r\n"
6143 "vm_conf_page_size:%llu\r\n"
6144 "vm_conf_pages:%llu\r\n"
6145 "vm_stats_used_pages:%llu\r\n"
6146 "vm_stats_swapped_objects:%llu\r\n"
6147 "vm_stats_swappin_count:%llu\r\n"
6148 "vm_stats_swappout_count:%llu\r\n"
6149 "vm_stats_io_newjobs_len:%lu\r\n"
6150 "vm_stats_io_processing_len:%lu\r\n"
6151 "vm_stats_io_processed_len:%lu\r\n"
6152 "vm_stats_io_active_threads:%lu\r\n"
6153 "vm_stats_blocked_clients:%lu\r\n"
6154 ,(unsigned long long) server
.vm_max_memory
,
6155 (unsigned long long) server
.vm_page_size
,
6156 (unsigned long long) server
.vm_pages
,
6157 (unsigned long long) server
.vm_stats_used_pages
,
6158 (unsigned long long) server
.vm_stats_swapped_objects
,
6159 (unsigned long long) server
.vm_stats_swapins
,
6160 (unsigned long long) server
.vm_stats_swapouts
,
6161 (unsigned long) listLength(server
.io_newjobs
),
6162 (unsigned long) listLength(server
.io_processing
),
6163 (unsigned long) listLength(server
.io_processed
),
6164 (unsigned long) server
.io_active_threads
,
6165 (unsigned long) server
.vm_blocked_clients
6169 for (j
= 0; j
< server
.dbnum
; j
++) {
6170 long long keys
, vkeys
;
6172 keys
= dictSize(server
.db
[j
].dict
);
6173 vkeys
= dictSize(server
.db
[j
].expires
);
6174 if (keys
|| vkeys
) {
6175 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
6182 static void infoCommand(redisClient
*c
) {
6183 sds info
= genRedisInfoString();
6184 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
6185 (unsigned long)sdslen(info
)));
6186 addReplySds(c
,info
);
6187 addReply(c
,shared
.crlf
);
6190 static void monitorCommand(redisClient
*c
) {
6191 /* ignore MONITOR if aleady slave or in monitor mode */
6192 if (c
->flags
& REDIS_SLAVE
) return;
6194 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
6196 listAddNodeTail(server
.monitors
,c
);
6197 addReply(c
,shared
.ok
);
6200 /* ================================= Expire ================================= */
6201 static int removeExpire(redisDb
*db
, robj
*key
) {
6202 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
6209 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
6210 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
6218 /* Return the expire time of the specified key, or -1 if no expire
6219 * is associated with this key (i.e. the key is non volatile) */
6220 static time_t getExpire(redisDb
*db
, robj
*key
) {
6223 /* No expire? return ASAP */
6224 if (dictSize(db
->expires
) == 0 ||
6225 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
6227 return (time_t) dictGetEntryVal(de
);
6230 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
6234 /* No expire? return ASAP */
6235 if (dictSize(db
->expires
) == 0 ||
6236 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
6238 /* Lookup the expire */
6239 when
= (time_t) dictGetEntryVal(de
);
6240 if (time(NULL
) <= when
) return 0;
6242 /* Delete the key */
6243 dictDelete(db
->expires
,key
);
6244 return dictDelete(db
->dict
,key
) == DICT_OK
;
6247 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
6250 /* No expire? return ASAP */
6251 if (dictSize(db
->expires
) == 0 ||
6252 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
6254 /* Delete the key */
6256 dictDelete(db
->expires
,key
);
6257 return dictDelete(db
->dict
,key
) == DICT_OK
;
6260 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
6263 de
= dictFind(c
->db
->dict
,key
);
6265 addReply(c
,shared
.czero
);
6269 if (deleteKey(c
->db
,key
)) server
.dirty
++;
6270 addReply(c
, shared
.cone
);
6273 time_t when
= time(NULL
)+seconds
;
6274 if (setExpire(c
->db
,key
,when
)) {
6275 addReply(c
,shared
.cone
);
6278 addReply(c
,shared
.czero
);
6284 static void expireCommand(redisClient
*c
) {
6285 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
6288 static void expireatCommand(redisClient
*c
) {
6289 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
6292 static void ttlCommand(redisClient
*c
) {
6296 expire
= getExpire(c
->db
,c
->argv
[1]);
6298 ttl
= (int) (expire
-time(NULL
));
6299 if (ttl
< 0) ttl
= -1;
6301 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
6304 /* ================================ MULTI/EXEC ============================== */
6306 /* Client state initialization for MULTI/EXEC */
6307 static void initClientMultiState(redisClient
*c
) {
6308 c
->mstate
.commands
= NULL
;
6309 c
->mstate
.count
= 0;
6312 /* Release all the resources associated with MULTI/EXEC state */
6313 static void freeClientMultiState(redisClient
*c
) {
6316 for (j
= 0; j
< c
->mstate
.count
; j
++) {
6318 multiCmd
*mc
= c
->mstate
.commands
+j
;
6320 for (i
= 0; i
< mc
->argc
; i
++)
6321 decrRefCount(mc
->argv
[i
]);
6324 zfree(c
->mstate
.commands
);
6327 /* Add a new command into the MULTI commands queue */
6328 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
6332 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
6333 sizeof(multiCmd
)*(c
->mstate
.count
+1));
6334 mc
= c
->mstate
.commands
+c
->mstate
.count
;
6337 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
6338 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
6339 for (j
= 0; j
< c
->argc
; j
++)
6340 incrRefCount(mc
->argv
[j
]);
6344 static void multiCommand(redisClient
*c
) {
6345 c
->flags
|= REDIS_MULTI
;
6346 addReply(c
,shared
.ok
);
6349 static void discardCommand(redisClient
*c
) {
6350 if (!(c
->flags
& REDIS_MULTI
)) {
6351 addReplySds(c
,sdsnew("-ERR DISCARD without MULTI\r\n"));
6355 freeClientMultiState(c
);
6356 initClientMultiState(c
);
6357 c
->flags
&= (~REDIS_MULTI
);
6358 addReply(c
,shared
.ok
);
6361 static void execCommand(redisClient
*c
) {
6366 if (!(c
->flags
& REDIS_MULTI
)) {
6367 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
6371 orig_argv
= c
->argv
;
6372 orig_argc
= c
->argc
;
6373 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
6374 for (j
= 0; j
< c
->mstate
.count
; j
++) {
6375 c
->argc
= c
->mstate
.commands
[j
].argc
;
6376 c
->argv
= c
->mstate
.commands
[j
].argv
;
6377 call(c
,c
->mstate
.commands
[j
].cmd
);
6379 c
->argv
= orig_argv
;
6380 c
->argc
= orig_argc
;
6381 freeClientMultiState(c
);
6382 initClientMultiState(c
);
6383 c
->flags
&= (~REDIS_MULTI
);
6386 /* =========================== Blocking Operations ========================= */
6388 /* Currently Redis blocking operations support is limited to list POP ops,
6389 * so the current implementation is not fully generic, but it is also not
6390 * completely specific so it will not require a rewrite to support new
6391 * kind of blocking operations in the future.
6393 * Still it's important to note that list blocking operations can be already
6394 * used as a notification mechanism in order to implement other blocking
6395 * operations at application level, so there must be a very strong evidence
6396 * of usefulness and generality before new blocking operations are implemented.
6398 * This is how the current blocking POP works, we use BLPOP as example:
6399 * - If the user calls BLPOP and the key exists and contains a non empty list
6400 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
6401 * if there is not to block.
6402 * - If instead BLPOP is called and the key does not exists or the list is
6403 * empty we need to block. In order to do so we remove the notification for
6404 * new data to read in the client socket (so that we'll not serve new
6405 * requests if the blocking request is not served). Also we put the client
6406 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
6407 * blocking for this keys.
6408 * - If a PUSH operation against a key with blocked clients waiting is
6409 * performed, we serve the first in the list: basically instead to push
6410 * the new element inside the list we return it to the (first / oldest)
6411 * blocking client, unblock the client, and remove it form the list.
6413 * The above comment and the source code should be enough in order to understand
6414 * the implementation and modify / fix it later.
6417 /* Set a client in blocking mode for the specified key, with the specified
6419 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
6424 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
6425 c
->blockingkeysnum
= numkeys
;
6426 c
->blockingto
= timeout
;
6427 for (j
= 0; j
< numkeys
; j
++) {
6428 /* Add the key in the client structure, to map clients -> keys */
6429 c
->blockingkeys
[j
] = keys
[j
];
6430 incrRefCount(keys
[j
]);
6432 /* And in the other "side", to map keys -> clients */
6433 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
6437 /* For every key we take a list of clients blocked for it */
6439 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
6440 incrRefCount(keys
[j
]);
6441 assert(retval
== DICT_OK
);
6443 l
= dictGetEntryVal(de
);
6445 listAddNodeTail(l
,c
);
6447 /* Mark the client as a blocked client */
6448 c
->flags
|= REDIS_BLOCKED
;
6449 server
.blpop_blocked_clients
++;
6452 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
6453 static void unblockClientWaitingData(redisClient
*c
) {
6458 assert(c
->blockingkeys
!= NULL
);
6459 /* The client may wait for multiple keys, so unblock it for every key. */
6460 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
6461 /* Remove this client from the list of clients waiting for this key. */
6462 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
6464 l
= dictGetEntryVal(de
);
6465 listDelNode(l
,listSearchKey(l
,c
));
6466 /* If the list is empty we need to remove it to avoid wasting memory */
6467 if (listLength(l
) == 0)
6468 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
6469 decrRefCount(c
->blockingkeys
[j
]);
6471 /* Cleanup the client structure */
6472 zfree(c
->blockingkeys
);
6473 c
->blockingkeys
= NULL
;
6474 c
->flags
&= (~REDIS_BLOCKED
);
6475 server
.blpop_blocked_clients
--;
6476 /* We want to process data if there is some command waiting
6477 * in the input buffer. Note that this is safe even if
6478 * unblockClientWaitingData() gets called from freeClient() because
6479 * freeClient() will be smart enough to call this function
6480 * *after* c->querybuf was set to NULL. */
6481 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
6484 /* This should be called from any function PUSHing into lists.
6485 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
6486 * 'ele' is the element pushed.
6488 * If the function returns 0 there was no client waiting for a list push
6491 * If the function returns 1 there was a client waiting for a list push
6492 * against this key, the element was passed to this client thus it's not
6493 * needed to actually add it to the list and the caller should return asap. */
6494 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
6495 struct dictEntry
*de
;
6496 redisClient
*receiver
;
6500 de
= dictFind(c
->db
->blockingkeys
,key
);
6501 if (de
== NULL
) return 0;
6502 l
= dictGetEntryVal(de
);
6505 receiver
= ln
->value
;
6507 addReplySds(receiver
,sdsnew("*2\r\n"));
6508 addReplyBulkLen(receiver
,key
);
6509 addReply(receiver
,key
);
6510 addReply(receiver
,shared
.crlf
);
6511 addReplyBulkLen(receiver
,ele
);
6512 addReply(receiver
,ele
);
6513 addReply(receiver
,shared
.crlf
);
6514 unblockClientWaitingData(receiver
);
6518 /* Blocking RPOP/LPOP */
6519 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
6524 for (j
= 1; j
< c
->argc
-1; j
++) {
6525 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
6527 if (o
->type
!= REDIS_LIST
) {
6528 addReply(c
,shared
.wrongtypeerr
);
6531 list
*list
= o
->ptr
;
6532 if (listLength(list
) != 0) {
6533 /* If the list contains elements fall back to the usual
6534 * non-blocking POP operation */
6535 robj
*argv
[2], **orig_argv
;
6538 /* We need to alter the command arguments before to call
6539 * popGenericCommand() as the command takes a single key. */
6540 orig_argv
= c
->argv
;
6541 orig_argc
= c
->argc
;
6542 argv
[1] = c
->argv
[j
];
6546 /* Also the return value is different, we need to output
6547 * the multi bulk reply header and the key name. The
6548 * "real" command will add the last element (the value)
6549 * for us. If this souds like an hack to you it's just
6550 * because it is... */
6551 addReplySds(c
,sdsnew("*2\r\n"));
6552 addReplyBulkLen(c
,argv
[1]);
6553 addReply(c
,argv
[1]);
6554 addReply(c
,shared
.crlf
);
6555 popGenericCommand(c
,where
);
6557 /* Fix the client structure with the original stuff */
6558 c
->argv
= orig_argv
;
6559 c
->argc
= orig_argc
;
6565 /* If the list is empty or the key does not exists we must block */
6566 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
6567 if (timeout
> 0) timeout
+= time(NULL
);
6568 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
6571 static void blpopCommand(redisClient
*c
) {
6572 blockingPopGenericCommand(c
,REDIS_HEAD
);
6575 static void brpopCommand(redisClient
*c
) {
6576 blockingPopGenericCommand(c
,REDIS_TAIL
);
6579 /* =============================== Replication ============================= */
6581 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6582 ssize_t nwritten
, ret
= size
;
6583 time_t start
= time(NULL
);
6587 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
6588 nwritten
= write(fd
,ptr
,size
);
6589 if (nwritten
== -1) return -1;
6593 if ((time(NULL
)-start
) > timeout
) {
6601 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6602 ssize_t nread
, totread
= 0;
6603 time_t start
= time(NULL
);
6607 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
6608 nread
= read(fd
,ptr
,size
);
6609 if (nread
== -1) return -1;
6614 if ((time(NULL
)-start
) > timeout
) {
6622 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
6629 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
6632 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
6643 static void syncCommand(redisClient
*c
) {
6644 /* ignore SYNC if aleady slave or in monitor mode */
6645 if (c
->flags
& REDIS_SLAVE
) return;
6647 /* SYNC can't be issued when the server has pending data to send to
6648 * the client about already issued commands. We need a fresh reply
6649 * buffer registering the differences between the BGSAVE and the current
6650 * dataset, so that we can copy to other slaves if needed. */
6651 if (listLength(c
->reply
) != 0) {
6652 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
6656 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
6657 /* Here we need to check if there is a background saving operation
6658 * in progress, or if it is required to start one */
6659 if (server
.bgsavechildpid
!= -1) {
6660 /* Ok a background save is in progress. Let's check if it is a good
6661 * one for replication, i.e. if there is another slave that is
6662 * registering differences since the server forked to save */
6667 listRewind(server
.slaves
,&li
);
6668 while((ln
= listNext(&li
))) {
6670 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
6673 /* Perfect, the server is already registering differences for
6674 * another slave. Set the right state, and copy the buffer. */
6675 listRelease(c
->reply
);
6676 c
->reply
= listDup(slave
->reply
);
6677 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6678 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
6680 /* No way, we need to wait for the next BGSAVE in order to
6681 * register differences */
6682 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
6683 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
6686 /* Ok we don't have a BGSAVE in progress, let's start one */
6687 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
6688 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6689 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
6690 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
6693 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6696 c
->flags
|= REDIS_SLAVE
;
6698 listAddNodeTail(server
.slaves
,c
);
6702 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
6703 redisClient
*slave
= privdata
;
6705 REDIS_NOTUSED(mask
);
6706 char buf
[REDIS_IOBUF_LEN
];
6707 ssize_t nwritten
, buflen
;
6709 if (slave
->repldboff
== 0) {
6710 /* Write the bulk write count before to transfer the DB. In theory here
6711 * we don't know how much room there is in the output buffer of the
6712 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
6713 * operations) will never be smaller than the few bytes we need. */
6716 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
6718 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
6726 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
6727 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
6729 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
6730 (buflen
== 0) ? "premature EOF" : strerror(errno
));
6734 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
6735 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
6740 slave
->repldboff
+= nwritten
;
6741 if (slave
->repldboff
== slave
->repldbsize
) {
6742 close(slave
->repldbfd
);
6743 slave
->repldbfd
= -1;
6744 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6745 slave
->replstate
= REDIS_REPL_ONLINE
;
6746 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
6747 sendReplyToClient
, slave
) == AE_ERR
) {
6751 addReplySds(slave
,sdsempty());
6752 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
6756 /* This function is called at the end of every backgrond saving.
6757 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
6758 * otherwise REDIS_ERR is passed to the function.
6760 * The goal of this function is to handle slaves waiting for a successful
6761 * background saving in order to perform non-blocking synchronization. */
6762 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
6764 int startbgsave
= 0;
6767 listRewind(server
.slaves
,&li
);
6768 while((ln
= listNext(&li
))) {
6769 redisClient
*slave
= ln
->value
;
6771 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
6773 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
6774 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
6775 struct redis_stat buf
;
6777 if (bgsaveerr
!= REDIS_OK
) {
6779 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
6782 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
6783 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
6785 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
6788 slave
->repldboff
= 0;
6789 slave
->repldbsize
= buf
.st_size
;
6790 slave
->replstate
= REDIS_REPL_SEND_BULK
;
6791 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
6792 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
6799 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
6802 listRewind(server
.slaves
,&li
);
6803 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
6804 while((ln
= listNext(&li
))) {
6805 redisClient
*slave
= ln
->value
;
6807 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
6814 static int syncWithMaster(void) {
6815 char buf
[1024], tmpfile
[256], authcmd
[1024];
6817 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
6821 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
6826 /* AUTH with the master if required. */
6827 if(server
.masterauth
) {
6828 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
6829 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
6831 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
6835 /* Read the AUTH result. */
6836 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6838 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
6842 if (buf
[0] != '+') {
6844 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
6849 /* Issue the SYNC command */
6850 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
6852 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
6856 /* Read the bulk write count */
6857 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
6859 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
6863 if (buf
[0] != '$') {
6865 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
6868 dumpsize
= strtol(buf
+1,NULL
,10);
6869 redisLog(REDIS_NOTICE
,"Receiving %ld bytes data dump from MASTER",dumpsize
);
6870 /* Read the bulk write data on a temp file */
6871 snprintf(tmpfile
,256,"temp-%d.%ld.rdb",(int)time(NULL
),(long int)random());
6872 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
,0644);
6875 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
6879 int nread
, nwritten
;
6881 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
6883 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
6889 nwritten
= write(dfd
,buf
,nread
);
6890 if (nwritten
== -1) {
6891 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
6899 if (rename(tmpfile
,server
.dbfilename
) == -1) {
6900 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
6906 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
6907 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
6911 server
.master
= createClient(fd
);
6912 server
.master
->flags
|= REDIS_MASTER
;
6913 server
.master
->authenticated
= 1;
6914 server
.replstate
= REDIS_REPL_CONNECTED
;
6918 static void slaveofCommand(redisClient
*c
) {
6919 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
6920 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
6921 if (server
.masterhost
) {
6922 sdsfree(server
.masterhost
);
6923 server
.masterhost
= NULL
;
6924 if (server
.master
) freeClient(server
.master
);
6925 server
.replstate
= REDIS_REPL_NONE
;
6926 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
6929 sdsfree(server
.masterhost
);
6930 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
6931 server
.masterport
= atoi(c
->argv
[2]->ptr
);
6932 if (server
.master
) freeClient(server
.master
);
6933 server
.replstate
= REDIS_REPL_CONNECT
;
6934 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
6935 server
.masterhost
, server
.masterport
);
6937 addReply(c
,shared
.ok
);
6940 /* ============================ Maxmemory directive ======================== */
6942 /* Try to free one object form the pre-allocated objects free list.
6943 * This is useful under low mem conditions as by default we take 1 million
6944 * free objects allocated. On success REDIS_OK is returned, otherwise
6946 static int tryFreeOneObjectFromFreelist(void) {
6949 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
6950 if (listLength(server
.objfreelist
)) {
6951 listNode
*head
= listFirst(server
.objfreelist
);
6952 o
= listNodeValue(head
);
6953 listDelNode(server
.objfreelist
,head
);
6954 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6958 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
6963 /* This function gets called when 'maxmemory' is set on the config file to limit
6964 * the max memory used by the server, and we are out of memory.
6965 * This function will try to, in order:
6967 * - Free objects from the free list
6968 * - Try to remove keys with an EXPIRE set
6970 * It is not possible to free enough memory to reach used-memory < maxmemory
6971 * the server will start refusing commands that will enlarge even more the
6974 static void freeMemoryIfNeeded(void) {
6975 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
6976 int j
, k
, freed
= 0;
6978 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
6979 for (j
= 0; j
< server
.dbnum
; j
++) {
6981 robj
*minkey
= NULL
;
6982 struct dictEntry
*de
;
6984 if (dictSize(server
.db
[j
].expires
)) {
6986 /* From a sample of three keys drop the one nearest to
6987 * the natural expire */
6988 for (k
= 0; k
< 3; k
++) {
6991 de
= dictGetRandomKey(server
.db
[j
].expires
);
6992 t
= (time_t) dictGetEntryVal(de
);
6993 if (minttl
== -1 || t
< minttl
) {
6994 minkey
= dictGetEntryKey(de
);
6998 deleteKey(server
.db
+j
,minkey
);
7001 if (!freed
) return; /* nothing to free... */
7005 /* ============================== Append Only file ========================== */
7007 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
7008 sds buf
= sdsempty();
7014 /* The DB this command was targetting is not the same as the last command
7015 * we appendend. To issue a SELECT command is needed. */
7016 if (dictid
!= server
.appendseldb
) {
7019 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
7020 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
7021 (unsigned long)strlen(seldb
),seldb
);
7022 server
.appendseldb
= dictid
;
7025 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
7026 * EXPIREs into EXPIREATs calls */
7027 if (cmd
->proc
== expireCommand
) {
7030 tmpargv
[0] = createStringObject("EXPIREAT",8);
7031 tmpargv
[1] = argv
[1];
7032 incrRefCount(argv
[1]);
7033 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
7034 tmpargv
[2] = createObject(REDIS_STRING
,
7035 sdscatprintf(sdsempty(),"%ld",when
));
7039 /* Append the actual command */
7040 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
7041 for (j
= 0; j
< argc
; j
++) {
7044 o
= getDecodedObject(o
);
7045 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
7046 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
7047 buf
= sdscatlen(buf
,"\r\n",2);
7051 /* Free the objects from the modified argv for EXPIREAT */
7052 if (cmd
->proc
== expireCommand
) {
7053 for (j
= 0; j
< 3; j
++)
7054 decrRefCount(argv
[j
]);
7057 /* We want to perform a single write. This should be guaranteed atomic
7058 * at least if the filesystem we are writing is a real physical one.
7059 * While this will save us against the server being killed I don't think
7060 * there is much to do about the whole server stopping for power problems
7062 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
7063 if (nwritten
!= (signed)sdslen(buf
)) {
7064 /* Ooops, we are in troubles. The best thing to do for now is
7065 * to simply exit instead to give the illusion that everything is
7066 * working as expected. */
7067 if (nwritten
== -1) {
7068 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
7070 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
7074 /* If a background append only file rewriting is in progress we want to
7075 * accumulate the differences between the child DB and the current one
7076 * in a buffer, so that when the child process will do its work we
7077 * can append the differences to the new append only file. */
7078 if (server
.bgrewritechildpid
!= -1)
7079 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
7083 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
7084 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
7085 now
-server
.lastfsync
> 1))
7087 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
7088 server
.lastfsync
= now
;
7092 /* In Redis commands are always executed in the context of a client, so in
7093 * order to load the append only file we need to create a fake client. */
7094 static struct redisClient
*createFakeClient(void) {
7095 struct redisClient
*c
= zmalloc(sizeof(*c
));
7099 c
->querybuf
= sdsempty();
7103 /* We set the fake client as a slave waiting for the synchronization
7104 * so that Redis will not try to send replies to this client. */
7105 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
7106 c
->reply
= listCreate();
7107 listSetFreeMethod(c
->reply
,decrRefCount
);
7108 listSetDupMethod(c
->reply
,dupClientReplyValue
);
7112 static void freeFakeClient(struct redisClient
*c
) {
7113 sdsfree(c
->querybuf
);
7114 listRelease(c
->reply
);
7118 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
7119 * error (the append only file is zero-length) REDIS_ERR is returned. On
7120 * fatal error an error message is logged and the program exists. */
7121 int loadAppendOnlyFile(char *filename
) {
7122 struct redisClient
*fakeClient
;
7123 FILE *fp
= fopen(filename
,"r");
7124 struct redis_stat sb
;
7125 unsigned long long loadedkeys
= 0;
7127 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
7131 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
7135 fakeClient
= createFakeClient();
7142 struct redisCommand
*cmd
;
7144 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
7150 if (buf
[0] != '*') goto fmterr
;
7152 argv
= zmalloc(sizeof(robj
*)*argc
);
7153 for (j
= 0; j
< argc
; j
++) {
7154 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
7155 if (buf
[0] != '$') goto fmterr
;
7156 len
= strtol(buf
+1,NULL
,10);
7157 argsds
= sdsnewlen(NULL
,len
);
7158 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
7159 argv
[j
] = createObject(REDIS_STRING
,argsds
);
7160 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
7163 /* Command lookup */
7164 cmd
= lookupCommand(argv
[0]->ptr
);
7166 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
7169 /* Try object sharing and encoding */
7170 if (server
.shareobjects
) {
7172 for(j
= 1; j
< argc
; j
++)
7173 argv
[j
] = tryObjectSharing(argv
[j
]);
7175 if (cmd
->flags
& REDIS_CMD_BULK
)
7176 tryObjectEncoding(argv
[argc
-1]);
7177 /* Run the command in the context of a fake client */
7178 fakeClient
->argc
= argc
;
7179 fakeClient
->argv
= argv
;
7180 cmd
->proc(fakeClient
);
7181 /* Discard the reply objects list from the fake client */
7182 while(listLength(fakeClient
->reply
))
7183 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
7184 /* Clean up, ready for the next command */
7185 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
7187 /* Handle swapping while loading big datasets when VM is on */
7189 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
7190 while (zmalloc_used_memory() > server
.vm_max_memory
) {
7191 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
7196 freeFakeClient(fakeClient
);
7201 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
7203 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
7207 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
7211 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
7212 static int fwriteBulk(FILE *fp
, robj
*obj
) {
7216 /* Avoid the incr/decr ref count business if possible to help
7217 * copy-on-write (we are often in a child process when this function
7219 * Also makes sure that key objects don't get incrRefCount-ed when VM
7221 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
7222 obj
= getDecodedObject(obj
);
7225 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
7226 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
7227 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
7229 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
7230 if (decrrc
) decrRefCount(obj
);
7233 if (decrrc
) decrRefCount(obj
);
7237 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
7238 static int fwriteBulkDouble(FILE *fp
, double d
) {
7239 char buf
[128], dbuf
[128];
7241 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
7242 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
7243 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7244 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
7248 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
7249 static int fwriteBulkLong(FILE *fp
, long l
) {
7250 char buf
[128], lbuf
[128];
7252 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
7253 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
7254 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7255 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
7259 /* Write a sequence of commands able to fully rebuild the dataset into
7260 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
7261 static int rewriteAppendOnlyFile(char *filename
) {
7262 dictIterator
*di
= NULL
;
7267 time_t now
= time(NULL
);
7269 /* Note that we have to use a different temp name here compared to the
7270 * one used by rewriteAppendOnlyFileBackground() function. */
7271 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
7272 fp
= fopen(tmpfile
,"w");
7274 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
7277 for (j
= 0; j
< server
.dbnum
; j
++) {
7278 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
7279 redisDb
*db
= server
.db
+j
;
7281 if (dictSize(d
) == 0) continue;
7282 di
= dictGetIterator(d
);
7288 /* SELECT the new DB */
7289 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
7290 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
7292 /* Iterate this DB writing every entry */
7293 while((de
= dictNext(di
)) != NULL
) {
7298 key
= dictGetEntryKey(de
);
7299 /* If the value for this key is swapped, load a preview in memory.
7300 * We use a "swapped" flag to remember if we need to free the
7301 * value object instead to just increment the ref count anyway
7302 * in order to avoid copy-on-write of pages if we are forked() */
7303 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
7304 key
->storage
== REDIS_VM_SWAPPING
) {
7305 o
= dictGetEntryVal(de
);
7308 o
= vmPreviewObject(key
);
7311 expiretime
= getExpire(db
,key
);
7313 /* Save the key and associated value */
7314 if (o
->type
== REDIS_STRING
) {
7315 /* Emit a SET command */
7316 char cmd
[]="*3\r\n$3\r\nSET\r\n";
7317 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7319 if (fwriteBulk(fp
,key
) == 0) goto werr
;
7320 if (fwriteBulk(fp
,o
) == 0) goto werr
;
7321 } else if (o
->type
== REDIS_LIST
) {
7322 /* Emit the RPUSHes needed to rebuild the list */
7323 list
*list
= o
->ptr
;
7327 listRewind(list
,&li
);
7328 while((ln
= listNext(&li
))) {
7329 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
7330 robj
*eleobj
= listNodeValue(ln
);
7332 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7333 if (fwriteBulk(fp
,key
) == 0) goto werr
;
7334 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
7336 } else if (o
->type
== REDIS_SET
) {
7337 /* Emit the SADDs needed to rebuild the set */
7339 dictIterator
*di
= dictGetIterator(set
);
7342 while((de
= dictNext(di
)) != NULL
) {
7343 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
7344 robj
*eleobj
= dictGetEntryKey(de
);
7346 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7347 if (fwriteBulk(fp
,key
) == 0) goto werr
;
7348 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
7350 dictReleaseIterator(di
);
7351 } else if (o
->type
== REDIS_ZSET
) {
7352 /* Emit the ZADDs needed to rebuild the sorted set */
7354 dictIterator
*di
= dictGetIterator(zs
->dict
);
7357 while((de
= dictNext(di
)) != NULL
) {
7358 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
7359 robj
*eleobj
= dictGetEntryKey(de
);
7360 double *score
= dictGetEntryVal(de
);
7362 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7363 if (fwriteBulk(fp
,key
) == 0) goto werr
;
7364 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
7365 if (fwriteBulk(fp
,eleobj
) == 0) goto werr
;
7367 dictReleaseIterator(di
);
7369 redisAssert(0 != 0);
7371 /* Save the expire time */
7372 if (expiretime
!= -1) {
7373 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
7374 /* If this key is already expired skip it */
7375 if (expiretime
< now
) continue;
7376 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7377 if (fwriteBulk(fp
,key
) == 0) goto werr
;
7378 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
7380 if (swapped
) decrRefCount(o
);
7382 dictReleaseIterator(di
);
7385 /* Make sure data will not remain on the OS's output buffers */
7390 /* Use RENAME to make sure the DB file is changed atomically only
7391 * if the generate DB file is ok. */
7392 if (rename(tmpfile
,filename
) == -1) {
7393 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
7397 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
7403 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
7404 if (di
) dictReleaseIterator(di
);
7408 /* This is how rewriting of the append only file in background works:
7410 * 1) The user calls BGREWRITEAOF
7411 * 2) Redis calls this function, that forks():
7412 * 2a) the child rewrite the append only file in a temp file.
7413 * 2b) the parent accumulates differences in server.bgrewritebuf.
7414 * 3) When the child finished '2a' exists.
7415 * 4) The parent will trap the exit code, if it's OK, will append the
7416 * data accumulated into server.bgrewritebuf into the temp file, and
7417 * finally will rename(2) the temp file in the actual file name.
7418 * The the new file is reopened as the new append only file. Profit!
7420 static int rewriteAppendOnlyFileBackground(void) {
7423 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
7424 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
7425 if ((childpid
= fork()) == 0) {
7429 if (server
.vm_enabled
) vmReopenSwapFile();
7431 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
7432 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
7439 if (childpid
== -1) {
7440 redisLog(REDIS_WARNING
,
7441 "Can't rewrite append only file in background: fork: %s",
7445 redisLog(REDIS_NOTICE
,
7446 "Background append only file rewriting started by pid %d",childpid
);
7447 server
.bgrewritechildpid
= childpid
;
7448 /* We set appendseldb to -1 in order to force the next call to the
7449 * feedAppendOnlyFile() to issue a SELECT command, so the differences
7450 * accumulated by the parent into server.bgrewritebuf will start
7451 * with a SELECT statement and it will be safe to merge. */
7452 server
.appendseldb
= -1;
7455 return REDIS_OK
; /* unreached */
7458 static void bgrewriteaofCommand(redisClient
*c
) {
7459 if (server
.bgrewritechildpid
!= -1) {
7460 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
7463 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
7464 char *status
= "+Background append only file rewriting started\r\n";
7465 addReplySds(c
,sdsnew(status
));
7467 addReply(c
,shared
.err
);
7471 static void aofRemoveTempFile(pid_t childpid
) {
7474 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
7478 /* Virtual Memory is composed mainly of two subsystems:
7479 * - Blocking Virutal Memory
7480 * - Threaded Virtual Memory I/O
7481 * The two parts are not fully decoupled, but functions are split among two
7482 * different sections of the source code (delimited by comments) in order to
7483 * make more clear what functionality is about the blocking VM and what about
7484 * the threaded (not blocking) VM.
7488 * Redis VM is a blocking VM (one that blocks reading swapped values from
7489 * disk into memory when a value swapped out is needed in memory) that is made
7490 * unblocking by trying to examine the command argument vector in order to
7491 * load in background values that will likely be needed in order to exec
7492 * the command. The command is executed only once all the relevant keys
7493 * are loaded into memory.
7495 * This basically is almost as simple of a blocking VM, but almost as parallel
7496 * as a fully non-blocking VM.
7499 /* =================== Virtual Memory - Blocking Side ====================== */
7501 /* substitute the first occurrence of '%p' with the process pid in the
7502 * swap file name. */
7503 static void expandVmSwapFilename(void) {
7504 char *p
= strstr(server
.vm_swap_file
,"%p");
7510 new = sdscat(new,server
.vm_swap_file
);
7511 new = sdscatprintf(new,"%ld",(long) getpid());
7512 new = sdscat(new,p
+2);
7513 zfree(server
.vm_swap_file
);
7514 server
.vm_swap_file
= new;
7517 static void vmInit(void) {
7522 if (server
.vm_max_threads
!= 0)
7523 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
7525 expandVmSwapFilename();
7526 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
7527 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
7528 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
7530 if (server
.vm_fp
== NULL
) {
7531 redisLog(REDIS_WARNING
,
7532 "Impossible to open the swap file: %s. Exiting.",
7536 server
.vm_fd
= fileno(server
.vm_fp
);
7537 server
.vm_next_page
= 0;
7538 server
.vm_near_pages
= 0;
7539 server
.vm_stats_used_pages
= 0;
7540 server
.vm_stats_swapped_objects
= 0;
7541 server
.vm_stats_swapouts
= 0;
7542 server
.vm_stats_swapins
= 0;
7543 totsize
= server
.vm_pages
*server
.vm_page_size
;
7544 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
7545 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
7546 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
7550 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
7552 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
7553 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
7554 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
7555 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
7557 /* Initialize threaded I/O (used by Virtual Memory) */
7558 server
.io_newjobs
= listCreate();
7559 server
.io_processing
= listCreate();
7560 server
.io_processed
= listCreate();
7561 server
.io_ready_clients
= listCreate();
7562 pthread_mutex_init(&server
.io_mutex
,NULL
);
7563 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
7564 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
7565 server
.io_active_threads
= 0;
7566 if (pipe(pipefds
) == -1) {
7567 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
7571 server
.io_ready_pipe_read
= pipefds
[0];
7572 server
.io_ready_pipe_write
= pipefds
[1];
7573 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
7574 /* LZF requires a lot of stack */
7575 pthread_attr_init(&server
.io_threads_attr
);
7576 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
7577 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
7578 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
7579 /* Listen for events in the threaded I/O pipe */
7580 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
7581 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
7582 oom("creating file event");
7585 /* Mark the page as used */
7586 static void vmMarkPageUsed(off_t page
) {
7587 off_t byte
= page
/8;
7589 redisAssert(vmFreePage(page
) == 1);
7590 server
.vm_bitmap
[byte
] |= 1<<bit
;
7593 /* Mark N contiguous pages as used, with 'page' being the first. */
7594 static void vmMarkPagesUsed(off_t page
, off_t count
) {
7597 for (j
= 0; j
< count
; j
++)
7598 vmMarkPageUsed(page
+j
);
7599 server
.vm_stats_used_pages
+= count
;
7600 redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n",
7601 (long long)count
, (long long)page
);
7604 /* Mark the page as free */
7605 static void vmMarkPageFree(off_t page
) {
7606 off_t byte
= page
/8;
7608 redisAssert(vmFreePage(page
) == 0);
7609 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
7612 /* Mark N contiguous pages as free, with 'page' being the first. */
7613 static void vmMarkPagesFree(off_t page
, off_t count
) {
7616 for (j
= 0; j
< count
; j
++)
7617 vmMarkPageFree(page
+j
);
7618 server
.vm_stats_used_pages
-= count
;
7619 redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n",
7620 (long long)count
, (long long)page
);
7623 /* Test if the page is free */
7624 static int vmFreePage(off_t page
) {
7625 off_t byte
= page
/8;
7627 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
7630 /* Find N contiguous free pages storing the first page of the cluster in *first.
7631 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
7632 * REDIS_ERR is returned.
7634 * This function uses a simple algorithm: we try to allocate
7635 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
7636 * again from the start of the swap file searching for free spaces.
7638 * If it looks pretty clear that there are no free pages near our offset
7639 * we try to find less populated places doing a forward jump of
7640 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
7641 * without hurry, and then we jump again and so forth...
7643 * This function can be improved using a free list to avoid to guess
7644 * too much, since we could collect data about freed pages.
7646 * note: I implemented this function just after watching an episode of
7647 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
7649 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
7650 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
7652 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
7653 server
.vm_near_pages
= 0;
7654 server
.vm_next_page
= 0;
7656 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
7657 base
= server
.vm_next_page
;
7659 while(offset
< server
.vm_pages
) {
7660 off_t
this = base
+offset
;
7662 /* If we overflow, restart from page zero */
7663 if (this >= server
.vm_pages
) {
7664 this -= server
.vm_pages
;
7666 /* Just overflowed, what we found on tail is no longer
7667 * interesting, as it's no longer contiguous. */
7671 if (vmFreePage(this)) {
7672 /* This is a free page */
7674 /* Already got N free pages? Return to the caller, with success */
7676 *first
= this-(n
-1);
7677 server
.vm_next_page
= this+1;
7678 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
);
7682 /* The current one is not a free page */
7686 /* Fast-forward if the current page is not free and we already
7687 * searched enough near this place. */
7689 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
7690 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
7692 /* Note that even if we rewind after the jump, we are don't need
7693 * to make sure numfree is set to zero as we only jump *if* it
7694 * is set to zero. */
7696 /* Otherwise just check the next page */
7703 /* Write the specified object at the specified page of the swap file */
7704 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
7705 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7706 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7707 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7708 redisLog(REDIS_WARNING
,
7709 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
7713 rdbSaveObject(server
.vm_fp
,o
);
7714 fflush(server
.vm_fp
);
7715 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7719 /* Swap the 'val' object relative to 'key' into disk. Store all the information
7720 * needed to later retrieve the object into the key object.
7721 * If we can't find enough contiguous empty pages to swap the object on disk
7722 * REDIS_ERR is returned. */
7723 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
7724 off_t pages
= rdbSavedObjectPages(val
,NULL
);
7727 assert(key
->storage
== REDIS_VM_MEMORY
);
7728 assert(key
->refcount
== 1);
7729 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
7730 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
7731 key
->vm
.page
= page
;
7732 key
->vm
.usedpages
= pages
;
7733 key
->storage
= REDIS_VM_SWAPPED
;
7734 key
->vtype
= val
->type
;
7735 decrRefCount(val
); /* Deallocate the object from memory. */
7736 vmMarkPagesUsed(page
,pages
);
7737 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
7738 (unsigned char*) key
->ptr
,
7739 (unsigned long long) page
, (unsigned long long) pages
);
7740 server
.vm_stats_swapped_objects
++;
7741 server
.vm_stats_swapouts
++;
7745 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
7748 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
7749 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
7750 redisLog(REDIS_WARNING
,
7751 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
7755 o
= rdbLoadObject(type
,server
.vm_fp
);
7757 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
7760 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
7764 /* Load the value object relative to the 'key' object from swap to memory.
7765 * The newly allocated object is returned.
7767 * If preview is true the unserialized object is returned to the caller but
7768 * no changes are made to the key object, nor the pages are marked as freed */
7769 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
7772 redisAssert(key
->storage
== REDIS_VM_SWAPPED
|| key
->storage
== REDIS_VM_LOADING
);
7773 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
7775 key
->storage
= REDIS_VM_MEMORY
;
7776 key
->vm
.atime
= server
.unixtime
;
7777 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
7778 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
7779 (unsigned char*) key
->ptr
);
7780 server
.vm_stats_swapped_objects
--;
7782 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
7783 (unsigned char*) key
->ptr
);
7785 server
.vm_stats_swapins
++;
7789 /* Plain object loading, from swap to memory */
7790 static robj
*vmLoadObject(robj
*key
) {
7791 /* If we are loading the object in background, stop it, we
7792 * need to load this object synchronously ASAP. */
7793 if (key
->storage
== REDIS_VM_LOADING
)
7794 vmCancelThreadedIOJob(key
);
7795 return vmGenericLoadObject(key
,0);
7798 /* Just load the value on disk, without to modify the key.
7799 * This is useful when we want to perform some operation on the value
7800 * without to really bring it from swap to memory, like while saving the
7801 * dataset or rewriting the append only log. */
7802 static robj
*vmPreviewObject(robj
*key
) {
7803 return vmGenericLoadObject(key
,1);
7806 /* How a good candidate is this object for swapping?
7807 * The better candidate it is, the greater the returned value.
7809 * Currently we try to perform a fast estimation of the object size in
7810 * memory, and combine it with aging informations.
7812 * Basically swappability = idle-time * log(estimated size)
7814 * Bigger objects are preferred over smaller objects, but not
7815 * proportionally, this is why we use the logarithm. This algorithm is
7816 * just a first try and will probably be tuned later. */
7817 static double computeObjectSwappability(robj
*o
) {
7818 time_t age
= server
.unixtime
- o
->vm
.atime
;
7822 struct dictEntry
*de
;
7825 if (age
<= 0) return 0;
7828 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
7831 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
7836 listNode
*ln
= listFirst(l
);
7838 asize
= sizeof(list
);
7840 robj
*ele
= ln
->value
;
7843 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7844 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7846 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
7851 z
= (o
->type
== REDIS_ZSET
);
7852 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
7854 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
7855 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
7860 de
= dictGetRandomKey(d
);
7861 ele
= dictGetEntryKey(de
);
7862 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
7863 (sizeof(*o
)+sdslen(ele
->ptr
)) :
7865 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
7866 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
7870 return (double)age
*log(1+asize
);
7873 /* Try to swap an object that's a good candidate for swapping.
7874 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
7875 * to swap any object at all.
7877 * If 'usethreaded' is true, Redis will try to swap the object in background
7878 * using I/O threads. */
7879 static int vmSwapOneObject(int usethreads
) {
7881 struct dictEntry
*best
= NULL
;
7882 double best_swappability
= 0;
7883 redisDb
*best_db
= NULL
;
7886 for (j
= 0; j
< server
.dbnum
; j
++) {
7887 redisDb
*db
= server
.db
+j
;
7888 /* Why maxtries is set to 100?
7889 * Because this way (usually) we'll find 1 object even if just 1% - 2%
7890 * are swappable objects */
7893 if (dictSize(db
->dict
) == 0) continue;
7894 for (i
= 0; i
< 5; i
++) {
7896 double swappability
;
7898 if (maxtries
) maxtries
--;
7899 de
= dictGetRandomKey(db
->dict
);
7900 key
= dictGetEntryKey(de
);
7901 val
= dictGetEntryVal(de
);
7902 /* Only swap objects that are currently in memory.
7904 * Also don't swap shared objects if threaded VM is on, as we
7905 * try to ensure that the main thread does not touch the
7906 * object while the I/O thread is using it, but we can't
7907 * control other keys without adding additional mutex. */
7908 if (key
->storage
!= REDIS_VM_MEMORY
||
7909 (server
.vm_max_threads
!= 0 && val
->refcount
!= 1)) {
7910 if (maxtries
) i
--; /* don't count this try */
7913 swappability
= computeObjectSwappability(val
);
7914 if (!best
|| swappability
> best_swappability
) {
7916 best_swappability
= swappability
;
7921 if (best
== NULL
) return REDIS_ERR
;
7922 key
= dictGetEntryKey(best
);
7923 val
= dictGetEntryVal(best
);
7925 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
7926 key
->ptr
, best_swappability
);
7928 /* Unshare the key if needed */
7929 if (key
->refcount
> 1) {
7930 robj
*newkey
= dupStringObject(key
);
7932 key
= dictGetEntryKey(best
) = newkey
;
7936 vmSwapObjectThreaded(key
,val
,best_db
);
7939 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
7940 dictGetEntryVal(best
) = NULL
;
7948 static int vmSwapOneObjectBlocking() {
7949 return vmSwapOneObject(0);
7952 static int vmSwapOneObjectThreaded() {
7953 return vmSwapOneObject(1);
7956 /* Return true if it's safe to swap out objects in a given moment.
7957 * Basically we don't want to swap objects out while there is a BGSAVE
7958 * or a BGAEOREWRITE running in backgroud. */
7959 static int vmCanSwapOut(void) {
7960 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
7963 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
7964 * and was deleted. Otherwise 0 is returned. */
7965 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
7969 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
7970 foundkey
= dictGetEntryKey(de
);
7971 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
7976 /* =================== Virtual Memory - Threaded I/O ======================= */
7978 static void freeIOJob(iojob
*j
) {
7979 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
7980 j
->type
== REDIS_IOJOB_DO_SWAP
||
7981 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
7982 decrRefCount(j
->val
);
7983 decrRefCount(j
->key
);
7987 /* Every time a thread finished a Job, it writes a byte into the write side
7988 * of an unix pipe in order to "awake" the main thread, and this function
7990 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
7994 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
7996 REDIS_NOTUSED(mask
);
7997 REDIS_NOTUSED(privdata
);
7999 /* For every byte we read in the read side of the pipe, there is one
8000 * I/O job completed to process. */
8001 while((retval
= read(fd
,buf
,1)) == 1) {
8005 struct dictEntry
*de
;
8007 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
8009 /* Get the processed element (the oldest one) */
8011 assert(listLength(server
.io_processed
) != 0);
8012 if (toprocess
== -1) {
8013 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
8014 if (toprocess
<= 0) toprocess
= 1;
8016 ln
= listFirst(server
.io_processed
);
8018 listDelNode(server
.io_processed
,ln
);
8020 /* If this job is marked as canceled, just ignore it */
8025 /* Post process it in the main thread, as there are things we
8026 * can do just here to avoid race conditions and/or invasive locks */
8027 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
);
8028 de
= dictFind(j
->db
->dict
,j
->key
);
8030 key
= dictGetEntryKey(de
);
8031 if (j
->type
== REDIS_IOJOB_LOAD
) {
8034 /* Key loaded, bring it at home */
8035 key
->storage
= REDIS_VM_MEMORY
;
8036 key
->vm
.atime
= server
.unixtime
;
8037 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
8038 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
8039 (unsigned char*) key
->ptr
);
8040 server
.vm_stats_swapped_objects
--;
8041 server
.vm_stats_swapins
++;
8042 dictGetEntryVal(de
) = j
->val
;
8043 incrRefCount(j
->val
);
8046 /* Handle clients waiting for this key to be loaded. */
8047 handleClientsBlockedOnSwappedKey(db
,key
);
8048 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
8049 /* Now we know the amount of pages required to swap this object.
8050 * Let's find some space for it, and queue this task again
8051 * rebranded as REDIS_IOJOB_DO_SWAP. */
8052 if (!vmCanSwapOut() ||
8053 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
8055 /* Ooops... no space or we can't swap as there is
8056 * a fork()ed Redis trying to save stuff on disk. */
8058 key
->storage
= REDIS_VM_MEMORY
; /* undo operation */
8060 /* Note that we need to mark this pages as used now,
8061 * if the job will be canceled, we'll mark them as freed
8063 vmMarkPagesUsed(j
->page
,j
->pages
);
8064 j
->type
= REDIS_IOJOB_DO_SWAP
;
8069 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
8072 /* Key swapped. We can finally free some memory. */
8073 if (key
->storage
!= REDIS_VM_SWAPPING
) {
8074 printf("key->storage: %d\n",key
->storage
);
8075 printf("key->name: %s\n",(char*)key
->ptr
);
8076 printf("key->refcount: %d\n",key
->refcount
);
8077 printf("val: %p\n",(void*)j
->val
);
8078 printf("val->type: %d\n",j
->val
->type
);
8079 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
8081 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
8082 val
= dictGetEntryVal(de
);
8083 key
->vm
.page
= j
->page
;
8084 key
->vm
.usedpages
= j
->pages
;
8085 key
->storage
= REDIS_VM_SWAPPED
;
8086 key
->vtype
= j
->val
->type
;
8087 decrRefCount(val
); /* Deallocate the object from memory. */
8088 dictGetEntryVal(de
) = NULL
;
8089 redisLog(REDIS_DEBUG
,
8090 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
8091 (unsigned char*) key
->ptr
,
8092 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
8093 server
.vm_stats_swapped_objects
++;
8094 server
.vm_stats_swapouts
++;
8096 /* Put a few more swap requests in queue if we are still
8098 if (trytoswap
&& vmCanSwapOut() &&
8099 zmalloc_used_memory() > server
.vm_max_memory
)
8104 more
= listLength(server
.io_newjobs
) <
8105 (unsigned) server
.vm_max_threads
;
8107 /* Don't waste CPU time if swappable objects are rare. */
8108 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
8116 if (processed
== toprocess
) return;
8118 if (retval
< 0 && errno
!= EAGAIN
) {
8119 redisLog(REDIS_WARNING
,
8120 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
8125 static void lockThreadedIO(void) {
8126 pthread_mutex_lock(&server
.io_mutex
);
8129 static void unlockThreadedIO(void) {
8130 pthread_mutex_unlock(&server
.io_mutex
);
8133 /* Remove the specified object from the threaded I/O queue if still not
8134 * processed, otherwise make sure to flag it as canceled. */
8135 static void vmCancelThreadedIOJob(robj
*o
) {
8137 server
.io_newjobs
, /* 0 */
8138 server
.io_processing
, /* 1 */
8139 server
.io_processed
/* 2 */
8143 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
8146 /* Search for a matching key in one of the queues */
8147 for (i
= 0; i
< 3; i
++) {
8151 listRewind(lists
[i
],&li
);
8152 while ((ln
= listNext(&li
)) != NULL
) {
8153 iojob
*job
= ln
->value
;
8155 if (job
->canceled
) continue; /* Skip this, already canceled. */
8156 if (compareStringObjects(job
->key
,o
) == 0) {
8157 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
8158 (void*)job
, (char*)o
->ptr
, job
->type
, i
);
8159 /* Mark the pages as free since the swap didn't happened
8160 * or happened but is now discarded. */
8161 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
8162 vmMarkPagesFree(job
->page
,job
->pages
);
8163 /* Cancel the job. It depends on the list the job is
8166 case 0: /* io_newjobs */
8167 /* If the job was yet not processed the best thing to do
8168 * is to remove it from the queue at all */
8170 listDelNode(lists
[i
],ln
);
8172 case 1: /* io_processing */
8173 /* Oh Shi- the thread is messing with the Job:
8175 * Probably it's accessing the object if this is a
8176 * PREPARE_SWAP or DO_SWAP job.
8177 * If it's a LOAD job it may be reading from disk and
8178 * if we don't wait for the job to terminate before to
8179 * cancel it, maybe in a few microseconds data can be
8180 * corrupted in this pages. So the short story is:
8182 * Better to wait for the job to move into the
8183 * next queue (processed)... */
8185 /* We try again and again until the job is completed. */
8187 /* But let's wait some time for the I/O thread
8188 * to finish with this job. After all this condition
8189 * should be very rare. */
8192 case 2: /* io_processed */
8193 /* The job was already processed, that's easy...
8194 * just mark it as canceled so that we'll ignore it
8195 * when processing completed jobs. */
8199 /* Finally we have to adjust the storage type of the object
8200 * in order to "UNDO" the operaiton. */
8201 if (o
->storage
== REDIS_VM_LOADING
)
8202 o
->storage
= REDIS_VM_SWAPPED
;
8203 else if (o
->storage
== REDIS_VM_SWAPPING
)
8204 o
->storage
= REDIS_VM_MEMORY
;
8211 assert(1 != 1); /* We should never reach this */
8214 static void *IOThreadEntryPoint(void *arg
) {
8219 pthread_detach(pthread_self());
8221 /* Get a new job to process */
8223 if (listLength(server
.io_newjobs
) == 0) {
8224 /* No new jobs in queue, exit. */
8225 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
8226 (long) pthread_self());
8227 server
.io_active_threads
--;
8231 ln
= listFirst(server
.io_newjobs
);
8233 listDelNode(server
.io_newjobs
,ln
);
8234 /* Add the job in the processing queue */
8235 j
->thread
= pthread_self();
8236 listAddNodeTail(server
.io_processing
,j
);
8237 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
8239 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
8240 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
8242 /* Process the Job */
8243 if (j
->type
== REDIS_IOJOB_LOAD
) {
8244 j
->val
= vmReadObjectFromSwap(j
->page
,j
->key
->vtype
);
8245 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
8246 FILE *fp
= fopen("/dev/null","w+");
8247 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
8249 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
8250 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
8254 /* Done: insert the job into the processed queue */
8255 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
8256 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
8258 listDelNode(server
.io_processing
,ln
);
8259 listAddNodeTail(server
.io_processed
,j
);
8262 /* Signal the main thread there is new stuff to process */
8263 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
8265 return NULL
; /* never reached */
8268 static void spawnIOThread(void) {
8270 sigset_t mask
, omask
;
8273 sigaddset(&mask
,SIGCHLD
);
8274 sigaddset(&mask
,SIGHUP
);
8275 sigaddset(&mask
,SIGPIPE
);
8276 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
8277 pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
);
8278 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
8279 server
.io_active_threads
++;
8282 /* We need to wait for the last thread to exit before we are able to
8283 * fork() in order to BGSAVE or BGREWRITEAOF. */
8284 static void waitEmptyIOJobsQueue(void) {
8286 int io_processed_len
;
8289 if (listLength(server
.io_newjobs
) == 0 &&
8290 listLength(server
.io_processing
) == 0 &&
8291 server
.io_active_threads
== 0)
8296 /* While waiting for empty jobs queue condition we post-process some
8297 * finshed job, as I/O threads may be hanging trying to write against
8298 * the io_ready_pipe_write FD but there are so much pending jobs that
8300 io_processed_len
= listLength(server
.io_processed
);
8302 if (io_processed_len
) {
8303 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,NULL
,0);
8304 usleep(1000); /* 1 millisecond */
8306 usleep(10000); /* 10 milliseconds */
8311 static void vmReopenSwapFile(void) {
8312 /* Note: we don't close the old one as we are in the child process
8313 * and don't want to mess at all with the original file object. */
8314 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
8315 if (server
.vm_fp
== NULL
) {
8316 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
8317 server
.vm_swap_file
);
8320 server
.vm_fd
= fileno(server
.vm_fp
);
8323 /* This function must be called while with threaded IO locked */
8324 static void queueIOJob(iojob
*j
) {
8325 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
8326 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
8327 listAddNodeTail(server
.io_newjobs
,j
);
8328 if (server
.io_active_threads
< server
.vm_max_threads
)
8332 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
8335 assert(key
->storage
== REDIS_VM_MEMORY
);
8336 assert(key
->refcount
== 1);
8338 j
= zmalloc(sizeof(*j
));
8339 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
8341 j
->key
= dupStringObject(key
);
8345 j
->thread
= (pthread_t
) -1;
8346 key
->storage
= REDIS_VM_SWAPPING
;
8354 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
8356 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
8357 * If there is not already a job loading the key, it is craeted.
8358 * The key is added to the io_keys list in the client structure, and also
8359 * in the hash table mapping swapped keys to waiting clients, that is,
8360 * server.io_waited_keys. */
8361 static int waitForSwappedKey(redisClient
*c
, robj
*key
) {
8362 struct dictEntry
*de
;
8366 /* If the key does not exist or is already in RAM we don't need to
8367 * block the client at all. */
8368 de
= dictFind(c
->db
->dict
,key
);
8369 if (de
== NULL
) return 0;
8370 o
= dictGetEntryKey(de
);
8371 if (o
->storage
== REDIS_VM_MEMORY
) {
8373 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
8374 /* We were swapping the key, undo it! */
8375 vmCancelThreadedIOJob(o
);
8379 /* OK: the key is either swapped, or being loaded just now. */
8381 /* Add the key to the list of keys this client is waiting for.
8382 * This maps clients to keys they are waiting for. */
8383 listAddNodeTail(c
->io_keys
,key
);
8386 /* Add the client to the swapped keys => clients waiting map. */
8387 de
= dictFind(c
->db
->io_keys
,key
);
8391 /* For every key we take a list of clients blocked for it */
8393 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
8395 assert(retval
== DICT_OK
);
8397 l
= dictGetEntryVal(de
);
8399 listAddNodeTail(l
,c
);
8401 /* Are we already loading the key from disk? If not create a job */
8402 if (o
->storage
== REDIS_VM_SWAPPED
) {
8405 o
->storage
= REDIS_VM_LOADING
;
8406 j
= zmalloc(sizeof(*j
));
8407 j
->type
= REDIS_IOJOB_LOAD
;
8409 j
->key
= dupStringObject(key
);
8410 j
->key
->vtype
= o
->vtype
;
8411 j
->page
= o
->vm
.page
;
8414 j
->thread
= (pthread_t
) -1;
8422 /* Is this client attempting to run a command against swapped keys?
8423 * If so, block it ASAP, load the keys in background, then resume it.
8425 * The important idea about this function is that it can fail! If keys will
8426 * still be swapped when the client is resumed, this key lookups will
8427 * just block loading keys from disk. In practical terms this should only
8428 * happen with SORT BY command or if there is a bug in this function.
8430 * Return 1 if the client is marked as blocked, 0 if the client can
8431 * continue as the keys it is going to access appear to be in memory. */
8432 static int blockClientOnSwappedKeys(struct redisCommand
*cmd
, redisClient
*c
) {
8435 if (cmd
->vm_firstkey
== 0) return 0;
8436 last
= cmd
->vm_lastkey
;
8437 if (last
< 0) last
= c
->argc
+last
;
8438 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
)
8439 waitForSwappedKey(c
,c
->argv
[j
]);
8440 /* If the client was blocked for at least one key, mark it as blocked. */
8441 if (listLength(c
->io_keys
)) {
8442 c
->flags
|= REDIS_IO_WAIT
;
8443 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
8444 server
.vm_blocked_clients
++;
8451 /* Remove the 'key' from the list of blocked keys for a given client.
8453 * The function returns 1 when there are no longer blocking keys after
8454 * the current one was removed (and the client can be unblocked). */
8455 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
8459 struct dictEntry
*de
;
8461 /* Remove the key from the list of keys this client is waiting for. */
8462 listRewind(c
->io_keys
,&li
);
8463 while ((ln
= listNext(&li
)) != NULL
) {
8464 if (compareStringObjects(ln
->value
,key
) == 0) {
8465 listDelNode(c
->io_keys
,ln
);
8471 /* Remove the client form the key => waiting clients map. */
8472 de
= dictFind(c
->db
->io_keys
,key
);
8474 l
= dictGetEntryVal(de
);
8475 ln
= listSearchKey(l
,c
);
8478 if (listLength(l
) == 0)
8479 dictDelete(c
->db
->io_keys
,key
);
8481 return listLength(c
->io_keys
) == 0;
8484 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
8485 struct dictEntry
*de
;
8490 de
= dictFind(db
->io_keys
,key
);
8493 l
= dictGetEntryVal(de
);
8494 len
= listLength(l
);
8495 /* Note: we can't use something like while(listLength(l)) as the list
8496 * can be freed by the calling function when we remove the last element. */
8499 redisClient
*c
= ln
->value
;
8501 if (dontWaitForSwappedKey(c
,key
)) {
8502 /* Put the client in the list of clients ready to go as we
8503 * loaded all the keys about it. */
8504 listAddNodeTail(server
.io_ready_clients
,c
);
8509 /* ================================= Debugging ============================== */
8511 static void debugCommand(redisClient
*c
) {
8512 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
8514 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
8515 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
8516 addReply(c
,shared
.err
);
8520 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
8521 addReply(c
,shared
.err
);
8524 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
8525 addReply(c
,shared
.ok
);
8526 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
8528 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
8529 addReply(c
,shared
.err
);
8532 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
8533 addReply(c
,shared
.ok
);
8534 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
8535 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
8539 addReply(c
,shared
.nokeyerr
);
8542 key
= dictGetEntryKey(de
);
8543 val
= dictGetEntryVal(de
);
8544 if (!server
.vm_enabled
|| (key
->storage
== REDIS_VM_MEMORY
||
8545 key
->storage
== REDIS_VM_SWAPPING
)) {
8546 addReplySds(c
,sdscatprintf(sdsempty(),
8547 "+Key at:%p refcount:%d, value at:%p refcount:%d "
8548 "encoding:%d serializedlength:%lld\r\n",
8549 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
8550 val
->encoding
, (long long) rdbSavedObjectLen(val
,NULL
)));
8552 addReplySds(c
,sdscatprintf(sdsempty(),
8553 "+Key at:%p refcount:%d, value swapped at: page %llu "
8554 "using %llu pages\r\n",
8555 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
8556 (unsigned long long) key
->vm
.usedpages
));
8558 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
8559 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
8562 if (!server
.vm_enabled
) {
8563 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
8567 addReply(c
,shared
.nokeyerr
);
8570 key
= dictGetEntryKey(de
);
8571 val
= dictGetEntryVal(de
);
8572 /* If the key is shared we want to create a copy */
8573 if (key
->refcount
> 1) {
8574 robj
*newkey
= dupStringObject(key
);
8576 key
= dictGetEntryKey(de
) = newkey
;
8579 if (key
->storage
!= REDIS_VM_MEMORY
) {
8580 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
8581 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
8582 dictGetEntryVal(de
) = NULL
;
8583 addReply(c
,shared
.ok
);
8585 addReply(c
,shared
.err
);
8588 addReplySds(c
,sdsnew(
8589 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
8593 static void _redisAssert(char *estr
, char *file
, int line
) {
8594 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
8595 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
);
8596 #ifdef HAVE_BACKTRACE
8597 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
8602 /* =================================== Main! ================================ */
8605 int linuxOvercommitMemoryValue(void) {
8606 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
8610 if (fgets(buf
,64,fp
) == NULL
) {
8619 void linuxOvercommitMemoryWarning(void) {
8620 if (linuxOvercommitMemoryValue() == 0) {
8621 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.");
8624 #endif /* __linux__ */
8626 static void daemonize(void) {
8630 if (fork() != 0) exit(0); /* parent exits */
8631 setsid(); /* create a new session */
8633 /* Every output goes to /dev/null. If Redis is daemonized but
8634 * the 'logfile' is set to 'stdout' in the configuration file
8635 * it will not log at all. */
8636 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
8637 dup2(fd
, STDIN_FILENO
);
8638 dup2(fd
, STDOUT_FILENO
);
8639 dup2(fd
, STDERR_FILENO
);
8640 if (fd
> STDERR_FILENO
) close(fd
);
8642 /* Try to write the pid file */
8643 fp
= fopen(server
.pidfile
,"w");
8645 fprintf(fp
,"%d\n",getpid());
8650 int main(int argc
, char **argv
) {
8655 resetServerSaveParams();
8656 loadServerConfig(argv
[1]);
8657 } else if (argc
> 2) {
8658 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
8661 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'");
8663 if (server
.daemonize
) daemonize();
8665 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
8667 linuxOvercommitMemoryWarning();
8670 if (server
.appendonly
) {
8671 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
8672 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
8674 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
8675 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
8677 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
8678 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
8680 aeDeleteEventLoop(server
.el
);
8684 /* ============================= Backtrace support ========================= */
8686 #ifdef HAVE_BACKTRACE
8687 static char *findFuncName(void *pointer
, unsigned long *offset
);
8689 static void *getMcontextEip(ucontext_t
*uc
) {
8690 #if defined(__FreeBSD__)
8691 return (void*) uc
->uc_mcontext
.mc_eip
;
8692 #elif defined(__dietlibc__)
8693 return (void*) uc
->uc_mcontext
.eip
;
8694 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
8696 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
8698 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
8700 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
8701 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
8702 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
8704 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
8706 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
8707 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
8708 #elif defined(__ia64__) /* Linux IA64 */
8709 return (void*) uc
->uc_mcontext
.sc_ip
;
8715 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
8717 char **messages
= NULL
;
8718 int i
, trace_size
= 0;
8719 unsigned long offset
=0;
8720 ucontext_t
*uc
= (ucontext_t
*) secret
;
8722 REDIS_NOTUSED(info
);
8724 redisLog(REDIS_WARNING
,
8725 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
8726 infostring
= genRedisInfoString();
8727 redisLog(REDIS_WARNING
, "%s",infostring
);
8728 /* It's not safe to sdsfree() the returned string under memory
8729 * corruption conditions. Let it leak as we are going to abort */
8731 trace_size
= backtrace(trace
, 100);
8732 /* overwrite sigaction with caller's address */
8733 if (getMcontextEip(uc
) != NULL
) {
8734 trace
[1] = getMcontextEip(uc
);
8736 messages
= backtrace_symbols(trace
, trace_size
);
8738 for (i
=1; i
<trace_size
; ++i
) {
8739 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
8741 p
= strchr(messages
[i
],'+');
8742 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
8743 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
8745 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
8748 /* free(messages); Don't call free() with possibly corrupted memory. */
8752 static void setupSigSegvAction(void) {
8753 struct sigaction act
;
8755 sigemptyset (&act
.sa_mask
);
8756 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
8757 * is used. Otherwise, sa_handler is used */
8758 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
8759 act
.sa_sigaction
= segvHandler
;
8760 sigaction (SIGSEGV
, &act
, NULL
);
8761 sigaction (SIGBUS
, &act
, NULL
);
8762 sigaction (SIGFPE
, &act
, NULL
);
8763 sigaction (SIGILL
, &act
, NULL
);
8764 sigaction (SIGBUS
, &act
, NULL
);
8768 #include "staticsymbols.h"
8769 /* This function try to convert a pointer into a function name. It's used in
8770 * oreder to provide a backtrace under segmentation fault that's able to
8771 * display functions declared as static (otherwise the backtrace is useless). */
8772 static char *findFuncName(void *pointer
, unsigned long *offset
){
8774 unsigned long off
, minoff
= 0;
8776 /* Try to match against the Symbol with the smallest offset */
8777 for (i
=0; symsTable
[i
].pointer
; i
++) {
8778 unsigned long lp
= (unsigned long) pointer
;
8780 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
8781 off
=lp
-symsTable
[i
].pointer
;
8782 if (ret
< 0 || off
< minoff
) {
8788 if (ret
== -1) return NULL
;
8790 return symsTable
[ret
].name
;
8792 #else /* HAVE_BACKTRACE */
8793 static void setupSigSegvAction(void) {
8795 #endif /* HAVE_BACKTRACE */