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.7"
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 10 /* try to expire 10 keys/loop */
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 static char* strencoding
[] = {
131 "raw", "int", "zipmap", "hashtable"
134 /* Object types only used for dumping to disk */
135 #define REDIS_EXPIRETIME 253
136 #define REDIS_SELECTDB 254
137 #define REDIS_EOF 255
139 /* Defines related to the dump file format. To store 32 bits lengths for short
140 * keys requires a lot of space, so we check the most significant 2 bits of
141 * the first byte to interpreter the length:
143 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
144 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
145 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
146 * 11|000000 this means: specially encoded object will follow. The six bits
147 * number specify the kind of object that follows.
148 * See the REDIS_RDB_ENC_* defines.
150 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
151 * values, will fit inside. */
152 #define REDIS_RDB_6BITLEN 0
153 #define REDIS_RDB_14BITLEN 1
154 #define REDIS_RDB_32BITLEN 2
155 #define REDIS_RDB_ENCVAL 3
156 #define REDIS_RDB_LENERR UINT_MAX
158 /* When a length of a string object stored on disk has the first two bits
159 * set, the remaining two bits specify a special encoding for the object
160 * accordingly to the following defines: */
161 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
162 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
163 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
164 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
166 /* Virtual memory object->where field. */
167 #define REDIS_VM_MEMORY 0 /* The object is on memory */
168 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
169 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
170 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
172 /* Virtual memory static configuration stuff.
173 * Check vmFindContiguousPages() to know more about this magic numbers. */
174 #define REDIS_VM_MAX_NEAR_PAGES 65536
175 #define REDIS_VM_MAX_RANDOM_JUMP 4096
176 #define REDIS_VM_MAX_THREADS 32
177 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
178 /* The following is the *percentage* of completed I/O jobs to process when the
179 * handelr is called. While Virtual Memory I/O operations are performed by
180 * threads, this operations must be processed by the main thread when completed
181 * in order to take effect. */
182 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
185 #define REDIS_SLAVE 1 /* This client is a slave server */
186 #define REDIS_MASTER 2 /* This client is a master server */
187 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
188 #define REDIS_MULTI 8 /* This client is in a MULTI context */
189 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
190 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
192 /* Slave replication state - slave side */
193 #define REDIS_REPL_NONE 0 /* No active replication */
194 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
195 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
197 /* Slave replication state - from the point of view of master
198 * Note that in SEND_BULK and ONLINE state the slave receives new updates
199 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
200 * to start the next background saving in order to send updates to it. */
201 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
202 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
203 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
204 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
206 /* List related stuff */
210 /* Sort operations */
211 #define REDIS_SORT_GET 0
212 #define REDIS_SORT_ASC 1
213 #define REDIS_SORT_DESC 2
214 #define REDIS_SORTKEY_MAX 1024
217 #define REDIS_DEBUG 0
218 #define REDIS_VERBOSE 1
219 #define REDIS_NOTICE 2
220 #define REDIS_WARNING 3
222 /* Anti-warning macro... */
223 #define REDIS_NOTUSED(V) ((void) V)
225 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
226 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
228 /* Append only defines */
229 #define APPENDFSYNC_NO 0
230 #define APPENDFSYNC_ALWAYS 1
231 #define APPENDFSYNC_EVERYSEC 2
233 /* Hashes related defaults */
234 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
235 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
237 /* We can print the stacktrace, so our assert is defined this way: */
238 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
239 static void _redisAssert(char *estr
, char *file
, int line
);
241 /*================================= Data types ============================== */
243 /* A redis object, that is a type able to hold a string / list / set */
245 /* The VM object structure */
246 struct redisObjectVM
{
247 off_t page
; /* the page at witch the object is stored on disk */
248 off_t usedpages
; /* number of pages used on disk */
249 time_t atime
; /* Last access time */
252 /* The actual Redis Object */
253 typedef struct redisObject
{
256 unsigned char encoding
;
257 unsigned char storage
; /* If this object is a key, where is the value?
258 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
259 unsigned char vtype
; /* If this object is a key, and value is swapped out,
260 * this is the type of the swapped out object. */
262 /* VM fields, this are only allocated if VM is active, otherwise the
263 * object allocation function will just allocate
264 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
265 * Redis without VM active will not have any overhead. */
266 struct redisObjectVM vm
;
269 /* Macro used to initalize a Redis object allocated on the stack.
270 * Note that this macro is taken near the structure definition to make sure
271 * we'll update it when the structure is changed, to avoid bugs like
272 * bug #85 introduced exactly in this way. */
273 #define initStaticStringObject(_var,_ptr) do { \
275 _var.type = REDIS_STRING; \
276 _var.encoding = REDIS_ENCODING_RAW; \
278 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
281 typedef struct redisDb
{
282 dict
*dict
; /* The keyspace for this DB */
283 dict
*expires
; /* Timeout of keys with a timeout set */
284 dict
*blockingkeys
; /* Keys with clients waiting for data (BLPOP) */
285 dict
*io_keys
; /* Keys with clients waiting for VM I/O */
289 /* Client MULTI/EXEC state */
290 typedef struct multiCmd
{
293 struct redisCommand
*cmd
;
296 typedef struct multiState
{
297 multiCmd
*commands
; /* Array of MULTI commands */
298 int count
; /* Total number of MULTI commands */
301 /* With multiplexing we need to take per-clinet state.
302 * Clients are taken in a liked list. */
303 typedef struct redisClient
{
308 robj
**argv
, **mbargv
;
310 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
311 int multibulk
; /* multi bulk command format active */
314 time_t lastinteraction
; /* time of the last interaction, used for timeout */
315 int flags
; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
316 int slaveseldb
; /* slave selected db, if this client is a slave */
317 int authenticated
; /* when requirepass is non-NULL */
318 int replstate
; /* replication state if this is a slave */
319 int repldbfd
; /* replication DB file descriptor */
320 long repldboff
; /* replication DB file offset */
321 off_t repldbsize
; /* replication DB file size */
322 multiState mstate
; /* MULTI/EXEC state */
323 robj
**blockingkeys
; /* The key we are waiting to terminate a blocking
324 * operation such as BLPOP. Otherwise NULL. */
325 int blockingkeysnum
; /* Number of blocking keys */
326 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
327 * is >= blockingto then the operation timed out. */
328 list
*io_keys
; /* Keys this client is waiting to be loaded from the
329 * swap file in order to continue. */
337 /* Global server state structure */
342 dict
*sharingpool
; /* Poll used for object sharing */
343 unsigned int sharingpoolsize
;
344 long long dirty
; /* changes to DB from the last save */
346 list
*slaves
, *monitors
;
347 char neterr
[ANET_ERR_LEN
];
349 int cronloops
; /* number of times the cron function run */
350 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
351 time_t lastsave
; /* Unix time of last save succeeede */
352 /* Fields used only for stats */
353 time_t stat_starttime
; /* server start time */
354 long long stat_numcommands
; /* number of processed commands */
355 long long stat_numconnections
; /* number of connections received */
356 long long stat_expiredkeys
; /* number of expired keys */
369 pid_t bgsavechildpid
;
370 pid_t bgrewritechildpid
;
371 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
372 struct saveparam
*saveparams
;
377 char *appendfilename
;
381 /* Replication related */
386 redisClient
*master
; /* client that is master for this slave */
388 unsigned int maxclients
;
389 unsigned long long maxmemory
;
390 unsigned int blpop_blocked_clients
;
391 unsigned int vm_blocked_clients
;
392 /* Sort parameters - qsort_r() is only available under BSD so we
393 * have to take this state global, in order to pass it to sortCompare() */
397 /* Virtual memory configuration */
402 unsigned long long vm_max_memory
;
404 size_t hash_max_zipmap_entries
;
405 size_t hash_max_zipmap_value
;
406 /* Virtual memory state */
409 off_t vm_next_page
; /* Next probably empty page */
410 off_t vm_near_pages
; /* Number of pages allocated sequentially */
411 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
412 time_t unixtime
; /* Unix time sampled every second. */
413 /* Virtual memory I/O threads stuff */
414 /* An I/O thread process an element taken from the io_jobs queue and
415 * put the result of the operation in the io_done list. While the
416 * job is being processed, it's put on io_processing queue. */
417 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
418 list
*io_processing
; /* List of VM I/O jobs being processed */
419 list
*io_processed
; /* List of VM I/O jobs already processed */
420 list
*io_ready_clients
; /* Clients ready to be unblocked. All keys loaded */
421 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
422 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
423 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
424 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
425 int io_active_threads
; /* Number of running I/O threads */
426 int vm_max_threads
; /* Max number of I/O threads running at the same time */
427 /* Our main thread is blocked on the event loop, locking for sockets ready
428 * to be read or written, so when a threaded I/O operation is ready to be
429 * processed by the main thread, the I/O thread will use a unix pipe to
430 * awake the main thread. The followings are the two pipe FDs. */
431 int io_ready_pipe_read
;
432 int io_ready_pipe_write
;
433 /* Virtual memory stats */
434 unsigned long long vm_stats_used_pages
;
435 unsigned long long vm_stats_swapped_objects
;
436 unsigned long long vm_stats_swapouts
;
437 unsigned long long vm_stats_swapins
;
441 typedef void redisCommandProc(redisClient
*c
);
442 struct redisCommand
{
444 redisCommandProc
*proc
;
447 /* Use a function to determine which keys need to be loaded
448 * in the background prior to executing this command. Takes precedence
449 * over vm_firstkey and others, ignored when NULL */
450 redisCommandProc
*vm_preload_proc
;
451 /* What keys should be loaded in background when calling this command? */
452 int vm_firstkey
; /* The first argument that's a key (0 = no keys) */
453 int vm_lastkey
; /* THe last argument that's a key */
454 int vm_keystep
; /* The step between first and last key */
457 struct redisFunctionSym
{
459 unsigned long pointer
;
462 typedef struct _redisSortObject
{
470 typedef struct _redisSortOperation
{
473 } redisSortOperation
;
475 /* ZSETs use a specialized version of Skiplists */
477 typedef struct zskiplistNode
{
478 struct zskiplistNode
**forward
;
479 struct zskiplistNode
*backward
;
485 typedef struct zskiplist
{
486 struct zskiplistNode
*header
, *tail
;
487 unsigned long length
;
491 typedef struct zset
{
496 /* Our shared "common" objects */
498 struct sharedObjectsStruct
{
499 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
500 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
501 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
502 *outofrangeerr
, *plus
,
503 *select0
, *select1
, *select2
, *select3
, *select4
,
504 *select5
, *select6
, *select7
, *select8
, *select9
;
507 /* Global vars that are actally used as constants. The following double
508 * values are used for double on-disk serialization, and are initialized
509 * at runtime to avoid strange compiler optimizations. */
511 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
513 /* VM threaded I/O request message */
514 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
515 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
516 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
517 typedef struct iojob
{
518 int type
; /* Request type, REDIS_IOJOB_* */
519 redisDb
*db
;/* Redis database */
520 robj
*key
; /* This I/O request is about swapping this key */
521 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
522 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
523 off_t page
; /* Swap page where to read/write the object */
524 off_t pages
; /* Swap pages needed to safe object. PREPARE_SWAP return val */
525 int canceled
; /* True if this command was canceled by blocking side of VM */
526 pthread_t thread
; /* ID of the thread processing this entry */
529 /*================================ Prototypes =============================== */
531 static void freeStringObject(robj
*o
);
532 static void freeListObject(robj
*o
);
533 static void freeSetObject(robj
*o
);
534 static void decrRefCount(void *o
);
535 static robj
*createObject(int type
, void *ptr
);
536 static void freeClient(redisClient
*c
);
537 static int rdbLoad(char *filename
);
538 static void addReply(redisClient
*c
, robj
*obj
);
539 static void addReplySds(redisClient
*c
, sds s
);
540 static void incrRefCount(robj
*o
);
541 static int rdbSaveBackground(char *filename
);
542 static robj
*createStringObject(char *ptr
, size_t len
);
543 static robj
*dupStringObject(robj
*o
);
544 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
545 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
546 static int syncWithMaster(void);
547 static robj
*tryObjectSharing(robj
*o
);
548 static int tryObjectEncoding(robj
*o
);
549 static robj
*getDecodedObject(robj
*o
);
550 static int removeExpire(redisDb
*db
, robj
*key
);
551 static int expireIfNeeded(redisDb
*db
, robj
*key
);
552 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
553 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
554 static int deleteKey(redisDb
*db
, robj
*key
);
555 static time_t getExpire(redisDb
*db
, robj
*key
);
556 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
557 static void updateSlavesWaitingBgsave(int bgsaveerr
);
558 static void freeMemoryIfNeeded(void);
559 static int processCommand(redisClient
*c
);
560 static void setupSigSegvAction(void);
561 static void rdbRemoveTempFile(pid_t childpid
);
562 static void aofRemoveTempFile(pid_t childpid
);
563 static size_t stringObjectLen(robj
*o
);
564 static void processInputBuffer(redisClient
*c
);
565 static zskiplist
*zslCreate(void);
566 static void zslFree(zskiplist
*zsl
);
567 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
568 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
569 static void initClientMultiState(redisClient
*c
);
570 static void freeClientMultiState(redisClient
*c
);
571 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
572 static void unblockClientWaitingData(redisClient
*c
);
573 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
574 static void vmInit(void);
575 static void vmMarkPagesFree(off_t page
, off_t count
);
576 static robj
*vmLoadObject(robj
*key
);
577 static robj
*vmPreviewObject(robj
*key
);
578 static int vmSwapOneObjectBlocking(void);
579 static int vmSwapOneObjectThreaded(void);
580 static int vmCanSwapOut(void);
581 static int tryFreeOneObjectFromFreelist(void);
582 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
583 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
584 static void vmCancelThreadedIOJob(robj
*o
);
585 static void lockThreadedIO(void);
586 static void unlockThreadedIO(void);
587 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
588 static void freeIOJob(iojob
*j
);
589 static void queueIOJob(iojob
*j
);
590 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
591 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
592 static void waitEmptyIOJobsQueue(void);
593 static void vmReopenSwapFile(void);
594 static int vmFreePage(off_t page
);
595 static void zunionInterBlockClientOnSwappedKeys(redisClient
*c
);
596 static int blockClientOnSwappedKeys(struct redisCommand
*cmd
, redisClient
*c
);
597 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
);
598 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
);
599 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
600 static struct redisCommand
*lookupCommand(char *name
);
601 static void call(redisClient
*c
, struct redisCommand
*cmd
);
602 static void resetClient(redisClient
*c
);
603 static void convertToRealHash(robj
*o
);
605 static void authCommand(redisClient
*c
);
606 static void pingCommand(redisClient
*c
);
607 static void echoCommand(redisClient
*c
);
608 static void setCommand(redisClient
*c
);
609 static void setnxCommand(redisClient
*c
);
610 static void getCommand(redisClient
*c
);
611 static void delCommand(redisClient
*c
);
612 static void existsCommand(redisClient
*c
);
613 static void incrCommand(redisClient
*c
);
614 static void decrCommand(redisClient
*c
);
615 static void incrbyCommand(redisClient
*c
);
616 static void decrbyCommand(redisClient
*c
);
617 static void selectCommand(redisClient
*c
);
618 static void randomkeyCommand(redisClient
*c
);
619 static void keysCommand(redisClient
*c
);
620 static void dbsizeCommand(redisClient
*c
);
621 static void lastsaveCommand(redisClient
*c
);
622 static void saveCommand(redisClient
*c
);
623 static void bgsaveCommand(redisClient
*c
);
624 static void bgrewriteaofCommand(redisClient
*c
);
625 static void shutdownCommand(redisClient
*c
);
626 static void moveCommand(redisClient
*c
);
627 static void renameCommand(redisClient
*c
);
628 static void renamenxCommand(redisClient
*c
);
629 static void lpushCommand(redisClient
*c
);
630 static void rpushCommand(redisClient
*c
);
631 static void lpopCommand(redisClient
*c
);
632 static void rpopCommand(redisClient
*c
);
633 static void llenCommand(redisClient
*c
);
634 static void lindexCommand(redisClient
*c
);
635 static void lrangeCommand(redisClient
*c
);
636 static void ltrimCommand(redisClient
*c
);
637 static void typeCommand(redisClient
*c
);
638 static void lsetCommand(redisClient
*c
);
639 static void saddCommand(redisClient
*c
);
640 static void sremCommand(redisClient
*c
);
641 static void smoveCommand(redisClient
*c
);
642 static void sismemberCommand(redisClient
*c
);
643 static void scardCommand(redisClient
*c
);
644 static void spopCommand(redisClient
*c
);
645 static void srandmemberCommand(redisClient
*c
);
646 static void sinterCommand(redisClient
*c
);
647 static void sinterstoreCommand(redisClient
*c
);
648 static void sunionCommand(redisClient
*c
);
649 static void sunionstoreCommand(redisClient
*c
);
650 static void sdiffCommand(redisClient
*c
);
651 static void sdiffstoreCommand(redisClient
*c
);
652 static void syncCommand(redisClient
*c
);
653 static void flushdbCommand(redisClient
*c
);
654 static void flushallCommand(redisClient
*c
);
655 static void sortCommand(redisClient
*c
);
656 static void lremCommand(redisClient
*c
);
657 static void rpoplpushcommand(redisClient
*c
);
658 static void infoCommand(redisClient
*c
);
659 static void mgetCommand(redisClient
*c
);
660 static void monitorCommand(redisClient
*c
);
661 static void expireCommand(redisClient
*c
);
662 static void expireatCommand(redisClient
*c
);
663 static void getsetCommand(redisClient
*c
);
664 static void ttlCommand(redisClient
*c
);
665 static void slaveofCommand(redisClient
*c
);
666 static void debugCommand(redisClient
*c
);
667 static void msetCommand(redisClient
*c
);
668 static void msetnxCommand(redisClient
*c
);
669 static void zaddCommand(redisClient
*c
);
670 static void zincrbyCommand(redisClient
*c
);
671 static void zrangeCommand(redisClient
*c
);
672 static void zrangebyscoreCommand(redisClient
*c
);
673 static void zcountCommand(redisClient
*c
);
674 static void zrevrangeCommand(redisClient
*c
);
675 static void zcardCommand(redisClient
*c
);
676 static void zremCommand(redisClient
*c
);
677 static void zscoreCommand(redisClient
*c
);
678 static void zremrangebyscoreCommand(redisClient
*c
);
679 static void multiCommand(redisClient
*c
);
680 static void execCommand(redisClient
*c
);
681 static void discardCommand(redisClient
*c
);
682 static void blpopCommand(redisClient
*c
);
683 static void brpopCommand(redisClient
*c
);
684 static void appendCommand(redisClient
*c
);
685 static void substrCommand(redisClient
*c
);
686 static void zrankCommand(redisClient
*c
);
687 static void zrevrankCommand(redisClient
*c
);
688 static void hsetCommand(redisClient
*c
);
689 static void hgetCommand(redisClient
*c
);
690 static void hdelCommand(redisClient
*c
);
691 static void hlenCommand(redisClient
*c
);
692 static void zremrangebyrankCommand(redisClient
*c
);
693 static void zunionCommand(redisClient
*c
);
694 static void zinterCommand(redisClient
*c
);
695 static void hkeysCommand(redisClient
*c
);
696 static void hvalsCommand(redisClient
*c
);
697 static void hgetallCommand(redisClient
*c
);
698 static void hexistsCommand(redisClient
*c
);
700 /*================================= Globals ================================= */
703 static struct redisServer server
; /* server global state */
704 static struct redisCommand cmdTable
[] = {
705 {"get",getCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
706 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
707 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
708 {"append",appendCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
709 {"substr",substrCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
710 {"del",delCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
711 {"exists",existsCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
712 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
713 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
714 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
,NULL
,1,-1,1},
715 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
716 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
717 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
718 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
719 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
,NULL
,1,1,1},
720 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
,NULL
,1,1,1},
721 {"llen",llenCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
722 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
723 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
724 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
725 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
726 {"lrem",lremCommand
,4,REDIS_CMD_BULK
,NULL
,1,1,1},
727 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,2,1},
728 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
729 {"srem",sremCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
730 {"smove",smoveCommand
,4,REDIS_CMD_BULK
,NULL
,1,2,1},
731 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
732 {"scard",scardCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
733 {"spop",spopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
734 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
735 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
736 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
737 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
738 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
739 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
740 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
741 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
742 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
743 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
744 {"zrem",zremCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
745 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
746 {"zremrangebyrank",zremrangebyrankCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
747 {"zunion",zunionCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
748 {"zinter",zinterCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
749 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
750 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
751 {"zcount",zcountCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
752 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
753 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
754 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
755 {"zrank",zrankCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
756 {"zrevrank",zrevrankCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
757 {"hset",hsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
758 {"hget",hgetCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
759 {"hdel",hdelCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
760 {"hlen",hlenCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
761 {"hkeys",hkeysCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
762 {"hvals",hvalsCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
763 {"hgetall",hgetallCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
764 {"hexists",hexistsCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
765 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
766 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
767 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
768 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
769 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
770 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
771 {"select",selectCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
772 {"move",moveCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
773 {"rename",renameCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
774 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
775 {"expire",expireCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
776 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
777 {"keys",keysCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
778 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
779 {"auth",authCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
780 {"ping",pingCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
781 {"echo",echoCommand
,2,REDIS_CMD_BULK
,NULL
,0,0,0},
782 {"save",saveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
783 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
784 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
785 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
786 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
787 {"type",typeCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
788 {"multi",multiCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
789 {"exec",execCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
790 {"discard",discardCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
791 {"sync",syncCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
792 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
793 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
794 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
795 {"info",infoCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
796 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
797 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
798 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
799 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
800 {NULL
,NULL
,0,0,NULL
,0,0,0}
805 /*============================ Utility functions ============================ */
807 /* Glob-style pattern matching. */
808 int stringmatchlen(const char *pattern
, int patternLen
,
809 const char *string
, int stringLen
, int nocase
)
814 while (pattern
[1] == '*') {
819 return 1; /* match */
821 if (stringmatchlen(pattern
+1, patternLen
-1,
822 string
, stringLen
, nocase
))
823 return 1; /* match */
827 return 0; /* no match */
831 return 0; /* no match */
841 not = pattern
[0] == '^';
848 if (pattern
[0] == '\\') {
851 if (pattern
[0] == string
[0])
853 } else if (pattern
[0] == ']') {
855 } else if (patternLen
== 0) {
859 } else if (pattern
[1] == '-' && patternLen
>= 3) {
860 int start
= pattern
[0];
861 int end
= pattern
[2];
869 start
= tolower(start
);
875 if (c
>= start
&& c
<= end
)
879 if (pattern
[0] == string
[0])
882 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
892 return 0; /* no match */
898 if (patternLen
>= 2) {
905 if (pattern
[0] != string
[0])
906 return 0; /* no match */
908 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
909 return 0; /* no match */
917 if (stringLen
== 0) {
918 while(*pattern
== '*') {
925 if (patternLen
== 0 && stringLen
== 0)
930 static void redisLog(int level
, const char *fmt
, ...) {
934 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
938 if (level
>= server
.verbosity
) {
944 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
945 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
946 vfprintf(fp
, fmt
, ap
);
952 if (server
.logfile
) fclose(fp
);
955 /*====================== Hash table type implementation ==================== */
957 /* This is an hash table type that uses the SDS dynamic strings libary as
958 * keys and radis objects as values (objects can hold SDS strings,
961 static void dictVanillaFree(void *privdata
, void *val
)
963 DICT_NOTUSED(privdata
);
967 static void dictListDestructor(void *privdata
, void *val
)
969 DICT_NOTUSED(privdata
);
970 listRelease((list
*)val
);
973 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
977 DICT_NOTUSED(privdata
);
979 l1
= sdslen((sds
)key1
);
980 l2
= sdslen((sds
)key2
);
981 if (l1
!= l2
) return 0;
982 return memcmp(key1
, key2
, l1
) == 0;
985 static void dictRedisObjectDestructor(void *privdata
, void *val
)
987 DICT_NOTUSED(privdata
);
989 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
993 static int dictObjKeyCompare(void *privdata
, const void *key1
,
996 const robj
*o1
= key1
, *o2
= key2
;
997 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1000 static unsigned int dictObjHash(const void *key
) {
1001 const robj
*o
= key
;
1002 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1005 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
1008 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
1011 if (o1
->encoding
== REDIS_ENCODING_INT
&&
1012 o2
->encoding
== REDIS_ENCODING_INT
&&
1013 o1
->ptr
== o2
->ptr
) return 1;
1015 o1
= getDecodedObject(o1
);
1016 o2
= getDecodedObject(o2
);
1017 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1023 static unsigned int dictEncObjHash(const void *key
) {
1024 robj
*o
= (robj
*) key
;
1026 if (o
->encoding
== REDIS_ENCODING_RAW
) {
1027 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1029 if (o
->encoding
== REDIS_ENCODING_INT
) {
1033 len
= snprintf(buf
,32,"%ld",(long)o
->ptr
);
1034 return dictGenHashFunction((unsigned char*)buf
, len
);
1038 o
= getDecodedObject(o
);
1039 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1046 /* Sets type and expires */
1047 static dictType setDictType
= {
1048 dictEncObjHash
, /* hash function */
1051 dictEncObjKeyCompare
, /* key compare */
1052 dictRedisObjectDestructor
, /* key destructor */
1053 NULL
/* val destructor */
1056 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1057 static dictType zsetDictType
= {
1058 dictEncObjHash
, /* hash function */
1061 dictEncObjKeyCompare
, /* key compare */
1062 dictRedisObjectDestructor
, /* key destructor */
1063 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
1067 static dictType dbDictType
= {
1068 dictObjHash
, /* hash function */
1071 dictObjKeyCompare
, /* key compare */
1072 dictRedisObjectDestructor
, /* key destructor */
1073 dictRedisObjectDestructor
/* val destructor */
1077 static dictType keyptrDictType
= {
1078 dictObjHash
, /* hash function */
1081 dictObjKeyCompare
, /* key compare */
1082 dictRedisObjectDestructor
, /* key destructor */
1083 NULL
/* val destructor */
1086 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1087 static dictType hashDictType
= {
1088 dictEncObjHash
, /* hash function */
1091 dictEncObjKeyCompare
, /* key compare */
1092 dictRedisObjectDestructor
, /* key destructor */
1093 dictRedisObjectDestructor
/* val destructor */
1096 /* Keylist hash table type has unencoded redis objects as keys and
1097 * lists as values. It's used for blocking operations (BLPOP) and to
1098 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1099 static dictType keylistDictType
= {
1100 dictObjHash
, /* hash function */
1103 dictObjKeyCompare
, /* key compare */
1104 dictRedisObjectDestructor
, /* key destructor */
1105 dictListDestructor
/* val destructor */
1108 static void version();
1110 /* ========================= Random utility functions ======================= */
1112 /* Redis generally does not try to recover from out of memory conditions
1113 * when allocating objects or strings, it is not clear if it will be possible
1114 * to report this condition to the client since the networking layer itself
1115 * is based on heap allocation for send buffers, so we simply abort.
1116 * At least the code will be simpler to read... */
1117 static void oom(const char *msg
) {
1118 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1123 /* ====================== Redis server networking stuff ===================== */
1124 static void closeTimedoutClients(void) {
1127 time_t now
= time(NULL
);
1130 listRewind(server
.clients
,&li
);
1131 while ((ln
= listNext(&li
)) != NULL
) {
1132 c
= listNodeValue(ln
);
1133 if (server
.maxidletime
&&
1134 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1135 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1136 (now
- c
->lastinteraction
> server
.maxidletime
))
1138 redisLog(REDIS_VERBOSE
,"Closing idle client");
1140 } else if (c
->flags
& REDIS_BLOCKED
) {
1141 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1142 addReply(c
,shared
.nullmultibulk
);
1143 unblockClientWaitingData(c
);
1149 static int htNeedsResize(dict
*dict
) {
1150 long long size
, used
;
1152 size
= dictSlots(dict
);
1153 used
= dictSize(dict
);
1154 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1155 (used
*100/size
< REDIS_HT_MINFILL
));
1158 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1159 * we resize the hash table to save memory */
1160 static void tryResizeHashTables(void) {
1163 for (j
= 0; j
< server
.dbnum
; j
++) {
1164 if (htNeedsResize(server
.db
[j
].dict
)) {
1165 redisLog(REDIS_VERBOSE
,"The hash table %d is too sparse, resize it...",j
);
1166 dictResize(server
.db
[j
].dict
);
1167 redisLog(REDIS_VERBOSE
,"Hash table %d resized.",j
);
1169 if (htNeedsResize(server
.db
[j
].expires
))
1170 dictResize(server
.db
[j
].expires
);
1174 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1175 void backgroundSaveDoneHandler(int statloc
) {
1176 int exitcode
= WEXITSTATUS(statloc
);
1177 int bysignal
= WIFSIGNALED(statloc
);
1179 if (!bysignal
&& exitcode
== 0) {
1180 redisLog(REDIS_NOTICE
,
1181 "Background saving terminated with success");
1183 server
.lastsave
= time(NULL
);
1184 } else if (!bysignal
&& exitcode
!= 0) {
1185 redisLog(REDIS_WARNING
, "Background saving error");
1187 redisLog(REDIS_WARNING
,
1188 "Background saving terminated by signal");
1189 rdbRemoveTempFile(server
.bgsavechildpid
);
1191 server
.bgsavechildpid
= -1;
1192 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1193 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1194 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1197 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1199 void backgroundRewriteDoneHandler(int statloc
) {
1200 int exitcode
= WEXITSTATUS(statloc
);
1201 int bysignal
= WIFSIGNALED(statloc
);
1203 if (!bysignal
&& exitcode
== 0) {
1207 redisLog(REDIS_NOTICE
,
1208 "Background append only file rewriting terminated with success");
1209 /* Now it's time to flush the differences accumulated by the parent */
1210 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1211 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1213 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1216 /* Flush our data... */
1217 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1218 (signed) sdslen(server
.bgrewritebuf
)) {
1219 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
));
1223 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1224 /* Now our work is to rename the temp file into the stable file. And
1225 * switch the file descriptor used by the server for append only. */
1226 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1227 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1231 /* Mission completed... almost */
1232 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1233 if (server
.appendfd
!= -1) {
1234 /* If append only is actually enabled... */
1235 close(server
.appendfd
);
1236 server
.appendfd
= fd
;
1238 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1239 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1241 /* If append only is disabled we just generate a dump in this
1242 * format. Why not? */
1245 } else if (!bysignal
&& exitcode
!= 0) {
1246 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1248 redisLog(REDIS_WARNING
,
1249 "Background append only file rewriting terminated by signal");
1252 sdsfree(server
.bgrewritebuf
);
1253 server
.bgrewritebuf
= sdsempty();
1254 aofRemoveTempFile(server
.bgrewritechildpid
);
1255 server
.bgrewritechildpid
= -1;
1258 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1259 int j
, loops
= server
.cronloops
++;
1260 REDIS_NOTUSED(eventLoop
);
1262 REDIS_NOTUSED(clientData
);
1264 /* We take a cached value of the unix time in the global state because
1265 * with virtual memory and aging there is to store the current time
1266 * in objects at every object access, and accuracy is not needed.
1267 * To access a global var is faster than calling time(NULL) */
1268 server
.unixtime
= time(NULL
);
1270 /* Show some info about non-empty databases */
1271 for (j
= 0; j
< server
.dbnum
; j
++) {
1272 long long size
, used
, vkeys
;
1274 size
= dictSlots(server
.db
[j
].dict
);
1275 used
= dictSize(server
.db
[j
].dict
);
1276 vkeys
= dictSize(server
.db
[j
].expires
);
1277 if (!(loops
% 50) && (used
|| vkeys
)) {
1278 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1279 /* dictPrintStats(server.dict); */
1283 /* We don't want to resize the hash tables while a bacground saving
1284 * is in progress: the saving child is created using fork() that is
1285 * implemented with a copy-on-write semantic in most modern systems, so
1286 * if we resize the HT while there is the saving child at work actually
1287 * a lot of memory movements in the parent will cause a lot of pages
1289 if (server
.bgsavechildpid
== -1 && !(loops
% 10)) tryResizeHashTables();
1291 /* Show information about connected clients */
1292 if (!(loops
% 50)) {
1293 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use, %d shared objects",
1294 listLength(server
.clients
)-listLength(server
.slaves
),
1295 listLength(server
.slaves
),
1296 zmalloc_used_memory(),
1297 dictSize(server
.sharingpool
));
1300 /* Close connections of timedout clients */
1301 if ((server
.maxidletime
&& !(loops
% 100)) || server
.blpop_blocked_clients
)
1302 closeTimedoutClients();
1304 /* Check if a background saving or AOF rewrite in progress terminated */
1305 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1309 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1310 if (pid
== server
.bgsavechildpid
) {
1311 backgroundSaveDoneHandler(statloc
);
1313 backgroundRewriteDoneHandler(statloc
);
1317 /* If there is not a background saving in progress check if
1318 * we have to save now */
1319 time_t now
= time(NULL
);
1320 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1321 struct saveparam
*sp
= server
.saveparams
+j
;
1323 if (server
.dirty
>= sp
->changes
&&
1324 now
-server
.lastsave
> sp
->seconds
) {
1325 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1326 sp
->changes
, sp
->seconds
);
1327 rdbSaveBackground(server
.dbfilename
);
1333 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1334 * will use few CPU cycles if there are few expiring keys, otherwise
1335 * it will get more aggressive to avoid that too much memory is used by
1336 * keys that can be removed from the keyspace. */
1337 for (j
= 0; j
< server
.dbnum
; j
++) {
1339 redisDb
*db
= server
.db
+j
;
1341 /* Continue to expire if at the end of the cycle more than 25%
1342 * of the keys were expired. */
1344 long num
= dictSize(db
->expires
);
1345 time_t now
= time(NULL
);
1348 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1349 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1354 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1355 t
= (time_t) dictGetEntryVal(de
);
1357 deleteKey(db
,dictGetEntryKey(de
));
1359 server
.stat_expiredkeys
++;
1362 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1365 /* Swap a few keys on disk if we are over the memory limit and VM
1366 * is enbled. Try to free objects from the free list first. */
1367 if (vmCanSwapOut()) {
1368 while (server
.vm_enabled
&& zmalloc_used_memory() >
1369 server
.vm_max_memory
)
1373 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1374 retval
= (server
.vm_max_threads
== 0) ?
1375 vmSwapOneObjectBlocking() :
1376 vmSwapOneObjectThreaded();
1377 if (retval
== REDIS_ERR
&& !(loops
% 300) &&
1378 zmalloc_used_memory() >
1379 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1381 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1383 /* Note that when using threade I/O we free just one object,
1384 * because anyway when the I/O thread in charge to swap this
1385 * object out will finish, the handler of completed jobs
1386 * will try to swap more objects if we are still out of memory. */
1387 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1391 /* Check if we should connect to a MASTER */
1392 if (server
.replstate
== REDIS_REPL_CONNECT
&& !(loops
% 10)) {
1393 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1394 if (syncWithMaster() == REDIS_OK
) {
1395 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1401 /* This function gets called every time Redis is entering the
1402 * main loop of the event driven library, that is, before to sleep
1403 * for ready file descriptors. */
1404 static void beforeSleep(struct aeEventLoop
*eventLoop
) {
1405 REDIS_NOTUSED(eventLoop
);
1407 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
1411 listRewind(server
.io_ready_clients
,&li
);
1412 while((ln
= listNext(&li
))) {
1413 redisClient
*c
= ln
->value
;
1414 struct redisCommand
*cmd
;
1416 /* Resume the client. */
1417 listDelNode(server
.io_ready_clients
,ln
);
1418 c
->flags
&= (~REDIS_IO_WAIT
);
1419 server
.vm_blocked_clients
--;
1420 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1421 readQueryFromClient
, c
);
1422 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1423 assert(cmd
!= NULL
);
1426 /* There may be more data to process in the input buffer. */
1427 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
1428 processInputBuffer(c
);
1433 static void createSharedObjects(void) {
1434 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1435 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1436 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1437 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1438 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1439 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1440 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1441 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1442 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1443 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1444 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1445 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1446 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1447 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1448 "-ERR no such key\r\n"));
1449 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1450 "-ERR syntax error\r\n"));
1451 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1452 "-ERR source and destination objects are the same\r\n"));
1453 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1454 "-ERR index out of range\r\n"));
1455 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1456 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1457 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1458 shared
.select0
= createStringObject("select 0\r\n",10);
1459 shared
.select1
= createStringObject("select 1\r\n",10);
1460 shared
.select2
= createStringObject("select 2\r\n",10);
1461 shared
.select3
= createStringObject("select 3\r\n",10);
1462 shared
.select4
= createStringObject("select 4\r\n",10);
1463 shared
.select5
= createStringObject("select 5\r\n",10);
1464 shared
.select6
= createStringObject("select 6\r\n",10);
1465 shared
.select7
= createStringObject("select 7\r\n",10);
1466 shared
.select8
= createStringObject("select 8\r\n",10);
1467 shared
.select9
= createStringObject("select 9\r\n",10);
1470 static void appendServerSaveParams(time_t seconds
, int changes
) {
1471 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1472 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1473 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1474 server
.saveparamslen
++;
1477 static void resetServerSaveParams() {
1478 zfree(server
.saveparams
);
1479 server
.saveparams
= NULL
;
1480 server
.saveparamslen
= 0;
1483 static void initServerConfig() {
1484 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1485 server
.port
= REDIS_SERVERPORT
;
1486 server
.verbosity
= REDIS_VERBOSE
;
1487 server
.maxidletime
= REDIS_MAXIDLETIME
;
1488 server
.saveparams
= NULL
;
1489 server
.logfile
= NULL
; /* NULL = log on standard output */
1490 server
.bindaddr
= NULL
;
1491 server
.glueoutputbuf
= 1;
1492 server
.daemonize
= 0;
1493 server
.appendonly
= 0;
1494 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1495 server
.lastfsync
= time(NULL
);
1496 server
.appendfd
= -1;
1497 server
.appendseldb
= -1; /* Make sure the first time will not match */
1498 server
.pidfile
= "/var/run/redis.pid";
1499 server
.dbfilename
= "dump.rdb";
1500 server
.appendfilename
= "appendonly.aof";
1501 server
.requirepass
= NULL
;
1502 server
.shareobjects
= 0;
1503 server
.rdbcompression
= 1;
1504 server
.sharingpoolsize
= 1024;
1505 server
.maxclients
= 0;
1506 server
.blpop_blocked_clients
= 0;
1507 server
.maxmemory
= 0;
1508 server
.vm_enabled
= 0;
1509 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
1510 server
.vm_page_size
= 256; /* 256 bytes per page */
1511 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1512 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1513 server
.vm_max_threads
= 4;
1514 server
.vm_blocked_clients
= 0;
1515 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
1516 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
1518 resetServerSaveParams();
1520 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1521 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1522 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1523 /* Replication related */
1525 server
.masterauth
= NULL
;
1526 server
.masterhost
= NULL
;
1527 server
.masterport
= 6379;
1528 server
.master
= NULL
;
1529 server
.replstate
= REDIS_REPL_NONE
;
1531 /* Double constants initialization */
1533 R_PosInf
= 1.0/R_Zero
;
1534 R_NegInf
= -1.0/R_Zero
;
1535 R_Nan
= R_Zero
/R_Zero
;
1538 static void initServer() {
1541 signal(SIGHUP
, SIG_IGN
);
1542 signal(SIGPIPE
, SIG_IGN
);
1543 setupSigSegvAction();
1545 server
.devnull
= fopen("/dev/null","w");
1546 if (server
.devnull
== NULL
) {
1547 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1550 server
.clients
= listCreate();
1551 server
.slaves
= listCreate();
1552 server
.monitors
= listCreate();
1553 server
.objfreelist
= listCreate();
1554 createSharedObjects();
1555 server
.el
= aeCreateEventLoop();
1556 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1557 server
.sharingpool
= dictCreate(&setDictType
,NULL
);
1558 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1559 if (server
.fd
== -1) {
1560 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1563 for (j
= 0; j
< server
.dbnum
; j
++) {
1564 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
1565 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1566 server
.db
[j
].blockingkeys
= dictCreate(&keylistDictType
,NULL
);
1567 if (server
.vm_enabled
)
1568 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
1569 server
.db
[j
].id
= j
;
1571 server
.cronloops
= 0;
1572 server
.bgsavechildpid
= -1;
1573 server
.bgrewritechildpid
= -1;
1574 server
.bgrewritebuf
= sdsempty();
1575 server
.lastsave
= time(NULL
);
1577 server
.stat_numcommands
= 0;
1578 server
.stat_numconnections
= 0;
1579 server
.stat_expiredkeys
= 0;
1580 server
.stat_starttime
= time(NULL
);
1581 server
.unixtime
= time(NULL
);
1582 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1583 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1584 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1586 if (server
.appendonly
) {
1587 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1588 if (server
.appendfd
== -1) {
1589 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1595 if (server
.vm_enabled
) vmInit();
1598 /* Empty the whole database */
1599 static long long emptyDb() {
1601 long long removed
= 0;
1603 for (j
= 0; j
< server
.dbnum
; j
++) {
1604 removed
+= dictSize(server
.db
[j
].dict
);
1605 dictEmpty(server
.db
[j
].dict
);
1606 dictEmpty(server
.db
[j
].expires
);
1611 static int yesnotoi(char *s
) {
1612 if (!strcasecmp(s
,"yes")) return 1;
1613 else if (!strcasecmp(s
,"no")) return 0;
1617 /* I agree, this is a very rudimental way to load a configuration...
1618 will improve later if the config gets more complex */
1619 static void loadServerConfig(char *filename
) {
1621 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1624 char *errormsg
= "Fatal error, can't open config file '%s'";
1625 char *errorbuf
= zmalloc(sizeof(char)*(strlen(errormsg
)+strlen(filename
)));
1626 sprintf(errorbuf
, errormsg
, filename
);
1628 if (filename
[0] == '-' && filename
[1] == '\0')
1631 if ((fp
= fopen(filename
,"r")) == NULL
) {
1632 redisLog(REDIS_WARNING
, errorbuf
);
1637 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1643 line
= sdstrim(line
," \t\r\n");
1645 /* Skip comments and blank lines*/
1646 if (line
[0] == '#' || line
[0] == '\0') {
1651 /* Split into arguments */
1652 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1653 sdstolower(argv
[0]);
1655 /* Execute config directives */
1656 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1657 server
.maxidletime
= atoi(argv
[1]);
1658 if (server
.maxidletime
< 0) {
1659 err
= "Invalid timeout value"; goto loaderr
;
1661 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1662 server
.port
= atoi(argv
[1]);
1663 if (server
.port
< 1 || server
.port
> 65535) {
1664 err
= "Invalid port"; goto loaderr
;
1666 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1667 server
.bindaddr
= zstrdup(argv
[1]);
1668 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1669 int seconds
= atoi(argv
[1]);
1670 int changes
= atoi(argv
[2]);
1671 if (seconds
< 1 || changes
< 0) {
1672 err
= "Invalid save parameters"; goto loaderr
;
1674 appendServerSaveParams(seconds
,changes
);
1675 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1676 if (chdir(argv
[1]) == -1) {
1677 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1678 argv
[1], strerror(errno
));
1681 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1682 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1683 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1684 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1685 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1687 err
= "Invalid log level. Must be one of debug, notice, warning";
1690 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1693 server
.logfile
= zstrdup(argv
[1]);
1694 if (!strcasecmp(server
.logfile
,"stdout")) {
1695 zfree(server
.logfile
);
1696 server
.logfile
= NULL
;
1698 if (server
.logfile
) {
1699 /* Test if we are able to open the file. The server will not
1700 * be able to abort just for this problem later... */
1701 logfp
= fopen(server
.logfile
,"a");
1702 if (logfp
== NULL
) {
1703 err
= sdscatprintf(sdsempty(),
1704 "Can't open the log file: %s", strerror(errno
));
1709 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1710 server
.dbnum
= atoi(argv
[1]);
1711 if (server
.dbnum
< 1) {
1712 err
= "Invalid number of databases"; goto loaderr
;
1714 } else if (!strcasecmp(argv
[0],"include") && argc
== 2) {
1715 loadServerConfig(argv
[1]);
1716 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1717 server
.maxclients
= atoi(argv
[1]);
1718 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1719 server
.maxmemory
= strtoll(argv
[1], NULL
, 10);
1720 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1721 server
.masterhost
= sdsnew(argv
[1]);
1722 server
.masterport
= atoi(argv
[2]);
1723 server
.replstate
= REDIS_REPL_CONNECT
;
1724 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1725 server
.masterauth
= zstrdup(argv
[1]);
1726 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1727 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1728 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1730 } else if (!strcasecmp(argv
[0],"shareobjects") && argc
== 2) {
1731 if ((server
.shareobjects
= yesnotoi(argv
[1])) == -1) {
1732 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1734 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1735 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1736 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1738 } else if (!strcasecmp(argv
[0],"shareobjectspoolsize") && argc
== 2) {
1739 server
.sharingpoolsize
= atoi(argv
[1]);
1740 if (server
.sharingpoolsize
< 1) {
1741 err
= "invalid object sharing pool size"; goto loaderr
;
1743 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1744 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1745 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1747 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1748 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1749 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1751 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1752 if (!strcasecmp(argv
[1],"no")) {
1753 server
.appendfsync
= APPENDFSYNC_NO
;
1754 } else if (!strcasecmp(argv
[1],"always")) {
1755 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1756 } else if (!strcasecmp(argv
[1],"everysec")) {
1757 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1759 err
= "argument must be 'no', 'always' or 'everysec'";
1762 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1763 server
.requirepass
= zstrdup(argv
[1]);
1764 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1765 server
.pidfile
= zstrdup(argv
[1]);
1766 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1767 server
.dbfilename
= zstrdup(argv
[1]);
1768 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1769 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1770 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1772 } else if (!strcasecmp(argv
[0],"vm-swap-file") && argc
== 2) {
1773 zfree(server
.vm_swap_file
);
1774 server
.vm_swap_file
= zstrdup(argv
[1]);
1775 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1776 server
.vm_max_memory
= strtoll(argv
[1], NULL
, 10);
1777 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1778 server
.vm_page_size
= strtoll(argv
[1], NULL
, 10);
1779 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1780 server
.vm_pages
= strtoll(argv
[1], NULL
, 10);
1781 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1782 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1783 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-entries") && argc
== 2){
1784 server
.hash_max_zipmap_entries
= strtol(argv
[1], NULL
, 10);
1785 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-value") && argc
== 2){
1786 server
.hash_max_zipmap_value
= strtol(argv
[1], NULL
, 10);
1787 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1788 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1790 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1792 for (j
= 0; j
< argc
; j
++)
1797 if (fp
!= stdin
) fclose(fp
);
1801 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1802 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1803 fprintf(stderr
, ">>> '%s'\n", line
);
1804 fprintf(stderr
, "%s\n", err
);
1808 static void freeClientArgv(redisClient
*c
) {
1811 for (j
= 0; j
< c
->argc
; j
++)
1812 decrRefCount(c
->argv
[j
]);
1813 for (j
= 0; j
< c
->mbargc
; j
++)
1814 decrRefCount(c
->mbargv
[j
]);
1819 static void freeClient(redisClient
*c
) {
1822 /* Note that if the client we are freeing is blocked into a blocking
1823 * call, we have to set querybuf to NULL *before* to call
1824 * unblockClientWaitingData() to avoid processInputBuffer() will get
1825 * called. Also it is important to remove the file events after
1826 * this, because this call adds the READABLE event. */
1827 sdsfree(c
->querybuf
);
1829 if (c
->flags
& REDIS_BLOCKED
)
1830 unblockClientWaitingData(c
);
1832 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
1833 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1834 listRelease(c
->reply
);
1837 /* Remove from the list of clients */
1838 ln
= listSearchKey(server
.clients
,c
);
1839 redisAssert(ln
!= NULL
);
1840 listDelNode(server
.clients
,ln
);
1841 /* Remove from the list of clients waiting for swapped keys */
1842 if (c
->flags
& REDIS_IO_WAIT
&& listLength(c
->io_keys
) == 0) {
1843 ln
= listSearchKey(server
.io_ready_clients
,c
);
1845 listDelNode(server
.io_ready_clients
,ln
);
1846 server
.vm_blocked_clients
--;
1849 while (server
.vm_enabled
&& listLength(c
->io_keys
)) {
1850 ln
= listFirst(c
->io_keys
);
1851 dontWaitForSwappedKey(c
,ln
->value
);
1853 listRelease(c
->io_keys
);
1855 if (c
->flags
& REDIS_SLAVE
) {
1856 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
1858 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
1859 ln
= listSearchKey(l
,c
);
1860 redisAssert(ln
!= NULL
);
1863 if (c
->flags
& REDIS_MASTER
) {
1864 server
.master
= NULL
;
1865 server
.replstate
= REDIS_REPL_CONNECT
;
1869 freeClientMultiState(c
);
1873 #define GLUEREPLY_UP_TO (1024)
1874 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
1876 char buf
[GLUEREPLY_UP_TO
];
1881 listRewind(c
->reply
,&li
);
1882 while((ln
= listNext(&li
))) {
1886 objlen
= sdslen(o
->ptr
);
1887 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
1888 memcpy(buf
+copylen
,o
->ptr
,objlen
);
1890 listDelNode(c
->reply
,ln
);
1892 if (copylen
== 0) return;
1896 /* Now the output buffer is empty, add the new single element */
1897 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
1898 listAddNodeHead(c
->reply
,o
);
1901 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
1902 redisClient
*c
= privdata
;
1903 int nwritten
= 0, totwritten
= 0, objlen
;
1906 REDIS_NOTUSED(mask
);
1908 /* Use writev() if we have enough buffers to send */
1909 if (!server
.glueoutputbuf
&&
1910 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
1911 !(c
->flags
& REDIS_MASTER
))
1913 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
1917 while(listLength(c
->reply
)) {
1918 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
1919 glueReplyBuffersIfNeeded(c
);
1921 o
= listNodeValue(listFirst(c
->reply
));
1922 objlen
= sdslen(o
->ptr
);
1925 listDelNode(c
->reply
,listFirst(c
->reply
));
1929 if (c
->flags
& REDIS_MASTER
) {
1930 /* Don't reply to a master */
1931 nwritten
= objlen
- c
->sentlen
;
1933 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
1934 if (nwritten
<= 0) break;
1936 c
->sentlen
+= nwritten
;
1937 totwritten
+= nwritten
;
1938 /* If we fully sent the object on head go to the next one */
1939 if (c
->sentlen
== objlen
) {
1940 listDelNode(c
->reply
,listFirst(c
->reply
));
1943 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
1944 * bytes, in a single threaded server it's a good idea to serve
1945 * other clients as well, even if a very large request comes from
1946 * super fast link that is always able to accept data (in real world
1947 * scenario think about 'KEYS *' against the loopback interfae) */
1948 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
1950 if (nwritten
== -1) {
1951 if (errno
== EAGAIN
) {
1954 redisLog(REDIS_VERBOSE
,
1955 "Error writing to client: %s", strerror(errno
));
1960 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
1961 if (listLength(c
->reply
) == 0) {
1963 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
1967 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
1969 redisClient
*c
= privdata
;
1970 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
1972 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
1973 int offset
, ion
= 0;
1975 REDIS_NOTUSED(mask
);
1978 while (listLength(c
->reply
)) {
1979 offset
= c
->sentlen
;
1983 /* fill-in the iov[] array */
1984 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
1985 o
= listNodeValue(node
);
1986 objlen
= sdslen(o
->ptr
);
1988 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
1991 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
1992 break; /* no more iovecs */
1994 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
1995 iov
[ion
].iov_len
= objlen
- offset
;
1996 willwrite
+= objlen
- offset
;
1997 offset
= 0; /* just for the first item */
2004 /* write all collected blocks at once */
2005 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
2006 if (errno
!= EAGAIN
) {
2007 redisLog(REDIS_VERBOSE
,
2008 "Error writing to client: %s", strerror(errno
));
2015 totwritten
+= nwritten
;
2016 offset
= c
->sentlen
;
2018 /* remove written robjs from c->reply */
2019 while (nwritten
&& listLength(c
->reply
)) {
2020 o
= listNodeValue(listFirst(c
->reply
));
2021 objlen
= sdslen(o
->ptr
);
2023 if(nwritten
>= objlen
- offset
) {
2024 listDelNode(c
->reply
, listFirst(c
->reply
));
2025 nwritten
-= objlen
- offset
;
2029 c
->sentlen
+= nwritten
;
2037 c
->lastinteraction
= time(NULL
);
2039 if (listLength(c
->reply
) == 0) {
2041 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2045 static struct redisCommand
*lookupCommand(char *name
) {
2047 while(cmdTable
[j
].name
!= NULL
) {
2048 if (!strcasecmp(name
,cmdTable
[j
].name
)) return &cmdTable
[j
];
2054 /* resetClient prepare the client to process the next command */
2055 static void resetClient(redisClient
*c
) {
2061 /* Call() is the core of Redis execution of a command */
2062 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
2065 dirty
= server
.dirty
;
2067 if (server
.appendonly
&& server
.dirty
-dirty
)
2068 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2069 if (server
.dirty
-dirty
&& listLength(server
.slaves
))
2070 replicationFeedSlaves(server
.slaves
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2071 if (listLength(server
.monitors
))
2072 replicationFeedSlaves(server
.monitors
,cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2073 server
.stat_numcommands
++;
2076 /* If this function gets called we already read a whole
2077 * command, argments are in the client argv/argc fields.
2078 * processCommand() execute the command or prepare the
2079 * server for a bulk read from the client.
2081 * If 1 is returned the client is still alive and valid and
2082 * and other operations can be performed by the caller. Otherwise
2083 * if 0 is returned the client was destroied (i.e. after QUIT). */
2084 static int processCommand(redisClient
*c
) {
2085 struct redisCommand
*cmd
;
2087 /* Free some memory if needed (maxmemory setting) */
2088 if (server
.maxmemory
) freeMemoryIfNeeded();
2090 /* Handle the multi bulk command type. This is an alternative protocol
2091 * supported by Redis in order to receive commands that are composed of
2092 * multiple binary-safe "bulk" arguments. The latency of processing is
2093 * a bit higher but this allows things like multi-sets, so if this
2094 * protocol is used only for MSET and similar commands this is a big win. */
2095 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
2096 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2097 if (c
->multibulk
<= 0) {
2101 decrRefCount(c
->argv
[c
->argc
-1]);
2105 } else if (c
->multibulk
) {
2106 if (c
->bulklen
== -1) {
2107 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
2108 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
2112 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2113 decrRefCount(c
->argv
[0]);
2114 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2116 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2121 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2125 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
2126 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
2130 if (c
->multibulk
== 0) {
2134 /* Here we need to swap the multi-bulk argc/argv with the
2135 * normal argc/argv of the client structure. */
2137 c
->argv
= c
->mbargv
;
2138 c
->mbargv
= auxargv
;
2141 c
->argc
= c
->mbargc
;
2142 c
->mbargc
= auxargc
;
2144 /* We need to set bulklen to something different than -1
2145 * in order for the code below to process the command without
2146 * to try to read the last argument of a bulk command as
2147 * a special argument. */
2149 /* continue below and process the command */
2156 /* -- end of multi bulk commands processing -- */
2158 /* The QUIT command is handled as a special case. Normal command
2159 * procs are unable to close the client connection safely */
2160 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2165 /* Now lookup the command and check ASAP about trivial error conditions
2166 * such wrong arity, bad command name and so forth. */
2167 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2170 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2171 (char*)c
->argv
[0]->ptr
));
2174 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2175 (c
->argc
< -cmd
->arity
)) {
2177 sdscatprintf(sdsempty(),
2178 "-ERR wrong number of arguments for '%s' command\r\n",
2182 } else if (server
.maxmemory
&& cmd
->flags
& REDIS_CMD_DENYOOM
&& zmalloc_used_memory() > server
.maxmemory
) {
2183 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2186 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2187 /* This is a bulk command, we have to read the last argument yet. */
2188 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2190 decrRefCount(c
->argv
[c
->argc
-1]);
2191 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2193 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2198 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2199 /* It is possible that the bulk read is already in the
2200 * buffer. Check this condition and handle it accordingly.
2201 * This is just a fast path, alternative to call processInputBuffer().
2202 * It's a good idea since the code is small and this condition
2203 * happens most of the times. */
2204 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2205 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2207 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2209 /* Otherwise return... there is to read the last argument
2210 * from the socket. */
2214 /* Let's try to share objects on the command arguments vector */
2215 if (server
.shareobjects
) {
2217 for(j
= 1; j
< c
->argc
; j
++)
2218 c
->argv
[j
] = tryObjectSharing(c
->argv
[j
]);
2220 /* Let's try to encode the bulk object to save space. */
2221 if (cmd
->flags
& REDIS_CMD_BULK
)
2222 tryObjectEncoding(c
->argv
[c
->argc
-1]);
2224 /* Check if the user is authenticated */
2225 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2226 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2231 /* Exec the command */
2232 if (c
->flags
& REDIS_MULTI
&& cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
) {
2233 queueMultiCommand(c
,cmd
);
2234 addReply(c
,shared
.queued
);
2236 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
2237 blockClientOnSwappedKeys(cmd
,c
)) return 1;
2241 /* Prepare the client for the next command */
2246 static void replicationFeedSlaves(list
*slaves
, struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
2251 /* (args*2)+1 is enough room for args, spaces, newlines */
2252 robj
*static_outv
[REDIS_STATIC_ARGS
*2+1];
2254 if (argc
<= REDIS_STATIC_ARGS
) {
2257 outv
= zmalloc(sizeof(robj
*)*(argc
*2+1));
2260 for (j
= 0; j
< argc
; j
++) {
2261 if (j
!= 0) outv
[outc
++] = shared
.space
;
2262 if ((cmd
->flags
& REDIS_CMD_BULK
) && j
== argc
-1) {
2265 lenobj
= createObject(REDIS_STRING
,
2266 sdscatprintf(sdsempty(),"%lu\r\n",
2267 (unsigned long) stringObjectLen(argv
[j
])));
2268 lenobj
->refcount
= 0;
2269 outv
[outc
++] = lenobj
;
2271 outv
[outc
++] = argv
[j
];
2273 outv
[outc
++] = shared
.crlf
;
2275 /* Increment all the refcounts at start and decrement at end in order to
2276 * be sure to free objects if there is no slave in a replication state
2277 * able to be feed with commands */
2278 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2279 listRewind(slaves
,&li
);
2280 while((ln
= listNext(&li
))) {
2281 redisClient
*slave
= ln
->value
;
2283 /* Don't feed slaves that are still waiting for BGSAVE to start */
2284 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2286 /* Feed all the other slaves, MONITORs and so on */
2287 if (slave
->slaveseldb
!= dictid
) {
2291 case 0: selectcmd
= shared
.select0
; break;
2292 case 1: selectcmd
= shared
.select1
; break;
2293 case 2: selectcmd
= shared
.select2
; break;
2294 case 3: selectcmd
= shared
.select3
; break;
2295 case 4: selectcmd
= shared
.select4
; break;
2296 case 5: selectcmd
= shared
.select5
; break;
2297 case 6: selectcmd
= shared
.select6
; break;
2298 case 7: selectcmd
= shared
.select7
; break;
2299 case 8: selectcmd
= shared
.select8
; break;
2300 case 9: selectcmd
= shared
.select9
; break;
2302 selectcmd
= createObject(REDIS_STRING
,
2303 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2304 selectcmd
->refcount
= 0;
2307 addReply(slave
,selectcmd
);
2308 slave
->slaveseldb
= dictid
;
2310 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2312 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2313 if (outv
!= static_outv
) zfree(outv
);
2316 static void processInputBuffer(redisClient
*c
) {
2318 /* Before to process the input buffer, make sure the client is not
2319 * waitig for a blocking operation such as BLPOP. Note that the first
2320 * iteration the client is never blocked, otherwise the processInputBuffer
2321 * would not be called at all, but after the execution of the first commands
2322 * in the input buffer the client may be blocked, and the "goto again"
2323 * will try to reiterate. The following line will make it return asap. */
2324 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2325 if (c
->bulklen
== -1) {
2326 /* Read the first line of the query */
2327 char *p
= strchr(c
->querybuf
,'\n');
2334 query
= c
->querybuf
;
2335 c
->querybuf
= sdsempty();
2336 querylen
= 1+(p
-(query
));
2337 if (sdslen(query
) > querylen
) {
2338 /* leave data after the first line of the query in the buffer */
2339 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2341 *p
= '\0'; /* remove "\n" */
2342 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2343 sdsupdatelen(query
);
2345 /* Now we can split the query in arguments */
2346 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2349 if (c
->argv
) zfree(c
->argv
);
2350 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2352 for (j
= 0; j
< argc
; j
++) {
2353 if (sdslen(argv
[j
])) {
2354 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2362 /* Execute the command. If the client is still valid
2363 * after processCommand() return and there is something
2364 * on the query buffer try to process the next command. */
2365 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2367 /* Nothing to process, argc == 0. Just process the query
2368 * buffer if it's not empty or return to the caller */
2369 if (sdslen(c
->querybuf
)) goto again
;
2372 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2373 redisLog(REDIS_VERBOSE
, "Client protocol error");
2378 /* Bulk read handling. Note that if we are at this point
2379 the client already sent a command terminated with a newline,
2380 we are reading the bulk data that is actually the last
2381 argument of the command. */
2382 int qbl
= sdslen(c
->querybuf
);
2384 if (c
->bulklen
<= qbl
) {
2385 /* Copy everything but the final CRLF as final argument */
2386 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2388 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2389 /* Process the command. If the client is still valid after
2390 * the processing and there is more data in the buffer
2391 * try to parse it. */
2392 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2398 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2399 redisClient
*c
= (redisClient
*) privdata
;
2400 char buf
[REDIS_IOBUF_LEN
];
2403 REDIS_NOTUSED(mask
);
2405 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2407 if (errno
== EAGAIN
) {
2410 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2414 } else if (nread
== 0) {
2415 redisLog(REDIS_VERBOSE
, "Client closed connection");
2420 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2421 c
->lastinteraction
= time(NULL
);
2425 if (!(c
->flags
& REDIS_BLOCKED
))
2426 processInputBuffer(c
);
2429 static int selectDb(redisClient
*c
, int id
) {
2430 if (id
< 0 || id
>= server
.dbnum
)
2432 c
->db
= &server
.db
[id
];
2436 static void *dupClientReplyValue(void *o
) {
2437 incrRefCount((robj
*)o
);
2441 static redisClient
*createClient(int fd
) {
2442 redisClient
*c
= zmalloc(sizeof(*c
));
2444 anetNonBlock(NULL
,fd
);
2445 anetTcpNoDelay(NULL
,fd
);
2446 if (!c
) return NULL
;
2449 c
->querybuf
= sdsempty();
2458 c
->lastinteraction
= time(NULL
);
2459 c
->authenticated
= 0;
2460 c
->replstate
= REDIS_REPL_NONE
;
2461 c
->reply
= listCreate();
2462 listSetFreeMethod(c
->reply
,decrRefCount
);
2463 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2464 c
->blockingkeys
= NULL
;
2465 c
->blockingkeysnum
= 0;
2466 c
->io_keys
= listCreate();
2467 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2468 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2469 readQueryFromClient
, c
) == AE_ERR
) {
2473 listAddNodeTail(server
.clients
,c
);
2474 initClientMultiState(c
);
2478 static void addReply(redisClient
*c
, robj
*obj
) {
2479 if (listLength(c
->reply
) == 0 &&
2480 (c
->replstate
== REDIS_REPL_NONE
||
2481 c
->replstate
== REDIS_REPL_ONLINE
) &&
2482 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2483 sendReplyToClient
, c
) == AE_ERR
) return;
2485 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2486 obj
= dupStringObject(obj
);
2487 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2489 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2492 static void addReplySds(redisClient
*c
, sds s
) {
2493 robj
*o
= createObject(REDIS_STRING
,s
);
2498 static void addReplyDouble(redisClient
*c
, double d
) {
2501 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2502 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2503 (unsigned long) strlen(buf
),buf
));
2506 static void addReplyLong(redisClient
*c
, long l
) {
2511 addReply(c
,shared
.czero
);
2513 } else if (l
== 1) {
2514 addReply(c
,shared
.cone
);
2517 len
= snprintf(buf
,sizeof(buf
),":%ld\r\n",l
);
2518 addReplySds(c
,sdsnewlen(buf
,len
));
2521 static void addReplyUlong(redisClient
*c
, unsigned long ul
) {
2526 addReply(c
,shared
.czero
);
2528 } else if (ul
== 1) {
2529 addReply(c
,shared
.cone
);
2532 len
= snprintf(buf
,sizeof(buf
),":%lu\r\n",ul
);
2533 addReplySds(c
,sdsnewlen(buf
,len
));
2536 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2539 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2540 len
= sdslen(obj
->ptr
);
2542 long n
= (long)obj
->ptr
;
2544 /* Compute how many bytes will take this integer as a radix 10 string */
2550 while((n
= n
/10) != 0) {
2554 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",(unsigned long)len
));
2557 static void addReplyBulk(redisClient
*c
, robj
*obj
) {
2558 addReplyBulkLen(c
,obj
);
2560 addReply(c
,shared
.crlf
);
2563 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2568 REDIS_NOTUSED(mask
);
2569 REDIS_NOTUSED(privdata
);
2571 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2572 if (cfd
== AE_ERR
) {
2573 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2576 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2577 if ((c
= createClient(cfd
)) == NULL
) {
2578 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2579 close(cfd
); /* May be already closed, just ingore errors */
2582 /* If maxclient directive is set and this is one client more... close the
2583 * connection. Note that we create the client instead to check before
2584 * for this condition, since now the socket is already set in nonblocking
2585 * mode and we can send an error for free using the Kernel I/O */
2586 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2587 char *err
= "-ERR max number of clients reached\r\n";
2589 /* That's a best effort error message, don't check write errors */
2590 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2591 /* Nothing to do, Just to avoid the warning... */
2596 server
.stat_numconnections
++;
2599 /* ======================= Redis objects implementation ===================== */
2601 static robj
*createObject(int type
, void *ptr
) {
2604 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2605 if (listLength(server
.objfreelist
)) {
2606 listNode
*head
= listFirst(server
.objfreelist
);
2607 o
= listNodeValue(head
);
2608 listDelNode(server
.objfreelist
,head
);
2609 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2611 if (server
.vm_enabled
) {
2612 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2613 o
= zmalloc(sizeof(*o
));
2615 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2619 o
->encoding
= REDIS_ENCODING_RAW
;
2622 if (server
.vm_enabled
) {
2623 /* Note that this code may run in the context of an I/O thread
2624 * and accessing to server.unixtime in theory is an error
2625 * (no locks). But in practice this is safe, and even if we read
2626 * garbage Redis will not fail, as it's just a statistical info */
2627 o
->vm
.atime
= server
.unixtime
;
2628 o
->storage
= REDIS_VM_MEMORY
;
2633 static robj
*createStringObject(char *ptr
, size_t len
) {
2634 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2637 static robj
*dupStringObject(robj
*o
) {
2638 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2639 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2642 static robj
*createListObject(void) {
2643 list
*l
= listCreate();
2645 listSetFreeMethod(l
,decrRefCount
);
2646 return createObject(REDIS_LIST
,l
);
2649 static robj
*createSetObject(void) {
2650 dict
*d
= dictCreate(&setDictType
,NULL
);
2651 return createObject(REDIS_SET
,d
);
2654 static robj
*createHashObject(void) {
2655 /* All the Hashes start as zipmaps. Will be automatically converted
2656 * into hash tables if there are enough elements or big elements
2658 unsigned char *zm
= zipmapNew();
2659 robj
*o
= createObject(REDIS_HASH
,zm
);
2660 o
->encoding
= REDIS_ENCODING_ZIPMAP
;
2664 static robj
*createZsetObject(void) {
2665 zset
*zs
= zmalloc(sizeof(*zs
));
2667 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
2668 zs
->zsl
= zslCreate();
2669 return createObject(REDIS_ZSET
,zs
);
2672 static void freeStringObject(robj
*o
) {
2673 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2678 static void freeListObject(robj
*o
) {
2679 listRelease((list
*) o
->ptr
);
2682 static void freeSetObject(robj
*o
) {
2683 dictRelease((dict
*) o
->ptr
);
2686 static void freeZsetObject(robj
*o
) {
2689 dictRelease(zs
->dict
);
2694 static void freeHashObject(robj
*o
) {
2695 switch (o
->encoding
) {
2696 case REDIS_ENCODING_HT
:
2697 dictRelease((dict
*) o
->ptr
);
2699 case REDIS_ENCODING_ZIPMAP
:
2708 static void incrRefCount(robj
*o
) {
2709 redisAssert(!server
.vm_enabled
|| o
->storage
== REDIS_VM_MEMORY
);
2713 static void decrRefCount(void *obj
) {
2716 /* Object is a key of a swapped out value, or in the process of being
2718 if (server
.vm_enabled
&&
2719 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
2721 if (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
) {
2722 redisAssert(o
->refcount
== 1);
2724 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
2725 redisAssert(o
->type
== REDIS_STRING
);
2726 freeStringObject(o
);
2727 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
2728 pthread_mutex_lock(&server
.obj_freelist_mutex
);
2729 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2730 !listAddNodeHead(server
.objfreelist
,o
))
2732 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2733 server
.vm_stats_swapped_objects
--;
2736 /* Object is in memory, or in the process of being swapped out. */
2737 if (--(o
->refcount
) == 0) {
2738 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
2739 vmCancelThreadedIOJob(obj
);
2741 case REDIS_STRING
: freeStringObject(o
); break;
2742 case REDIS_LIST
: freeListObject(o
); break;
2743 case REDIS_SET
: freeSetObject(o
); break;
2744 case REDIS_ZSET
: freeZsetObject(o
); break;
2745 case REDIS_HASH
: freeHashObject(o
); break;
2746 default: redisAssert(0); break;
2748 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2749 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
2750 !listAddNodeHead(server
.objfreelist
,o
))
2752 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2756 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
2757 dictEntry
*de
= dictFind(db
->dict
,key
);
2759 robj
*key
= dictGetEntryKey(de
);
2760 robj
*val
= dictGetEntryVal(de
);
2762 if (server
.vm_enabled
) {
2763 if (key
->storage
== REDIS_VM_MEMORY
||
2764 key
->storage
== REDIS_VM_SWAPPING
)
2766 /* If we were swapping the object out, stop it, this key
2768 if (key
->storage
== REDIS_VM_SWAPPING
)
2769 vmCancelThreadedIOJob(key
);
2770 /* Update the access time of the key for the aging algorithm. */
2771 key
->vm
.atime
= server
.unixtime
;
2773 int notify
= (key
->storage
== REDIS_VM_LOADING
);
2775 /* Our value was swapped on disk. Bring it at home. */
2776 redisAssert(val
== NULL
);
2777 val
= vmLoadObject(key
);
2778 dictGetEntryVal(de
) = val
;
2780 /* Clients blocked by the VM subsystem may be waiting for
2782 if (notify
) handleClientsBlockedOnSwappedKey(db
,key
);
2791 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
2792 expireIfNeeded(db
,key
);
2793 return lookupKey(db
,key
);
2796 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
2797 deleteIfVolatile(db
,key
);
2798 return lookupKey(db
,key
);
2801 static robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
2802 robj
*o
= lookupKeyRead(c
->db
, key
);
2803 if (!o
) addReply(c
,reply
);
2807 static robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
2808 robj
*o
= lookupKeyWrite(c
->db
, key
);
2809 if (!o
) addReply(c
,reply
);
2813 static int checkType(redisClient
*c
, robj
*o
, int type
) {
2814 if (o
->type
!= type
) {
2815 addReply(c
,shared
.wrongtypeerr
);
2821 static int deleteKey(redisDb
*db
, robj
*key
) {
2824 /* We need to protect key from destruction: after the first dictDelete()
2825 * it may happen that 'key' is no longer valid if we don't increment
2826 * it's count. This may happen when we get the object reference directly
2827 * from the hash table with dictRandomKey() or dict iterators */
2829 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
2830 retval
= dictDelete(db
->dict
,key
);
2833 return retval
== DICT_OK
;
2836 /* Try to share an object against the shared objects pool */
2837 static robj
*tryObjectSharing(robj
*o
) {
2838 struct dictEntry
*de
;
2841 if (o
== NULL
|| server
.shareobjects
== 0) return o
;
2843 redisAssert(o
->type
== REDIS_STRING
);
2844 de
= dictFind(server
.sharingpool
,o
);
2846 robj
*shared
= dictGetEntryKey(de
);
2848 c
= ((unsigned long) dictGetEntryVal(de
))+1;
2849 dictGetEntryVal(de
) = (void*) c
;
2850 incrRefCount(shared
);
2854 /* Here we are using a stream algorihtm: Every time an object is
2855 * shared we increment its count, everytime there is a miss we
2856 * recrement the counter of a random object. If this object reaches
2857 * zero we remove the object and put the current object instead. */
2858 if (dictSize(server
.sharingpool
) >=
2859 server
.sharingpoolsize
) {
2860 de
= dictGetRandomKey(server
.sharingpool
);
2861 redisAssert(de
!= NULL
);
2862 c
= ((unsigned long) dictGetEntryVal(de
))-1;
2863 dictGetEntryVal(de
) = (void*) c
;
2865 dictDelete(server
.sharingpool
,de
->key
);
2868 c
= 0; /* If the pool is empty we want to add this object */
2873 retval
= dictAdd(server
.sharingpool
,o
,(void*)1);
2874 redisAssert(retval
== DICT_OK
);
2881 /* Check if the nul-terminated string 's' can be represented by a long
2882 * (that is, is a number that fits into long without any other space or
2883 * character before or after the digits).
2885 * If so, the function returns REDIS_OK and *longval is set to the value
2886 * of the number. Otherwise REDIS_ERR is returned */
2887 static int isStringRepresentableAsLong(sds s
, long *longval
) {
2888 char buf
[32], *endptr
;
2892 value
= strtol(s
, &endptr
, 10);
2893 if (endptr
[0] != '\0') return REDIS_ERR
;
2894 slen
= snprintf(buf
,32,"%ld",value
);
2896 /* If the number converted back into a string is not identical
2897 * then it's not possible to encode the string as integer */
2898 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
2899 if (longval
) *longval
= value
;
2903 /* Try to encode a string object in order to save space */
2904 static int tryObjectEncoding(robj
*o
) {
2908 if (o
->encoding
!= REDIS_ENCODING_RAW
)
2909 return REDIS_ERR
; /* Already encoded */
2911 /* It's not save to encode shared objects: shared objects can be shared
2912 * everywhere in the "object space" of Redis. Encoded objects can only
2913 * appear as "values" (and not, for instance, as keys) */
2914 if (o
->refcount
> 1) return REDIS_ERR
;
2916 /* Currently we try to encode only strings */
2917 redisAssert(o
->type
== REDIS_STRING
);
2919 /* Check if we can represent this string as a long integer */
2920 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return REDIS_ERR
;
2922 /* Ok, this object can be encoded */
2923 o
->encoding
= REDIS_ENCODING_INT
;
2925 o
->ptr
= (void*) value
;
2929 /* Get a decoded version of an encoded object (returned as a new object).
2930 * If the object is already raw-encoded just increment the ref count. */
2931 static robj
*getDecodedObject(robj
*o
) {
2934 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2938 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
2941 snprintf(buf
,32,"%ld",(long)o
->ptr
);
2942 dec
= createStringObject(buf
,strlen(buf
));
2945 redisAssert(1 != 1);
2949 /* Compare two string objects via strcmp() or alike.
2950 * Note that the objects may be integer-encoded. In such a case we
2951 * use snprintf() to get a string representation of the numbers on the stack
2952 * and compare the strings, it's much faster than calling getDecodedObject().
2954 * Important note: if objects are not integer encoded, but binary-safe strings,
2955 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
2957 static int compareStringObjects(robj
*a
, robj
*b
) {
2958 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
2959 char bufa
[128], bufb
[128], *astr
, *bstr
;
2962 if (a
== b
) return 0;
2963 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
2964 snprintf(bufa
,sizeof(bufa
),"%ld",(long) a
->ptr
);
2970 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
2971 snprintf(bufb
,sizeof(bufb
),"%ld",(long) b
->ptr
);
2977 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
2980 static size_t stringObjectLen(robj
*o
) {
2981 redisAssert(o
->type
== REDIS_STRING
);
2982 if (o
->encoding
== REDIS_ENCODING_RAW
) {
2983 return sdslen(o
->ptr
);
2987 return snprintf(buf
,32,"%ld",(long)o
->ptr
);
2991 /*============================ RDB saving/loading =========================== */
2993 static int rdbSaveType(FILE *fp
, unsigned char type
) {
2994 if (fwrite(&type
,1,1,fp
) == 0) return -1;
2998 static int rdbSaveTime(FILE *fp
, time_t t
) {
2999 int32_t t32
= (int32_t) t
;
3000 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
3004 /* check rdbLoadLen() comments for more info */
3005 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
3006 unsigned char buf
[2];
3009 /* Save a 6 bit len */
3010 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
3011 if (fwrite(buf
,1,1,fp
) == 0) return -1;
3012 } else if (len
< (1<<14)) {
3013 /* Save a 14 bit len */
3014 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
3016 if (fwrite(buf
,2,1,fp
) == 0) return -1;
3018 /* Save a 32 bit len */
3019 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
3020 if (fwrite(buf
,1,1,fp
) == 0) return -1;
3022 if (fwrite(&len
,4,1,fp
) == 0) return -1;
3027 /* String objects in the form "2391" "-100" without any space and with a
3028 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3029 * encoded as integers to save space */
3030 static int rdbTryIntegerEncoding(char *s
, size_t len
, unsigned char *enc
) {
3032 char *endptr
, buf
[32];
3034 /* Check if it's possible to encode this value as a number */
3035 value
= strtoll(s
, &endptr
, 10);
3036 if (endptr
[0] != '\0') return 0;
3037 snprintf(buf
,32,"%lld",value
);
3039 /* If the number converted back into a string is not identical
3040 * then it's not possible to encode the string as integer */
3041 if (strlen(buf
) != len
|| memcmp(buf
,s
,len
)) return 0;
3043 /* Finally check if it fits in our ranges */
3044 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
3045 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
3046 enc
[1] = value
&0xFF;
3048 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
3049 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
3050 enc
[1] = value
&0xFF;
3051 enc
[2] = (value
>>8)&0xFF;
3053 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
3054 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
3055 enc
[1] = value
&0xFF;
3056 enc
[2] = (value
>>8)&0xFF;
3057 enc
[3] = (value
>>16)&0xFF;
3058 enc
[4] = (value
>>24)&0xFF;
3065 static int rdbSaveLzfStringObject(FILE *fp
, unsigned char *s
, size_t len
) {
3066 size_t comprlen
, outlen
;
3070 /* We require at least four bytes compression for this to be worth it */
3071 if (len
<= 4) return 0;
3073 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
3074 comprlen
= lzf_compress(s
, len
, out
, outlen
);
3075 if (comprlen
== 0) {
3079 /* Data compressed! Let's save it on disk */
3080 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
3081 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
3082 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
3083 if (rdbSaveLen(fp
,len
) == -1) goto writeerr
;
3084 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
3093 /* Save a string objet as [len][data] on disk. If the object is a string
3094 * representation of an integer value we try to safe it in a special form */
3095 static int rdbSaveRawString(FILE *fp
, unsigned char *s
, size_t len
) {
3098 /* Try integer encoding */
3100 unsigned char buf
[5];
3101 if ((enclen
= rdbTryIntegerEncoding((char*)s
,len
,buf
)) > 0) {
3102 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3107 /* Try LZF compression - under 20 bytes it's unable to compress even
3108 * aaaaaaaaaaaaaaaaaa so skip it */
3109 if (server
.rdbcompression
&& len
> 20) {
3112 retval
= rdbSaveLzfStringObject(fp
,s
,len
);
3113 if (retval
== -1) return -1;
3114 if (retval
> 0) return 0;
3115 /* retval == 0 means data can't be compressed, save the old way */
3118 /* Store verbatim */
3119 if (rdbSaveLen(fp
,len
) == -1) return -1;
3120 if (len
&& fwrite(s
,len
,1,fp
) == 0) return -1;
3124 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3125 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
3128 /* Avoid incr/decr ref count business when possible.
3129 * This plays well with copy-on-write given that we are probably
3130 * in a child process (BGSAVE). Also this makes sure key objects
3131 * of swapped objects are not incRefCount-ed (an assert does not allow
3132 * this in order to avoid bugs) */
3133 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
3134 obj
= getDecodedObject(obj
);
3135 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3138 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3143 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3144 * 8 bit integer specifing the length of the representation.
3145 * This 8 bit integer has special values in order to specify the following
3151 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
3152 unsigned char buf
[128];
3158 } else if (!isfinite(val
)) {
3160 buf
[0] = (val
< 0) ? 255 : 254;
3162 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
3163 buf
[0] = strlen((char*)buf
+1);
3166 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
3170 /* Save a Redis object. */
3171 static int rdbSaveObject(FILE *fp
, robj
*o
) {
3172 if (o
->type
== REDIS_STRING
) {
3173 /* Save a string value */
3174 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
3175 } else if (o
->type
== REDIS_LIST
) {
3176 /* Save a list value */
3177 list
*list
= o
->ptr
;
3181 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
3182 listRewind(list
,&li
);
3183 while((ln
= listNext(&li
))) {
3184 robj
*eleobj
= listNodeValue(ln
);
3186 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3188 } else if (o
->type
== REDIS_SET
) {
3189 /* Save a set value */
3191 dictIterator
*di
= dictGetIterator(set
);
3194 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
3195 while((de
= dictNext(di
)) != NULL
) {
3196 robj
*eleobj
= dictGetEntryKey(de
);
3198 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3200 dictReleaseIterator(di
);
3201 } else if (o
->type
== REDIS_ZSET
) {
3202 /* Save a set value */
3204 dictIterator
*di
= dictGetIterator(zs
->dict
);
3207 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
3208 while((de
= dictNext(di
)) != NULL
) {
3209 robj
*eleobj
= dictGetEntryKey(de
);
3210 double *score
= dictGetEntryVal(de
);
3212 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3213 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
3215 dictReleaseIterator(di
);
3216 } else if (o
->type
== REDIS_HASH
) {
3217 /* Save a hash value */
3218 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
3219 unsigned char *p
= zipmapRewind(o
->ptr
);
3220 unsigned int count
= zipmapLen(o
->ptr
);
3221 unsigned char *key
, *val
;
3222 unsigned int klen
, vlen
;
3224 if (rdbSaveLen(fp
,count
) == -1) return -1;
3225 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
3226 if (rdbSaveRawString(fp
,key
,klen
) == -1) return -1;
3227 if (rdbSaveRawString(fp
,val
,vlen
) == -1) return -1;
3230 dictIterator
*di
= dictGetIterator(o
->ptr
);
3233 if (rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
)) == -1) return -1;
3234 while((de
= dictNext(di
)) != NULL
) {
3235 robj
*key
= dictGetEntryKey(de
);
3236 robj
*val
= dictGetEntryVal(de
);
3238 if (rdbSaveStringObject(fp
,key
) == -1) return -1;
3239 if (rdbSaveStringObject(fp
,val
) == -1) return -1;
3241 dictReleaseIterator(di
);
3249 /* Return the length the object will have on disk if saved with
3250 * the rdbSaveObject() function. Currently we use a trick to get
3251 * this length with very little changes to the code. In the future
3252 * we could switch to a faster solution. */
3253 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
3254 if (fp
== NULL
) fp
= server
.devnull
;
3256 assert(rdbSaveObject(fp
,o
) != 1);
3260 /* Return the number of pages required to save this object in the swap file */
3261 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
3262 off_t bytes
= rdbSavedObjectLen(o
,fp
);
3264 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
3267 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3268 static int rdbSave(char *filename
) {
3269 dictIterator
*di
= NULL
;
3274 time_t now
= time(NULL
);
3276 /* Wait for I/O therads to terminate, just in case this is a
3277 * foreground-saving, to avoid seeking the swap file descriptor at the
3279 if (server
.vm_enabled
)
3280 waitEmptyIOJobsQueue();
3282 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3283 fp
= fopen(tmpfile
,"w");
3285 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3288 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3289 for (j
= 0; j
< server
.dbnum
; j
++) {
3290 redisDb
*db
= server
.db
+j
;
3292 if (dictSize(d
) == 0) continue;
3293 di
= dictGetIterator(d
);
3299 /* Write the SELECT DB opcode */
3300 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3301 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3303 /* Iterate this DB writing every entry */
3304 while((de
= dictNext(di
)) != NULL
) {
3305 robj
*key
= dictGetEntryKey(de
);
3306 robj
*o
= dictGetEntryVal(de
);
3307 time_t expiretime
= getExpire(db
,key
);
3309 /* Save the expire time */
3310 if (expiretime
!= -1) {
3311 /* If this key is already expired skip it */
3312 if (expiretime
< now
) continue;
3313 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3314 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3316 /* Save the key and associated value. This requires special
3317 * handling if the value is swapped out. */
3318 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3319 key
->storage
== REDIS_VM_SWAPPING
) {
3320 /* Save type, key, value */
3321 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3322 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3323 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3325 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3327 /* Get a preview of the object in memory */
3328 po
= vmPreviewObject(key
);
3329 /* Save type, key, value */
3330 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3331 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3332 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3333 /* Remove the loaded object from memory */
3337 dictReleaseIterator(di
);
3340 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3342 /* Make sure data will not remain on the OS's output buffers */
3347 /* Use RENAME to make sure the DB file is changed atomically only
3348 * if the generate DB file is ok. */
3349 if (rename(tmpfile
,filename
) == -1) {
3350 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3354 redisLog(REDIS_NOTICE
,"DB saved on disk");
3356 server
.lastsave
= time(NULL
);
3362 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3363 if (di
) dictReleaseIterator(di
);
3367 static int rdbSaveBackground(char *filename
) {
3370 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3371 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
3372 if ((childpid
= fork()) == 0) {
3374 if (server
.vm_enabled
) vmReopenSwapFile();
3376 if (rdbSave(filename
) == REDIS_OK
) {
3383 if (childpid
== -1) {
3384 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3388 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3389 server
.bgsavechildpid
= childpid
;
3392 return REDIS_OK
; /* unreached */
3395 static void rdbRemoveTempFile(pid_t childpid
) {
3398 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3402 static int rdbLoadType(FILE *fp
) {
3404 if (fread(&type
,1,1,fp
) == 0) return -1;
3408 static time_t rdbLoadTime(FILE *fp
) {
3410 if (fread(&t32
,4,1,fp
) == 0) return -1;
3411 return (time_t) t32
;
3414 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3415 * of this file for a description of how this are stored on disk.
3417 * isencoded is set to 1 if the readed length is not actually a length but
3418 * an "encoding type", check the above comments for more info */
3419 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3420 unsigned char buf
[2];
3424 if (isencoded
) *isencoded
= 0;
3425 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3426 type
= (buf
[0]&0xC0)>>6;
3427 if (type
== REDIS_RDB_6BITLEN
) {
3428 /* Read a 6 bit len */
3430 } else if (type
== REDIS_RDB_ENCVAL
) {
3431 /* Read a 6 bit len encoding type */
3432 if (isencoded
) *isencoded
= 1;
3434 } else if (type
== REDIS_RDB_14BITLEN
) {
3435 /* Read a 14 bit len */
3436 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3437 return ((buf
[0]&0x3F)<<8)|buf
[1];
3439 /* Read a 32 bit len */
3440 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3445 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
) {
3446 unsigned char enc
[4];
3449 if (enctype
== REDIS_RDB_ENC_INT8
) {
3450 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3451 val
= (signed char)enc
[0];
3452 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3454 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3455 v
= enc
[0]|(enc
[1]<<8);
3457 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3459 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3460 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3463 val
= 0; /* anti-warning */
3466 return createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",val
));
3469 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3470 unsigned int len
, clen
;
3471 unsigned char *c
= NULL
;
3474 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3475 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3476 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3477 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3478 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3479 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3481 return createObject(REDIS_STRING
,val
);
3488 static robj
*rdbLoadStringObject(FILE*fp
) {
3493 len
= rdbLoadLen(fp
,&isencoded
);
3496 case REDIS_RDB_ENC_INT8
:
3497 case REDIS_RDB_ENC_INT16
:
3498 case REDIS_RDB_ENC_INT32
:
3499 return tryObjectSharing(rdbLoadIntegerObject(fp
,len
));
3500 case REDIS_RDB_ENC_LZF
:
3501 return tryObjectSharing(rdbLoadLzfStringObject(fp
));
3507 if (len
== REDIS_RDB_LENERR
) return NULL
;
3508 val
= sdsnewlen(NULL
,len
);
3509 if (len
&& fread(val
,len
,1,fp
) == 0) {
3513 return tryObjectSharing(createObject(REDIS_STRING
,val
));
3516 /* For information about double serialization check rdbSaveDoubleValue() */
3517 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3521 if (fread(&len
,1,1,fp
) == 0) return -1;
3523 case 255: *val
= R_NegInf
; return 0;
3524 case 254: *val
= R_PosInf
; return 0;
3525 case 253: *val
= R_Nan
; return 0;
3527 if (fread(buf
,len
,1,fp
) == 0) return -1;
3529 sscanf(buf
, "%lg", val
);
3534 /* Load a Redis object of the specified type from the specified file.
3535 * On success a newly allocated object is returned, otherwise NULL. */
3536 static robj
*rdbLoadObject(int type
, FILE *fp
) {
3539 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
3540 if (type
== REDIS_STRING
) {
3541 /* Read string value */
3542 if ((o
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3543 tryObjectEncoding(o
);
3544 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
3545 /* Read list/set value */
3548 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3549 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
3550 /* It's faster to expand the dict to the right size asap in order
3551 * to avoid rehashing */
3552 if (type
== REDIS_SET
&& listlen
> DICT_HT_INITIAL_SIZE
)
3553 dictExpand(o
->ptr
,listlen
);
3554 /* Load every single element of the list/set */
3558 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3559 tryObjectEncoding(ele
);
3560 if (type
== REDIS_LIST
) {
3561 listAddNodeTail((list
*)o
->ptr
,ele
);
3563 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
3566 } else if (type
== REDIS_ZSET
) {
3567 /* Read list/set value */
3571 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3572 o
= createZsetObject();
3574 /* Load every single element of the list/set */
3577 double *score
= zmalloc(sizeof(double));
3579 if ((ele
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3580 tryObjectEncoding(ele
);
3581 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
3582 dictAdd(zs
->dict
,ele
,score
);
3583 zslInsert(zs
->zsl
,*score
,ele
);
3584 incrRefCount(ele
); /* added to skiplist */
3586 } else if (type
== REDIS_HASH
) {
3589 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3590 o
= createHashObject();
3591 /* Too many entries? Use an hash table. */
3592 if (hashlen
> server
.hash_max_zipmap_entries
)
3593 convertToRealHash(o
);
3594 /* Load every key/value, then set it into the zipmap or hash
3595 * table, as needed. */
3599 if ((key
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3600 if ((val
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
3601 /* If we are using a zipmap and there are too big values
3602 * the object is converted to real hash table encoding. */
3603 if (o
->encoding
!= REDIS_ENCODING_HT
&&
3604 (sdslen(key
->ptr
) > server
.hash_max_zipmap_value
||
3605 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
))
3607 convertToRealHash(o
);
3610 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
3611 unsigned char *zm
= o
->ptr
;
3613 zm
= zipmapSet(zm
,key
->ptr
,sdslen(key
->ptr
),
3614 val
->ptr
,sdslen(val
->ptr
),NULL
);
3619 tryObjectEncoding(key
);
3620 tryObjectEncoding(val
);
3621 dictAdd((dict
*)o
->ptr
,key
,val
);
3630 static int rdbLoad(char *filename
) {
3632 robj
*keyobj
= NULL
;
3634 int type
, retval
, rdbver
;
3635 dict
*d
= server
.db
[0].dict
;
3636 redisDb
*db
= server
.db
+0;
3638 time_t expiretime
= -1, now
= time(NULL
);
3639 long long loadedkeys
= 0;
3641 fp
= fopen(filename
,"r");
3642 if (!fp
) return REDIS_ERR
;
3643 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
3645 if (memcmp(buf
,"REDIS",5) != 0) {
3647 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
3650 rdbver
= atoi(buf
+5);
3653 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
3660 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3661 if (type
== REDIS_EXPIRETIME
) {
3662 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
3663 /* We read the time so we need to read the object type again */
3664 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
3666 if (type
== REDIS_EOF
) break;
3667 /* Handle SELECT DB opcode as a special case */
3668 if (type
== REDIS_SELECTDB
) {
3669 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
3671 if (dbid
>= (unsigned)server
.dbnum
) {
3672 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
3675 db
= server
.db
+dbid
;
3680 if ((keyobj
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
3682 if ((o
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
3683 /* Add the new object in the hash table */
3684 retval
= dictAdd(d
,keyobj
,o
);
3685 if (retval
== DICT_ERR
) {
3686 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", keyobj
->ptr
);
3689 /* Set the expire time if needed */
3690 if (expiretime
!= -1) {
3691 setExpire(db
,keyobj
,expiretime
);
3692 /* Delete this key if already expired */
3693 if (expiretime
< now
) deleteKey(db
,keyobj
);
3697 /* Handle swapping while loading big datasets when VM is on */
3699 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
3700 while (zmalloc_used_memory() > server
.vm_max_memory
) {
3701 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
3708 eoferr
: /* unexpected end of file is handled here with a fatal exit */
3709 if (keyobj
) decrRefCount(keyobj
);
3710 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
3712 return REDIS_ERR
; /* Just to avoid warning */
3715 /*================================== Commands =============================== */
3717 static void authCommand(redisClient
*c
) {
3718 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
3719 c
->authenticated
= 1;
3720 addReply(c
,shared
.ok
);
3722 c
->authenticated
= 0;
3723 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
3727 static void pingCommand(redisClient
*c
) {
3728 addReply(c
,shared
.pong
);
3731 static void echoCommand(redisClient
*c
) {
3732 addReplyBulk(c
,c
->argv
[1]);
3735 /*=================================== Strings =============================== */
3737 static void setGenericCommand(redisClient
*c
, int nx
) {
3740 if (nx
) deleteIfVolatile(c
->db
,c
->argv
[1]);
3741 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3742 if (retval
== DICT_ERR
) {
3744 /* If the key is about a swapped value, we want a new key object
3745 * to overwrite the old. So we delete the old key in the database.
3746 * This will also make sure that swap pages about the old object
3747 * will be marked as free. */
3748 if (server
.vm_enabled
&& deleteIfSwapped(c
->db
,c
->argv
[1]))
3749 incrRefCount(c
->argv
[1]);
3750 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3751 incrRefCount(c
->argv
[2]);
3753 addReply(c
,shared
.czero
);
3757 incrRefCount(c
->argv
[1]);
3758 incrRefCount(c
->argv
[2]);
3761 removeExpire(c
->db
,c
->argv
[1]);
3762 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3765 static void setCommand(redisClient
*c
) {
3766 setGenericCommand(c
,0);
3769 static void setnxCommand(redisClient
*c
) {
3770 setGenericCommand(c
,1);
3773 static int getGenericCommand(redisClient
*c
) {
3776 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
)
3779 if (o
->type
!= REDIS_STRING
) {
3780 addReply(c
,shared
.wrongtypeerr
);
3788 static void getCommand(redisClient
*c
) {
3789 getGenericCommand(c
);
3792 static void getsetCommand(redisClient
*c
) {
3793 if (getGenericCommand(c
) == REDIS_ERR
) return;
3794 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
3795 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3797 incrRefCount(c
->argv
[1]);
3799 incrRefCount(c
->argv
[2]);
3801 removeExpire(c
->db
,c
->argv
[1]);
3804 static void mgetCommand(redisClient
*c
) {
3807 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
3808 for (j
= 1; j
< c
->argc
; j
++) {
3809 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
3811 addReply(c
,shared
.nullbulk
);
3813 if (o
->type
!= REDIS_STRING
) {
3814 addReply(c
,shared
.nullbulk
);
3822 static void msetGenericCommand(redisClient
*c
, int nx
) {
3823 int j
, busykeys
= 0;
3825 if ((c
->argc
% 2) == 0) {
3826 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
3829 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
3830 * set nothing at all if at least one already key exists. */
3832 for (j
= 1; j
< c
->argc
; j
+= 2) {
3833 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
3839 addReply(c
, shared
.czero
);
3843 for (j
= 1; j
< c
->argc
; j
+= 2) {
3846 tryObjectEncoding(c
->argv
[j
+1]);
3847 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3848 if (retval
== DICT_ERR
) {
3849 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
3850 incrRefCount(c
->argv
[j
+1]);
3852 incrRefCount(c
->argv
[j
]);
3853 incrRefCount(c
->argv
[j
+1]);
3855 removeExpire(c
->db
,c
->argv
[j
]);
3857 server
.dirty
+= (c
->argc
-1)/2;
3858 addReply(c
, nx
? shared
.cone
: shared
.ok
);
3861 static void msetCommand(redisClient
*c
) {
3862 msetGenericCommand(c
,0);
3865 static void msetnxCommand(redisClient
*c
) {
3866 msetGenericCommand(c
,1);
3869 static void incrDecrCommand(redisClient
*c
, long long incr
) {
3874 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3878 if (o
->type
!= REDIS_STRING
) {
3883 if (o
->encoding
== REDIS_ENCODING_RAW
)
3884 value
= strtoll(o
->ptr
, &eptr
, 10);
3885 else if (o
->encoding
== REDIS_ENCODING_INT
)
3886 value
= (long)o
->ptr
;
3888 redisAssert(1 != 1);
3893 o
= createObject(REDIS_STRING
,sdscatprintf(sdsempty(),"%lld",value
));
3894 tryObjectEncoding(o
);
3895 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
3896 if (retval
== DICT_ERR
) {
3897 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3898 removeExpire(c
->db
,c
->argv
[1]);
3900 incrRefCount(c
->argv
[1]);
3903 addReply(c
,shared
.colon
);
3905 addReply(c
,shared
.crlf
);
3908 static void incrCommand(redisClient
*c
) {
3909 incrDecrCommand(c
,1);
3912 static void decrCommand(redisClient
*c
) {
3913 incrDecrCommand(c
,-1);
3916 static void incrbyCommand(redisClient
*c
) {
3917 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3918 incrDecrCommand(c
,incr
);
3921 static void decrbyCommand(redisClient
*c
) {
3922 long long incr
= strtoll(c
->argv
[2]->ptr
, NULL
, 10);
3923 incrDecrCommand(c
,-incr
);
3926 static void appendCommand(redisClient
*c
) {
3931 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
3933 /* Create the key */
3934 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
3935 incrRefCount(c
->argv
[1]);
3936 incrRefCount(c
->argv
[2]);
3937 totlen
= stringObjectLen(c
->argv
[2]);
3941 de
= dictFind(c
->db
->dict
,c
->argv
[1]);
3944 o
= dictGetEntryVal(de
);
3945 if (o
->type
!= REDIS_STRING
) {
3946 addReply(c
,shared
.wrongtypeerr
);
3949 /* If the object is specially encoded or shared we have to make
3951 if (o
->refcount
!= 1 || o
->encoding
!= REDIS_ENCODING_RAW
) {
3952 robj
*decoded
= getDecodedObject(o
);
3954 o
= createStringObject(decoded
->ptr
, sdslen(decoded
->ptr
));
3955 decrRefCount(decoded
);
3956 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
3959 if (c
->argv
[2]->encoding
== REDIS_ENCODING_RAW
) {
3960 o
->ptr
= sdscatlen(o
->ptr
,
3961 c
->argv
[2]->ptr
, sdslen(c
->argv
[2]->ptr
));
3963 o
->ptr
= sdscatprintf(o
->ptr
, "%ld",
3964 (unsigned long) c
->argv
[2]->ptr
);
3966 totlen
= sdslen(o
->ptr
);
3969 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen
));
3972 static void substrCommand(redisClient
*c
) {
3974 long start
= atoi(c
->argv
[2]->ptr
);
3975 long end
= atoi(c
->argv
[3]->ptr
);
3976 size_t rangelen
, strlen
;
3979 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
3980 checkType(c
,o
,REDIS_STRING
)) return;
3982 o
= getDecodedObject(o
);
3983 strlen
= sdslen(o
->ptr
);
3985 /* convert negative indexes */
3986 if (start
< 0) start
= strlen
+start
;
3987 if (end
< 0) end
= strlen
+end
;
3988 if (start
< 0) start
= 0;
3989 if (end
< 0) end
= 0;
3991 /* indexes sanity checks */
3992 if (start
> end
|| (size_t)start
>= strlen
) {
3993 /* Out of range start or start > end result in null reply */
3994 addReply(c
,shared
.nullbulk
);
3998 if ((size_t)end
>= strlen
) end
= strlen
-1;
3999 rangelen
= (end
-start
)+1;
4001 /* Return the result */
4002 addReplySds(c
,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen
));
4003 range
= sdsnewlen((char*)o
->ptr
+start
,rangelen
);
4004 addReplySds(c
,range
);
4005 addReply(c
,shared
.crlf
);
4009 /* ========================= Type agnostic commands ========================= */
4011 static void delCommand(redisClient
*c
) {
4014 for (j
= 1; j
< c
->argc
; j
++) {
4015 if (deleteKey(c
->db
,c
->argv
[j
])) {
4020 addReplyLong(c
,deleted
);
4023 static void existsCommand(redisClient
*c
) {
4024 addReply(c
,lookupKeyRead(c
->db
,c
->argv
[1]) ? shared
.cone
: shared
.czero
);
4027 static void selectCommand(redisClient
*c
) {
4028 int id
= atoi(c
->argv
[1]->ptr
);
4030 if (selectDb(c
,id
) == REDIS_ERR
) {
4031 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
4033 addReply(c
,shared
.ok
);
4037 static void randomkeyCommand(redisClient
*c
) {
4041 de
= dictGetRandomKey(c
->db
->dict
);
4042 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
4045 addReply(c
,shared
.plus
);
4046 addReply(c
,shared
.crlf
);
4048 addReply(c
,shared
.plus
);
4049 addReply(c
,dictGetEntryKey(de
));
4050 addReply(c
,shared
.crlf
);
4054 static void keysCommand(redisClient
*c
) {
4057 sds pattern
= c
->argv
[1]->ptr
;
4058 int plen
= sdslen(pattern
);
4059 unsigned long numkeys
= 0;
4060 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
4062 di
= dictGetIterator(c
->db
->dict
);
4064 decrRefCount(lenobj
);
4065 while((de
= dictNext(di
)) != NULL
) {
4066 robj
*keyobj
= dictGetEntryKey(de
);
4068 sds key
= keyobj
->ptr
;
4069 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
4070 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
4071 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
4072 addReplyBulk(c
,keyobj
);
4077 dictReleaseIterator(di
);
4078 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",numkeys
);
4081 static void dbsizeCommand(redisClient
*c
) {
4083 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
4086 static void lastsaveCommand(redisClient
*c
) {
4088 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
4091 static void typeCommand(redisClient
*c
) {
4095 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4100 case REDIS_STRING
: type
= "+string"; break;
4101 case REDIS_LIST
: type
= "+list"; break;
4102 case REDIS_SET
: type
= "+set"; break;
4103 case REDIS_ZSET
: type
= "+zset"; break;
4104 case REDIS_HASH
: type
= "+hash"; break;
4105 default: type
= "+unknown"; break;
4108 addReplySds(c
,sdsnew(type
));
4109 addReply(c
,shared
.crlf
);
4112 static void saveCommand(redisClient
*c
) {
4113 if (server
.bgsavechildpid
!= -1) {
4114 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
4117 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4118 addReply(c
,shared
.ok
);
4120 addReply(c
,shared
.err
);
4124 static void bgsaveCommand(redisClient
*c
) {
4125 if (server
.bgsavechildpid
!= -1) {
4126 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
4129 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
4130 char *status
= "+Background saving started\r\n";
4131 addReplySds(c
,sdsnew(status
));
4133 addReply(c
,shared
.err
);
4137 static void shutdownCommand(redisClient
*c
) {
4138 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
4139 /* Kill the saving child if there is a background saving in progress.
4140 We want to avoid race conditions, for instance our saving child may
4141 overwrite the synchronous saving did by SHUTDOWN. */
4142 if (server
.bgsavechildpid
!= -1) {
4143 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
4144 kill(server
.bgsavechildpid
,SIGKILL
);
4145 rdbRemoveTempFile(server
.bgsavechildpid
);
4147 if (server
.appendonly
) {
4148 /* Append only file: fsync() the AOF and exit */
4149 fsync(server
.appendfd
);
4150 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
4153 /* Snapshotting. Perform a SYNC SAVE and exit */
4154 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4155 if (server
.daemonize
)
4156 unlink(server
.pidfile
);
4157 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
4158 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
4159 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
4162 /* Ooops.. error saving! The best we can do is to continue
4163 * operating. Note that if there was a background saving process,
4164 * in the next cron() Redis will be notified that the background
4165 * saving aborted, handling special stuff like slaves pending for
4166 * synchronization... */
4167 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
4169 sdsnew("-ERR can't quit, problems saving the DB\r\n"));
4174 static void renameGenericCommand(redisClient
*c
, int nx
) {
4177 /* To use the same key as src and dst is probably an error */
4178 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
4179 addReply(c
,shared
.sameobjecterr
);
4183 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
4187 deleteIfVolatile(c
->db
,c
->argv
[2]);
4188 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
4191 addReply(c
,shared
.czero
);
4194 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
4196 incrRefCount(c
->argv
[2]);
4198 deleteKey(c
->db
,c
->argv
[1]);
4200 addReply(c
,nx
? shared
.cone
: shared
.ok
);
4203 static void renameCommand(redisClient
*c
) {
4204 renameGenericCommand(c
,0);
4207 static void renamenxCommand(redisClient
*c
) {
4208 renameGenericCommand(c
,1);
4211 static void moveCommand(redisClient
*c
) {
4216 /* Obtain source and target DB pointers */
4219 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
4220 addReply(c
,shared
.outofrangeerr
);
4224 selectDb(c
,srcid
); /* Back to the source DB */
4226 /* If the user is moving using as target the same
4227 * DB as the source DB it is probably an error. */
4229 addReply(c
,shared
.sameobjecterr
);
4233 /* Check if the element exists and get a reference */
4234 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4236 addReply(c
,shared
.czero
);
4240 /* Try to add the element to the target DB */
4241 deleteIfVolatile(dst
,c
->argv
[1]);
4242 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
4243 addReply(c
,shared
.czero
);
4246 incrRefCount(c
->argv
[1]);
4249 /* OK! key moved, free the entry in the source DB */
4250 deleteKey(src
,c
->argv
[1]);
4252 addReply(c
,shared
.cone
);
4255 /* =================================== Lists ================================ */
4256 static void pushGenericCommand(redisClient
*c
, int where
) {
4260 lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4262 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4263 addReply(c
,shared
.cone
);
4266 lobj
= createListObject();
4268 if (where
== REDIS_HEAD
) {
4269 listAddNodeHead(list
,c
->argv
[2]);
4271 listAddNodeTail(list
,c
->argv
[2]);
4273 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
4274 incrRefCount(c
->argv
[1]);
4275 incrRefCount(c
->argv
[2]);
4277 if (lobj
->type
!= REDIS_LIST
) {
4278 addReply(c
,shared
.wrongtypeerr
);
4281 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4282 addReply(c
,shared
.cone
);
4286 if (where
== REDIS_HEAD
) {
4287 listAddNodeHead(list
,c
->argv
[2]);
4289 listAddNodeTail(list
,c
->argv
[2]);
4291 incrRefCount(c
->argv
[2]);
4294 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",listLength(list
)));
4297 static void lpushCommand(redisClient
*c
) {
4298 pushGenericCommand(c
,REDIS_HEAD
);
4301 static void rpushCommand(redisClient
*c
) {
4302 pushGenericCommand(c
,REDIS_TAIL
);
4305 static void llenCommand(redisClient
*c
) {
4309 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
4310 checkType(c
,o
,REDIS_LIST
)) return;
4313 addReplyUlong(c
,listLength(l
));
4316 static void lindexCommand(redisClient
*c
) {
4318 int index
= atoi(c
->argv
[2]->ptr
);
4322 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4323 checkType(c
,o
,REDIS_LIST
)) return;
4326 ln
= listIndex(list
, index
);
4328 addReply(c
,shared
.nullbulk
);
4330 robj
*ele
= listNodeValue(ln
);
4331 addReplyBulk(c
,ele
);
4335 static void lsetCommand(redisClient
*c
) {
4337 int index
= atoi(c
->argv
[2]->ptr
);
4341 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
||
4342 checkType(c
,o
,REDIS_LIST
)) return;
4345 ln
= listIndex(list
, index
);
4347 addReply(c
,shared
.outofrangeerr
);
4349 robj
*ele
= listNodeValue(ln
);
4352 listNodeValue(ln
) = c
->argv
[3];
4353 incrRefCount(c
->argv
[3]);
4354 addReply(c
,shared
.ok
);
4359 static void popGenericCommand(redisClient
*c
, int where
) {
4364 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4365 checkType(c
,o
,REDIS_LIST
)) return;
4368 if (where
== REDIS_HEAD
)
4369 ln
= listFirst(list
);
4371 ln
= listLast(list
);
4374 addReply(c
,shared
.nullbulk
);
4376 robj
*ele
= listNodeValue(ln
);
4377 addReplyBulk(c
,ele
);
4378 listDelNode(list
,ln
);
4379 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4384 static void lpopCommand(redisClient
*c
) {
4385 popGenericCommand(c
,REDIS_HEAD
);
4388 static void rpopCommand(redisClient
*c
) {
4389 popGenericCommand(c
,REDIS_TAIL
);
4392 static void lrangeCommand(redisClient
*c
) {
4394 int start
= atoi(c
->argv
[2]->ptr
);
4395 int end
= atoi(c
->argv
[3]->ptr
);
4402 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullmultibulk
)) == NULL
||
4403 checkType(c
,o
,REDIS_LIST
)) return;
4405 llen
= listLength(list
);
4407 /* convert negative indexes */
4408 if (start
< 0) start
= llen
+start
;
4409 if (end
< 0) end
= llen
+end
;
4410 if (start
< 0) start
= 0;
4411 if (end
< 0) end
= 0;
4413 /* indexes sanity checks */
4414 if (start
> end
|| start
>= llen
) {
4415 /* Out of range start or start > end result in empty list */
4416 addReply(c
,shared
.emptymultibulk
);
4419 if (end
>= llen
) end
= llen
-1;
4420 rangelen
= (end
-start
)+1;
4422 /* Return the result in form of a multi-bulk reply */
4423 ln
= listIndex(list
, start
);
4424 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
4425 for (j
= 0; j
< rangelen
; j
++) {
4426 ele
= listNodeValue(ln
);
4427 addReplyBulk(c
,ele
);
4432 static void ltrimCommand(redisClient
*c
) {
4434 int start
= atoi(c
->argv
[2]->ptr
);
4435 int end
= atoi(c
->argv
[3]->ptr
);
4437 int j
, ltrim
, rtrim
;
4441 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.ok
)) == NULL
||
4442 checkType(c
,o
,REDIS_LIST
)) return;
4444 llen
= listLength(list
);
4446 /* convert negative indexes */
4447 if (start
< 0) start
= llen
+start
;
4448 if (end
< 0) end
= llen
+end
;
4449 if (start
< 0) start
= 0;
4450 if (end
< 0) end
= 0;
4452 /* indexes sanity checks */
4453 if (start
> end
|| start
>= llen
) {
4454 /* Out of range start or start > end result in empty list */
4458 if (end
>= llen
) end
= llen
-1;
4463 /* Remove list elements to perform the trim */
4464 for (j
= 0; j
< ltrim
; j
++) {
4465 ln
= listFirst(list
);
4466 listDelNode(list
,ln
);
4468 for (j
= 0; j
< rtrim
; j
++) {
4469 ln
= listLast(list
);
4470 listDelNode(list
,ln
);
4472 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4474 addReply(c
,shared
.ok
);
4477 static void lremCommand(redisClient
*c
) {
4480 listNode
*ln
, *next
;
4481 int toremove
= atoi(c
->argv
[2]->ptr
);
4485 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
4486 checkType(c
,o
,REDIS_LIST
)) return;
4490 toremove
= -toremove
;
4493 ln
= fromtail
? list
->tail
: list
->head
;
4495 robj
*ele
= listNodeValue(ln
);
4497 next
= fromtail
? ln
->prev
: ln
->next
;
4498 if (compareStringObjects(ele
,c
->argv
[3]) == 0) {
4499 listDelNode(list
,ln
);
4502 if (toremove
&& removed
== toremove
) break;
4506 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4507 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
4510 /* This is the semantic of this command:
4511 * RPOPLPUSH srclist dstlist:
4512 * IF LLEN(srclist) > 0
4513 * element = RPOP srclist
4514 * LPUSH dstlist element
4521 * The idea is to be able to get an element from a list in a reliable way
4522 * since the element is not just returned but pushed against another list
4523 * as well. This command was originally proposed by Ezra Zygmuntowicz.
4525 static void rpoplpushcommand(redisClient
*c
) {
4530 if ((sobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4531 checkType(c
,sobj
,REDIS_LIST
)) return;
4532 srclist
= sobj
->ptr
;
4533 ln
= listLast(srclist
);
4536 addReply(c
,shared
.nullbulk
);
4538 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4539 robj
*ele
= listNodeValue(ln
);
4542 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
4543 addReply(c
,shared
.wrongtypeerr
);
4547 /* Add the element to the target list (unless it's directly
4548 * passed to some BLPOP-ing client */
4549 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
4551 /* Create the list if the key does not exist */
4552 dobj
= createListObject();
4553 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
4554 incrRefCount(c
->argv
[2]);
4556 dstlist
= dobj
->ptr
;
4557 listAddNodeHead(dstlist
,ele
);
4561 /* Send the element to the client as reply as well */
4562 addReplyBulk(c
,ele
);
4564 /* Finally remove the element from the source list */
4565 listDelNode(srclist
,ln
);
4566 if (listLength(srclist
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4571 /* ==================================== Sets ================================ */
4573 static void saddCommand(redisClient
*c
) {
4576 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4578 set
= createSetObject();
4579 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
4580 incrRefCount(c
->argv
[1]);
4582 if (set
->type
!= REDIS_SET
) {
4583 addReply(c
,shared
.wrongtypeerr
);
4587 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
4588 incrRefCount(c
->argv
[2]);
4590 addReply(c
,shared
.cone
);
4592 addReply(c
,shared
.czero
);
4596 static void sremCommand(redisClient
*c
) {
4599 if ((set
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
4600 checkType(c
,set
,REDIS_SET
)) return;
4602 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
4604 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4605 if (dictSize((dict
*)set
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4606 addReply(c
,shared
.cone
);
4608 addReply(c
,shared
.czero
);
4612 static void smoveCommand(redisClient
*c
) {
4613 robj
*srcset
, *dstset
;
4615 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4616 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
4618 /* If the source key does not exist return 0, if it's of the wrong type
4620 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
4621 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
4624 /* Error if the destination key is not a set as well */
4625 if (dstset
&& dstset
->type
!= REDIS_SET
) {
4626 addReply(c
,shared
.wrongtypeerr
);
4629 /* Remove the element from the source set */
4630 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
4631 /* Key not found in the src set! return zero */
4632 addReply(c
,shared
.czero
);
4635 if (dictSize((dict
*)srcset
->ptr
) == 0 && srcset
!= dstset
)
4636 deleteKey(c
->db
,c
->argv
[1]);
4638 /* Add the element to the destination set */
4640 dstset
= createSetObject();
4641 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
4642 incrRefCount(c
->argv
[2]);
4644 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
4645 incrRefCount(c
->argv
[3]);
4646 addReply(c
,shared
.cone
);
4649 static void sismemberCommand(redisClient
*c
) {
4652 if ((set
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
4653 checkType(c
,set
,REDIS_SET
)) return;
4655 if (dictFind(set
->ptr
,c
->argv
[2]))
4656 addReply(c
,shared
.cone
);
4658 addReply(c
,shared
.czero
);
4661 static void scardCommand(redisClient
*c
) {
4665 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
4666 checkType(c
,o
,REDIS_SET
)) return;
4669 addReplyUlong(c
,dictSize(s
));
4672 static void spopCommand(redisClient
*c
) {
4676 if ((set
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4677 checkType(c
,set
,REDIS_SET
)) return;
4679 de
= dictGetRandomKey(set
->ptr
);
4681 addReply(c
,shared
.nullbulk
);
4683 robj
*ele
= dictGetEntryKey(de
);
4685 addReplyBulk(c
,ele
);
4686 dictDelete(set
->ptr
,ele
);
4687 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
4688 if (dictSize((dict
*)set
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
4693 static void srandmemberCommand(redisClient
*c
) {
4697 if ((set
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4698 checkType(c
,set
,REDIS_SET
)) return;
4700 de
= dictGetRandomKey(set
->ptr
);
4702 addReply(c
,shared
.nullbulk
);
4704 robj
*ele
= dictGetEntryKey(de
);
4706 addReplyBulk(c
,ele
);
4710 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
4711 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
4713 return dictSize(*d1
)-dictSize(*d2
);
4716 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
4717 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4720 robj
*lenobj
= NULL
, *dstset
= NULL
;
4721 unsigned long j
, cardinality
= 0;
4723 for (j
= 0; j
< setsnum
; j
++) {
4727 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4728 lookupKeyRead(c
->db
,setskeys
[j
]);
4732 if (deleteKey(c
->db
,dstkey
))
4734 addReply(c
,shared
.czero
);
4736 addReply(c
,shared
.nullmultibulk
);
4740 if (setobj
->type
!= REDIS_SET
) {
4742 addReply(c
,shared
.wrongtypeerr
);
4745 dv
[j
] = setobj
->ptr
;
4747 /* Sort sets from the smallest to largest, this will improve our
4748 * algorithm's performace */
4749 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
4751 /* The first thing we should output is the total number of elements...
4752 * since this is a multi-bulk write, but at this stage we don't know
4753 * the intersection set size, so we use a trick, append an empty object
4754 * to the output list and save the pointer to later modify it with the
4757 lenobj
= createObject(REDIS_STRING
,NULL
);
4759 decrRefCount(lenobj
);
4761 /* If we have a target key where to store the resulting set
4762 * create this key with an empty set inside */
4763 dstset
= createSetObject();
4766 /* Iterate all the elements of the first (smallest) set, and test
4767 * the element against all the other sets, if at least one set does
4768 * not include the element it is discarded */
4769 di
= dictGetIterator(dv
[0]);
4771 while((de
= dictNext(di
)) != NULL
) {
4774 for (j
= 1; j
< setsnum
; j
++)
4775 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
4777 continue; /* at least one set does not contain the member */
4778 ele
= dictGetEntryKey(de
);
4780 addReplyBulk(c
,ele
);
4783 dictAdd(dstset
->ptr
,ele
,NULL
);
4787 dictReleaseIterator(di
);
4790 /* Store the resulting set into the target, if the intersection
4791 * is not an empty set. */
4792 deleteKey(c
->db
,dstkey
);
4793 if (dictSize((dict
*)dstset
->ptr
) > 0) {
4794 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4795 incrRefCount(dstkey
);
4796 addReplyLong(c
,dictSize((dict
*)dstset
->ptr
));
4798 decrRefCount(dstset
);
4799 addReply(c
,shared
.czero
);
4803 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
4808 static void sinterCommand(redisClient
*c
) {
4809 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
4812 static void sinterstoreCommand(redisClient
*c
) {
4813 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
4816 #define REDIS_OP_UNION 0
4817 #define REDIS_OP_DIFF 1
4818 #define REDIS_OP_INTER 2
4820 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
4821 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
4824 robj
*dstset
= NULL
;
4825 int j
, cardinality
= 0;
4827 for (j
= 0; j
< setsnum
; j
++) {
4831 lookupKeyWrite(c
->db
,setskeys
[j
]) :
4832 lookupKeyRead(c
->db
,setskeys
[j
]);
4837 if (setobj
->type
!= REDIS_SET
) {
4839 addReply(c
,shared
.wrongtypeerr
);
4842 dv
[j
] = setobj
->ptr
;
4845 /* We need a temp set object to store our union. If the dstkey
4846 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
4847 * this set object will be the resulting object to set into the target key*/
4848 dstset
= createSetObject();
4850 /* Iterate all the elements of all the sets, add every element a single
4851 * time to the result set */
4852 for (j
= 0; j
< setsnum
; j
++) {
4853 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
4854 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
4856 di
= dictGetIterator(dv
[j
]);
4858 while((de
= dictNext(di
)) != NULL
) {
4861 /* dictAdd will not add the same element multiple times */
4862 ele
= dictGetEntryKey(de
);
4863 if (op
== REDIS_OP_UNION
|| j
== 0) {
4864 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
4868 } else if (op
== REDIS_OP_DIFF
) {
4869 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
4874 dictReleaseIterator(di
);
4876 /* result set is empty? Exit asap. */
4877 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break;
4880 /* Output the content of the resulting set, if not in STORE mode */
4882 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
4883 di
= dictGetIterator(dstset
->ptr
);
4884 while((de
= dictNext(di
)) != NULL
) {
4887 ele
= dictGetEntryKey(de
);
4888 addReplyBulk(c
,ele
);
4890 dictReleaseIterator(di
);
4891 decrRefCount(dstset
);
4893 /* If we have a target key where to store the resulting set
4894 * create this key with the result set inside */
4895 deleteKey(c
->db
,dstkey
);
4896 if (dictSize((dict
*)dstset
->ptr
) > 0) {
4897 dictAdd(c
->db
->dict
,dstkey
,dstset
);
4898 incrRefCount(dstkey
);
4899 addReplyLong(c
,dictSize((dict
*)dstset
->ptr
));
4901 decrRefCount(dstset
);
4902 addReply(c
,shared
.czero
);
4909 static void sunionCommand(redisClient
*c
) {
4910 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
4913 static void sunionstoreCommand(redisClient
*c
) {
4914 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
4917 static void sdiffCommand(redisClient
*c
) {
4918 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
4921 static void sdiffstoreCommand(redisClient
*c
) {
4922 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
4925 /* ==================================== ZSets =============================== */
4927 /* ZSETs are ordered sets using two data structures to hold the same elements
4928 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
4931 * The elements are added to an hash table mapping Redis objects to scores.
4932 * At the same time the elements are added to a skip list mapping scores
4933 * to Redis objects (so objects are sorted by scores in this "view"). */
4935 /* This skiplist implementation is almost a C translation of the original
4936 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
4937 * Alternative to Balanced Trees", modified in three ways:
4938 * a) this implementation allows for repeated values.
4939 * b) the comparison is not just by key (our 'score') but by satellite data.
4940 * c) there is a back pointer, so it's a doubly linked list with the back
4941 * pointers being only at "level 1". This allows to traverse the list
4942 * from tail to head, useful for ZREVRANGE. */
4944 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
4945 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
4947 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
4949 zn
->span
= zmalloc(sizeof(unsigned int) * (level
- 1));
4955 static zskiplist
*zslCreate(void) {
4959 zsl
= zmalloc(sizeof(*zsl
));
4962 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
4963 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
4964 zsl
->header
->forward
[j
] = NULL
;
4966 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
4967 if (j
< ZSKIPLIST_MAXLEVEL
-1)
4968 zsl
->header
->span
[j
] = 0;
4970 zsl
->header
->backward
= NULL
;
4975 static void zslFreeNode(zskiplistNode
*node
) {
4976 decrRefCount(node
->obj
);
4977 zfree(node
->forward
);
4982 static void zslFree(zskiplist
*zsl
) {
4983 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
4985 zfree(zsl
->header
->forward
);
4986 zfree(zsl
->header
->span
);
4989 next
= node
->forward
[0];
4996 static int zslRandomLevel(void) {
4998 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
5003 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
5004 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5005 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
5009 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5010 /* store rank that is crossed to reach the insert position */
5011 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
5013 while (x
->forward
[i
] &&
5014 (x
->forward
[i
]->score
< score
||
5015 (x
->forward
[i
]->score
== score
&&
5016 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0))) {
5017 rank
[i
] += i
> 0 ? x
->span
[i
-1] : 1;
5022 /* we assume the key is not already inside, since we allow duplicated
5023 * scores, and the re-insertion of score and redis object should never
5024 * happpen since the caller of zslInsert() should test in the hash table
5025 * if the element is already inside or not. */
5026 level
= zslRandomLevel();
5027 if (level
> zsl
->level
) {
5028 for (i
= zsl
->level
; i
< level
; i
++) {
5030 update
[i
] = zsl
->header
;
5031 update
[i
]->span
[i
-1] = zsl
->length
;
5035 x
= zslCreateNode(level
,score
,obj
);
5036 for (i
= 0; i
< level
; i
++) {
5037 x
->forward
[i
] = update
[i
]->forward
[i
];
5038 update
[i
]->forward
[i
] = x
;
5040 /* update span covered by update[i] as x is inserted here */
5042 x
->span
[i
-1] = update
[i
]->span
[i
-1] - (rank
[0] - rank
[i
]);
5043 update
[i
]->span
[i
-1] = (rank
[0] - rank
[i
]) + 1;
5047 /* increment span for untouched levels */
5048 for (i
= level
; i
< zsl
->level
; i
++) {
5049 update
[i
]->span
[i
-1]++;
5052 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
5054 x
->forward
[0]->backward
= x
;
5060 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5061 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
5063 for (i
= 0; i
< zsl
->level
; i
++) {
5064 if (update
[i
]->forward
[i
] == x
) {
5066 update
[i
]->span
[i
-1] += x
->span
[i
-1] - 1;
5068 update
[i
]->forward
[i
] = x
->forward
[i
];
5070 /* invariant: i > 0, because update[0]->forward[0]
5071 * is always equal to x */
5072 update
[i
]->span
[i
-1] -= 1;
5075 if (x
->forward
[0]) {
5076 x
->forward
[0]->backward
= x
->backward
;
5078 zsl
->tail
= x
->backward
;
5080 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
5085 /* Delete an element with matching score/object from the skiplist. */
5086 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
5087 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5091 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5092 while (x
->forward
[i
] &&
5093 (x
->forward
[i
]->score
< score
||
5094 (x
->forward
[i
]->score
== score
&&
5095 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
5099 /* We may have multiple elements with the same score, what we need
5100 * is to find the element with both the right score and object. */
5102 if (x
&& score
== x
->score
&& compareStringObjects(x
->obj
,obj
) == 0) {
5103 zslDeleteNode(zsl
, x
, update
);
5107 return 0; /* not found */
5109 return 0; /* not found */
5112 /* Delete all the elements with score between min and max from the skiplist.
5113 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5114 * Note that this function takes the reference to the hash table view of the
5115 * sorted set, in order to remove the elements from the hash table too. */
5116 static unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
5117 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5118 unsigned long removed
= 0;
5122 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5123 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
5127 /* We may have multiple elements with the same score, what we need
5128 * is to find the element with both the right score and object. */
5130 while (x
&& x
->score
<= max
) {
5131 zskiplistNode
*next
= x
->forward
[0];
5132 zslDeleteNode(zsl
, x
, update
);
5133 dictDelete(dict
,x
->obj
);
5138 return removed
; /* not found */
5141 /* Delete all the elements with rank between start and end from the skiplist.
5142 * Start and end are inclusive. Note that start and end need to be 1-based */
5143 static unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
5144 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5145 unsigned long traversed
= 0, removed
= 0;
5149 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5150 while (x
->forward
[i
] && (traversed
+ (i
> 0 ? x
->span
[i
-1] : 1)) < start
) {
5151 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5159 while (x
&& traversed
<= end
) {
5160 zskiplistNode
*next
= x
->forward
[0];
5161 zslDeleteNode(zsl
, x
, update
);
5162 dictDelete(dict
,x
->obj
);
5171 /* Find the first node having a score equal or greater than the specified one.
5172 * Returns NULL if there is no match. */
5173 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
5178 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5179 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
5182 /* We may have multiple elements with the same score, what we need
5183 * is to find the element with both the right score and object. */
5184 return x
->forward
[0];
5187 /* Find the rank for an element by both score and key.
5188 * Returns 0 when the element cannot be found, rank otherwise.
5189 * Note that the rank is 1-based due to the span of zsl->header to the
5191 static unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
5193 unsigned long rank
= 0;
5197 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5198 while (x
->forward
[i
] &&
5199 (x
->forward
[i
]->score
< score
||
5200 (x
->forward
[i
]->score
== score
&&
5201 compareStringObjects(x
->forward
[i
]->obj
,o
) <= 0))) {
5202 rank
+= i
> 0 ? x
->span
[i
-1] : 1;
5206 /* x might be equal to zsl->header, so test if obj is non-NULL */
5207 if (x
->obj
&& compareStringObjects(x
->obj
,o
) == 0) {
5214 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5215 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
5217 unsigned long traversed
= 0;
5221 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5222 while (x
->forward
[i
] && (traversed
+ (i
>0 ? x
->span
[i
-1] : 1)) <= rank
)
5224 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5227 if (traversed
== rank
) {
5234 /* The actual Z-commands implementations */
5236 /* This generic command implements both ZADD and ZINCRBY.
5237 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5238 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5239 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
5244 zsetobj
= lookupKeyWrite(c
->db
,key
);
5245 if (zsetobj
== NULL
) {
5246 zsetobj
= createZsetObject();
5247 dictAdd(c
->db
->dict
,key
,zsetobj
);
5250 if (zsetobj
->type
!= REDIS_ZSET
) {
5251 addReply(c
,shared
.wrongtypeerr
);
5257 /* Ok now since we implement both ZADD and ZINCRBY here the code
5258 * needs to handle the two different conditions. It's all about setting
5259 * '*score', that is, the new score to set, to the right value. */
5260 score
= zmalloc(sizeof(double));
5264 /* Read the old score. If the element was not present starts from 0 */
5265 de
= dictFind(zs
->dict
,ele
);
5267 double *oldscore
= dictGetEntryVal(de
);
5268 *score
= *oldscore
+ scoreval
;
5276 /* What follows is a simple remove and re-insert operation that is common
5277 * to both ZADD and ZINCRBY... */
5278 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
5279 /* case 1: New element */
5280 incrRefCount(ele
); /* added to hash */
5281 zslInsert(zs
->zsl
,*score
,ele
);
5282 incrRefCount(ele
); /* added to skiplist */
5285 addReplyDouble(c
,*score
);
5287 addReply(c
,shared
.cone
);
5292 /* case 2: Score update operation */
5293 de
= dictFind(zs
->dict
,ele
);
5294 redisAssert(de
!= NULL
);
5295 oldscore
= dictGetEntryVal(de
);
5296 if (*score
!= *oldscore
) {
5299 /* Remove and insert the element in the skip list with new score */
5300 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
5301 redisAssert(deleted
!= 0);
5302 zslInsert(zs
->zsl
,*score
,ele
);
5304 /* Update the score in the hash table */
5305 dictReplace(zs
->dict
,ele
,score
);
5311 addReplyDouble(c
,*score
);
5313 addReply(c
,shared
.czero
);
5317 static void zaddCommand(redisClient
*c
) {
5320 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
5321 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
5324 static void zincrbyCommand(redisClient
*c
) {
5327 scoreval
= strtod(c
->argv
[2]->ptr
,NULL
);
5328 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
5331 static void zremCommand(redisClient
*c
) {
5338 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5339 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5342 de
= dictFind(zs
->dict
,c
->argv
[2]);
5344 addReply(c
,shared
.czero
);
5347 /* Delete from the skiplist */
5348 oldscore
= dictGetEntryVal(de
);
5349 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
5350 redisAssert(deleted
!= 0);
5352 /* Delete from the hash table */
5353 dictDelete(zs
->dict
,c
->argv
[2]);
5354 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5355 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5357 addReply(c
,shared
.cone
);
5360 static void zremrangebyscoreCommand(redisClient
*c
) {
5361 double min
= strtod(c
->argv
[2]->ptr
,NULL
);
5362 double max
= strtod(c
->argv
[3]->ptr
,NULL
);
5367 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5368 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5371 deleted
= zslDeleteRangeByScore(zs
->zsl
,min
,max
,zs
->dict
);
5372 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5373 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5374 server
.dirty
+= deleted
;
5375 addReplyLong(c
,deleted
);
5378 static void zremrangebyrankCommand(redisClient
*c
) {
5379 int start
= atoi(c
->argv
[2]->ptr
);
5380 int end
= atoi(c
->argv
[3]->ptr
);
5386 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5387 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
5389 llen
= zs
->zsl
->length
;
5391 /* convert negative indexes */
5392 if (start
< 0) start
= llen
+start
;
5393 if (end
< 0) end
= llen
+end
;
5394 if (start
< 0) start
= 0;
5395 if (end
< 0) end
= 0;
5397 /* indexes sanity checks */
5398 if (start
> end
|| start
>= llen
) {
5399 addReply(c
,shared
.czero
);
5402 if (end
>= llen
) end
= llen
-1;
5404 /* increment start and end because zsl*Rank functions
5405 * use 1-based rank */
5406 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
5407 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
5408 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5409 server
.dirty
+= deleted
;
5410 addReplyLong(c
, deleted
);
5418 static int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) {
5419 zsetopsrc
*d1
= (void*) s1
, *d2
= (void*) s2
;
5420 unsigned long size1
, size2
;
5421 size1
= d1
->dict
? dictSize(d1
->dict
) : 0;
5422 size2
= d2
->dict
? dictSize(d2
->dict
) : 0;
5423 return size1
- size2
;
5426 #define REDIS_AGGR_SUM 1
5427 #define REDIS_AGGR_MIN 2
5428 #define REDIS_AGGR_MAX 3
5430 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
5431 if (aggregate
== REDIS_AGGR_SUM
) {
5432 *target
= *target
+ val
;
5433 } else if (aggregate
== REDIS_AGGR_MIN
) {
5434 *target
= val
< *target
? val
: *target
;
5435 } else if (aggregate
== REDIS_AGGR_MAX
) {
5436 *target
= val
> *target
? val
: *target
;
5439 redisAssert(0 != 0);
5443 static void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
5445 int aggregate
= REDIS_AGGR_SUM
;
5452 /* expect zsetnum input keys to be given */
5453 zsetnum
= atoi(c
->argv
[2]->ptr
);
5455 addReplySds(c
,sdsnew("-ERR at least 1 input key is needed for ZUNION/ZINTER\r\n"));
5459 /* test if the expected number of keys would overflow */
5460 if (3+zsetnum
> c
->argc
) {
5461 addReply(c
,shared
.syntaxerr
);
5465 /* read keys to be used for input */
5466 src
= zmalloc(sizeof(zsetopsrc
) * zsetnum
);
5467 for (i
= 0, j
= 3; i
< zsetnum
; i
++, j
++) {
5468 robj
*zsetobj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
5472 if (zsetobj
->type
!= REDIS_ZSET
) {
5474 addReply(c
,shared
.wrongtypeerr
);
5477 src
[i
].dict
= ((zset
*)zsetobj
->ptr
)->dict
;
5480 /* default all weights to 1 */
5481 src
[i
].weight
= 1.0;
5484 /* parse optional extra arguments */
5486 int remaining
= c
->argc
- j
;
5489 if (remaining
>= (zsetnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
5491 for (i
= 0; i
< zsetnum
; i
++, j
++, remaining
--) {
5492 src
[i
].weight
= strtod(c
->argv
[j
]->ptr
, NULL
);
5494 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
5496 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
5497 aggregate
= REDIS_AGGR_SUM
;
5498 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
5499 aggregate
= REDIS_AGGR_MIN
;
5500 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
5501 aggregate
= REDIS_AGGR_MAX
;
5504 addReply(c
,shared
.syntaxerr
);
5510 addReply(c
,shared
.syntaxerr
);
5516 /* sort sets from the smallest to largest, this will improve our
5517 * algorithm's performance */
5518 qsort(src
,zsetnum
,sizeof(zsetopsrc
), qsortCompareZsetopsrcByCardinality
);
5520 dstobj
= createZsetObject();
5521 dstzset
= dstobj
->ptr
;
5523 if (op
== REDIS_OP_INTER
) {
5524 /* skip going over all entries if the smallest zset is NULL or empty */
5525 if (src
[0].dict
&& dictSize(src
[0].dict
) > 0) {
5526 /* precondition: as src[0].dict is non-empty and the zsets are ordered
5527 * from small to large, all src[i > 0].dict are non-empty too */
5528 di
= dictGetIterator(src
[0].dict
);
5529 while((de
= dictNext(di
)) != NULL
) {
5530 double *score
= zmalloc(sizeof(double)), value
;
5531 *score
= src
[0].weight
* (*(double*)dictGetEntryVal(de
));
5533 for (j
= 1; j
< zsetnum
; j
++) {
5534 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
5536 value
= src
[j
].weight
* (*(double*)dictGetEntryVal(other
));
5537 zunionInterAggregate(score
, value
, aggregate
);
5543 /* skip entry when not present in every source dict */
5547 robj
*o
= dictGetEntryKey(de
);
5548 dictAdd(dstzset
->dict
,o
,score
);
5549 incrRefCount(o
); /* added to dictionary */
5550 zslInsert(dstzset
->zsl
,*score
,o
);
5551 incrRefCount(o
); /* added to skiplist */
5554 dictReleaseIterator(di
);
5556 } else if (op
== REDIS_OP_UNION
) {
5557 for (i
= 0; i
< zsetnum
; i
++) {
5558 if (!src
[i
].dict
) continue;
5560 di
= dictGetIterator(src
[i
].dict
);
5561 while((de
= dictNext(di
)) != NULL
) {
5562 /* skip key when already processed */
5563 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
) continue;
5565 double *score
= zmalloc(sizeof(double)), value
;
5566 *score
= src
[i
].weight
* (*(double*)dictGetEntryVal(de
));
5568 /* because the zsets are sorted by size, its only possible
5569 * for sets at larger indices to hold this entry */
5570 for (j
= (i
+1); j
< zsetnum
; j
++) {
5571 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
5573 value
= src
[j
].weight
* (*(double*)dictGetEntryVal(other
));
5574 zunionInterAggregate(score
, value
, aggregate
);
5578 robj
*o
= dictGetEntryKey(de
);
5579 dictAdd(dstzset
->dict
,o
,score
);
5580 incrRefCount(o
); /* added to dictionary */
5581 zslInsert(dstzset
->zsl
,*score
,o
);
5582 incrRefCount(o
); /* added to skiplist */
5584 dictReleaseIterator(di
);
5587 /* unknown operator */
5588 redisAssert(op
== REDIS_OP_INTER
|| op
== REDIS_OP_UNION
);
5591 deleteKey(c
->db
,dstkey
);
5592 if (dstzset
->zsl
->length
) {
5593 dictAdd(c
->db
->dict
,dstkey
,dstobj
);
5594 incrRefCount(dstkey
);
5595 addReplyLong(c
, dstzset
->zsl
->length
);
5598 decrRefCount(dstzset
);
5599 addReply(c
, shared
.czero
);
5604 static void zunionCommand(redisClient
*c
) {
5605 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
5608 static void zinterCommand(redisClient
*c
) {
5609 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
5612 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
5614 int start
= atoi(c
->argv
[2]->ptr
);
5615 int end
= atoi(c
->argv
[3]->ptr
);
5624 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
5626 } else if (c
->argc
>= 5) {
5627 addReply(c
,shared
.syntaxerr
);
5631 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullmultibulk
)) == NULL
||
5632 checkType(c
,o
,REDIS_ZSET
)) return;
5637 /* convert negative indexes */
5638 if (start
< 0) start
= llen
+start
;
5639 if (end
< 0) end
= llen
+end
;
5640 if (start
< 0) start
= 0;
5641 if (end
< 0) end
= 0;
5643 /* indexes sanity checks */
5644 if (start
> end
|| start
>= llen
) {
5645 /* Out of range start or start > end result in empty list */
5646 addReply(c
,shared
.emptymultibulk
);
5649 if (end
>= llen
) end
= llen
-1;
5650 rangelen
= (end
-start
)+1;
5652 /* check if starting point is trivial, before searching
5653 * the element in log(N) time */
5655 ln
= start
== 0 ? zsl
->tail
: zslGetElementByRank(zsl
, llen
-start
);
5658 zsl
->header
->forward
[0] : zslGetElementByRank(zsl
, start
+1);
5661 /* Return the result in form of a multi-bulk reply */
5662 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
5663 withscores
? (rangelen
*2) : rangelen
));
5664 for (j
= 0; j
< rangelen
; j
++) {
5666 addReplyBulk(c
,ele
);
5668 addReplyDouble(c
,ln
->score
);
5669 ln
= reverse
? ln
->backward
: ln
->forward
[0];
5673 static void zrangeCommand(redisClient
*c
) {
5674 zrangeGenericCommand(c
,0);
5677 static void zrevrangeCommand(redisClient
*c
) {
5678 zrangeGenericCommand(c
,1);
5681 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
5682 * If justcount is non-zero, just the count is returned. */
5683 static void genericZrangebyscoreCommand(redisClient
*c
, int justcount
) {
5686 int minex
= 0, maxex
= 0; /* are min or max exclusive? */
5687 int offset
= 0, limit
= -1;
5691 /* Parse the min-max interval. If one of the values is prefixed
5692 * by the "(" character, it's considered "open". For instance
5693 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
5694 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
5695 if (((char*)c
->argv
[2]->ptr
)[0] == '(') {
5696 min
= strtod((char*)c
->argv
[2]->ptr
+1,NULL
);
5699 min
= strtod(c
->argv
[2]->ptr
,NULL
);
5701 if (((char*)c
->argv
[3]->ptr
)[0] == '(') {
5702 max
= strtod((char*)c
->argv
[3]->ptr
+1,NULL
);
5705 max
= strtod(c
->argv
[3]->ptr
,NULL
);
5708 /* Parse "WITHSCORES": note that if the command was called with
5709 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
5710 * enter the following paths to parse WITHSCORES and LIMIT. */
5711 if (c
->argc
== 5 || c
->argc
== 8) {
5712 if (strcasecmp(c
->argv
[c
->argc
-1]->ptr
,"withscores") == 0)
5717 if (c
->argc
!= (4 + withscores
) && c
->argc
!= (7 + withscores
))
5721 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
5726 if (c
->argc
== (7 + withscores
) && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
5727 addReply(c
,shared
.syntaxerr
);
5729 } else if (c
->argc
== (7 + withscores
)) {
5730 offset
= atoi(c
->argv
[5]->ptr
);
5731 limit
= atoi(c
->argv
[6]->ptr
);
5732 if (offset
< 0) offset
= 0;
5735 /* Ok, lookup the key and get the range */
5736 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
5738 addReply(c
,justcount
? shared
.czero
: shared
.nullmultibulk
);
5740 if (o
->type
!= REDIS_ZSET
) {
5741 addReply(c
,shared
.wrongtypeerr
);
5743 zset
*zsetobj
= o
->ptr
;
5744 zskiplist
*zsl
= zsetobj
->zsl
;
5746 robj
*ele
, *lenobj
= NULL
;
5747 unsigned long rangelen
= 0;
5749 /* Get the first node with the score >= min, or with
5750 * score > min if 'minex' is true. */
5751 ln
= zslFirstWithScore(zsl
,min
);
5752 while (minex
&& ln
&& ln
->score
== min
) ln
= ln
->forward
[0];
5755 /* No element matching the speciifed interval */
5756 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
5760 /* We don't know in advance how many matching elements there
5761 * are in the list, so we push this object that will represent
5762 * the multi-bulk length in the output buffer, and will "fix"
5765 lenobj
= createObject(REDIS_STRING
,NULL
);
5767 decrRefCount(lenobj
);
5770 while(ln
&& (maxex
? (ln
->score
< max
) : (ln
->score
<= max
))) {
5773 ln
= ln
->forward
[0];
5776 if (limit
== 0) break;
5779 addReplyBulk(c
,ele
);
5781 addReplyDouble(c
,ln
->score
);
5783 ln
= ln
->forward
[0];
5785 if (limit
> 0) limit
--;
5788 addReplyLong(c
,(long)rangelen
);
5790 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",
5791 withscores
? (rangelen
*2) : rangelen
);
5797 static void zrangebyscoreCommand(redisClient
*c
) {
5798 genericZrangebyscoreCommand(c
,0);
5801 static void zcountCommand(redisClient
*c
) {
5802 genericZrangebyscoreCommand(c
,1);
5805 static void zcardCommand(redisClient
*c
) {
5809 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5810 checkType(c
,o
,REDIS_ZSET
)) return;
5813 addReplyUlong(c
,zs
->zsl
->length
);
5816 static void zscoreCommand(redisClient
*c
) {
5821 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5822 checkType(c
,o
,REDIS_ZSET
)) return;
5825 de
= dictFind(zs
->dict
,c
->argv
[2]);
5827 addReply(c
,shared
.nullbulk
);
5829 double *score
= dictGetEntryVal(de
);
5831 addReplyDouble(c
,*score
);
5835 static void zrankGenericCommand(redisClient
*c
, int reverse
) {
5843 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5844 checkType(c
,o
,REDIS_ZSET
)) return;
5848 de
= dictFind(zs
->dict
,c
->argv
[2]);
5850 addReply(c
,shared
.nullbulk
);
5854 score
= dictGetEntryVal(de
);
5855 rank
= zslGetRank(zsl
, *score
, c
->argv
[2]);
5858 addReplyLong(c
, zsl
->length
- rank
);
5860 addReplyLong(c
, rank
-1);
5863 addReply(c
,shared
.nullbulk
);
5867 static void zrankCommand(redisClient
*c
) {
5868 zrankGenericCommand(c
, 0);
5871 static void zrevrankCommand(redisClient
*c
) {
5872 zrankGenericCommand(c
, 1);
5875 /* =================================== Hashes =============================== */
5876 static void hsetCommand(redisClient
*c
) {
5878 robj
*o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5881 o
= createHashObject();
5882 dictAdd(c
->db
->dict
,c
->argv
[1],o
);
5883 incrRefCount(c
->argv
[1]);
5885 if (o
->type
!= REDIS_HASH
) {
5886 addReply(c
,shared
.wrongtypeerr
);
5890 /* We want to convert the zipmap into an hash table right now if the
5891 * entry to be added is too big. Note that we check if the object
5892 * is integer encoded before to try fetching the length in the test below.
5893 * This is because integers are small, but currently stringObjectLen()
5894 * performs a slow conversion: not worth it. */
5895 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
&&
5896 ((c
->argv
[2]->encoding
== REDIS_ENCODING_RAW
&&
5897 sdslen(c
->argv
[2]->ptr
) > server
.hash_max_zipmap_value
) ||
5898 (c
->argv
[3]->encoding
== REDIS_ENCODING_RAW
&&
5899 sdslen(c
->argv
[3]->ptr
) > server
.hash_max_zipmap_value
)))
5901 convertToRealHash(o
);
5904 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
5905 unsigned char *zm
= o
->ptr
;
5906 robj
*valobj
= getDecodedObject(c
->argv
[3]);
5908 zm
= zipmapSet(zm
,c
->argv
[2]->ptr
,sdslen(c
->argv
[2]->ptr
),
5909 valobj
->ptr
,sdslen(valobj
->ptr
),&update
);
5910 decrRefCount(valobj
);
5913 /* And here there is the second check for hash conversion...
5914 * we want to do it only if the operation was not just an update as
5915 * zipmapLen() is O(N). */
5916 if (!update
&& zipmapLen(zm
) > server
.hash_max_zipmap_entries
)
5917 convertToRealHash(o
);
5919 tryObjectEncoding(c
->argv
[2]);
5920 /* note that c->argv[3] is already encoded, as the latest arg
5921 * of a bulk command is always integer encoded if possible. */
5922 if (dictReplace(o
->ptr
,c
->argv
[2],c
->argv
[3])) {
5923 incrRefCount(c
->argv
[2]);
5927 incrRefCount(c
->argv
[3]);
5930 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",update
== 0));
5933 static void hgetCommand(redisClient
*c
) {
5936 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5937 checkType(c
,o
,REDIS_HASH
)) return;
5939 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
5940 unsigned char *zm
= o
->ptr
;
5945 field
= getDecodedObject(c
->argv
[2]);
5946 if (zipmapGet(zm
,field
->ptr
,sdslen(field
->ptr
), &val
,&vlen
)) {
5947 addReplySds(c
,sdscatprintf(sdsempty(),"$%u\r\n", vlen
));
5948 addReplySds(c
,sdsnewlen(val
,vlen
));
5949 addReply(c
,shared
.crlf
);
5950 decrRefCount(field
);
5953 addReply(c
,shared
.nullbulk
);
5954 decrRefCount(field
);
5958 struct dictEntry
*de
;
5960 de
= dictFind(o
->ptr
,c
->argv
[2]);
5962 addReply(c
,shared
.nullbulk
);
5964 robj
*e
= dictGetEntryVal(de
);
5971 static void hdelCommand(redisClient
*c
) {
5975 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5976 checkType(c
,o
,REDIS_HASH
)) return;
5978 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
5979 robj
*field
= getDecodedObject(c
->argv
[2]);
5981 o
->ptr
= zipmapDel((unsigned char*) o
->ptr
,
5982 (unsigned char*) field
->ptr
,
5983 sdslen(field
->ptr
), &deleted
);
5984 decrRefCount(field
);
5985 if (zipmapLen((unsigned char*) o
->ptr
) == 0)
5986 deleteKey(c
->db
,c
->argv
[1]);
5988 deleted
= dictDelete((dict
*)o
->ptr
,c
->argv
[2]) == DICT_OK
;
5989 if (htNeedsResize(o
->ptr
)) dictResize(o
->ptr
);
5990 if (dictSize((dict
*)o
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5992 if (deleted
) server
.dirty
++;
5993 addReply(c
,deleted
? shared
.cone
: shared
.czero
);
5996 static void hlenCommand(redisClient
*c
) {
6000 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6001 checkType(c
,o
,REDIS_HASH
)) return;
6003 len
= (o
->encoding
== REDIS_ENCODING_ZIPMAP
) ?
6004 zipmapLen((unsigned char*)o
->ptr
) : dictSize((dict
*)o
->ptr
);
6005 addReplyUlong(c
,len
);
6008 #define REDIS_GETALL_KEYS 1
6009 #define REDIS_GETALL_VALS 2
6010 static void genericHgetallCommand(redisClient
*c
, int flags
) {
6012 unsigned long count
= 0;
6014 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullmultibulk
)) == NULL
6015 || checkType(c
,o
,REDIS_HASH
)) return;
6017 lenobj
= createObject(REDIS_STRING
,NULL
);
6019 decrRefCount(lenobj
);
6021 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6022 unsigned char *p
= zipmapRewind(o
->ptr
);
6023 unsigned char *field
, *val
;
6024 unsigned int flen
, vlen
;
6026 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
6029 if (flags
& REDIS_GETALL_KEYS
) {
6030 aux
= createStringObject((char*)field
,flen
);
6031 addReplyBulk(c
,aux
);
6035 if (flags
& REDIS_GETALL_VALS
) {
6036 aux
= createStringObject((char*)val
,vlen
);
6037 addReplyBulk(c
,aux
);
6043 dictIterator
*di
= dictGetIterator(o
->ptr
);
6046 while((de
= dictNext(di
)) != NULL
) {
6047 robj
*fieldobj
= dictGetEntryKey(de
);
6048 robj
*valobj
= dictGetEntryVal(de
);
6050 if (flags
& REDIS_GETALL_KEYS
) {
6051 addReplyBulk(c
,fieldobj
);
6054 if (flags
& REDIS_GETALL_VALS
) {
6055 addReplyBulk(c
,valobj
);
6059 dictReleaseIterator(di
);
6061 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",count
);
6064 static void hkeysCommand(redisClient
*c
) {
6065 genericHgetallCommand(c
,REDIS_GETALL_KEYS
);
6068 static void hvalsCommand(redisClient
*c
) {
6069 genericHgetallCommand(c
,REDIS_GETALL_VALS
);
6072 static void hgetallCommand(redisClient
*c
) {
6073 genericHgetallCommand(c
,REDIS_GETALL_KEYS
|REDIS_GETALL_VALS
);
6076 static void hexistsCommand(redisClient
*c
) {
6080 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6081 checkType(c
,o
,REDIS_HASH
)) return;
6083 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6085 unsigned char *zm
= o
->ptr
;
6087 field
= getDecodedObject(c
->argv
[2]);
6088 exists
= zipmapExists(zm
,field
->ptr
,sdslen(field
->ptr
));
6089 decrRefCount(field
);
6091 exists
= dictFind(o
->ptr
,c
->argv
[2]) != NULL
;
6093 addReply(c
,exists
? shared
.cone
: shared
.czero
);
6096 static void convertToRealHash(robj
*o
) {
6097 unsigned char *key
, *val
, *p
, *zm
= o
->ptr
;
6098 unsigned int klen
, vlen
;
6099 dict
*dict
= dictCreate(&hashDictType
,NULL
);
6101 assert(o
->type
== REDIS_HASH
&& o
->encoding
!= REDIS_ENCODING_HT
);
6102 p
= zipmapRewind(zm
);
6103 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
6104 robj
*keyobj
, *valobj
;
6106 keyobj
= createStringObject((char*)key
,klen
);
6107 valobj
= createStringObject((char*)val
,vlen
);
6108 tryObjectEncoding(keyobj
);
6109 tryObjectEncoding(valobj
);
6110 dictAdd(dict
,keyobj
,valobj
);
6112 o
->encoding
= REDIS_ENCODING_HT
;
6117 /* ========================= Non type-specific commands ==================== */
6119 static void flushdbCommand(redisClient
*c
) {
6120 server
.dirty
+= dictSize(c
->db
->dict
);
6121 dictEmpty(c
->db
->dict
);
6122 dictEmpty(c
->db
->expires
);
6123 addReply(c
,shared
.ok
);
6126 static void flushallCommand(redisClient
*c
) {
6127 server
.dirty
+= emptyDb();
6128 addReply(c
,shared
.ok
);
6129 rdbSave(server
.dbfilename
);
6133 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
6134 redisSortOperation
*so
= zmalloc(sizeof(*so
));
6136 so
->pattern
= pattern
;
6140 /* Return the value associated to the key with a name obtained
6141 * substituting the first occurence of '*' in 'pattern' with 'subst' */
6142 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
6146 int prefixlen
, sublen
, postfixlen
;
6147 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
6151 char buf
[REDIS_SORTKEY_MAX
+1];
6154 /* If the pattern is "#" return the substitution object itself in order
6155 * to implement the "SORT ... GET #" feature. */
6156 spat
= pattern
->ptr
;
6157 if (spat
[0] == '#' && spat
[1] == '\0') {
6161 /* The substitution object may be specially encoded. If so we create
6162 * a decoded object on the fly. Otherwise getDecodedObject will just
6163 * increment the ref count, that we'll decrement later. */
6164 subst
= getDecodedObject(subst
);
6167 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
6168 p
= strchr(spat
,'*');
6170 decrRefCount(subst
);
6175 sublen
= sdslen(ssub
);
6176 postfixlen
= sdslen(spat
)-(prefixlen
+1);
6177 memcpy(keyname
.buf
,spat
,prefixlen
);
6178 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
6179 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
6180 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
6181 keyname
.len
= prefixlen
+sublen
+postfixlen
;
6183 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2))
6184 decrRefCount(subst
);
6186 /* printf("lookup '%s' => %p\n", keyname.buf,de); */
6187 return lookupKeyRead(db
,&keyobj
);
6190 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
6191 * the additional parameter is not standard but a BSD-specific we have to
6192 * pass sorting parameters via the global 'server' structure */
6193 static int sortCompare(const void *s1
, const void *s2
) {
6194 const redisSortObject
*so1
= s1
, *so2
= s2
;
6197 if (!server
.sort_alpha
) {
6198 /* Numeric sorting. Here it's trivial as we precomputed scores */
6199 if (so1
->u
.score
> so2
->u
.score
) {
6201 } else if (so1
->u
.score
< so2
->u
.score
) {
6207 /* Alphanumeric sorting */
6208 if (server
.sort_bypattern
) {
6209 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
6210 /* At least one compare object is NULL */
6211 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
6213 else if (so1
->u
.cmpobj
== NULL
)
6218 /* We have both the objects, use strcoll */
6219 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
6222 /* Compare elements directly */
6225 dec1
= getDecodedObject(so1
->obj
);
6226 dec2
= getDecodedObject(so2
->obj
);
6227 cmp
= strcoll(dec1
->ptr
,dec2
->ptr
);
6232 return server
.sort_desc
? -cmp
: cmp
;
6235 /* The SORT command is the most complex command in Redis. Warning: this code
6236 * is optimized for speed and a bit less for readability */
6237 static void sortCommand(redisClient
*c
) {
6240 int desc
= 0, alpha
= 0;
6241 int limit_start
= 0, limit_count
= -1, start
, end
;
6242 int j
, dontsort
= 0, vectorlen
;
6243 int getop
= 0; /* GET operation counter */
6244 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
6245 redisSortObject
*vector
; /* Resulting vector to sort */
6247 /* Lookup the key to sort. It must be of the right types */
6248 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
6249 if (sortval
== NULL
) {
6250 addReply(c
,shared
.nullmultibulk
);
6253 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
6254 sortval
->type
!= REDIS_ZSET
)
6256 addReply(c
,shared
.wrongtypeerr
);
6260 /* Create a list of operations to perform for every sorted element.
6261 * Operations can be GET/DEL/INCR/DECR */
6262 operations
= listCreate();
6263 listSetFreeMethod(operations
,zfree
);
6266 /* Now we need to protect sortval incrementing its count, in the future
6267 * SORT may have options able to overwrite/delete keys during the sorting
6268 * and the sorted key itself may get destroied */
6269 incrRefCount(sortval
);
6271 /* The SORT command has an SQL-alike syntax, parse it */
6272 while(j
< c
->argc
) {
6273 int leftargs
= c
->argc
-j
-1;
6274 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
6276 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
6278 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
6280 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
6281 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
6282 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
6284 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
6285 storekey
= c
->argv
[j
+1];
6287 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
6288 sortby
= c
->argv
[j
+1];
6289 /* If the BY pattern does not contain '*', i.e. it is constant,
6290 * we don't need to sort nor to lookup the weight keys. */
6291 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
6293 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
6294 listAddNodeTail(operations
,createSortOperation(
6295 REDIS_SORT_GET
,c
->argv
[j
+1]));
6299 decrRefCount(sortval
);
6300 listRelease(operations
);
6301 addReply(c
,shared
.syntaxerr
);
6307 /* Load the sorting vector with all the objects to sort */
6308 switch(sortval
->type
) {
6309 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
6310 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
6311 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
6312 default: vectorlen
= 0; redisAssert(0); /* Avoid GCC warning */
6314 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
6317 if (sortval
->type
== REDIS_LIST
) {
6318 list
*list
= sortval
->ptr
;
6322 listRewind(list
,&li
);
6323 while((ln
= listNext(&li
))) {
6324 robj
*ele
= ln
->value
;
6325 vector
[j
].obj
= ele
;
6326 vector
[j
].u
.score
= 0;
6327 vector
[j
].u
.cmpobj
= NULL
;
6335 if (sortval
->type
== REDIS_SET
) {
6338 zset
*zs
= sortval
->ptr
;
6342 di
= dictGetIterator(set
);
6343 while((setele
= dictNext(di
)) != NULL
) {
6344 vector
[j
].obj
= dictGetEntryKey(setele
);
6345 vector
[j
].u
.score
= 0;
6346 vector
[j
].u
.cmpobj
= NULL
;
6349 dictReleaseIterator(di
);
6351 redisAssert(j
== vectorlen
);
6353 /* Now it's time to load the right scores in the sorting vector */
6354 if (dontsort
== 0) {
6355 for (j
= 0; j
< vectorlen
; j
++) {
6359 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
6360 if (!byval
|| byval
->type
!= REDIS_STRING
) continue;
6362 vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
6364 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
6365 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
6367 /* Don't need to decode the object if it's
6368 * integer-encoded (the only encoding supported) so
6369 * far. We can just cast it */
6370 if (byval
->encoding
== REDIS_ENCODING_INT
) {
6371 vector
[j
].u
.score
= (long)byval
->ptr
;
6373 redisAssert(1 != 1);
6378 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_RAW
)
6379 vector
[j
].u
.score
= strtod(vector
[j
].obj
->ptr
,NULL
);
6381 if (vector
[j
].obj
->encoding
== REDIS_ENCODING_INT
)
6382 vector
[j
].u
.score
= (long) vector
[j
].obj
->ptr
;
6384 redisAssert(1 != 1);
6391 /* We are ready to sort the vector... perform a bit of sanity check
6392 * on the LIMIT option too. We'll use a partial version of quicksort. */
6393 start
= (limit_start
< 0) ? 0 : limit_start
;
6394 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
6395 if (start
>= vectorlen
) {
6396 start
= vectorlen
-1;
6399 if (end
>= vectorlen
) end
= vectorlen
-1;
6401 if (dontsort
== 0) {
6402 server
.sort_desc
= desc
;
6403 server
.sort_alpha
= alpha
;
6404 server
.sort_bypattern
= sortby
? 1 : 0;
6405 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
6406 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
6408 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
6411 /* Send command output to the output buffer, performing the specified
6412 * GET/DEL/INCR/DECR operations if any. */
6413 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
6414 if (storekey
== NULL
) {
6415 /* STORE option not specified, sent the sorting result to client */
6416 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
6417 for (j
= start
; j
<= end
; j
++) {
6421 if (!getop
) addReplyBulk(c
,vector
[j
].obj
);
6422 listRewind(operations
,&li
);
6423 while((ln
= listNext(&li
))) {
6424 redisSortOperation
*sop
= ln
->value
;
6425 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
6428 if (sop
->type
== REDIS_SORT_GET
) {
6429 if (!val
|| val
->type
!= REDIS_STRING
) {
6430 addReply(c
,shared
.nullbulk
);
6432 addReplyBulk(c
,val
);
6435 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
6440 robj
*listObject
= createListObject();
6441 list
*listPtr
= (list
*) listObject
->ptr
;
6443 /* STORE option specified, set the sorting result as a List object */
6444 for (j
= start
; j
<= end
; j
++) {
6449 listAddNodeTail(listPtr
,vector
[j
].obj
);
6450 incrRefCount(vector
[j
].obj
);
6452 listRewind(operations
,&li
);
6453 while((ln
= listNext(&li
))) {
6454 redisSortOperation
*sop
= ln
->value
;
6455 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
6458 if (sop
->type
== REDIS_SORT_GET
) {
6459 if (!val
|| val
->type
!= REDIS_STRING
) {
6460 listAddNodeTail(listPtr
,createStringObject("",0));
6462 listAddNodeTail(listPtr
,val
);
6466 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
6470 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
6471 incrRefCount(storekey
);
6473 /* Note: we add 1 because the DB is dirty anyway since even if the
6474 * SORT result is empty a new key is set and maybe the old content
6476 server
.dirty
+= 1+outputlen
;
6477 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
6481 decrRefCount(sortval
);
6482 listRelease(operations
);
6483 for (j
= 0; j
< vectorlen
; j
++) {
6484 if (sortby
&& alpha
&& vector
[j
].u
.cmpobj
)
6485 decrRefCount(vector
[j
].u
.cmpobj
);
6490 /* Convert an amount of bytes into a human readable string in the form
6491 * of 100B, 2G, 100M, 4K, and so forth. */
6492 static void bytesToHuman(char *s
, unsigned long long n
) {
6497 sprintf(s
,"%lluB",n
);
6499 } else if (n
< (1024*1024)) {
6500 d
= (double)n
/(1024);
6501 sprintf(s
,"%.2fK",d
);
6502 } else if (n
< (1024LL*1024*1024)) {
6503 d
= (double)n
/(1024*1024);
6504 sprintf(s
,"%.2fM",d
);
6505 } else if (n
< (1024LL*1024*1024*1024)) {
6506 d
= (double)n
/(1024LL*1024*1024);
6507 sprintf(s
,"%.2fG",d
);
6511 /* Create the string returned by the INFO command. This is decoupled
6512 * by the INFO command itself as we need to report the same information
6513 * on memory corruption problems. */
6514 static sds
genRedisInfoString(void) {
6516 time_t uptime
= time(NULL
)-server
.stat_starttime
;
6520 bytesToHuman(hmem
,zmalloc_used_memory());
6521 info
= sdscatprintf(sdsempty(),
6522 "redis_version:%s\r\n"
6524 "multiplexing_api:%s\r\n"
6525 "process_id:%ld\r\n"
6526 "uptime_in_seconds:%ld\r\n"
6527 "uptime_in_days:%ld\r\n"
6528 "connected_clients:%d\r\n"
6529 "connected_slaves:%d\r\n"
6530 "blocked_clients:%d\r\n"
6531 "used_memory:%zu\r\n"
6532 "used_memory_human:%s\r\n"
6533 "changes_since_last_save:%lld\r\n"
6534 "bgsave_in_progress:%d\r\n"
6535 "last_save_time:%ld\r\n"
6536 "bgrewriteaof_in_progress:%d\r\n"
6537 "total_connections_received:%lld\r\n"
6538 "total_commands_processed:%lld\r\n"
6539 "expired_keys:%lld\r\n"
6540 "hash_max_zipmap_entries:%ld\r\n"
6541 "hash_max_zipmap_value:%ld\r\n"
6545 (sizeof(long) == 8) ? "64" : "32",
6550 listLength(server
.clients
)-listLength(server
.slaves
),
6551 listLength(server
.slaves
),
6552 server
.blpop_blocked_clients
,
6553 zmalloc_used_memory(),
6556 server
.bgsavechildpid
!= -1,
6558 server
.bgrewritechildpid
!= -1,
6559 server
.stat_numconnections
,
6560 server
.stat_numcommands
,
6561 server
.stat_expiredkeys
,
6562 server
.hash_max_zipmap_entries
,
6563 server
.hash_max_zipmap_value
,
6564 server
.vm_enabled
!= 0,
6565 server
.masterhost
== NULL
? "master" : "slave"
6567 if (server
.masterhost
) {
6568 info
= sdscatprintf(info
,
6569 "master_host:%s\r\n"
6570 "master_port:%d\r\n"
6571 "master_link_status:%s\r\n"
6572 "master_last_io_seconds_ago:%d\r\n"
6575 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
6577 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
6580 if (server
.vm_enabled
) {
6582 info
= sdscatprintf(info
,
6583 "vm_conf_max_memory:%llu\r\n"
6584 "vm_conf_page_size:%llu\r\n"
6585 "vm_conf_pages:%llu\r\n"
6586 "vm_stats_used_pages:%llu\r\n"
6587 "vm_stats_swapped_objects:%llu\r\n"
6588 "vm_stats_swappin_count:%llu\r\n"
6589 "vm_stats_swappout_count:%llu\r\n"
6590 "vm_stats_io_newjobs_len:%lu\r\n"
6591 "vm_stats_io_processing_len:%lu\r\n"
6592 "vm_stats_io_processed_len:%lu\r\n"
6593 "vm_stats_io_active_threads:%lu\r\n"
6594 "vm_stats_blocked_clients:%lu\r\n"
6595 ,(unsigned long long) server
.vm_max_memory
,
6596 (unsigned long long) server
.vm_page_size
,
6597 (unsigned long long) server
.vm_pages
,
6598 (unsigned long long) server
.vm_stats_used_pages
,
6599 (unsigned long long) server
.vm_stats_swapped_objects
,
6600 (unsigned long long) server
.vm_stats_swapins
,
6601 (unsigned long long) server
.vm_stats_swapouts
,
6602 (unsigned long) listLength(server
.io_newjobs
),
6603 (unsigned long) listLength(server
.io_processing
),
6604 (unsigned long) listLength(server
.io_processed
),
6605 (unsigned long) server
.io_active_threads
,
6606 (unsigned long) server
.vm_blocked_clients
6610 for (j
= 0; j
< server
.dbnum
; j
++) {
6611 long long keys
, vkeys
;
6613 keys
= dictSize(server
.db
[j
].dict
);
6614 vkeys
= dictSize(server
.db
[j
].expires
);
6615 if (keys
|| vkeys
) {
6616 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
6623 static void infoCommand(redisClient
*c
) {
6624 sds info
= genRedisInfoString();
6625 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
6626 (unsigned long)sdslen(info
)));
6627 addReplySds(c
,info
);
6628 addReply(c
,shared
.crlf
);
6631 static void monitorCommand(redisClient
*c
) {
6632 /* ignore MONITOR if aleady slave or in monitor mode */
6633 if (c
->flags
& REDIS_SLAVE
) return;
6635 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
6637 listAddNodeTail(server
.monitors
,c
);
6638 addReply(c
,shared
.ok
);
6641 /* ================================= Expire ================================= */
6642 static int removeExpire(redisDb
*db
, robj
*key
) {
6643 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
6650 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
6651 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
6659 /* Return the expire time of the specified key, or -1 if no expire
6660 * is associated with this key (i.e. the key is non volatile) */
6661 static time_t getExpire(redisDb
*db
, robj
*key
) {
6664 /* No expire? return ASAP */
6665 if (dictSize(db
->expires
) == 0 ||
6666 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
6668 return (time_t) dictGetEntryVal(de
);
6671 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
6675 /* No expire? return ASAP */
6676 if (dictSize(db
->expires
) == 0 ||
6677 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
6679 /* Lookup the expire */
6680 when
= (time_t) dictGetEntryVal(de
);
6681 if (time(NULL
) <= when
) return 0;
6683 /* Delete the key */
6684 dictDelete(db
->expires
,key
);
6685 server
.stat_expiredkeys
++;
6686 return dictDelete(db
->dict
,key
) == DICT_OK
;
6689 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
6692 /* No expire? return ASAP */
6693 if (dictSize(db
->expires
) == 0 ||
6694 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
6696 /* Delete the key */
6698 server
.stat_expiredkeys
++;
6699 dictDelete(db
->expires
,key
);
6700 return dictDelete(db
->dict
,key
) == DICT_OK
;
6703 static void expireGenericCommand(redisClient
*c
, robj
*key
, time_t seconds
) {
6706 de
= dictFind(c
->db
->dict
,key
);
6708 addReply(c
,shared
.czero
);
6712 if (deleteKey(c
->db
,key
)) server
.dirty
++;
6713 addReply(c
, shared
.cone
);
6716 time_t when
= time(NULL
)+seconds
;
6717 if (setExpire(c
->db
,key
,when
)) {
6718 addReply(c
,shared
.cone
);
6721 addReply(c
,shared
.czero
);
6727 static void expireCommand(redisClient
*c
) {
6728 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10));
6731 static void expireatCommand(redisClient
*c
) {
6732 expireGenericCommand(c
,c
->argv
[1],strtol(c
->argv
[2]->ptr
,NULL
,10)-time(NULL
));
6735 static void ttlCommand(redisClient
*c
) {
6739 expire
= getExpire(c
->db
,c
->argv
[1]);
6741 ttl
= (int) (expire
-time(NULL
));
6742 if (ttl
< 0) ttl
= -1;
6744 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
6747 /* ================================ MULTI/EXEC ============================== */
6749 /* Client state initialization for MULTI/EXEC */
6750 static void initClientMultiState(redisClient
*c
) {
6751 c
->mstate
.commands
= NULL
;
6752 c
->mstate
.count
= 0;
6755 /* Release all the resources associated with MULTI/EXEC state */
6756 static void freeClientMultiState(redisClient
*c
) {
6759 for (j
= 0; j
< c
->mstate
.count
; j
++) {
6761 multiCmd
*mc
= c
->mstate
.commands
+j
;
6763 for (i
= 0; i
< mc
->argc
; i
++)
6764 decrRefCount(mc
->argv
[i
]);
6767 zfree(c
->mstate
.commands
);
6770 /* Add a new command into the MULTI commands queue */
6771 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
6775 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
6776 sizeof(multiCmd
)*(c
->mstate
.count
+1));
6777 mc
= c
->mstate
.commands
+c
->mstate
.count
;
6780 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
6781 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
6782 for (j
= 0; j
< c
->argc
; j
++)
6783 incrRefCount(mc
->argv
[j
]);
6787 static void multiCommand(redisClient
*c
) {
6788 c
->flags
|= REDIS_MULTI
;
6789 addReply(c
,shared
.ok
);
6792 static void discardCommand(redisClient
*c
) {
6793 if (!(c
->flags
& REDIS_MULTI
)) {
6794 addReplySds(c
,sdsnew("-ERR DISCARD without MULTI\r\n"));
6798 freeClientMultiState(c
);
6799 initClientMultiState(c
);
6800 c
->flags
&= (~REDIS_MULTI
);
6801 addReply(c
,shared
.ok
);
6804 static void execCommand(redisClient
*c
) {
6809 if (!(c
->flags
& REDIS_MULTI
)) {
6810 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
6814 orig_argv
= c
->argv
;
6815 orig_argc
= c
->argc
;
6816 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
6817 for (j
= 0; j
< c
->mstate
.count
; j
++) {
6818 c
->argc
= c
->mstate
.commands
[j
].argc
;
6819 c
->argv
= c
->mstate
.commands
[j
].argv
;
6820 call(c
,c
->mstate
.commands
[j
].cmd
);
6822 c
->argv
= orig_argv
;
6823 c
->argc
= orig_argc
;
6824 freeClientMultiState(c
);
6825 initClientMultiState(c
);
6826 c
->flags
&= (~REDIS_MULTI
);
6829 /* =========================== Blocking Operations ========================= */
6831 /* Currently Redis blocking operations support is limited to list POP ops,
6832 * so the current implementation is not fully generic, but it is also not
6833 * completely specific so it will not require a rewrite to support new
6834 * kind of blocking operations in the future.
6836 * Still it's important to note that list blocking operations can be already
6837 * used as a notification mechanism in order to implement other blocking
6838 * operations at application level, so there must be a very strong evidence
6839 * of usefulness and generality before new blocking operations are implemented.
6841 * This is how the current blocking POP works, we use BLPOP as example:
6842 * - If the user calls BLPOP and the key exists and contains a non empty list
6843 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
6844 * if there is not to block.
6845 * - If instead BLPOP is called and the key does not exists or the list is
6846 * empty we need to block. In order to do so we remove the notification for
6847 * new data to read in the client socket (so that we'll not serve new
6848 * requests if the blocking request is not served). Also we put the client
6849 * in a dictionary (db->blockingkeys) mapping keys to a list of clients
6850 * blocking for this keys.
6851 * - If a PUSH operation against a key with blocked clients waiting is
6852 * performed, we serve the first in the list: basically instead to push
6853 * the new element inside the list we return it to the (first / oldest)
6854 * blocking client, unblock the client, and remove it form the list.
6856 * The above comment and the source code should be enough in order to understand
6857 * the implementation and modify / fix it later.
6860 /* Set a client in blocking mode for the specified key, with the specified
6862 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
6867 c
->blockingkeys
= zmalloc(sizeof(robj
*)*numkeys
);
6868 c
->blockingkeysnum
= numkeys
;
6869 c
->blockingto
= timeout
;
6870 for (j
= 0; j
< numkeys
; j
++) {
6871 /* Add the key in the client structure, to map clients -> keys */
6872 c
->blockingkeys
[j
] = keys
[j
];
6873 incrRefCount(keys
[j
]);
6875 /* And in the other "side", to map keys -> clients */
6876 de
= dictFind(c
->db
->blockingkeys
,keys
[j
]);
6880 /* For every key we take a list of clients blocked for it */
6882 retval
= dictAdd(c
->db
->blockingkeys
,keys
[j
],l
);
6883 incrRefCount(keys
[j
]);
6884 assert(retval
== DICT_OK
);
6886 l
= dictGetEntryVal(de
);
6888 listAddNodeTail(l
,c
);
6890 /* Mark the client as a blocked client */
6891 c
->flags
|= REDIS_BLOCKED
;
6892 server
.blpop_blocked_clients
++;
6895 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
6896 static void unblockClientWaitingData(redisClient
*c
) {
6901 assert(c
->blockingkeys
!= NULL
);
6902 /* The client may wait for multiple keys, so unblock it for every key. */
6903 for (j
= 0; j
< c
->blockingkeysnum
; j
++) {
6904 /* Remove this client from the list of clients waiting for this key. */
6905 de
= dictFind(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
6907 l
= dictGetEntryVal(de
);
6908 listDelNode(l
,listSearchKey(l
,c
));
6909 /* If the list is empty we need to remove it to avoid wasting memory */
6910 if (listLength(l
) == 0)
6911 dictDelete(c
->db
->blockingkeys
,c
->blockingkeys
[j
]);
6912 decrRefCount(c
->blockingkeys
[j
]);
6914 /* Cleanup the client structure */
6915 zfree(c
->blockingkeys
);
6916 c
->blockingkeys
= NULL
;
6917 c
->flags
&= (~REDIS_BLOCKED
);
6918 server
.blpop_blocked_clients
--;
6919 /* We want to process data if there is some command waiting
6920 * in the input buffer. Note that this is safe even if
6921 * unblockClientWaitingData() gets called from freeClient() because
6922 * freeClient() will be smart enough to call this function
6923 * *after* c->querybuf was set to NULL. */
6924 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
6927 /* This should be called from any function PUSHing into lists.
6928 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
6929 * 'ele' is the element pushed.
6931 * If the function returns 0 there was no client waiting for a list push
6934 * If the function returns 1 there was a client waiting for a list push
6935 * against this key, the element was passed to this client thus it's not
6936 * needed to actually add it to the list and the caller should return asap. */
6937 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
6938 struct dictEntry
*de
;
6939 redisClient
*receiver
;
6943 de
= dictFind(c
->db
->blockingkeys
,key
);
6944 if (de
== NULL
) return 0;
6945 l
= dictGetEntryVal(de
);
6948 receiver
= ln
->value
;
6950 addReplySds(receiver
,sdsnew("*2\r\n"));
6951 addReplyBulk(receiver
,key
);
6952 addReplyBulk(receiver
,ele
);
6953 unblockClientWaitingData(receiver
);
6957 /* Blocking RPOP/LPOP */
6958 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
6963 for (j
= 1; j
< c
->argc
-1; j
++) {
6964 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
6966 if (o
->type
!= REDIS_LIST
) {
6967 addReply(c
,shared
.wrongtypeerr
);
6970 list
*list
= o
->ptr
;
6971 if (listLength(list
) != 0) {
6972 /* If the list contains elements fall back to the usual
6973 * non-blocking POP operation */
6974 robj
*argv
[2], **orig_argv
;
6977 /* We need to alter the command arguments before to call
6978 * popGenericCommand() as the command takes a single key. */
6979 orig_argv
= c
->argv
;
6980 orig_argc
= c
->argc
;
6981 argv
[1] = c
->argv
[j
];
6985 /* Also the return value is different, we need to output
6986 * the multi bulk reply header and the key name. The
6987 * "real" command will add the last element (the value)
6988 * for us. If this souds like an hack to you it's just
6989 * because it is... */
6990 addReplySds(c
,sdsnew("*2\r\n"));
6991 addReplyBulk(c
,argv
[1]);
6992 popGenericCommand(c
,where
);
6994 /* Fix the client structure with the original stuff */
6995 c
->argv
= orig_argv
;
6996 c
->argc
= orig_argc
;
7002 /* If the list is empty or the key does not exists we must block */
7003 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
7004 if (timeout
> 0) timeout
+= time(NULL
);
7005 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
7008 static void blpopCommand(redisClient
*c
) {
7009 blockingPopGenericCommand(c
,REDIS_HEAD
);
7012 static void brpopCommand(redisClient
*c
) {
7013 blockingPopGenericCommand(c
,REDIS_TAIL
);
7016 /* =============================== Replication ============================= */
7018 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7019 ssize_t nwritten
, ret
= size
;
7020 time_t start
= time(NULL
);
7024 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
7025 nwritten
= write(fd
,ptr
,size
);
7026 if (nwritten
== -1) return -1;
7030 if ((time(NULL
)-start
) > timeout
) {
7038 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7039 ssize_t nread
, totread
= 0;
7040 time_t start
= time(NULL
);
7044 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
7045 nread
= read(fd
,ptr
,size
);
7046 if (nread
== -1) return -1;
7051 if ((time(NULL
)-start
) > timeout
) {
7059 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7066 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
7069 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
7080 static void syncCommand(redisClient
*c
) {
7081 /* ignore SYNC if aleady slave or in monitor mode */
7082 if (c
->flags
& REDIS_SLAVE
) return;
7084 /* SYNC can't be issued when the server has pending data to send to
7085 * the client about already issued commands. We need a fresh reply
7086 * buffer registering the differences between the BGSAVE and the current
7087 * dataset, so that we can copy to other slaves if needed. */
7088 if (listLength(c
->reply
) != 0) {
7089 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
7093 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
7094 /* Here we need to check if there is a background saving operation
7095 * in progress, or if it is required to start one */
7096 if (server
.bgsavechildpid
!= -1) {
7097 /* Ok a background save is in progress. Let's check if it is a good
7098 * one for replication, i.e. if there is another slave that is
7099 * registering differences since the server forked to save */
7104 listRewind(server
.slaves
,&li
);
7105 while((ln
= listNext(&li
))) {
7107 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
7110 /* Perfect, the server is already registering differences for
7111 * another slave. Set the right state, and copy the buffer. */
7112 listRelease(c
->reply
);
7113 c
->reply
= listDup(slave
->reply
);
7114 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7115 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
7117 /* No way, we need to wait for the next BGSAVE in order to
7118 * register differences */
7119 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
7120 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
7123 /* Ok we don't have a BGSAVE in progress, let's start one */
7124 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
7125 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7126 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
7127 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
7130 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7133 c
->flags
|= REDIS_SLAVE
;
7135 listAddNodeTail(server
.slaves
,c
);
7139 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
7140 redisClient
*slave
= privdata
;
7142 REDIS_NOTUSED(mask
);
7143 char buf
[REDIS_IOBUF_LEN
];
7144 ssize_t nwritten
, buflen
;
7146 if (slave
->repldboff
== 0) {
7147 /* Write the bulk write count before to transfer the DB. In theory here
7148 * we don't know how much room there is in the output buffer of the
7149 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
7150 * operations) will never be smaller than the few bytes we need. */
7153 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
7155 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
7163 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
7164 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
7166 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
7167 (buflen
== 0) ? "premature EOF" : strerror(errno
));
7171 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
7172 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
7177 slave
->repldboff
+= nwritten
;
7178 if (slave
->repldboff
== slave
->repldbsize
) {
7179 close(slave
->repldbfd
);
7180 slave
->repldbfd
= -1;
7181 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
7182 slave
->replstate
= REDIS_REPL_ONLINE
;
7183 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
7184 sendReplyToClient
, slave
) == AE_ERR
) {
7188 addReplySds(slave
,sdsempty());
7189 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
7193 /* This function is called at the end of every backgrond saving.
7194 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
7195 * otherwise REDIS_ERR is passed to the function.
7197 * The goal of this function is to handle slaves waiting for a successful
7198 * background saving in order to perform non-blocking synchronization. */
7199 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
7201 int startbgsave
= 0;
7204 listRewind(server
.slaves
,&li
);
7205 while((ln
= listNext(&li
))) {
7206 redisClient
*slave
= ln
->value
;
7208 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
7210 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
7211 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
7212 struct redis_stat buf
;
7214 if (bgsaveerr
!= REDIS_OK
) {
7216 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
7219 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
7220 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
7222 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
7225 slave
->repldboff
= 0;
7226 slave
->repldbsize
= buf
.st_size
;
7227 slave
->replstate
= REDIS_REPL_SEND_BULK
;
7228 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
7229 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
7236 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
7239 listRewind(server
.slaves
,&li
);
7240 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
7241 while((ln
= listNext(&li
))) {
7242 redisClient
*slave
= ln
->value
;
7244 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
7251 static int syncWithMaster(void) {
7252 char buf
[1024], tmpfile
[256], authcmd
[1024];
7254 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
7255 int dfd
, maxtries
= 5;
7258 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
7263 /* AUTH with the master if required. */
7264 if(server
.masterauth
) {
7265 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
7266 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
7268 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
7272 /* Read the AUTH result. */
7273 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
7275 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
7279 if (buf
[0] != '+') {
7281 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
7286 /* Issue the SYNC command */
7287 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
7289 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
7293 /* Read the bulk write count */
7294 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
7296 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
7300 if (buf
[0] != '$') {
7302 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
7305 dumpsize
= strtol(buf
+1,NULL
,10);
7306 redisLog(REDIS_NOTICE
,"Receiving %ld bytes data dump from MASTER",dumpsize
);
7307 /* Read the bulk write data on a temp file */
7309 snprintf(tmpfile
,256,
7310 "temp-%d.%ld.rdb",(int)time(NULL
),(long int)getpid());
7311 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
|O_EXCL
,0644);
7312 if (dfd
!= -1) break;
7317 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
7321 int nread
, nwritten
;
7323 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
7325 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
7331 nwritten
= write(dfd
,buf
,nread
);
7332 if (nwritten
== -1) {
7333 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
7341 if (rename(tmpfile
,server
.dbfilename
) == -1) {
7342 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
7348 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
7349 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
7353 server
.master
= createClient(fd
);
7354 server
.master
->flags
|= REDIS_MASTER
;
7355 server
.master
->authenticated
= 1;
7356 server
.replstate
= REDIS_REPL_CONNECTED
;
7360 static void slaveofCommand(redisClient
*c
) {
7361 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
7362 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
7363 if (server
.masterhost
) {
7364 sdsfree(server
.masterhost
);
7365 server
.masterhost
= NULL
;
7366 if (server
.master
) freeClient(server
.master
);
7367 server
.replstate
= REDIS_REPL_NONE
;
7368 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
7371 sdsfree(server
.masterhost
);
7372 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
7373 server
.masterport
= atoi(c
->argv
[2]->ptr
);
7374 if (server
.master
) freeClient(server
.master
);
7375 server
.replstate
= REDIS_REPL_CONNECT
;
7376 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
7377 server
.masterhost
, server
.masterport
);
7379 addReply(c
,shared
.ok
);
7382 /* ============================ Maxmemory directive ======================== */
7384 /* Try to free one object form the pre-allocated objects free list.
7385 * This is useful under low mem conditions as by default we take 1 million
7386 * free objects allocated. On success REDIS_OK is returned, otherwise
7388 static int tryFreeOneObjectFromFreelist(void) {
7391 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
7392 if (listLength(server
.objfreelist
)) {
7393 listNode
*head
= listFirst(server
.objfreelist
);
7394 o
= listNodeValue(head
);
7395 listDelNode(server
.objfreelist
,head
);
7396 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
7400 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
7405 /* This function gets called when 'maxmemory' is set on the config file to limit
7406 * the max memory used by the server, and we are out of memory.
7407 * This function will try to, in order:
7409 * - Free objects from the free list
7410 * - Try to remove keys with an EXPIRE set
7412 * It is not possible to free enough memory to reach used-memory < maxmemory
7413 * the server will start refusing commands that will enlarge even more the
7416 static void freeMemoryIfNeeded(void) {
7417 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
7418 int j
, k
, freed
= 0;
7420 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
7421 for (j
= 0; j
< server
.dbnum
; j
++) {
7423 robj
*minkey
= NULL
;
7424 struct dictEntry
*de
;
7426 if (dictSize(server
.db
[j
].expires
)) {
7428 /* From a sample of three keys drop the one nearest to
7429 * the natural expire */
7430 for (k
= 0; k
< 3; k
++) {
7433 de
= dictGetRandomKey(server
.db
[j
].expires
);
7434 t
= (time_t) dictGetEntryVal(de
);
7435 if (minttl
== -1 || t
< minttl
) {
7436 minkey
= dictGetEntryKey(de
);
7440 deleteKey(server
.db
+j
,minkey
);
7443 if (!freed
) return; /* nothing to free... */
7447 /* ============================== Append Only file ========================== */
7449 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
7450 sds buf
= sdsempty();
7456 /* The DB this command was targetting is not the same as the last command
7457 * we appendend. To issue a SELECT command is needed. */
7458 if (dictid
!= server
.appendseldb
) {
7461 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
7462 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
7463 (unsigned long)strlen(seldb
),seldb
);
7464 server
.appendseldb
= dictid
;
7467 /* "Fix" the argv vector if the command is EXPIRE. We want to translate
7468 * EXPIREs into EXPIREATs calls */
7469 if (cmd
->proc
== expireCommand
) {
7472 tmpargv
[0] = createStringObject("EXPIREAT",8);
7473 tmpargv
[1] = argv
[1];
7474 incrRefCount(argv
[1]);
7475 when
= time(NULL
)+strtol(argv
[2]->ptr
,NULL
,10);
7476 tmpargv
[2] = createObject(REDIS_STRING
,
7477 sdscatprintf(sdsempty(),"%ld",when
));
7481 /* Append the actual command */
7482 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
7483 for (j
= 0; j
< argc
; j
++) {
7486 o
= getDecodedObject(o
);
7487 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
7488 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
7489 buf
= sdscatlen(buf
,"\r\n",2);
7493 /* Free the objects from the modified argv for EXPIREAT */
7494 if (cmd
->proc
== expireCommand
) {
7495 for (j
= 0; j
< 3; j
++)
7496 decrRefCount(argv
[j
]);
7499 /* We want to perform a single write. This should be guaranteed atomic
7500 * at least if the filesystem we are writing is a real physical one.
7501 * While this will save us against the server being killed I don't think
7502 * there is much to do about the whole server stopping for power problems
7504 nwritten
= write(server
.appendfd
,buf
,sdslen(buf
));
7505 if (nwritten
!= (signed)sdslen(buf
)) {
7506 /* Ooops, we are in troubles. The best thing to do for now is
7507 * to simply exit instead to give the illusion that everything is
7508 * working as expected. */
7509 if (nwritten
== -1) {
7510 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
7512 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
7516 /* If a background append only file rewriting is in progress we want to
7517 * accumulate the differences between the child DB and the current one
7518 * in a buffer, so that when the child process will do its work we
7519 * can append the differences to the new append only file. */
7520 if (server
.bgrewritechildpid
!= -1)
7521 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
7525 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
7526 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
7527 now
-server
.lastfsync
> 1))
7529 fsync(server
.appendfd
); /* Let's try to get this data on the disk */
7530 server
.lastfsync
= now
;
7534 /* In Redis commands are always executed in the context of a client, so in
7535 * order to load the append only file we need to create a fake client. */
7536 static struct redisClient
*createFakeClient(void) {
7537 struct redisClient
*c
= zmalloc(sizeof(*c
));
7541 c
->querybuf
= sdsempty();
7545 /* We set the fake client as a slave waiting for the synchronization
7546 * so that Redis will not try to send replies to this client. */
7547 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
7548 c
->reply
= listCreate();
7549 listSetFreeMethod(c
->reply
,decrRefCount
);
7550 listSetDupMethod(c
->reply
,dupClientReplyValue
);
7554 static void freeFakeClient(struct redisClient
*c
) {
7555 sdsfree(c
->querybuf
);
7556 listRelease(c
->reply
);
7560 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
7561 * error (the append only file is zero-length) REDIS_ERR is returned. On
7562 * fatal error an error message is logged and the program exists. */
7563 int loadAppendOnlyFile(char *filename
) {
7564 struct redisClient
*fakeClient
;
7565 FILE *fp
= fopen(filename
,"r");
7566 struct redis_stat sb
;
7567 unsigned long long loadedkeys
= 0;
7569 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
7573 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
7577 fakeClient
= createFakeClient();
7584 struct redisCommand
*cmd
;
7586 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
7592 if (buf
[0] != '*') goto fmterr
;
7594 argv
= zmalloc(sizeof(robj
*)*argc
);
7595 for (j
= 0; j
< argc
; j
++) {
7596 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
7597 if (buf
[0] != '$') goto fmterr
;
7598 len
= strtol(buf
+1,NULL
,10);
7599 argsds
= sdsnewlen(NULL
,len
);
7600 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
7601 argv
[j
] = createObject(REDIS_STRING
,argsds
);
7602 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
7605 /* Command lookup */
7606 cmd
= lookupCommand(argv
[0]->ptr
);
7608 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
7611 /* Try object sharing and encoding */
7612 if (server
.shareobjects
) {
7614 for(j
= 1; j
< argc
; j
++)
7615 argv
[j
] = tryObjectSharing(argv
[j
]);
7617 if (cmd
->flags
& REDIS_CMD_BULK
)
7618 tryObjectEncoding(argv
[argc
-1]);
7619 /* Run the command in the context of a fake client */
7620 fakeClient
->argc
= argc
;
7621 fakeClient
->argv
= argv
;
7622 cmd
->proc(fakeClient
);
7623 /* Discard the reply objects list from the fake client */
7624 while(listLength(fakeClient
->reply
))
7625 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
7626 /* Clean up, ready for the next command */
7627 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
7629 /* Handle swapping while loading big datasets when VM is on */
7631 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
7632 while (zmalloc_used_memory() > server
.vm_max_memory
) {
7633 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
7638 freeFakeClient(fakeClient
);
7643 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
7645 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
7649 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
7653 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
7654 static int fwriteBulkObject(FILE *fp
, robj
*obj
) {
7658 /* Avoid the incr/decr ref count business if possible to help
7659 * copy-on-write (we are often in a child process when this function
7661 * Also makes sure that key objects don't get incrRefCount-ed when VM
7663 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
7664 obj
= getDecodedObject(obj
);
7667 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
7668 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
7669 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
7671 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
7672 if (decrrc
) decrRefCount(obj
);
7675 if (decrrc
) decrRefCount(obj
);
7679 /* Write binary-safe string into a file in the bulkformat
7680 * $<count>\r\n<payload>\r\n */
7681 static int fwriteBulkString(FILE *fp
, char *s
, unsigned long len
) {
7684 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(unsigned long)len
);
7685 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7686 if (len
&& fwrite(s
,len
,1,fp
) == 0) return 0;
7687 if (fwrite("\r\n",2,1,fp
) == 0) return 0;
7691 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
7692 static int fwriteBulkDouble(FILE *fp
, double d
) {
7693 char buf
[128], dbuf
[128];
7695 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
7696 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
7697 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7698 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
7702 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
7703 static int fwriteBulkLong(FILE *fp
, long l
) {
7704 char buf
[128], lbuf
[128];
7706 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
7707 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
7708 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
7709 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
7713 /* Write a sequence of commands able to fully rebuild the dataset into
7714 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
7715 static int rewriteAppendOnlyFile(char *filename
) {
7716 dictIterator
*di
= NULL
;
7721 time_t now
= time(NULL
);
7723 /* Note that we have to use a different temp name here compared to the
7724 * one used by rewriteAppendOnlyFileBackground() function. */
7725 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
7726 fp
= fopen(tmpfile
,"w");
7728 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
7731 for (j
= 0; j
< server
.dbnum
; j
++) {
7732 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
7733 redisDb
*db
= server
.db
+j
;
7735 if (dictSize(d
) == 0) continue;
7736 di
= dictGetIterator(d
);
7742 /* SELECT the new DB */
7743 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
7744 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
7746 /* Iterate this DB writing every entry */
7747 while((de
= dictNext(di
)) != NULL
) {
7752 key
= dictGetEntryKey(de
);
7753 /* If the value for this key is swapped, load a preview in memory.
7754 * We use a "swapped" flag to remember if we need to free the
7755 * value object instead to just increment the ref count anyway
7756 * in order to avoid copy-on-write of pages if we are forked() */
7757 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
7758 key
->storage
== REDIS_VM_SWAPPING
) {
7759 o
= dictGetEntryVal(de
);
7762 o
= vmPreviewObject(key
);
7765 expiretime
= getExpire(db
,key
);
7767 /* Save the key and associated value */
7768 if (o
->type
== REDIS_STRING
) {
7769 /* Emit a SET command */
7770 char cmd
[]="*3\r\n$3\r\nSET\r\n";
7771 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7773 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7774 if (fwriteBulkObject(fp
,o
) == 0) goto werr
;
7775 } else if (o
->type
== REDIS_LIST
) {
7776 /* Emit the RPUSHes needed to rebuild the list */
7777 list
*list
= o
->ptr
;
7781 listRewind(list
,&li
);
7782 while((ln
= listNext(&li
))) {
7783 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
7784 robj
*eleobj
= listNodeValue(ln
);
7786 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7787 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7788 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
7790 } else if (o
->type
== REDIS_SET
) {
7791 /* Emit the SADDs needed to rebuild the set */
7793 dictIterator
*di
= dictGetIterator(set
);
7796 while((de
= dictNext(di
)) != NULL
) {
7797 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
7798 robj
*eleobj
= dictGetEntryKey(de
);
7800 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7801 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7802 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
7804 dictReleaseIterator(di
);
7805 } else if (o
->type
== REDIS_ZSET
) {
7806 /* Emit the ZADDs needed to rebuild the sorted set */
7808 dictIterator
*di
= dictGetIterator(zs
->dict
);
7811 while((de
= dictNext(di
)) != NULL
) {
7812 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
7813 robj
*eleobj
= dictGetEntryKey(de
);
7814 double *score
= dictGetEntryVal(de
);
7816 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7817 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7818 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
7819 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
7821 dictReleaseIterator(di
);
7822 } else if (o
->type
== REDIS_HASH
) {
7823 char cmd
[]="*4\r\n$4\r\nHSET\r\n";
7825 /* Emit the HSETs needed to rebuild the hash */
7826 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
7827 unsigned char *p
= zipmapRewind(o
->ptr
);
7828 unsigned char *field
, *val
;
7829 unsigned int flen
, vlen
;
7831 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
7832 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7833 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7834 if (fwriteBulkString(fp
,(char*)field
,flen
) == -1)
7836 if (fwriteBulkString(fp
,(char*)val
,vlen
) == -1)
7840 dictIterator
*di
= dictGetIterator(o
->ptr
);
7843 while((de
= dictNext(di
)) != NULL
) {
7844 robj
*field
= dictGetEntryKey(de
);
7845 robj
*val
= dictGetEntryVal(de
);
7847 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7848 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7849 if (fwriteBulkObject(fp
,field
) == -1) return -1;
7850 if (fwriteBulkObject(fp
,val
) == -1) return -1;
7852 dictReleaseIterator(di
);
7857 /* Save the expire time */
7858 if (expiretime
!= -1) {
7859 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
7860 /* If this key is already expired skip it */
7861 if (expiretime
< now
) continue;
7862 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
7863 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
7864 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
7866 if (swapped
) decrRefCount(o
);
7868 dictReleaseIterator(di
);
7871 /* Make sure data will not remain on the OS's output buffers */
7876 /* Use RENAME to make sure the DB file is changed atomically only
7877 * if the generate DB file is ok. */
7878 if (rename(tmpfile
,filename
) == -1) {
7879 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
7883 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
7889 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
7890 if (di
) dictReleaseIterator(di
);
7894 /* This is how rewriting of the append only file in background works:
7896 * 1) The user calls BGREWRITEAOF
7897 * 2) Redis calls this function, that forks():
7898 * 2a) the child rewrite the append only file in a temp file.
7899 * 2b) the parent accumulates differences in server.bgrewritebuf.
7900 * 3) When the child finished '2a' exists.
7901 * 4) The parent will trap the exit code, if it's OK, will append the
7902 * data accumulated into server.bgrewritebuf into the temp file, and
7903 * finally will rename(2) the temp file in the actual file name.
7904 * The the new file is reopened as the new append only file. Profit!
7906 static int rewriteAppendOnlyFileBackground(void) {
7909 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
7910 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
7911 if ((childpid
= fork()) == 0) {
7915 if (server
.vm_enabled
) vmReopenSwapFile();
7917 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
7918 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
7925 if (childpid
== -1) {
7926 redisLog(REDIS_WARNING
,
7927 "Can't rewrite append only file in background: fork: %s",
7931 redisLog(REDIS_NOTICE
,
7932 "Background append only file rewriting started by pid %d",childpid
);
7933 server
.bgrewritechildpid
= childpid
;
7934 /* We set appendseldb to -1 in order to force the next call to the
7935 * feedAppendOnlyFile() to issue a SELECT command, so the differences
7936 * accumulated by the parent into server.bgrewritebuf will start
7937 * with a SELECT statement and it will be safe to merge. */
7938 server
.appendseldb
= -1;
7941 return REDIS_OK
; /* unreached */
7944 static void bgrewriteaofCommand(redisClient
*c
) {
7945 if (server
.bgrewritechildpid
!= -1) {
7946 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
7949 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
7950 char *status
= "+Background append only file rewriting started\r\n";
7951 addReplySds(c
,sdsnew(status
));
7953 addReply(c
,shared
.err
);
7957 static void aofRemoveTempFile(pid_t childpid
) {
7960 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
7964 /* Virtual Memory is composed mainly of two subsystems:
7965 * - Blocking Virutal Memory
7966 * - Threaded Virtual Memory I/O
7967 * The two parts are not fully decoupled, but functions are split among two
7968 * different sections of the source code (delimited by comments) in order to
7969 * make more clear what functionality is about the blocking VM and what about
7970 * the threaded (not blocking) VM.
7974 * Redis VM is a blocking VM (one that blocks reading swapped values from
7975 * disk into memory when a value swapped out is needed in memory) that is made
7976 * unblocking by trying to examine the command argument vector in order to
7977 * load in background values that will likely be needed in order to exec
7978 * the command. The command is executed only once all the relevant keys
7979 * are loaded into memory.
7981 * This basically is almost as simple of a blocking VM, but almost as parallel
7982 * as a fully non-blocking VM.
7985 /* =================== Virtual Memory - Blocking Side ====================== */
7987 /* substitute the first occurrence of '%p' with the process pid in the
7988 * swap file name. */
7989 static void expandVmSwapFilename(void) {
7990 char *p
= strstr(server
.vm_swap_file
,"%p");
7996 new = sdscat(new,server
.vm_swap_file
);
7997 new = sdscatprintf(new,"%ld",(long) getpid());
7998 new = sdscat(new,p
+2);
7999 zfree(server
.vm_swap_file
);
8000 server
.vm_swap_file
= new;
8003 static void vmInit(void) {
8008 if (server
.vm_max_threads
!= 0)
8009 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
8011 expandVmSwapFilename();
8012 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
8013 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
8014 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
8016 if (server
.vm_fp
== NULL
) {
8017 redisLog(REDIS_WARNING
,
8018 "Impossible to open the swap file: %s. Exiting.",
8022 server
.vm_fd
= fileno(server
.vm_fp
);
8023 server
.vm_next_page
= 0;
8024 server
.vm_near_pages
= 0;
8025 server
.vm_stats_used_pages
= 0;
8026 server
.vm_stats_swapped_objects
= 0;
8027 server
.vm_stats_swapouts
= 0;
8028 server
.vm_stats_swapins
= 0;
8029 totsize
= server
.vm_pages
*server
.vm_page_size
;
8030 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
8031 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
8032 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
8036 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
8038 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
8039 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
8040 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
8041 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
8043 /* Initialize threaded I/O (used by Virtual Memory) */
8044 server
.io_newjobs
= listCreate();
8045 server
.io_processing
= listCreate();
8046 server
.io_processed
= listCreate();
8047 server
.io_ready_clients
= listCreate();
8048 pthread_mutex_init(&server
.io_mutex
,NULL
);
8049 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
8050 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
8051 server
.io_active_threads
= 0;
8052 if (pipe(pipefds
) == -1) {
8053 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
8057 server
.io_ready_pipe_read
= pipefds
[0];
8058 server
.io_ready_pipe_write
= pipefds
[1];
8059 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
8060 /* LZF requires a lot of stack */
8061 pthread_attr_init(&server
.io_threads_attr
);
8062 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
8063 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
8064 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
8065 /* Listen for events in the threaded I/O pipe */
8066 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
8067 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
8068 oom("creating file event");
8071 /* Mark the page as used */
8072 static void vmMarkPageUsed(off_t page
) {
8073 off_t byte
= page
/8;
8075 redisAssert(vmFreePage(page
) == 1);
8076 server
.vm_bitmap
[byte
] |= 1<<bit
;
8079 /* Mark N contiguous pages as used, with 'page' being the first. */
8080 static void vmMarkPagesUsed(off_t page
, off_t count
) {
8083 for (j
= 0; j
< count
; j
++)
8084 vmMarkPageUsed(page
+j
);
8085 server
.vm_stats_used_pages
+= count
;
8086 redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n",
8087 (long long)count
, (long long)page
);
8090 /* Mark the page as free */
8091 static void vmMarkPageFree(off_t page
) {
8092 off_t byte
= page
/8;
8094 redisAssert(vmFreePage(page
) == 0);
8095 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
8098 /* Mark N contiguous pages as free, with 'page' being the first. */
8099 static void vmMarkPagesFree(off_t page
, off_t count
) {
8102 for (j
= 0; j
< count
; j
++)
8103 vmMarkPageFree(page
+j
);
8104 server
.vm_stats_used_pages
-= count
;
8105 redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n",
8106 (long long)count
, (long long)page
);
8109 /* Test if the page is free */
8110 static int vmFreePage(off_t page
) {
8111 off_t byte
= page
/8;
8113 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
8116 /* Find N contiguous free pages storing the first page of the cluster in *first.
8117 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
8118 * REDIS_ERR is returned.
8120 * This function uses a simple algorithm: we try to allocate
8121 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
8122 * again from the start of the swap file searching for free spaces.
8124 * If it looks pretty clear that there are no free pages near our offset
8125 * we try to find less populated places doing a forward jump of
8126 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
8127 * without hurry, and then we jump again and so forth...
8129 * This function can be improved using a free list to avoid to guess
8130 * too much, since we could collect data about freed pages.
8132 * note: I implemented this function just after watching an episode of
8133 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
8135 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
8136 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
8138 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
8139 server
.vm_near_pages
= 0;
8140 server
.vm_next_page
= 0;
8142 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
8143 base
= server
.vm_next_page
;
8145 while(offset
< server
.vm_pages
) {
8146 off_t
this = base
+offset
;
8148 /* If we overflow, restart from page zero */
8149 if (this >= server
.vm_pages
) {
8150 this -= server
.vm_pages
;
8152 /* Just overflowed, what we found on tail is no longer
8153 * interesting, as it's no longer contiguous. */
8157 if (vmFreePage(this)) {
8158 /* This is a free page */
8160 /* Already got N free pages? Return to the caller, with success */
8162 *first
= this-(n
-1);
8163 server
.vm_next_page
= this+1;
8164 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
);
8168 /* The current one is not a free page */
8172 /* Fast-forward if the current page is not free and we already
8173 * searched enough near this place. */
8175 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
8176 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
8178 /* Note that even if we rewind after the jump, we are don't need
8179 * to make sure numfree is set to zero as we only jump *if* it
8180 * is set to zero. */
8182 /* Otherwise just check the next page */
8189 /* Write the specified object at the specified page of the swap file */
8190 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
8191 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
8192 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
8193 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8194 redisLog(REDIS_WARNING
,
8195 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
8199 rdbSaveObject(server
.vm_fp
,o
);
8200 fflush(server
.vm_fp
);
8201 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8205 /* Swap the 'val' object relative to 'key' into disk. Store all the information
8206 * needed to later retrieve the object into the key object.
8207 * If we can't find enough contiguous empty pages to swap the object on disk
8208 * REDIS_ERR is returned. */
8209 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
8210 off_t pages
= rdbSavedObjectPages(val
,NULL
);
8213 assert(key
->storage
== REDIS_VM_MEMORY
);
8214 assert(key
->refcount
== 1);
8215 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
8216 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
8217 key
->vm
.page
= page
;
8218 key
->vm
.usedpages
= pages
;
8219 key
->storage
= REDIS_VM_SWAPPED
;
8220 key
->vtype
= val
->type
;
8221 decrRefCount(val
); /* Deallocate the object from memory. */
8222 vmMarkPagesUsed(page
,pages
);
8223 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
8224 (unsigned char*) key
->ptr
,
8225 (unsigned long long) page
, (unsigned long long) pages
);
8226 server
.vm_stats_swapped_objects
++;
8227 server
.vm_stats_swapouts
++;
8231 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
8234 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
8235 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
8236 redisLog(REDIS_WARNING
,
8237 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
8241 o
= rdbLoadObject(type
,server
.vm_fp
);
8243 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
8246 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
8250 /* Load the value object relative to the 'key' object from swap to memory.
8251 * The newly allocated object is returned.
8253 * If preview is true the unserialized object is returned to the caller but
8254 * no changes are made to the key object, nor the pages are marked as freed */
8255 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
8258 redisAssert(key
->storage
== REDIS_VM_SWAPPED
|| key
->storage
== REDIS_VM_LOADING
);
8259 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
8261 key
->storage
= REDIS_VM_MEMORY
;
8262 key
->vm
.atime
= server
.unixtime
;
8263 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
8264 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
8265 (unsigned char*) key
->ptr
);
8266 server
.vm_stats_swapped_objects
--;
8268 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
8269 (unsigned char*) key
->ptr
);
8271 server
.vm_stats_swapins
++;
8275 /* Plain object loading, from swap to memory */
8276 static robj
*vmLoadObject(robj
*key
) {
8277 /* If we are loading the object in background, stop it, we
8278 * need to load this object synchronously ASAP. */
8279 if (key
->storage
== REDIS_VM_LOADING
)
8280 vmCancelThreadedIOJob(key
);
8281 return vmGenericLoadObject(key
,0);
8284 /* Just load the value on disk, without to modify the key.
8285 * This is useful when we want to perform some operation on the value
8286 * without to really bring it from swap to memory, like while saving the
8287 * dataset or rewriting the append only log. */
8288 static robj
*vmPreviewObject(robj
*key
) {
8289 return vmGenericLoadObject(key
,1);
8292 /* How a good candidate is this object for swapping?
8293 * The better candidate it is, the greater the returned value.
8295 * Currently we try to perform a fast estimation of the object size in
8296 * memory, and combine it with aging informations.
8298 * Basically swappability = idle-time * log(estimated size)
8300 * Bigger objects are preferred over smaller objects, but not
8301 * proportionally, this is why we use the logarithm. This algorithm is
8302 * just a first try and will probably be tuned later. */
8303 static double computeObjectSwappability(robj
*o
) {
8304 time_t age
= server
.unixtime
- o
->vm
.atime
;
8308 struct dictEntry
*de
;
8311 if (age
<= 0) return 0;
8314 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
8317 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
8322 listNode
*ln
= listFirst(l
);
8324 asize
= sizeof(list
);
8326 robj
*ele
= ln
->value
;
8329 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
8330 (sizeof(*o
)+sdslen(ele
->ptr
)) :
8332 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
8337 z
= (o
->type
== REDIS_ZSET
);
8338 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
8340 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
8341 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
8346 de
= dictGetRandomKey(d
);
8347 ele
= dictGetEntryKey(de
);
8348 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
8349 (sizeof(*o
)+sdslen(ele
->ptr
)) :
8351 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
8352 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
8356 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
8357 unsigned char *p
= zipmapRewind((unsigned char*)o
->ptr
);
8358 unsigned int len
= zipmapLen((unsigned char*)o
->ptr
);
8359 unsigned int klen
, vlen
;
8360 unsigned char *key
, *val
;
8362 if ((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) == NULL
) {
8366 asize
= len
*(klen
+vlen
+3);
8367 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
8369 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
8374 de
= dictGetRandomKey(d
);
8375 ele
= dictGetEntryKey(de
);
8376 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
8377 (sizeof(*o
)+sdslen(ele
->ptr
)) :
8379 ele
= dictGetEntryVal(de
);
8380 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
8381 (sizeof(*o
)+sdslen(ele
->ptr
)) :
8383 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
8388 return (double)age
*log(1+asize
);
8391 /* Try to swap an object that's a good candidate for swapping.
8392 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
8393 * to swap any object at all.
8395 * If 'usethreaded' is true, Redis will try to swap the object in background
8396 * using I/O threads. */
8397 static int vmSwapOneObject(int usethreads
) {
8399 struct dictEntry
*best
= NULL
;
8400 double best_swappability
= 0;
8401 redisDb
*best_db
= NULL
;
8404 for (j
= 0; j
< server
.dbnum
; j
++) {
8405 redisDb
*db
= server
.db
+j
;
8406 /* Why maxtries is set to 100?
8407 * Because this way (usually) we'll find 1 object even if just 1% - 2%
8408 * are swappable objects */
8411 if (dictSize(db
->dict
) == 0) continue;
8412 for (i
= 0; i
< 5; i
++) {
8414 double swappability
;
8416 if (maxtries
) maxtries
--;
8417 de
= dictGetRandomKey(db
->dict
);
8418 key
= dictGetEntryKey(de
);
8419 val
= dictGetEntryVal(de
);
8420 /* Only swap objects that are currently in memory.
8422 * Also don't swap shared objects if threaded VM is on, as we
8423 * try to ensure that the main thread does not touch the
8424 * object while the I/O thread is using it, but we can't
8425 * control other keys without adding additional mutex. */
8426 if (key
->storage
!= REDIS_VM_MEMORY
||
8427 (server
.vm_max_threads
!= 0 && val
->refcount
!= 1)) {
8428 if (maxtries
) i
--; /* don't count this try */
8431 swappability
= computeObjectSwappability(val
);
8432 if (!best
|| swappability
> best_swappability
) {
8434 best_swappability
= swappability
;
8439 if (best
== NULL
) return REDIS_ERR
;
8440 key
= dictGetEntryKey(best
);
8441 val
= dictGetEntryVal(best
);
8443 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
8444 key
->ptr
, best_swappability
);
8446 /* Unshare the key if needed */
8447 if (key
->refcount
> 1) {
8448 robj
*newkey
= dupStringObject(key
);
8450 key
= dictGetEntryKey(best
) = newkey
;
8454 vmSwapObjectThreaded(key
,val
,best_db
);
8457 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
8458 dictGetEntryVal(best
) = NULL
;
8466 static int vmSwapOneObjectBlocking() {
8467 return vmSwapOneObject(0);
8470 static int vmSwapOneObjectThreaded() {
8471 return vmSwapOneObject(1);
8474 /* Return true if it's safe to swap out objects in a given moment.
8475 * Basically we don't want to swap objects out while there is a BGSAVE
8476 * or a BGAEOREWRITE running in backgroud. */
8477 static int vmCanSwapOut(void) {
8478 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
8481 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
8482 * and was deleted. Otherwise 0 is returned. */
8483 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
8487 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
8488 foundkey
= dictGetEntryKey(de
);
8489 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
8494 /* =================== Virtual Memory - Threaded I/O ======================= */
8496 static void freeIOJob(iojob
*j
) {
8497 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
8498 j
->type
== REDIS_IOJOB_DO_SWAP
||
8499 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
8500 decrRefCount(j
->val
);
8501 decrRefCount(j
->key
);
8505 /* Every time a thread finished a Job, it writes a byte into the write side
8506 * of an unix pipe in order to "awake" the main thread, and this function
8508 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
8512 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
8514 REDIS_NOTUSED(mask
);
8515 REDIS_NOTUSED(privdata
);
8517 /* For every byte we read in the read side of the pipe, there is one
8518 * I/O job completed to process. */
8519 while((retval
= read(fd
,buf
,1)) == 1) {
8523 struct dictEntry
*de
;
8525 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
8527 /* Get the processed element (the oldest one) */
8529 assert(listLength(server
.io_processed
) != 0);
8530 if (toprocess
== -1) {
8531 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
8532 if (toprocess
<= 0) toprocess
= 1;
8534 ln
= listFirst(server
.io_processed
);
8536 listDelNode(server
.io_processed
,ln
);
8538 /* If this job is marked as canceled, just ignore it */
8543 /* Post process it in the main thread, as there are things we
8544 * can do just here to avoid race conditions and/or invasive locks */
8545 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
);
8546 de
= dictFind(j
->db
->dict
,j
->key
);
8548 key
= dictGetEntryKey(de
);
8549 if (j
->type
== REDIS_IOJOB_LOAD
) {
8552 /* Key loaded, bring it at home */
8553 key
->storage
= REDIS_VM_MEMORY
;
8554 key
->vm
.atime
= server
.unixtime
;
8555 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
8556 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
8557 (unsigned char*) key
->ptr
);
8558 server
.vm_stats_swapped_objects
--;
8559 server
.vm_stats_swapins
++;
8560 dictGetEntryVal(de
) = j
->val
;
8561 incrRefCount(j
->val
);
8564 /* Handle clients waiting for this key to be loaded. */
8565 handleClientsBlockedOnSwappedKey(db
,key
);
8566 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
8567 /* Now we know the amount of pages required to swap this object.
8568 * Let's find some space for it, and queue this task again
8569 * rebranded as REDIS_IOJOB_DO_SWAP. */
8570 if (!vmCanSwapOut() ||
8571 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
8573 /* Ooops... no space or we can't swap as there is
8574 * a fork()ed Redis trying to save stuff on disk. */
8576 key
->storage
= REDIS_VM_MEMORY
; /* undo operation */
8578 /* Note that we need to mark this pages as used now,
8579 * if the job will be canceled, we'll mark them as freed
8581 vmMarkPagesUsed(j
->page
,j
->pages
);
8582 j
->type
= REDIS_IOJOB_DO_SWAP
;
8587 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
8590 /* Key swapped. We can finally free some memory. */
8591 if (key
->storage
!= REDIS_VM_SWAPPING
) {
8592 printf("key->storage: %d\n",key
->storage
);
8593 printf("key->name: %s\n",(char*)key
->ptr
);
8594 printf("key->refcount: %d\n",key
->refcount
);
8595 printf("val: %p\n",(void*)j
->val
);
8596 printf("val->type: %d\n",j
->val
->type
);
8597 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
8599 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
8600 val
= dictGetEntryVal(de
);
8601 key
->vm
.page
= j
->page
;
8602 key
->vm
.usedpages
= j
->pages
;
8603 key
->storage
= REDIS_VM_SWAPPED
;
8604 key
->vtype
= j
->val
->type
;
8605 decrRefCount(val
); /* Deallocate the object from memory. */
8606 dictGetEntryVal(de
) = NULL
;
8607 redisLog(REDIS_DEBUG
,
8608 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
8609 (unsigned char*) key
->ptr
,
8610 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
8611 server
.vm_stats_swapped_objects
++;
8612 server
.vm_stats_swapouts
++;
8614 /* Put a few more swap requests in queue if we are still
8616 if (trytoswap
&& vmCanSwapOut() &&
8617 zmalloc_used_memory() > server
.vm_max_memory
)
8622 more
= listLength(server
.io_newjobs
) <
8623 (unsigned) server
.vm_max_threads
;
8625 /* Don't waste CPU time if swappable objects are rare. */
8626 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
8634 if (processed
== toprocess
) return;
8636 if (retval
< 0 && errno
!= EAGAIN
) {
8637 redisLog(REDIS_WARNING
,
8638 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
8643 static void lockThreadedIO(void) {
8644 pthread_mutex_lock(&server
.io_mutex
);
8647 static void unlockThreadedIO(void) {
8648 pthread_mutex_unlock(&server
.io_mutex
);
8651 /* Remove the specified object from the threaded I/O queue if still not
8652 * processed, otherwise make sure to flag it as canceled. */
8653 static void vmCancelThreadedIOJob(robj
*o
) {
8655 server
.io_newjobs
, /* 0 */
8656 server
.io_processing
, /* 1 */
8657 server
.io_processed
/* 2 */
8661 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
8664 /* Search for a matching key in one of the queues */
8665 for (i
= 0; i
< 3; i
++) {
8669 listRewind(lists
[i
],&li
);
8670 while ((ln
= listNext(&li
)) != NULL
) {
8671 iojob
*job
= ln
->value
;
8673 if (job
->canceled
) continue; /* Skip this, already canceled. */
8674 if (compareStringObjects(job
->key
,o
) == 0) {
8675 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
8676 (void*)job
, (char*)o
->ptr
, job
->type
, i
);
8677 /* Mark the pages as free since the swap didn't happened
8678 * or happened but is now discarded. */
8679 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
8680 vmMarkPagesFree(job
->page
,job
->pages
);
8681 /* Cancel the job. It depends on the list the job is
8684 case 0: /* io_newjobs */
8685 /* If the job was yet not processed the best thing to do
8686 * is to remove it from the queue at all */
8688 listDelNode(lists
[i
],ln
);
8690 case 1: /* io_processing */
8691 /* Oh Shi- the thread is messing with the Job:
8693 * Probably it's accessing the object if this is a
8694 * PREPARE_SWAP or DO_SWAP job.
8695 * If it's a LOAD job it may be reading from disk and
8696 * if we don't wait for the job to terminate before to
8697 * cancel it, maybe in a few microseconds data can be
8698 * corrupted in this pages. So the short story is:
8700 * Better to wait for the job to move into the
8701 * next queue (processed)... */
8703 /* We try again and again until the job is completed. */
8705 /* But let's wait some time for the I/O thread
8706 * to finish with this job. After all this condition
8707 * should be very rare. */
8710 case 2: /* io_processed */
8711 /* The job was already processed, that's easy...
8712 * just mark it as canceled so that we'll ignore it
8713 * when processing completed jobs. */
8717 /* Finally we have to adjust the storage type of the object
8718 * in order to "UNDO" the operaiton. */
8719 if (o
->storage
== REDIS_VM_LOADING
)
8720 o
->storage
= REDIS_VM_SWAPPED
;
8721 else if (o
->storage
== REDIS_VM_SWAPPING
)
8722 o
->storage
= REDIS_VM_MEMORY
;
8729 assert(1 != 1); /* We should never reach this */
8732 static void *IOThreadEntryPoint(void *arg
) {
8737 pthread_detach(pthread_self());
8739 /* Get a new job to process */
8741 if (listLength(server
.io_newjobs
) == 0) {
8742 /* No new jobs in queue, exit. */
8743 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
8744 (long) pthread_self());
8745 server
.io_active_threads
--;
8749 ln
= listFirst(server
.io_newjobs
);
8751 listDelNode(server
.io_newjobs
,ln
);
8752 /* Add the job in the processing queue */
8753 j
->thread
= pthread_self();
8754 listAddNodeTail(server
.io_processing
,j
);
8755 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
8757 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
8758 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
8760 /* Process the Job */
8761 if (j
->type
== REDIS_IOJOB_LOAD
) {
8762 j
->val
= vmReadObjectFromSwap(j
->page
,j
->key
->vtype
);
8763 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
8764 FILE *fp
= fopen("/dev/null","w+");
8765 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
8767 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
8768 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
8772 /* Done: insert the job into the processed queue */
8773 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
8774 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
8776 listDelNode(server
.io_processing
,ln
);
8777 listAddNodeTail(server
.io_processed
,j
);
8780 /* Signal the main thread there is new stuff to process */
8781 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
8783 return NULL
; /* never reached */
8786 static void spawnIOThread(void) {
8788 sigset_t mask
, omask
;
8792 sigaddset(&mask
,SIGCHLD
);
8793 sigaddset(&mask
,SIGHUP
);
8794 sigaddset(&mask
,SIGPIPE
);
8795 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
8796 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
8797 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
8801 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
8802 server
.io_active_threads
++;
8805 /* We need to wait for the last thread to exit before we are able to
8806 * fork() in order to BGSAVE or BGREWRITEAOF. */
8807 static void waitEmptyIOJobsQueue(void) {
8809 int io_processed_len
;
8812 if (listLength(server
.io_newjobs
) == 0 &&
8813 listLength(server
.io_processing
) == 0 &&
8814 server
.io_active_threads
== 0)
8819 /* While waiting for empty jobs queue condition we post-process some
8820 * finshed job, as I/O threads may be hanging trying to write against
8821 * the io_ready_pipe_write FD but there are so much pending jobs that
8823 io_processed_len
= listLength(server
.io_processed
);
8825 if (io_processed_len
) {
8826 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,NULL
,0);
8827 usleep(1000); /* 1 millisecond */
8829 usleep(10000); /* 10 milliseconds */
8834 static void vmReopenSwapFile(void) {
8835 /* Note: we don't close the old one as we are in the child process
8836 * and don't want to mess at all with the original file object. */
8837 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
8838 if (server
.vm_fp
== NULL
) {
8839 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
8840 server
.vm_swap_file
);
8843 server
.vm_fd
= fileno(server
.vm_fp
);
8846 /* This function must be called while with threaded IO locked */
8847 static void queueIOJob(iojob
*j
) {
8848 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
8849 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
8850 listAddNodeTail(server
.io_newjobs
,j
);
8851 if (server
.io_active_threads
< server
.vm_max_threads
)
8855 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
8858 assert(key
->storage
== REDIS_VM_MEMORY
);
8859 assert(key
->refcount
== 1);
8861 j
= zmalloc(sizeof(*j
));
8862 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
8864 j
->key
= dupStringObject(key
);
8868 j
->thread
= (pthread_t
) -1;
8869 key
->storage
= REDIS_VM_SWAPPING
;
8877 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
8879 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
8880 * If there is not already a job loading the key, it is craeted.
8881 * The key is added to the io_keys list in the client structure, and also
8882 * in the hash table mapping swapped keys to waiting clients, that is,
8883 * server.io_waited_keys. */
8884 static int waitForSwappedKey(redisClient
*c
, robj
*key
) {
8885 struct dictEntry
*de
;
8889 /* If the key does not exist or is already in RAM we don't need to
8890 * block the client at all. */
8891 de
= dictFind(c
->db
->dict
,key
);
8892 if (de
== NULL
) return 0;
8893 o
= dictGetEntryKey(de
);
8894 if (o
->storage
== REDIS_VM_MEMORY
) {
8896 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
8897 /* We were swapping the key, undo it! */
8898 vmCancelThreadedIOJob(o
);
8902 /* OK: the key is either swapped, or being loaded just now. */
8904 /* Add the key to the list of keys this client is waiting for.
8905 * This maps clients to keys they are waiting for. */
8906 listAddNodeTail(c
->io_keys
,key
);
8909 /* Add the client to the swapped keys => clients waiting map. */
8910 de
= dictFind(c
->db
->io_keys
,key
);
8914 /* For every key we take a list of clients blocked for it */
8916 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
8918 assert(retval
== DICT_OK
);
8920 l
= dictGetEntryVal(de
);
8922 listAddNodeTail(l
,c
);
8924 /* Are we already loading the key from disk? If not create a job */
8925 if (o
->storage
== REDIS_VM_SWAPPED
) {
8928 o
->storage
= REDIS_VM_LOADING
;
8929 j
= zmalloc(sizeof(*j
));
8930 j
->type
= REDIS_IOJOB_LOAD
;
8932 j
->key
= dupStringObject(key
);
8933 j
->key
->vtype
= o
->vtype
;
8934 j
->page
= o
->vm
.page
;
8937 j
->thread
= (pthread_t
) -1;
8945 /* Preload keys needed for the ZUNION and ZINTER commands. */
8946 static void zunionInterBlockClientOnSwappedKeys(redisClient
*c
) {
8948 num
= atoi(c
->argv
[2]->ptr
);
8949 for (i
= 0; i
< num
; i
++) {
8950 waitForSwappedKey(c
,c
->argv
[3+i
]);
8954 /* Is this client attempting to run a command against swapped keys?
8955 * If so, block it ASAP, load the keys in background, then resume it.
8957 * The important idea about this function is that it can fail! If keys will
8958 * still be swapped when the client is resumed, this key lookups will
8959 * just block loading keys from disk. In practical terms this should only
8960 * happen with SORT BY command or if there is a bug in this function.
8962 * Return 1 if the client is marked as blocked, 0 if the client can
8963 * continue as the keys it is going to access appear to be in memory. */
8964 static int blockClientOnSwappedKeys(struct redisCommand
*cmd
, redisClient
*c
) {
8967 if (cmd
->vm_preload_proc
!= NULL
) {
8968 cmd
->vm_preload_proc(c
);
8970 if (cmd
->vm_firstkey
== 0) return 0;
8971 last
= cmd
->vm_lastkey
;
8972 if (last
< 0) last
= c
->argc
+last
;
8973 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
)
8974 waitForSwappedKey(c
,c
->argv
[j
]);
8977 /* If the client was blocked for at least one key, mark it as blocked. */
8978 if (listLength(c
->io_keys
)) {
8979 c
->flags
|= REDIS_IO_WAIT
;
8980 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
8981 server
.vm_blocked_clients
++;
8988 /* Remove the 'key' from the list of blocked keys for a given client.
8990 * The function returns 1 when there are no longer blocking keys after
8991 * the current one was removed (and the client can be unblocked). */
8992 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
8996 struct dictEntry
*de
;
8998 /* Remove the key from the list of keys this client is waiting for. */
8999 listRewind(c
->io_keys
,&li
);
9000 while ((ln
= listNext(&li
)) != NULL
) {
9001 if (compareStringObjects(ln
->value
,key
) == 0) {
9002 listDelNode(c
->io_keys
,ln
);
9008 /* Remove the client form the key => waiting clients map. */
9009 de
= dictFind(c
->db
->io_keys
,key
);
9011 l
= dictGetEntryVal(de
);
9012 ln
= listSearchKey(l
,c
);
9015 if (listLength(l
) == 0)
9016 dictDelete(c
->db
->io_keys
,key
);
9018 return listLength(c
->io_keys
) == 0;
9021 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
9022 struct dictEntry
*de
;
9027 de
= dictFind(db
->io_keys
,key
);
9030 l
= dictGetEntryVal(de
);
9031 len
= listLength(l
);
9032 /* Note: we can't use something like while(listLength(l)) as the list
9033 * can be freed by the calling function when we remove the last element. */
9036 redisClient
*c
= ln
->value
;
9038 if (dontWaitForSwappedKey(c
,key
)) {
9039 /* Put the client in the list of clients ready to go as we
9040 * loaded all the keys about it. */
9041 listAddNodeTail(server
.io_ready_clients
,c
);
9046 /* ================================= Debugging ============================== */
9048 static void debugCommand(redisClient
*c
) {
9049 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
9051 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
9052 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
9053 addReply(c
,shared
.err
);
9057 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
9058 addReply(c
,shared
.err
);
9061 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
9062 addReply(c
,shared
.ok
);
9063 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
9065 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
9066 addReply(c
,shared
.err
);
9069 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
9070 addReply(c
,shared
.ok
);
9071 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
9072 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
9076 addReply(c
,shared
.nokeyerr
);
9079 key
= dictGetEntryKey(de
);
9080 val
= dictGetEntryVal(de
);
9081 if (!server
.vm_enabled
|| (key
->storage
== REDIS_VM_MEMORY
||
9082 key
->storage
== REDIS_VM_SWAPPING
)) {
9086 if (val
->encoding
< (sizeof(strencoding
)/sizeof(char*))) {
9087 strenc
= strencoding
[val
->encoding
];
9089 snprintf(buf
,64,"unknown encoding %d\n", val
->encoding
);
9092 addReplySds(c
,sdscatprintf(sdsempty(),
9093 "+Key at:%p refcount:%d, value at:%p refcount:%d "
9094 "encoding:%s serializedlength:%lld\r\n",
9095 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
9096 strenc
, (long long) rdbSavedObjectLen(val
,NULL
)));
9098 addReplySds(c
,sdscatprintf(sdsempty(),
9099 "+Key at:%p refcount:%d, value swapped at: page %llu "
9100 "using %llu pages\r\n",
9101 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
9102 (unsigned long long) key
->vm
.usedpages
));
9104 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
9105 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
9108 if (!server
.vm_enabled
) {
9109 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
9113 addReply(c
,shared
.nokeyerr
);
9116 key
= dictGetEntryKey(de
);
9117 val
= dictGetEntryVal(de
);
9118 /* If the key is shared we want to create a copy */
9119 if (key
->refcount
> 1) {
9120 robj
*newkey
= dupStringObject(key
);
9122 key
= dictGetEntryKey(de
) = newkey
;
9125 if (key
->storage
!= REDIS_VM_MEMORY
) {
9126 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
9127 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
9128 dictGetEntryVal(de
) = NULL
;
9129 addReply(c
,shared
.ok
);
9131 addReply(c
,shared
.err
);
9134 addReplySds(c
,sdsnew(
9135 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPOUT <key>|RELOAD]\r\n"));
9139 static void _redisAssert(char *estr
, char *file
, int line
) {
9140 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
9141 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true\n",file
,line
,estr
);
9142 #ifdef HAVE_BACKTRACE
9143 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
9148 /* =================================== Main! ================================ */
9151 int linuxOvercommitMemoryValue(void) {
9152 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
9156 if (fgets(buf
,64,fp
) == NULL
) {
9165 void linuxOvercommitMemoryWarning(void) {
9166 if (linuxOvercommitMemoryValue() == 0) {
9167 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.");
9170 #endif /* __linux__ */
9172 static void daemonize(void) {
9176 if (fork() != 0) exit(0); /* parent exits */
9177 setsid(); /* create a new session */
9179 /* Every output goes to /dev/null. If Redis is daemonized but
9180 * the 'logfile' is set to 'stdout' in the configuration file
9181 * it will not log at all. */
9182 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
9183 dup2(fd
, STDIN_FILENO
);
9184 dup2(fd
, STDOUT_FILENO
);
9185 dup2(fd
, STDERR_FILENO
);
9186 if (fd
> STDERR_FILENO
) close(fd
);
9188 /* Try to write the pid file */
9189 fp
= fopen(server
.pidfile
,"w");
9191 fprintf(fp
,"%d\n",getpid());
9196 static void version() {
9197 printf("Redis server version %s\n", REDIS_VERSION
);
9201 static void usage() {
9202 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
9203 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
9207 int main(int argc
, char **argv
) {
9212 if (strcmp(argv
[1], "-v") == 0 ||
9213 strcmp(argv
[1], "--version") == 0) version();
9214 if (strcmp(argv
[1], "--help") == 0) usage();
9215 resetServerSaveParams();
9216 loadServerConfig(argv
[1]);
9217 } else if ((argc
> 2)) {
9220 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'");
9222 if (server
.daemonize
) daemonize();
9224 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
9226 linuxOvercommitMemoryWarning();
9229 if (server
.appendonly
) {
9230 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
9231 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
9233 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
9234 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
9236 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
9237 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
9239 aeDeleteEventLoop(server
.el
);
9243 /* ============================= Backtrace support ========================= */
9245 #ifdef HAVE_BACKTRACE
9246 static char *findFuncName(void *pointer
, unsigned long *offset
);
9248 static void *getMcontextEip(ucontext_t
*uc
) {
9249 #if defined(__FreeBSD__)
9250 return (void*) uc
->uc_mcontext
.mc_eip
;
9251 #elif defined(__dietlibc__)
9252 return (void*) uc
->uc_mcontext
.eip
;
9253 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
9255 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
9257 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
9259 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
9260 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
9261 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
9263 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
9265 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
9266 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
9267 #elif defined(__ia64__) /* Linux IA64 */
9268 return (void*) uc
->uc_mcontext
.sc_ip
;
9274 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
9276 char **messages
= NULL
;
9277 int i
, trace_size
= 0;
9278 unsigned long offset
=0;
9279 ucontext_t
*uc
= (ucontext_t
*) secret
;
9281 REDIS_NOTUSED(info
);
9283 redisLog(REDIS_WARNING
,
9284 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
9285 infostring
= genRedisInfoString();
9286 redisLog(REDIS_WARNING
, "%s",infostring
);
9287 /* It's not safe to sdsfree() the returned string under memory
9288 * corruption conditions. Let it leak as we are going to abort */
9290 trace_size
= backtrace(trace
, 100);
9291 /* overwrite sigaction with caller's address */
9292 if (getMcontextEip(uc
) != NULL
) {
9293 trace
[1] = getMcontextEip(uc
);
9295 messages
= backtrace_symbols(trace
, trace_size
);
9297 for (i
=1; i
<trace_size
; ++i
) {
9298 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
9300 p
= strchr(messages
[i
],'+');
9301 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
9302 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
9304 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
9307 /* free(messages); Don't call free() with possibly corrupted memory. */
9311 static void setupSigSegvAction(void) {
9312 struct sigaction act
;
9314 sigemptyset (&act
.sa_mask
);
9315 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
9316 * is used. Otherwise, sa_handler is used */
9317 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
9318 act
.sa_sigaction
= segvHandler
;
9319 sigaction (SIGSEGV
, &act
, NULL
);
9320 sigaction (SIGBUS
, &act
, NULL
);
9321 sigaction (SIGFPE
, &act
, NULL
);
9322 sigaction (SIGILL
, &act
, NULL
);
9323 sigaction (SIGBUS
, &act
, NULL
);
9327 #include "staticsymbols.h"
9328 /* This function try to convert a pointer into a function name. It's used in
9329 * oreder to provide a backtrace under segmentation fault that's able to
9330 * display functions declared as static (otherwise the backtrace is useless). */
9331 static char *findFuncName(void *pointer
, unsigned long *offset
){
9333 unsigned long off
, minoff
= 0;
9335 /* Try to match against the Symbol with the smallest offset */
9336 for (i
=0; symsTable
[i
].pointer
; i
++) {
9337 unsigned long lp
= (unsigned long) pointer
;
9339 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
9340 off
=lp
-symsTable
[i
].pointer
;
9341 if (ret
< 0 || off
< minoff
) {
9347 if (ret
== -1) return NULL
;
9349 return symsTable
[ret
].name
;
9351 #else /* HAVE_BACKTRACE */
9352 static void setupSigSegvAction(void) {
9354 #endif /* HAVE_BACKTRACE */