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 "2.1.1"
45 #endif /* HAVE_BACKTRACE */
53 #include <arpa/inet.h>
57 #include <sys/resource.h>
65 #include "solarisfixes.h"
69 #include "ae.h" /* Event driven programming library */
70 #include "sds.h" /* Dynamic safe strings */
71 #include "anet.h" /* Networking the easy way */
72 #include "dict.h" /* Hash tables */
73 #include "adlist.h" /* Linked lists */
74 #include "zmalloc.h" /* total memory usage aware version of malloc/free */
75 #include "lzf.h" /* LZF compression library */
76 #include "pqsort.h" /* Partial qsort for SORT+LIMIT */
77 #include "zipmap.h" /* Compact dictionary-alike data structure */
78 #include "ziplist.h" /* Compact list data structure */
79 #include "sha1.h" /* SHA1 is used for DEBUG DIGEST */
80 #include "release.h" /* Release and/or git repository information */
86 /* Static server configuration */
87 #define REDIS_SERVERPORT 6379 /* TCP port */
88 #define REDIS_MAXIDLETIME (60*5) /* default client timeout */
89 #define REDIS_IOBUF_LEN 1024
90 #define REDIS_LOADBUF_LEN 1024
91 #define REDIS_STATIC_ARGS 8
92 #define REDIS_DEFAULT_DBNUM 16
93 #define REDIS_CONFIGLINE_MAX 1024
94 #define REDIS_OBJFREELIST_MAX 1000000 /* Max number of objects to cache */
95 #define REDIS_MAX_SYNC_TIME 60 /* Slave can't take more to sync */
96 #define REDIS_EXPIRELOOKUPS_PER_CRON 10 /* lookup 10 expires per loop */
97 #define REDIS_MAX_WRITE_PER_EVENT (1024*64)
98 #define REDIS_REQUEST_MAX_SIZE (1024*1024*256) /* max bytes in inline command */
100 /* If more then REDIS_WRITEV_THRESHOLD write packets are pending use writev */
101 #define REDIS_WRITEV_THRESHOLD 3
102 /* Max number of iovecs used for each writev call */
103 #define REDIS_WRITEV_IOVEC_COUNT 256
105 /* Hash table parameters */
106 #define REDIS_HT_MINFILL 10 /* Minimal hash table fill 10% */
109 #define REDIS_CMD_BULK 1 /* Bulk write command */
110 #define REDIS_CMD_INLINE 2 /* Inline command */
111 /* REDIS_CMD_DENYOOM reserves a longer comment: all the commands marked with
112 this flags will return an error when the 'maxmemory' option is set in the
113 config file and the server is using more than maxmemory bytes of memory.
114 In short this commands are denied on low memory conditions. */
115 #define REDIS_CMD_DENYOOM 4
116 #define REDIS_CMD_FORCE_REPLICATION 8 /* Force replication even if dirty is 0 */
119 #define REDIS_STRING 0
125 /* Objects encoding. Some kind of objects like Strings and Hashes can be
126 * internally represented in multiple ways. The 'encoding' field of the object
127 * is set to one of this fields for this object. */
128 #define REDIS_ENCODING_RAW 0 /* Raw representation */
129 #define REDIS_ENCODING_INT 1 /* Encoded as integer */
130 #define REDIS_ENCODING_HT 2 /* Encoded as hash table */
131 #define REDIS_ENCODING_ZIPMAP 3 /* Encoded as zipmap */
132 #define REDIS_ENCODING_LIST 4 /* Encoded as zipmap */
133 #define REDIS_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
135 static char* strencoding
[] = {
136 "raw", "int", "zipmap", "hashtable"
139 /* Object types only used for dumping to disk */
140 #define REDIS_EXPIRETIME 253
141 #define REDIS_SELECTDB 254
142 #define REDIS_EOF 255
144 /* Defines related to the dump file format. To store 32 bits lengths for short
145 * keys requires a lot of space, so we check the most significant 2 bits of
146 * the first byte to interpreter the length:
148 * 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
149 * 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
150 * 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
151 * 11|000000 this means: specially encoded object will follow. The six bits
152 * number specify the kind of object that follows.
153 * See the REDIS_RDB_ENC_* defines.
155 * Lenghts up to 63 are stored using a single byte, most DB keys, and may
156 * values, will fit inside. */
157 #define REDIS_RDB_6BITLEN 0
158 #define REDIS_RDB_14BITLEN 1
159 #define REDIS_RDB_32BITLEN 2
160 #define REDIS_RDB_ENCVAL 3
161 #define REDIS_RDB_LENERR UINT_MAX
163 /* When a length of a string object stored on disk has the first two bits
164 * set, the remaining two bits specify a special encoding for the object
165 * accordingly to the following defines: */
166 #define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
167 #define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
168 #define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
169 #define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
171 /* Virtual memory object->where field. */
172 #define REDIS_VM_MEMORY 0 /* The object is on memory */
173 #define REDIS_VM_SWAPPED 1 /* The object is on disk */
174 #define REDIS_VM_SWAPPING 2 /* Redis is swapping this object on disk */
175 #define REDIS_VM_LOADING 3 /* Redis is loading this object from disk */
177 /* Virtual memory static configuration stuff.
178 * Check vmFindContiguousPages() to know more about this magic numbers. */
179 #define REDIS_VM_MAX_NEAR_PAGES 65536
180 #define REDIS_VM_MAX_RANDOM_JUMP 4096
181 #define REDIS_VM_MAX_THREADS 32
182 #define REDIS_THREAD_STACK_SIZE (1024*1024*4)
183 /* The following is the *percentage* of completed I/O jobs to process when the
184 * handelr is called. While Virtual Memory I/O operations are performed by
185 * threads, this operations must be processed by the main thread when completed
186 * in order to take effect. */
187 #define REDIS_MAX_COMPLETED_JOBS_PROCESSED 1
190 #define REDIS_SLAVE 1 /* This client is a slave server */
191 #define REDIS_MASTER 2 /* This client is a master server */
192 #define REDIS_MONITOR 4 /* This client is a slave monitor, see MONITOR */
193 #define REDIS_MULTI 8 /* This client is in a MULTI context */
194 #define REDIS_BLOCKED 16 /* The client is waiting in a blocking operation */
195 #define REDIS_IO_WAIT 32 /* The client is waiting for Virtual Memory I/O */
196 #define REDIS_DIRTY_CAS 64 /* Watched keys modified. EXEC will fail. */
198 /* Slave replication state - slave side */
199 #define REDIS_REPL_NONE 0 /* No active replication */
200 #define REDIS_REPL_CONNECT 1 /* Must connect to master */
201 #define REDIS_REPL_CONNECTED 2 /* Connected to master */
203 /* Slave replication state - from the point of view of master
204 * Note that in SEND_BULK and ONLINE state the slave receives new updates
205 * in its output queue. In the WAIT_BGSAVE state instead the server is waiting
206 * to start the next background saving in order to send updates to it. */
207 #define REDIS_REPL_WAIT_BGSAVE_START 3 /* master waits bgsave to start feeding it */
208 #define REDIS_REPL_WAIT_BGSAVE_END 4 /* master waits bgsave to start bulk DB transmission */
209 #define REDIS_REPL_SEND_BULK 5 /* master is sending the bulk DB */
210 #define REDIS_REPL_ONLINE 6 /* bulk DB already transmitted, receive updates */
212 /* List related stuff */
216 /* Sort operations */
217 #define REDIS_SORT_GET 0
218 #define REDIS_SORT_ASC 1
219 #define REDIS_SORT_DESC 2
220 #define REDIS_SORTKEY_MAX 1024
223 #define REDIS_DEBUG 0
224 #define REDIS_VERBOSE 1
225 #define REDIS_NOTICE 2
226 #define REDIS_WARNING 3
228 /* Anti-warning macro... */
229 #define REDIS_NOTUSED(V) ((void) V)
231 #define ZSKIPLIST_MAXLEVEL 32 /* Should be enough for 2^32 elements */
232 #define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
234 /* Append only defines */
235 #define APPENDFSYNC_NO 0
236 #define APPENDFSYNC_ALWAYS 1
237 #define APPENDFSYNC_EVERYSEC 2
239 /* Hashes related defaults */
240 #define REDIS_HASH_MAX_ZIPMAP_ENTRIES 64
241 #define REDIS_HASH_MAX_ZIPMAP_VALUE 512
243 /* We can print the stacktrace, so our assert is defined this way: */
244 #define redisAssert(_e) ((_e)?(void)0 : (_redisAssert(#_e,__FILE__,__LINE__),_exit(1)))
245 #define redisPanic(_e) _redisPanic(#_e,__FILE__,__LINE__),_exit(1)
246 static void _redisAssert(char *estr
, char *file
, int line
);
247 static void _redisPanic(char *msg
, char *file
, int line
);
249 /*================================= Data types ============================== */
251 /* A redis object, that is a type able to hold a string / list / set */
253 /* The VM object structure */
254 struct redisObjectVM
{
255 off_t page
; /* the page at witch the object is stored on disk */
256 off_t usedpages
; /* number of pages used on disk */
257 time_t atime
; /* Last access time */
260 /* The actual Redis Object */
261 typedef struct redisObject
{
264 unsigned char encoding
;
265 unsigned char storage
; /* If this object is a key, where is the value?
266 * REDIS_VM_MEMORY, REDIS_VM_SWAPPED, ... */
267 unsigned char vtype
; /* If this object is a key, and value is swapped out,
268 * this is the type of the swapped out object. */
270 /* VM fields, this are only allocated if VM is active, otherwise the
271 * object allocation function will just allocate
272 * sizeof(redisObjct) minus sizeof(redisObjectVM), so using
273 * Redis without VM active will not have any overhead. */
274 struct redisObjectVM vm
;
277 /* Macro used to initalize a Redis object allocated on the stack.
278 * Note that this macro is taken near the structure definition to make sure
279 * we'll update it when the structure is changed, to avoid bugs like
280 * bug #85 introduced exactly in this way. */
281 #define initStaticStringObject(_var,_ptr) do { \
283 _var.type = REDIS_STRING; \
284 _var.encoding = REDIS_ENCODING_RAW; \
286 if (server.vm_enabled) _var.storage = REDIS_VM_MEMORY; \
289 typedef struct redisDb
{
290 dict
*dict
; /* The keyspace for this DB */
291 dict
*expires
; /* Timeout of keys with a timeout set */
292 dict
*blocking_keys
; /* Keys with clients waiting for data (BLPOP) */
293 dict
*io_keys
; /* Keys with clients waiting for VM I/O */
294 dict
*watched_keys
; /* WATCHED keys for MULTI/EXEC CAS */
298 /* Client MULTI/EXEC state */
299 typedef struct multiCmd
{
302 struct redisCommand
*cmd
;
305 typedef struct multiState
{
306 multiCmd
*commands
; /* Array of MULTI commands */
307 int count
; /* Total number of MULTI commands */
310 /* With multiplexing we need to take per-clinet state.
311 * Clients are taken in a liked list. */
312 typedef struct redisClient
{
317 robj
**argv
, **mbargv
;
319 int bulklen
; /* bulk read len. -1 if not in bulk read mode */
320 int multibulk
; /* multi bulk command format active */
323 time_t lastinteraction
; /* time of the last interaction, used for timeout */
324 int flags
; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
325 int slaveseldb
; /* slave selected db, if this client is a slave */
326 int authenticated
; /* when requirepass is non-NULL */
327 int replstate
; /* replication state if this is a slave */
328 int repldbfd
; /* replication DB file descriptor */
329 long repldboff
; /* replication DB file offset */
330 off_t repldbsize
; /* replication DB file size */
331 multiState mstate
; /* MULTI/EXEC state */
332 robj
**blocking_keys
; /* The key we are waiting to terminate a blocking
333 * operation such as BLPOP. Otherwise NULL. */
334 int blocking_keys_num
; /* Number of blocking keys */
335 time_t blockingto
; /* Blocking operation timeout. If UNIX current time
336 * is >= blockingto then the operation timed out. */
337 list
*io_keys
; /* Keys this client is waiting to be loaded from the
338 * swap file in order to continue. */
339 list
*watched_keys
; /* Keys WATCHED for MULTI/EXEC CAS */
340 dict
*pubsub_channels
; /* channels a client is interested in (SUBSCRIBE) */
341 list
*pubsub_patterns
; /* patterns a client is interested in (SUBSCRIBE) */
349 /* Global server state structure */
354 long long dirty
; /* changes to DB from the last save */
356 list
*slaves
, *monitors
;
357 char neterr
[ANET_ERR_LEN
];
359 int cronloops
; /* number of times the cron function run */
360 list
*objfreelist
; /* A list of freed objects to avoid malloc() */
361 time_t lastsave
; /* Unix time of last save succeeede */
362 /* Fields used only for stats */
363 time_t stat_starttime
; /* server start time */
364 long long stat_numcommands
; /* number of processed commands */
365 long long stat_numconnections
; /* number of connections received */
366 long long stat_expiredkeys
; /* number of expired keys */
380 pid_t bgsavechildpid
;
381 pid_t bgrewritechildpid
;
382 sds bgrewritebuf
; /* buffer taken by parent during oppend only rewrite */
383 sds aofbuf
; /* AOF buffer, written before entering the event loop */
384 struct saveparam
*saveparams
;
389 char *appendfilename
;
393 /* Replication related */
398 redisClient
*master
; /* client that is master for this slave */
400 unsigned int maxclients
;
401 unsigned long long maxmemory
;
402 unsigned int blpop_blocked_clients
;
403 unsigned int vm_blocked_clients
;
404 /* Sort parameters - qsort_r() is only available under BSD so we
405 * have to take this state global, in order to pass it to sortCompare() */
409 /* Virtual memory configuration */
414 unsigned long long vm_max_memory
;
416 size_t hash_max_zipmap_entries
;
417 size_t hash_max_zipmap_value
;
418 /* Virtual memory state */
421 off_t vm_next_page
; /* Next probably empty page */
422 off_t vm_near_pages
; /* Number of pages allocated sequentially */
423 unsigned char *vm_bitmap
; /* Bitmap of free/used pages */
424 time_t unixtime
; /* Unix time sampled every second. */
425 /* Virtual memory I/O threads stuff */
426 /* An I/O thread process an element taken from the io_jobs queue and
427 * put the result of the operation in the io_done list. While the
428 * job is being processed, it's put on io_processing queue. */
429 list
*io_newjobs
; /* List of VM I/O jobs yet to be processed */
430 list
*io_processing
; /* List of VM I/O jobs being processed */
431 list
*io_processed
; /* List of VM I/O jobs already processed */
432 list
*io_ready_clients
; /* Clients ready to be unblocked. All keys loaded */
433 pthread_mutex_t io_mutex
; /* lock to access io_jobs/io_done/io_thread_job */
434 pthread_mutex_t obj_freelist_mutex
; /* safe redis objects creation/free */
435 pthread_mutex_t io_swapfile_mutex
; /* So we can lseek + write */
436 pthread_attr_t io_threads_attr
; /* attributes for threads creation */
437 int io_active_threads
; /* Number of running I/O threads */
438 int vm_max_threads
; /* Max number of I/O threads running at the same time */
439 /* Our main thread is blocked on the event loop, locking for sockets ready
440 * to be read or written, so when a threaded I/O operation is ready to be
441 * processed by the main thread, the I/O thread will use a unix pipe to
442 * awake the main thread. The followings are the two pipe FDs. */
443 int io_ready_pipe_read
;
444 int io_ready_pipe_write
;
445 /* Virtual memory stats */
446 unsigned long long vm_stats_used_pages
;
447 unsigned long long vm_stats_swapped_objects
;
448 unsigned long long vm_stats_swapouts
;
449 unsigned long long vm_stats_swapins
;
451 dict
*pubsub_channels
; /* Map channels to list of subscribed clients */
452 list
*pubsub_patterns
; /* A list of pubsub_patterns */
457 typedef struct pubsubPattern
{
462 typedef void redisCommandProc(redisClient
*c
);
463 typedef void redisVmPreloadProc(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
464 struct redisCommand
{
466 redisCommandProc
*proc
;
469 /* Use a function to determine which keys need to be loaded
470 * in the background prior to executing this command. Takes precedence
471 * over vm_firstkey and others, ignored when NULL */
472 redisVmPreloadProc
*vm_preload_proc
;
473 /* What keys should be loaded in background when calling this command? */
474 int vm_firstkey
; /* The first argument that's a key (0 = no keys) */
475 int vm_lastkey
; /* THe last argument that's a key */
476 int vm_keystep
; /* The step between first and last key */
479 struct redisFunctionSym
{
481 unsigned long pointer
;
484 typedef struct _redisSortObject
{
492 typedef struct _redisSortOperation
{
495 } redisSortOperation
;
497 /* ZSETs use a specialized version of Skiplists */
499 typedef struct zskiplistNode
{
500 struct zskiplistNode
**forward
;
501 struct zskiplistNode
*backward
;
507 typedef struct zskiplist
{
508 struct zskiplistNode
*header
, *tail
;
509 unsigned long length
;
513 typedef struct zset
{
518 /* Our shared "common" objects */
520 #define REDIS_SHARED_INTEGERS 10000
521 struct sharedObjectsStruct
{
522 robj
*crlf
, *ok
, *err
, *emptybulk
, *czero
, *cone
, *pong
, *space
,
523 *colon
, *nullbulk
, *nullmultibulk
, *queued
,
524 *emptymultibulk
, *wrongtypeerr
, *nokeyerr
, *syntaxerr
, *sameobjecterr
,
525 *outofrangeerr
, *plus
,
526 *select0
, *select1
, *select2
, *select3
, *select4
,
527 *select5
, *select6
, *select7
, *select8
, *select9
,
528 *messagebulk
, *pmessagebulk
, *subscribebulk
, *unsubscribebulk
, *mbulk3
,
529 *mbulk4
, *psubscribebulk
, *punsubscribebulk
,
530 *integers
[REDIS_SHARED_INTEGERS
];
533 /* Global vars that are actally used as constants. The following double
534 * values are used for double on-disk serialization, and are initialized
535 * at runtime to avoid strange compiler optimizations. */
537 static double R_Zero
, R_PosInf
, R_NegInf
, R_Nan
;
539 /* VM threaded I/O request message */
540 #define REDIS_IOJOB_LOAD 0 /* Load from disk to memory */
541 #define REDIS_IOJOB_PREPARE_SWAP 1 /* Compute needed pages */
542 #define REDIS_IOJOB_DO_SWAP 2 /* Swap from memory to disk */
543 typedef struct iojob
{
544 int type
; /* Request type, REDIS_IOJOB_* */
545 redisDb
*db
;/* Redis database */
546 robj
*key
; /* This I/O request is about swapping this key */
547 robj
*val
; /* the value to swap for REDIS_IOREQ_*_SWAP, otherwise this
548 * field is populated by the I/O thread for REDIS_IOREQ_LOAD. */
549 off_t page
; /* Swap page where to read/write the object */
550 off_t pages
; /* Swap pages needed to save object. PREPARE_SWAP return val */
551 int canceled
; /* True if this command was canceled by blocking side of VM */
552 pthread_t thread
; /* ID of the thread processing this entry */
555 /*================================ Prototypes =============================== */
557 static void freeStringObject(robj
*o
);
558 static void freeListObject(robj
*o
);
559 static void freeSetObject(robj
*o
);
560 static void decrRefCount(void *o
);
561 static robj
*createObject(int type
, void *ptr
);
562 static void freeClient(redisClient
*c
);
563 static int rdbLoad(char *filename
);
564 static void addReply(redisClient
*c
, robj
*obj
);
565 static void addReplySds(redisClient
*c
, sds s
);
566 static void incrRefCount(robj
*o
);
567 static int rdbSaveBackground(char *filename
);
568 static robj
*createStringObject(char *ptr
, size_t len
);
569 static robj
*dupStringObject(robj
*o
);
570 static void replicationFeedSlaves(list
*slaves
, int dictid
, robj
**argv
, int argc
);
571 static void replicationFeedMonitors(list
*monitors
, int dictid
, robj
**argv
, int argc
);
572 static void flushAppendOnlyFile(void);
573 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
);
574 static int syncWithMaster(void);
575 static robj
*tryObjectEncoding(robj
*o
);
576 static robj
*getDecodedObject(robj
*o
);
577 static int removeExpire(redisDb
*db
, robj
*key
);
578 static int expireIfNeeded(redisDb
*db
, robj
*key
);
579 static int deleteIfVolatile(redisDb
*db
, robj
*key
);
580 static int deleteIfSwapped(redisDb
*db
, robj
*key
);
581 static int deleteKey(redisDb
*db
, robj
*key
);
582 static time_t getExpire(redisDb
*db
, robj
*key
);
583 static int setExpire(redisDb
*db
, robj
*key
, time_t when
);
584 static void updateSlavesWaitingBgsave(int bgsaveerr
);
585 static void freeMemoryIfNeeded(void);
586 static int processCommand(redisClient
*c
);
587 static void setupSigSegvAction(void);
588 static void rdbRemoveTempFile(pid_t childpid
);
589 static void aofRemoveTempFile(pid_t childpid
);
590 static size_t stringObjectLen(robj
*o
);
591 static void processInputBuffer(redisClient
*c
);
592 static zskiplist
*zslCreate(void);
593 static void zslFree(zskiplist
*zsl
);
594 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
);
595 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
596 static void initClientMultiState(redisClient
*c
);
597 static void freeClientMultiState(redisClient
*c
);
598 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
);
599 static void unblockClientWaitingData(redisClient
*c
);
600 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
);
601 static void vmInit(void);
602 static void vmMarkPagesFree(off_t page
, off_t count
);
603 static robj
*vmLoadObject(robj
*key
);
604 static robj
*vmPreviewObject(robj
*key
);
605 static int vmSwapOneObjectBlocking(void);
606 static int vmSwapOneObjectThreaded(void);
607 static int vmCanSwapOut(void);
608 static int tryFreeOneObjectFromFreelist(void);
609 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
610 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
611 static void vmCancelThreadedIOJob(robj
*o
);
612 static void lockThreadedIO(void);
613 static void unlockThreadedIO(void);
614 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
);
615 static void freeIOJob(iojob
*j
);
616 static void queueIOJob(iojob
*j
);
617 static int vmWriteObjectOnSwap(robj
*o
, off_t page
);
618 static robj
*vmReadObjectFromSwap(off_t page
, int type
);
619 static void waitEmptyIOJobsQueue(void);
620 static void vmReopenSwapFile(void);
621 static int vmFreePage(off_t page
);
622 static void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
623 static void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
);
624 static int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
);
625 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
);
626 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
);
627 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
);
628 static struct redisCommand
*lookupCommand(char *name
);
629 static void call(redisClient
*c
, struct redisCommand
*cmd
);
630 static void resetClient(redisClient
*c
);
631 static void convertToRealHash(robj
*o
);
632 static int pubsubUnsubscribeAllChannels(redisClient
*c
, int notify
);
633 static int pubsubUnsubscribeAllPatterns(redisClient
*c
, int notify
);
634 static void freePubsubPattern(void *p
);
635 static int listMatchPubsubPattern(void *a
, void *b
);
636 static int compareStringObjects(robj
*a
, robj
*b
);
637 static int equalStringObjects(robj
*a
, robj
*b
);
639 static int rewriteAppendOnlyFileBackground(void);
640 static int vmSwapObjectBlocking(robj
*key
, robj
*val
);
641 static int prepareForShutdown();
642 static void touchWatchedKey(redisDb
*db
, robj
*key
);
643 static void touchWatchedKeysOnFlush(int dbid
);
644 static void unwatchAllKeys(redisClient
*c
);
646 static void authCommand(redisClient
*c
);
647 static void pingCommand(redisClient
*c
);
648 static void echoCommand(redisClient
*c
);
649 static void setCommand(redisClient
*c
);
650 static void setnxCommand(redisClient
*c
);
651 static void setexCommand(redisClient
*c
);
652 static void getCommand(redisClient
*c
);
653 static void delCommand(redisClient
*c
);
654 static void existsCommand(redisClient
*c
);
655 static void incrCommand(redisClient
*c
);
656 static void decrCommand(redisClient
*c
);
657 static void incrbyCommand(redisClient
*c
);
658 static void decrbyCommand(redisClient
*c
);
659 static void selectCommand(redisClient
*c
);
660 static void randomkeyCommand(redisClient
*c
);
661 static void keysCommand(redisClient
*c
);
662 static void dbsizeCommand(redisClient
*c
);
663 static void lastsaveCommand(redisClient
*c
);
664 static void saveCommand(redisClient
*c
);
665 static void bgsaveCommand(redisClient
*c
);
666 static void bgrewriteaofCommand(redisClient
*c
);
667 static void shutdownCommand(redisClient
*c
);
668 static void moveCommand(redisClient
*c
);
669 static void renameCommand(redisClient
*c
);
670 static void renamenxCommand(redisClient
*c
);
671 static void lpushCommand(redisClient
*c
);
672 static void rpushCommand(redisClient
*c
);
673 static void lpopCommand(redisClient
*c
);
674 static void rpopCommand(redisClient
*c
);
675 static void llenCommand(redisClient
*c
);
676 static void lindexCommand(redisClient
*c
);
677 static void lrangeCommand(redisClient
*c
);
678 static void ltrimCommand(redisClient
*c
);
679 static void typeCommand(redisClient
*c
);
680 static void lsetCommand(redisClient
*c
);
681 static void saddCommand(redisClient
*c
);
682 static void sremCommand(redisClient
*c
);
683 static void smoveCommand(redisClient
*c
);
684 static void sismemberCommand(redisClient
*c
);
685 static void scardCommand(redisClient
*c
);
686 static void spopCommand(redisClient
*c
);
687 static void srandmemberCommand(redisClient
*c
);
688 static void sinterCommand(redisClient
*c
);
689 static void sinterstoreCommand(redisClient
*c
);
690 static void sunionCommand(redisClient
*c
);
691 static void sunionstoreCommand(redisClient
*c
);
692 static void sdiffCommand(redisClient
*c
);
693 static void sdiffstoreCommand(redisClient
*c
);
694 static void syncCommand(redisClient
*c
);
695 static void flushdbCommand(redisClient
*c
);
696 static void flushallCommand(redisClient
*c
);
697 static void sortCommand(redisClient
*c
);
698 static void lremCommand(redisClient
*c
);
699 static void rpoplpushcommand(redisClient
*c
);
700 static void infoCommand(redisClient
*c
);
701 static void mgetCommand(redisClient
*c
);
702 static void monitorCommand(redisClient
*c
);
703 static void expireCommand(redisClient
*c
);
704 static void expireatCommand(redisClient
*c
);
705 static void getsetCommand(redisClient
*c
);
706 static void ttlCommand(redisClient
*c
);
707 static void slaveofCommand(redisClient
*c
);
708 static void debugCommand(redisClient
*c
);
709 static void msetCommand(redisClient
*c
);
710 static void msetnxCommand(redisClient
*c
);
711 static void zaddCommand(redisClient
*c
);
712 static void zincrbyCommand(redisClient
*c
);
713 static void zrangeCommand(redisClient
*c
);
714 static void zrangebyscoreCommand(redisClient
*c
);
715 static void zcountCommand(redisClient
*c
);
716 static void zrevrangeCommand(redisClient
*c
);
717 static void zcardCommand(redisClient
*c
);
718 static void zremCommand(redisClient
*c
);
719 static void zscoreCommand(redisClient
*c
);
720 static void zremrangebyscoreCommand(redisClient
*c
);
721 static void multiCommand(redisClient
*c
);
722 static void execCommand(redisClient
*c
);
723 static void discardCommand(redisClient
*c
);
724 static void blpopCommand(redisClient
*c
);
725 static void brpopCommand(redisClient
*c
);
726 static void appendCommand(redisClient
*c
);
727 static void substrCommand(redisClient
*c
);
728 static void zrankCommand(redisClient
*c
);
729 static void zrevrankCommand(redisClient
*c
);
730 static void hsetCommand(redisClient
*c
);
731 static void hsetnxCommand(redisClient
*c
);
732 static void hgetCommand(redisClient
*c
);
733 static void hmsetCommand(redisClient
*c
);
734 static void hmgetCommand(redisClient
*c
);
735 static void hdelCommand(redisClient
*c
);
736 static void hlenCommand(redisClient
*c
);
737 static void zremrangebyrankCommand(redisClient
*c
);
738 static void zunionstoreCommand(redisClient
*c
);
739 static void zinterstoreCommand(redisClient
*c
);
740 static void hkeysCommand(redisClient
*c
);
741 static void hvalsCommand(redisClient
*c
);
742 static void hgetallCommand(redisClient
*c
);
743 static void hexistsCommand(redisClient
*c
);
744 static void configCommand(redisClient
*c
);
745 static void hincrbyCommand(redisClient
*c
);
746 static void subscribeCommand(redisClient
*c
);
747 static void unsubscribeCommand(redisClient
*c
);
748 static void psubscribeCommand(redisClient
*c
);
749 static void punsubscribeCommand(redisClient
*c
);
750 static void publishCommand(redisClient
*c
);
751 static void watchCommand(redisClient
*c
);
752 static void unwatchCommand(redisClient
*c
);
754 /*================================= Globals ================================= */
757 static struct redisServer server
; /* server global state */
758 static struct redisCommand
*commandTable
;
759 static struct redisCommand readonlyCommandTable
[] = {
760 {"get",getCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
761 {"set",setCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
762 {"setnx",setnxCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
763 {"setex",setexCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,0,0,0},
764 {"append",appendCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
765 {"substr",substrCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
766 {"del",delCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
767 {"exists",existsCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
768 {"incr",incrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
769 {"decr",decrCommand
,2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
770 {"mget",mgetCommand
,-2,REDIS_CMD_INLINE
,NULL
,1,-1,1},
771 {"rpush",rpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
772 {"lpush",lpushCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
773 {"rpop",rpopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
774 {"lpop",lpopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
775 {"brpop",brpopCommand
,-3,REDIS_CMD_INLINE
,NULL
,1,1,1},
776 {"blpop",blpopCommand
,-3,REDIS_CMD_INLINE
,NULL
,1,1,1},
777 {"llen",llenCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
778 {"lindex",lindexCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
779 {"lset",lsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
780 {"lrange",lrangeCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
781 {"ltrim",ltrimCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
782 {"lrem",lremCommand
,4,REDIS_CMD_BULK
,NULL
,1,1,1},
783 {"rpoplpush",rpoplpushcommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,2,1},
784 {"sadd",saddCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
785 {"srem",sremCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
786 {"smove",smoveCommand
,4,REDIS_CMD_BULK
,NULL
,1,2,1},
787 {"sismember",sismemberCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
788 {"scard",scardCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
789 {"spop",spopCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
790 {"srandmember",srandmemberCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
791 {"sinter",sinterCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
792 {"sinterstore",sinterstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
793 {"sunion",sunionCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
794 {"sunionstore",sunionstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
795 {"sdiff",sdiffCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,-1,1},
796 {"sdiffstore",sdiffstoreCommand
,-3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,2,-1,1},
797 {"smembers",sinterCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
798 {"zadd",zaddCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
799 {"zincrby",zincrbyCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
800 {"zrem",zremCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
801 {"zremrangebyscore",zremrangebyscoreCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
802 {"zremrangebyrank",zremrangebyrankCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
803 {"zunionstore",zunionstoreCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
804 {"zinterstore",zinterstoreCommand
,-4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,zunionInterBlockClientOnSwappedKeys
,0,0,0},
805 {"zrange",zrangeCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
806 {"zrangebyscore",zrangebyscoreCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
807 {"zcount",zcountCommand
,4,REDIS_CMD_INLINE
,NULL
,1,1,1},
808 {"zrevrange",zrevrangeCommand
,-4,REDIS_CMD_INLINE
,NULL
,1,1,1},
809 {"zcard",zcardCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
810 {"zscore",zscoreCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
811 {"zrank",zrankCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
812 {"zrevrank",zrevrankCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
813 {"hset",hsetCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
814 {"hsetnx",hsetnxCommand
,4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
815 {"hget",hgetCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
816 {"hmset",hmsetCommand
,-4,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
817 {"hmget",hmgetCommand
,-3,REDIS_CMD_BULK
,NULL
,1,1,1},
818 {"hincrby",hincrbyCommand
,4,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
819 {"hdel",hdelCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
820 {"hlen",hlenCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
821 {"hkeys",hkeysCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
822 {"hvals",hvalsCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
823 {"hgetall",hgetallCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
824 {"hexists",hexistsCommand
,3,REDIS_CMD_BULK
,NULL
,1,1,1},
825 {"incrby",incrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
826 {"decrby",decrbyCommand
,3,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
827 {"getset",getsetCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
828 {"mset",msetCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
829 {"msetnx",msetnxCommand
,-3,REDIS_CMD_BULK
|REDIS_CMD_DENYOOM
,NULL
,1,-1,2},
830 {"randomkey",randomkeyCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
831 {"select",selectCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
832 {"move",moveCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
833 {"rename",renameCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
834 {"renamenx",renamenxCommand
,3,REDIS_CMD_INLINE
,NULL
,1,1,1},
835 {"expire",expireCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
836 {"expireat",expireatCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
837 {"keys",keysCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
838 {"dbsize",dbsizeCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
839 {"auth",authCommand
,2,REDIS_CMD_INLINE
,NULL
,0,0,0},
840 {"ping",pingCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
841 {"echo",echoCommand
,2,REDIS_CMD_BULK
,NULL
,0,0,0},
842 {"save",saveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
843 {"bgsave",bgsaveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
844 {"bgrewriteaof",bgrewriteaofCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
845 {"shutdown",shutdownCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
846 {"lastsave",lastsaveCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
847 {"type",typeCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
848 {"multi",multiCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
849 {"exec",execCommand
,1,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,execBlockClientOnSwappedKeys
,0,0,0},
850 {"discard",discardCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
851 {"sync",syncCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
852 {"flushdb",flushdbCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
853 {"flushall",flushallCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
854 {"sort",sortCommand
,-2,REDIS_CMD_INLINE
|REDIS_CMD_DENYOOM
,NULL
,1,1,1},
855 {"info",infoCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
856 {"monitor",monitorCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0},
857 {"ttl",ttlCommand
,2,REDIS_CMD_INLINE
,NULL
,1,1,1},
858 {"slaveof",slaveofCommand
,3,REDIS_CMD_INLINE
,NULL
,0,0,0},
859 {"debug",debugCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
860 {"config",configCommand
,-2,REDIS_CMD_BULK
,NULL
,0,0,0},
861 {"subscribe",subscribeCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
862 {"unsubscribe",unsubscribeCommand
,-1,REDIS_CMD_INLINE
,NULL
,0,0,0},
863 {"psubscribe",psubscribeCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
864 {"punsubscribe",punsubscribeCommand
,-1,REDIS_CMD_INLINE
,NULL
,0,0,0},
865 {"publish",publishCommand
,3,REDIS_CMD_BULK
|REDIS_CMD_FORCE_REPLICATION
,NULL
,0,0,0},
866 {"watch",watchCommand
,-2,REDIS_CMD_INLINE
,NULL
,0,0,0},
867 {"unwatch",unwatchCommand
,1,REDIS_CMD_INLINE
,NULL
,0,0,0}
870 /*============================ Utility functions ============================ */
872 /* Glob-style pattern matching. */
873 static int stringmatchlen(const char *pattern
, int patternLen
,
874 const char *string
, int stringLen
, int nocase
)
879 while (pattern
[1] == '*') {
884 return 1; /* match */
886 if (stringmatchlen(pattern
+1, patternLen
-1,
887 string
, stringLen
, nocase
))
888 return 1; /* match */
892 return 0; /* no match */
896 return 0; /* no match */
906 not = pattern
[0] == '^';
913 if (pattern
[0] == '\\') {
916 if (pattern
[0] == string
[0])
918 } else if (pattern
[0] == ']') {
920 } else if (patternLen
== 0) {
924 } else if (pattern
[1] == '-' && patternLen
>= 3) {
925 int start
= pattern
[0];
926 int end
= pattern
[2];
934 start
= tolower(start
);
940 if (c
>= start
&& c
<= end
)
944 if (pattern
[0] == string
[0])
947 if (tolower((int)pattern
[0]) == tolower((int)string
[0]))
957 return 0; /* no match */
963 if (patternLen
>= 2) {
970 if (pattern
[0] != string
[0])
971 return 0; /* no match */
973 if (tolower((int)pattern
[0]) != tolower((int)string
[0]))
974 return 0; /* no match */
982 if (stringLen
== 0) {
983 while(*pattern
== '*') {
990 if (patternLen
== 0 && stringLen
== 0)
995 static int stringmatch(const char *pattern
, const char *string
, int nocase
) {
996 return stringmatchlen(pattern
,strlen(pattern
),string
,strlen(string
),nocase
);
999 /* Convert a string representing an amount of memory into the number of
1000 * bytes, so for instance memtoll("1Gi") will return 1073741824 that is
1003 * On parsing error, if *err is not NULL, it's set to 1, otherwise it's
1005 static long long memtoll(const char *p
, int *err
) {
1008 long mul
; /* unit multiplier */
1010 unsigned int digits
;
1013 /* Search the first non digit character. */
1016 while(*u
&& isdigit(*u
)) u
++;
1017 if (*u
== '\0' || !strcasecmp(u
,"b")) {
1019 } else if (!strcasecmp(u
,"k")) {
1021 } else if (!strcasecmp(u
,"kb")) {
1023 } else if (!strcasecmp(u
,"m")) {
1025 } else if (!strcasecmp(u
,"mb")) {
1027 } else if (!strcasecmp(u
,"g")) {
1028 mul
= 1000L*1000*1000;
1029 } else if (!strcasecmp(u
,"gb")) {
1030 mul
= 1024L*1024*1024;
1036 if (digits
>= sizeof(buf
)) {
1040 memcpy(buf
,p
,digits
);
1042 val
= strtoll(buf
,NULL
,10);
1046 /* Convert a long long into a string. Returns the number of
1047 * characters needed to represent the number, that can be shorter if passed
1048 * buffer length is not enough to store the whole number. */
1049 static int ll2string(char *s
, size_t len
, long long value
) {
1051 unsigned long long v
;
1054 if (len
== 0) return 0;
1055 v
= (value
< 0) ? -value
: value
;
1056 p
= buf
+31; /* point to the last character */
1061 if (value
< 0) *p
-- = '-';
1064 if (l
+1 > len
) l
= len
-1; /* Make sure it fits, including the nul term */
1070 static void redisLog(int level
, const char *fmt
, ...) {
1074 fp
= (server
.logfile
== NULL
) ? stdout
: fopen(server
.logfile
,"a");
1078 if (level
>= server
.verbosity
) {
1084 strftime(buf
,64,"%d %b %H:%M:%S",localtime(&now
));
1085 fprintf(fp
,"[%d] %s %c ",(int)getpid(),buf
,c
[level
]);
1086 vfprintf(fp
, fmt
, ap
);
1092 if (server
.logfile
) fclose(fp
);
1095 /*====================== Hash table type implementation ==================== */
1097 /* This is an hash table type that uses the SDS dynamic strings libary as
1098 * keys and radis objects as values (objects can hold SDS strings,
1101 static void dictVanillaFree(void *privdata
, void *val
)
1103 DICT_NOTUSED(privdata
);
1107 static void dictListDestructor(void *privdata
, void *val
)
1109 DICT_NOTUSED(privdata
);
1110 listRelease((list
*)val
);
1113 static int sdsDictKeyCompare(void *privdata
, const void *key1
,
1117 DICT_NOTUSED(privdata
);
1119 l1
= sdslen((sds
)key1
);
1120 l2
= sdslen((sds
)key2
);
1121 if (l1
!= l2
) return 0;
1122 return memcmp(key1
, key2
, l1
) == 0;
1125 static void dictRedisObjectDestructor(void *privdata
, void *val
)
1127 DICT_NOTUSED(privdata
);
1129 if (val
== NULL
) return; /* Values of swapped out keys as set to NULL */
1133 static int dictObjKeyCompare(void *privdata
, const void *key1
,
1136 const robj
*o1
= key1
, *o2
= key2
;
1137 return sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1140 static unsigned int dictObjHash(const void *key
) {
1141 const robj
*o
= key
;
1142 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1145 static int dictEncObjKeyCompare(void *privdata
, const void *key1
,
1148 robj
*o1
= (robj
*) key1
, *o2
= (robj
*) key2
;
1151 if (o1
->encoding
== REDIS_ENCODING_INT
&&
1152 o2
->encoding
== REDIS_ENCODING_INT
)
1153 return o1
->ptr
== o2
->ptr
;
1155 o1
= getDecodedObject(o1
);
1156 o2
= getDecodedObject(o2
);
1157 cmp
= sdsDictKeyCompare(privdata
,o1
->ptr
,o2
->ptr
);
1163 static unsigned int dictEncObjHash(const void *key
) {
1164 robj
*o
= (robj
*) key
;
1166 if (o
->encoding
== REDIS_ENCODING_RAW
) {
1167 return dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1169 if (o
->encoding
== REDIS_ENCODING_INT
) {
1173 len
= ll2string(buf
,32,(long)o
->ptr
);
1174 return dictGenHashFunction((unsigned char*)buf
, len
);
1178 o
= getDecodedObject(o
);
1179 hash
= dictGenHashFunction(o
->ptr
, sdslen((sds
)o
->ptr
));
1186 /* Sets type and expires */
1187 static dictType setDictType
= {
1188 dictEncObjHash
, /* hash function */
1191 dictEncObjKeyCompare
, /* key compare */
1192 dictRedisObjectDestructor
, /* key destructor */
1193 NULL
/* val destructor */
1196 /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
1197 static dictType zsetDictType
= {
1198 dictEncObjHash
, /* hash function */
1201 dictEncObjKeyCompare
, /* key compare */
1202 dictRedisObjectDestructor
, /* key destructor */
1203 dictVanillaFree
/* val destructor of malloc(sizeof(double)) */
1207 static dictType dbDictType
= {
1208 dictObjHash
, /* hash function */
1211 dictObjKeyCompare
, /* key compare */
1212 dictRedisObjectDestructor
, /* key destructor */
1213 dictRedisObjectDestructor
/* val destructor */
1217 static dictType keyptrDictType
= {
1218 dictObjHash
, /* hash function */
1221 dictObjKeyCompare
, /* key compare */
1222 dictRedisObjectDestructor
, /* key destructor */
1223 NULL
/* val destructor */
1226 /* Hash type hash table (note that small hashes are represented with zimpaps) */
1227 static dictType hashDictType
= {
1228 dictEncObjHash
, /* hash function */
1231 dictEncObjKeyCompare
, /* key compare */
1232 dictRedisObjectDestructor
, /* key destructor */
1233 dictRedisObjectDestructor
/* val destructor */
1236 /* Keylist hash table type has unencoded redis objects as keys and
1237 * lists as values. It's used for blocking operations (BLPOP) and to
1238 * map swapped keys to a list of clients waiting for this keys to be loaded. */
1239 static dictType keylistDictType
= {
1240 dictObjHash
, /* hash function */
1243 dictObjKeyCompare
, /* key compare */
1244 dictRedisObjectDestructor
, /* key destructor */
1245 dictListDestructor
/* val destructor */
1248 static void version();
1250 /* ========================= Random utility functions ======================= */
1252 /* Redis generally does not try to recover from out of memory conditions
1253 * when allocating objects or strings, it is not clear if it will be possible
1254 * to report this condition to the client since the networking layer itself
1255 * is based on heap allocation for send buffers, so we simply abort.
1256 * At least the code will be simpler to read... */
1257 static void oom(const char *msg
) {
1258 redisLog(REDIS_WARNING
, "%s: Out of memory\n",msg
);
1263 /* ====================== Redis server networking stuff ===================== */
1264 static void closeTimedoutClients(void) {
1267 time_t now
= time(NULL
);
1270 listRewind(server
.clients
,&li
);
1271 while ((ln
= listNext(&li
)) != NULL
) {
1272 c
= listNodeValue(ln
);
1273 if (server
.maxidletime
&&
1274 !(c
->flags
& REDIS_SLAVE
) && /* no timeout for slaves */
1275 !(c
->flags
& REDIS_MASTER
) && /* no timeout for masters */
1276 dictSize(c
->pubsub_channels
) == 0 && /* no timeout for pubsub */
1277 listLength(c
->pubsub_patterns
) == 0 &&
1278 (now
- c
->lastinteraction
> server
.maxidletime
))
1280 redisLog(REDIS_VERBOSE
,"Closing idle client");
1282 } else if (c
->flags
& REDIS_BLOCKED
) {
1283 if (c
->blockingto
!= 0 && c
->blockingto
< now
) {
1284 addReply(c
,shared
.nullmultibulk
);
1285 unblockClientWaitingData(c
);
1291 static int htNeedsResize(dict
*dict
) {
1292 long long size
, used
;
1294 size
= dictSlots(dict
);
1295 used
= dictSize(dict
);
1296 return (size
&& used
&& size
> DICT_HT_INITIAL_SIZE
&&
1297 (used
*100/size
< REDIS_HT_MINFILL
));
1300 /* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
1301 * we resize the hash table to save memory */
1302 static void tryResizeHashTables(void) {
1305 for (j
= 0; j
< server
.dbnum
; j
++) {
1306 if (htNeedsResize(server
.db
[j
].dict
))
1307 dictResize(server
.db
[j
].dict
);
1308 if (htNeedsResize(server
.db
[j
].expires
))
1309 dictResize(server
.db
[j
].expires
);
1313 /* Our hash table implementation performs rehashing incrementally while
1314 * we write/read from the hash table. Still if the server is idle, the hash
1315 * table will use two tables for a long time. So we try to use 1 millisecond
1316 * of CPU time at every serverCron() loop in order to rehash some key. */
1317 static void incrementallyRehash(void) {
1320 for (j
= 0; j
< server
.dbnum
; j
++) {
1321 if (dictIsRehashing(server
.db
[j
].dict
)) {
1322 dictRehashMilliseconds(server
.db
[j
].dict
,1);
1323 break; /* already used our millisecond for this loop... */
1328 /* A background saving child (BGSAVE) terminated its work. Handle this. */
1329 void backgroundSaveDoneHandler(int statloc
) {
1330 int exitcode
= WEXITSTATUS(statloc
);
1331 int bysignal
= WIFSIGNALED(statloc
);
1333 if (!bysignal
&& exitcode
== 0) {
1334 redisLog(REDIS_NOTICE
,
1335 "Background saving terminated with success");
1337 server
.lastsave
= time(NULL
);
1338 } else if (!bysignal
&& exitcode
!= 0) {
1339 redisLog(REDIS_WARNING
, "Background saving error");
1341 redisLog(REDIS_WARNING
,
1342 "Background saving terminated by signal %d", WTERMSIG(statloc
));
1343 rdbRemoveTempFile(server
.bgsavechildpid
);
1345 server
.bgsavechildpid
= -1;
1346 /* Possibly there are slaves waiting for a BGSAVE in order to be served
1347 * (the first stage of SYNC is a bulk transfer of dump.rdb) */
1348 updateSlavesWaitingBgsave(exitcode
== 0 ? REDIS_OK
: REDIS_ERR
);
1351 /* A background append only file rewriting (BGREWRITEAOF) terminated its work.
1353 void backgroundRewriteDoneHandler(int statloc
) {
1354 int exitcode
= WEXITSTATUS(statloc
);
1355 int bysignal
= WIFSIGNALED(statloc
);
1357 if (!bysignal
&& exitcode
== 0) {
1361 redisLog(REDIS_NOTICE
,
1362 "Background append only file rewriting terminated with success");
1363 /* Now it's time to flush the differences accumulated by the parent */
1364 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) server
.bgrewritechildpid
);
1365 fd
= open(tmpfile
,O_WRONLY
|O_APPEND
);
1367 redisLog(REDIS_WARNING
, "Not able to open the temp append only file produced by the child: %s", strerror(errno
));
1370 /* Flush our data... */
1371 if (write(fd
,server
.bgrewritebuf
,sdslen(server
.bgrewritebuf
)) !=
1372 (signed) sdslen(server
.bgrewritebuf
)) {
1373 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
));
1377 redisLog(REDIS_NOTICE
,"Parent diff flushed into the new append log file with success (%lu bytes)",sdslen(server
.bgrewritebuf
));
1378 /* Now our work is to rename the temp file into the stable file. And
1379 * switch the file descriptor used by the server for append only. */
1380 if (rename(tmpfile
,server
.appendfilename
) == -1) {
1381 redisLog(REDIS_WARNING
,"Can't rename the temp append only file into the stable one: %s", strerror(errno
));
1385 /* Mission completed... almost */
1386 redisLog(REDIS_NOTICE
,"Append only file successfully rewritten.");
1387 if (server
.appendfd
!= -1) {
1388 /* If append only is actually enabled... */
1389 close(server
.appendfd
);
1390 server
.appendfd
= fd
;
1392 server
.appendseldb
= -1; /* Make sure it will issue SELECT */
1393 redisLog(REDIS_NOTICE
,"The new append only file was selected for future appends.");
1395 /* If append only is disabled we just generate a dump in this
1396 * format. Why not? */
1399 } else if (!bysignal
&& exitcode
!= 0) {
1400 redisLog(REDIS_WARNING
, "Background append only file rewriting error");
1402 redisLog(REDIS_WARNING
,
1403 "Background append only file rewriting terminated by signal %d",
1407 sdsfree(server
.bgrewritebuf
);
1408 server
.bgrewritebuf
= sdsempty();
1409 aofRemoveTempFile(server
.bgrewritechildpid
);
1410 server
.bgrewritechildpid
= -1;
1413 /* This function is called once a background process of some kind terminates,
1414 * as we want to avoid resizing the hash tables when there is a child in order
1415 * to play well with copy-on-write (otherwise when a resize happens lots of
1416 * memory pages are copied). The goal of this function is to update the ability
1417 * for dict.c to resize the hash tables accordingly to the fact we have o not
1418 * running childs. */
1419 static void updateDictResizePolicy(void) {
1420 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
1423 dictDisableResize();
1426 static int serverCron(struct aeEventLoop
*eventLoop
, long long id
, void *clientData
) {
1427 int j
, loops
= server
.cronloops
++;
1428 REDIS_NOTUSED(eventLoop
);
1430 REDIS_NOTUSED(clientData
);
1432 /* We take a cached value of the unix time in the global state because
1433 * with virtual memory and aging there is to store the current time
1434 * in objects at every object access, and accuracy is not needed.
1435 * To access a global var is faster than calling time(NULL) */
1436 server
.unixtime
= time(NULL
);
1438 /* We received a SIGTERM, shutting down here in a safe way, as it is
1439 * not ok doing so inside the signal handler. */
1440 if (server
.shutdown_asap
) {
1441 if (prepareForShutdown() == REDIS_OK
) exit(0);
1442 redisLog(REDIS_WARNING
,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
1445 /* Show some info about non-empty databases */
1446 for (j
= 0; j
< server
.dbnum
; j
++) {
1447 long long size
, used
, vkeys
;
1449 size
= dictSlots(server
.db
[j
].dict
);
1450 used
= dictSize(server
.db
[j
].dict
);
1451 vkeys
= dictSize(server
.db
[j
].expires
);
1452 if (!(loops
% 50) && (used
|| vkeys
)) {
1453 redisLog(REDIS_VERBOSE
,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j
,used
,vkeys
,size
);
1454 /* dictPrintStats(server.dict); */
1458 /* We don't want to resize the hash tables while a bacground saving
1459 * is in progress: the saving child is created using fork() that is
1460 * implemented with a copy-on-write semantic in most modern systems, so
1461 * if we resize the HT while there is the saving child at work actually
1462 * a lot of memory movements in the parent will cause a lot of pages
1464 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1) {
1465 if (!(loops
% 10)) tryResizeHashTables();
1466 if (server
.activerehashing
) incrementallyRehash();
1469 /* Show information about connected clients */
1470 if (!(loops
% 50)) {
1471 redisLog(REDIS_VERBOSE
,"%d clients connected (%d slaves), %zu bytes in use",
1472 listLength(server
.clients
)-listLength(server
.slaves
),
1473 listLength(server
.slaves
),
1474 zmalloc_used_memory());
1477 /* Close connections of timedout clients */
1478 if ((server
.maxidletime
&& !(loops
% 100)) || server
.blpop_blocked_clients
)
1479 closeTimedoutClients();
1481 /* Check if a background saving or AOF rewrite in progress terminated */
1482 if (server
.bgsavechildpid
!= -1 || server
.bgrewritechildpid
!= -1) {
1486 if ((pid
= wait3(&statloc
,WNOHANG
,NULL
)) != 0) {
1487 if (pid
== server
.bgsavechildpid
) {
1488 backgroundSaveDoneHandler(statloc
);
1490 backgroundRewriteDoneHandler(statloc
);
1492 updateDictResizePolicy();
1495 /* If there is not a background saving in progress check if
1496 * we have to save now */
1497 time_t now
= time(NULL
);
1498 for (j
= 0; j
< server
.saveparamslen
; j
++) {
1499 struct saveparam
*sp
= server
.saveparams
+j
;
1501 if (server
.dirty
>= sp
->changes
&&
1502 now
-server
.lastsave
> sp
->seconds
) {
1503 redisLog(REDIS_NOTICE
,"%d changes in %d seconds. Saving...",
1504 sp
->changes
, sp
->seconds
);
1505 rdbSaveBackground(server
.dbfilename
);
1511 /* Try to expire a few timed out keys. The algorithm used is adaptive and
1512 * will use few CPU cycles if there are few expiring keys, otherwise
1513 * it will get more aggressive to avoid that too much memory is used by
1514 * keys that can be removed from the keyspace. */
1515 for (j
= 0; j
< server
.dbnum
; j
++) {
1517 redisDb
*db
= server
.db
+j
;
1519 /* Continue to expire if at the end of the cycle more than 25%
1520 * of the keys were expired. */
1522 long num
= dictSize(db
->expires
);
1523 time_t now
= time(NULL
);
1526 if (num
> REDIS_EXPIRELOOKUPS_PER_CRON
)
1527 num
= REDIS_EXPIRELOOKUPS_PER_CRON
;
1532 if ((de
= dictGetRandomKey(db
->expires
)) == NULL
) break;
1533 t
= (time_t) dictGetEntryVal(de
);
1535 deleteKey(db
,dictGetEntryKey(de
));
1537 server
.stat_expiredkeys
++;
1540 } while (expired
> REDIS_EXPIRELOOKUPS_PER_CRON
/4);
1543 /* Swap a few keys on disk if we are over the memory limit and VM
1544 * is enbled. Try to free objects from the free list first. */
1545 if (vmCanSwapOut()) {
1546 while (server
.vm_enabled
&& zmalloc_used_memory() >
1547 server
.vm_max_memory
)
1551 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
1552 retval
= (server
.vm_max_threads
== 0) ?
1553 vmSwapOneObjectBlocking() :
1554 vmSwapOneObjectThreaded();
1555 if (retval
== REDIS_ERR
&& !(loops
% 300) &&
1556 zmalloc_used_memory() >
1557 (server
.vm_max_memory
+server
.vm_max_memory
/10))
1559 redisLog(REDIS_WARNING
,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
1561 /* Note that when using threade I/O we free just one object,
1562 * because anyway when the I/O thread in charge to swap this
1563 * object out will finish, the handler of completed jobs
1564 * will try to swap more objects if we are still out of memory. */
1565 if (retval
== REDIS_ERR
|| server
.vm_max_threads
> 0) break;
1569 /* Check if we should connect to a MASTER */
1570 if (server
.replstate
== REDIS_REPL_CONNECT
&& !(loops
% 10)) {
1571 redisLog(REDIS_NOTICE
,"Connecting to MASTER...");
1572 if (syncWithMaster() == REDIS_OK
) {
1573 redisLog(REDIS_NOTICE
,"MASTER <-> SLAVE sync succeeded");
1574 if (server
.appendonly
) rewriteAppendOnlyFileBackground();
1580 /* This function gets called every time Redis is entering the
1581 * main loop of the event driven library, that is, before to sleep
1582 * for ready file descriptors. */
1583 static void beforeSleep(struct aeEventLoop
*eventLoop
) {
1584 REDIS_NOTUSED(eventLoop
);
1586 /* Awake clients that got all the swapped keys they requested */
1587 if (server
.vm_enabled
&& listLength(server
.io_ready_clients
)) {
1591 listRewind(server
.io_ready_clients
,&li
);
1592 while((ln
= listNext(&li
))) {
1593 redisClient
*c
= ln
->value
;
1594 struct redisCommand
*cmd
;
1596 /* Resume the client. */
1597 listDelNode(server
.io_ready_clients
,ln
);
1598 c
->flags
&= (~REDIS_IO_WAIT
);
1599 server
.vm_blocked_clients
--;
1600 aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
1601 readQueryFromClient
, c
);
1602 cmd
= lookupCommand(c
->argv
[0]->ptr
);
1603 assert(cmd
!= NULL
);
1606 /* There may be more data to process in the input buffer. */
1607 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0)
1608 processInputBuffer(c
);
1611 /* Write the AOF buffer on disk */
1612 flushAppendOnlyFile();
1615 static void createSharedObjects(void) {
1618 shared
.crlf
= createObject(REDIS_STRING
,sdsnew("\r\n"));
1619 shared
.ok
= createObject(REDIS_STRING
,sdsnew("+OK\r\n"));
1620 shared
.err
= createObject(REDIS_STRING
,sdsnew("-ERR\r\n"));
1621 shared
.emptybulk
= createObject(REDIS_STRING
,sdsnew("$0\r\n\r\n"));
1622 shared
.czero
= createObject(REDIS_STRING
,sdsnew(":0\r\n"));
1623 shared
.cone
= createObject(REDIS_STRING
,sdsnew(":1\r\n"));
1624 shared
.nullbulk
= createObject(REDIS_STRING
,sdsnew("$-1\r\n"));
1625 shared
.nullmultibulk
= createObject(REDIS_STRING
,sdsnew("*-1\r\n"));
1626 shared
.emptymultibulk
= createObject(REDIS_STRING
,sdsnew("*0\r\n"));
1627 shared
.pong
= createObject(REDIS_STRING
,sdsnew("+PONG\r\n"));
1628 shared
.queued
= createObject(REDIS_STRING
,sdsnew("+QUEUED\r\n"));
1629 shared
.wrongtypeerr
= createObject(REDIS_STRING
,sdsnew(
1630 "-ERR Operation against a key holding the wrong kind of value\r\n"));
1631 shared
.nokeyerr
= createObject(REDIS_STRING
,sdsnew(
1632 "-ERR no such key\r\n"));
1633 shared
.syntaxerr
= createObject(REDIS_STRING
,sdsnew(
1634 "-ERR syntax error\r\n"));
1635 shared
.sameobjecterr
= createObject(REDIS_STRING
,sdsnew(
1636 "-ERR source and destination objects are the same\r\n"));
1637 shared
.outofrangeerr
= createObject(REDIS_STRING
,sdsnew(
1638 "-ERR index out of range\r\n"));
1639 shared
.space
= createObject(REDIS_STRING
,sdsnew(" "));
1640 shared
.colon
= createObject(REDIS_STRING
,sdsnew(":"));
1641 shared
.plus
= createObject(REDIS_STRING
,sdsnew("+"));
1642 shared
.select0
= createStringObject("select 0\r\n",10);
1643 shared
.select1
= createStringObject("select 1\r\n",10);
1644 shared
.select2
= createStringObject("select 2\r\n",10);
1645 shared
.select3
= createStringObject("select 3\r\n",10);
1646 shared
.select4
= createStringObject("select 4\r\n",10);
1647 shared
.select5
= createStringObject("select 5\r\n",10);
1648 shared
.select6
= createStringObject("select 6\r\n",10);
1649 shared
.select7
= createStringObject("select 7\r\n",10);
1650 shared
.select8
= createStringObject("select 8\r\n",10);
1651 shared
.select9
= createStringObject("select 9\r\n",10);
1652 shared
.messagebulk
= createStringObject("$7\r\nmessage\r\n",13);
1653 shared
.pmessagebulk
= createStringObject("$8\r\npmessage\r\n",14);
1654 shared
.subscribebulk
= createStringObject("$9\r\nsubscribe\r\n",15);
1655 shared
.unsubscribebulk
= createStringObject("$11\r\nunsubscribe\r\n",18);
1656 shared
.psubscribebulk
= createStringObject("$10\r\npsubscribe\r\n",17);
1657 shared
.punsubscribebulk
= createStringObject("$12\r\npunsubscribe\r\n",19);
1658 shared
.mbulk3
= createStringObject("*3\r\n",4);
1659 shared
.mbulk4
= createStringObject("*4\r\n",4);
1660 for (j
= 0; j
< REDIS_SHARED_INTEGERS
; j
++) {
1661 shared
.integers
[j
] = createObject(REDIS_STRING
,(void*)(long)j
);
1662 shared
.integers
[j
]->encoding
= REDIS_ENCODING_INT
;
1666 static void appendServerSaveParams(time_t seconds
, int changes
) {
1667 server
.saveparams
= zrealloc(server
.saveparams
,sizeof(struct saveparam
)*(server
.saveparamslen
+1));
1668 server
.saveparams
[server
.saveparamslen
].seconds
= seconds
;
1669 server
.saveparams
[server
.saveparamslen
].changes
= changes
;
1670 server
.saveparamslen
++;
1673 static void resetServerSaveParams() {
1674 zfree(server
.saveparams
);
1675 server
.saveparams
= NULL
;
1676 server
.saveparamslen
= 0;
1679 static void initServerConfig() {
1680 server
.dbnum
= REDIS_DEFAULT_DBNUM
;
1681 server
.port
= REDIS_SERVERPORT
;
1682 server
.verbosity
= REDIS_VERBOSE
;
1683 server
.maxidletime
= REDIS_MAXIDLETIME
;
1684 server
.saveparams
= NULL
;
1685 server
.logfile
= NULL
; /* NULL = log on standard output */
1686 server
.bindaddr
= NULL
;
1687 server
.glueoutputbuf
= 1;
1688 server
.daemonize
= 0;
1689 server
.appendonly
= 0;
1690 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1691 server
.lastfsync
= time(NULL
);
1692 server
.appendfd
= -1;
1693 server
.appendseldb
= -1; /* Make sure the first time will not match */
1694 server
.pidfile
= zstrdup("/var/run/redis.pid");
1695 server
.dbfilename
= zstrdup("dump.rdb");
1696 server
.appendfilename
= zstrdup("appendonly.aof");
1697 server
.requirepass
= NULL
;
1698 server
.rdbcompression
= 1;
1699 server
.activerehashing
= 1;
1700 server
.maxclients
= 0;
1701 server
.blpop_blocked_clients
= 0;
1702 server
.maxmemory
= 0;
1703 server
.vm_enabled
= 0;
1704 server
.vm_swap_file
= zstrdup("/tmp/redis-%p.vm");
1705 server
.vm_page_size
= 256; /* 256 bytes per page */
1706 server
.vm_pages
= 1024*1024*100; /* 104 millions of pages */
1707 server
.vm_max_memory
= 1024LL*1024*1024*1; /* 1 GB of RAM */
1708 server
.vm_max_threads
= 4;
1709 server
.vm_blocked_clients
= 0;
1710 server
.hash_max_zipmap_entries
= REDIS_HASH_MAX_ZIPMAP_ENTRIES
;
1711 server
.hash_max_zipmap_value
= REDIS_HASH_MAX_ZIPMAP_VALUE
;
1712 server
.shutdown_asap
= 0;
1714 resetServerSaveParams();
1716 appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
1717 appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
1718 appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
1719 /* Replication related */
1721 server
.masterauth
= NULL
;
1722 server
.masterhost
= NULL
;
1723 server
.masterport
= 6379;
1724 server
.master
= NULL
;
1725 server
.replstate
= REDIS_REPL_NONE
;
1727 /* Double constants initialization */
1729 R_PosInf
= 1.0/R_Zero
;
1730 R_NegInf
= -1.0/R_Zero
;
1731 R_Nan
= R_Zero
/R_Zero
;
1734 static void initServer() {
1737 signal(SIGHUP
, SIG_IGN
);
1738 signal(SIGPIPE
, SIG_IGN
);
1739 setupSigSegvAction();
1741 server
.devnull
= fopen("/dev/null","w");
1742 if (server
.devnull
== NULL
) {
1743 redisLog(REDIS_WARNING
, "Can't open /dev/null: %s", server
.neterr
);
1746 server
.clients
= listCreate();
1747 server
.slaves
= listCreate();
1748 server
.monitors
= listCreate();
1749 server
.objfreelist
= listCreate();
1750 createSharedObjects();
1751 server
.el
= aeCreateEventLoop();
1752 server
.db
= zmalloc(sizeof(redisDb
)*server
.dbnum
);
1753 server
.fd
= anetTcpServer(server
.neterr
, server
.port
, server
.bindaddr
);
1754 if (server
.fd
== -1) {
1755 redisLog(REDIS_WARNING
, "Opening TCP port: %s", server
.neterr
);
1758 for (j
= 0; j
< server
.dbnum
; j
++) {
1759 server
.db
[j
].dict
= dictCreate(&dbDictType
,NULL
);
1760 server
.db
[j
].expires
= dictCreate(&keyptrDictType
,NULL
);
1761 server
.db
[j
].blocking_keys
= dictCreate(&keylistDictType
,NULL
);
1762 server
.db
[j
].watched_keys
= dictCreate(&keylistDictType
,NULL
);
1763 if (server
.vm_enabled
)
1764 server
.db
[j
].io_keys
= dictCreate(&keylistDictType
,NULL
);
1765 server
.db
[j
].id
= j
;
1767 server
.pubsub_channels
= dictCreate(&keylistDictType
,NULL
);
1768 server
.pubsub_patterns
= listCreate();
1769 listSetFreeMethod(server
.pubsub_patterns
,freePubsubPattern
);
1770 listSetMatchMethod(server
.pubsub_patterns
,listMatchPubsubPattern
);
1771 server
.cronloops
= 0;
1772 server
.bgsavechildpid
= -1;
1773 server
.bgrewritechildpid
= -1;
1774 server
.bgrewritebuf
= sdsempty();
1775 server
.aofbuf
= sdsempty();
1776 server
.lastsave
= time(NULL
);
1778 server
.stat_numcommands
= 0;
1779 server
.stat_numconnections
= 0;
1780 server
.stat_expiredkeys
= 0;
1781 server
.stat_starttime
= time(NULL
);
1782 server
.unixtime
= time(NULL
);
1783 aeCreateTimeEvent(server
.el
, 1, serverCron
, NULL
, NULL
);
1784 if (aeCreateFileEvent(server
.el
, server
.fd
, AE_READABLE
,
1785 acceptHandler
, NULL
) == AE_ERR
) oom("creating file event");
1787 if (server
.appendonly
) {
1788 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
1789 if (server
.appendfd
== -1) {
1790 redisLog(REDIS_WARNING
, "Can't open the append-only file: %s",
1796 if (server
.vm_enabled
) vmInit();
1799 /* Empty the whole database */
1800 static long long emptyDb() {
1802 long long removed
= 0;
1804 for (j
= 0; j
< server
.dbnum
; j
++) {
1805 removed
+= dictSize(server
.db
[j
].dict
);
1806 dictEmpty(server
.db
[j
].dict
);
1807 dictEmpty(server
.db
[j
].expires
);
1812 static int yesnotoi(char *s
) {
1813 if (!strcasecmp(s
,"yes")) return 1;
1814 else if (!strcasecmp(s
,"no")) return 0;
1818 /* I agree, this is a very rudimental way to load a configuration...
1819 will improve later if the config gets more complex */
1820 static void loadServerConfig(char *filename
) {
1822 char buf
[REDIS_CONFIGLINE_MAX
+1], *err
= NULL
;
1826 if (filename
[0] == '-' && filename
[1] == '\0')
1829 if ((fp
= fopen(filename
,"r")) == NULL
) {
1830 redisLog(REDIS_WARNING
, "Fatal error, can't open config file '%s'", filename
);
1835 while(fgets(buf
,REDIS_CONFIGLINE_MAX
+1,fp
) != NULL
) {
1841 line
= sdstrim(line
," \t\r\n");
1843 /* Skip comments and blank lines*/
1844 if (line
[0] == '#' || line
[0] == '\0') {
1849 /* Split into arguments */
1850 argv
= sdssplitlen(line
,sdslen(line
)," ",1,&argc
);
1851 sdstolower(argv
[0]);
1853 /* Execute config directives */
1854 if (!strcasecmp(argv
[0],"timeout") && argc
== 2) {
1855 server
.maxidletime
= atoi(argv
[1]);
1856 if (server
.maxidletime
< 0) {
1857 err
= "Invalid timeout value"; goto loaderr
;
1859 } else if (!strcasecmp(argv
[0],"port") && argc
== 2) {
1860 server
.port
= atoi(argv
[1]);
1861 if (server
.port
< 1 || server
.port
> 65535) {
1862 err
= "Invalid port"; goto loaderr
;
1864 } else if (!strcasecmp(argv
[0],"bind") && argc
== 2) {
1865 server
.bindaddr
= zstrdup(argv
[1]);
1866 } else if (!strcasecmp(argv
[0],"save") && argc
== 3) {
1867 int seconds
= atoi(argv
[1]);
1868 int changes
= atoi(argv
[2]);
1869 if (seconds
< 1 || changes
< 0) {
1870 err
= "Invalid save parameters"; goto loaderr
;
1872 appendServerSaveParams(seconds
,changes
);
1873 } else if (!strcasecmp(argv
[0],"dir") && argc
== 2) {
1874 if (chdir(argv
[1]) == -1) {
1875 redisLog(REDIS_WARNING
,"Can't chdir to '%s': %s",
1876 argv
[1], strerror(errno
));
1879 } else if (!strcasecmp(argv
[0],"loglevel") && argc
== 2) {
1880 if (!strcasecmp(argv
[1],"debug")) server
.verbosity
= REDIS_DEBUG
;
1881 else if (!strcasecmp(argv
[1],"verbose")) server
.verbosity
= REDIS_VERBOSE
;
1882 else if (!strcasecmp(argv
[1],"notice")) server
.verbosity
= REDIS_NOTICE
;
1883 else if (!strcasecmp(argv
[1],"warning")) server
.verbosity
= REDIS_WARNING
;
1885 err
= "Invalid log level. Must be one of debug, notice, warning";
1888 } else if (!strcasecmp(argv
[0],"logfile") && argc
== 2) {
1891 server
.logfile
= zstrdup(argv
[1]);
1892 if (!strcasecmp(server
.logfile
,"stdout")) {
1893 zfree(server
.logfile
);
1894 server
.logfile
= NULL
;
1896 if (server
.logfile
) {
1897 /* Test if we are able to open the file. The server will not
1898 * be able to abort just for this problem later... */
1899 logfp
= fopen(server
.logfile
,"a");
1900 if (logfp
== NULL
) {
1901 err
= sdscatprintf(sdsempty(),
1902 "Can't open the log file: %s", strerror(errno
));
1907 } else if (!strcasecmp(argv
[0],"databases") && argc
== 2) {
1908 server
.dbnum
= atoi(argv
[1]);
1909 if (server
.dbnum
< 1) {
1910 err
= "Invalid number of databases"; goto loaderr
;
1912 } else if (!strcasecmp(argv
[0],"include") && argc
== 2) {
1913 loadServerConfig(argv
[1]);
1914 } else if (!strcasecmp(argv
[0],"maxclients") && argc
== 2) {
1915 server
.maxclients
= atoi(argv
[1]);
1916 } else if (!strcasecmp(argv
[0],"maxmemory") && argc
== 2) {
1917 server
.maxmemory
= memtoll(argv
[1],NULL
);
1918 } else if (!strcasecmp(argv
[0],"slaveof") && argc
== 3) {
1919 server
.masterhost
= sdsnew(argv
[1]);
1920 server
.masterport
= atoi(argv
[2]);
1921 server
.replstate
= REDIS_REPL_CONNECT
;
1922 } else if (!strcasecmp(argv
[0],"masterauth") && argc
== 2) {
1923 server
.masterauth
= zstrdup(argv
[1]);
1924 } else if (!strcasecmp(argv
[0],"glueoutputbuf") && argc
== 2) {
1925 if ((server
.glueoutputbuf
= yesnotoi(argv
[1])) == -1) {
1926 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1928 } else if (!strcasecmp(argv
[0],"rdbcompression") && argc
== 2) {
1929 if ((server
.rdbcompression
= yesnotoi(argv
[1])) == -1) {
1930 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1932 } else if (!strcasecmp(argv
[0],"activerehashing") && argc
== 2) {
1933 if ((server
.activerehashing
= yesnotoi(argv
[1])) == -1) {
1934 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1936 } else if (!strcasecmp(argv
[0],"daemonize") && argc
== 2) {
1937 if ((server
.daemonize
= yesnotoi(argv
[1])) == -1) {
1938 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1940 } else if (!strcasecmp(argv
[0],"appendonly") && argc
== 2) {
1941 if ((server
.appendonly
= yesnotoi(argv
[1])) == -1) {
1942 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1944 } else if (!strcasecmp(argv
[0],"appendfilename") && argc
== 2) {
1945 zfree(server
.appendfilename
);
1946 server
.appendfilename
= zstrdup(argv
[1]);
1947 } else if (!strcasecmp(argv
[0],"appendfsync") && argc
== 2) {
1948 if (!strcasecmp(argv
[1],"no")) {
1949 server
.appendfsync
= APPENDFSYNC_NO
;
1950 } else if (!strcasecmp(argv
[1],"always")) {
1951 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
1952 } else if (!strcasecmp(argv
[1],"everysec")) {
1953 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
1955 err
= "argument must be 'no', 'always' or 'everysec'";
1958 } else if (!strcasecmp(argv
[0],"requirepass") && argc
== 2) {
1959 server
.requirepass
= zstrdup(argv
[1]);
1960 } else if (!strcasecmp(argv
[0],"pidfile") && argc
== 2) {
1961 zfree(server
.pidfile
);
1962 server
.pidfile
= zstrdup(argv
[1]);
1963 } else if (!strcasecmp(argv
[0],"dbfilename") && argc
== 2) {
1964 zfree(server
.dbfilename
);
1965 server
.dbfilename
= zstrdup(argv
[1]);
1966 } else if (!strcasecmp(argv
[0],"vm-enabled") && argc
== 2) {
1967 if ((server
.vm_enabled
= yesnotoi(argv
[1])) == -1) {
1968 err
= "argument must be 'yes' or 'no'"; goto loaderr
;
1970 } else if (!strcasecmp(argv
[0],"vm-swap-file") && argc
== 2) {
1971 zfree(server
.vm_swap_file
);
1972 server
.vm_swap_file
= zstrdup(argv
[1]);
1973 } else if (!strcasecmp(argv
[0],"vm-max-memory") && argc
== 2) {
1974 server
.vm_max_memory
= memtoll(argv
[1],NULL
);
1975 } else if (!strcasecmp(argv
[0],"vm-page-size") && argc
== 2) {
1976 server
.vm_page_size
= memtoll(argv
[1], NULL
);
1977 } else if (!strcasecmp(argv
[0],"vm-pages") && argc
== 2) {
1978 server
.vm_pages
= memtoll(argv
[1], NULL
);
1979 } else if (!strcasecmp(argv
[0],"vm-max-threads") && argc
== 2) {
1980 server
.vm_max_threads
= strtoll(argv
[1], NULL
, 10);
1981 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-entries") && argc
== 2){
1982 server
.hash_max_zipmap_entries
= memtoll(argv
[1], NULL
);
1983 } else if (!strcasecmp(argv
[0],"hash-max-zipmap-value") && argc
== 2){
1984 server
.hash_max_zipmap_value
= memtoll(argv
[1], NULL
);
1986 err
= "Bad directive or wrong number of arguments"; goto loaderr
;
1988 for (j
= 0; j
< argc
; j
++)
1993 if (fp
!= stdin
) fclose(fp
);
1997 fprintf(stderr
, "\n*** FATAL CONFIG FILE ERROR ***\n");
1998 fprintf(stderr
, "Reading the configuration file, at line %d\n", linenum
);
1999 fprintf(stderr
, ">>> '%s'\n", line
);
2000 fprintf(stderr
, "%s\n", err
);
2004 static void freeClientArgv(redisClient
*c
) {
2007 for (j
= 0; j
< c
->argc
; j
++)
2008 decrRefCount(c
->argv
[j
]);
2009 for (j
= 0; j
< c
->mbargc
; j
++)
2010 decrRefCount(c
->mbargv
[j
]);
2015 static void freeClient(redisClient
*c
) {
2018 /* Note that if the client we are freeing is blocked into a blocking
2019 * call, we have to set querybuf to NULL *before* to call
2020 * unblockClientWaitingData() to avoid processInputBuffer() will get
2021 * called. Also it is important to remove the file events after
2022 * this, because this call adds the READABLE event. */
2023 sdsfree(c
->querybuf
);
2025 if (c
->flags
& REDIS_BLOCKED
)
2026 unblockClientWaitingData(c
);
2028 /* UNWATCH all the keys */
2030 listRelease(c
->watched_keys
);
2031 /* Unsubscribe from all the pubsub channels */
2032 pubsubUnsubscribeAllChannels(c
,0);
2033 pubsubUnsubscribeAllPatterns(c
,0);
2034 dictRelease(c
->pubsub_channels
);
2035 listRelease(c
->pubsub_patterns
);
2036 /* Obvious cleanup */
2037 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
2038 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2039 listRelease(c
->reply
);
2042 /* Remove from the list of clients */
2043 ln
= listSearchKey(server
.clients
,c
);
2044 redisAssert(ln
!= NULL
);
2045 listDelNode(server
.clients
,ln
);
2046 /* Remove from the list of clients that are now ready to be restarted
2047 * after waiting for swapped keys */
2048 if (c
->flags
& REDIS_IO_WAIT
&& listLength(c
->io_keys
) == 0) {
2049 ln
= listSearchKey(server
.io_ready_clients
,c
);
2051 listDelNode(server
.io_ready_clients
,ln
);
2052 server
.vm_blocked_clients
--;
2055 /* Remove from the list of clients waiting for swapped keys */
2056 while (server
.vm_enabled
&& listLength(c
->io_keys
)) {
2057 ln
= listFirst(c
->io_keys
);
2058 dontWaitForSwappedKey(c
,ln
->value
);
2060 listRelease(c
->io_keys
);
2061 /* Master/slave cleanup */
2062 if (c
->flags
& REDIS_SLAVE
) {
2063 if (c
->replstate
== REDIS_REPL_SEND_BULK
&& c
->repldbfd
!= -1)
2065 list
*l
= (c
->flags
& REDIS_MONITOR
) ? server
.monitors
: server
.slaves
;
2066 ln
= listSearchKey(l
,c
);
2067 redisAssert(ln
!= NULL
);
2070 if (c
->flags
& REDIS_MASTER
) {
2071 server
.master
= NULL
;
2072 server
.replstate
= REDIS_REPL_CONNECT
;
2074 /* Release memory */
2077 freeClientMultiState(c
);
2081 #define GLUEREPLY_UP_TO (1024)
2082 static void glueReplyBuffersIfNeeded(redisClient
*c
) {
2084 char buf
[GLUEREPLY_UP_TO
];
2089 listRewind(c
->reply
,&li
);
2090 while((ln
= listNext(&li
))) {
2094 objlen
= sdslen(o
->ptr
);
2095 if (copylen
+ objlen
<= GLUEREPLY_UP_TO
) {
2096 memcpy(buf
+copylen
,o
->ptr
,objlen
);
2098 listDelNode(c
->reply
,ln
);
2100 if (copylen
== 0) return;
2104 /* Now the output buffer is empty, add the new single element */
2105 o
= createObject(REDIS_STRING
,sdsnewlen(buf
,copylen
));
2106 listAddNodeHead(c
->reply
,o
);
2109 static void sendReplyToClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2110 redisClient
*c
= privdata
;
2111 int nwritten
= 0, totwritten
= 0, objlen
;
2114 REDIS_NOTUSED(mask
);
2116 /* Use writev() if we have enough buffers to send */
2117 if (!server
.glueoutputbuf
&&
2118 listLength(c
->reply
) > REDIS_WRITEV_THRESHOLD
&&
2119 !(c
->flags
& REDIS_MASTER
))
2121 sendReplyToClientWritev(el
, fd
, privdata
, mask
);
2125 while(listLength(c
->reply
)) {
2126 if (server
.glueoutputbuf
&& listLength(c
->reply
) > 1)
2127 glueReplyBuffersIfNeeded(c
);
2129 o
= listNodeValue(listFirst(c
->reply
));
2130 objlen
= sdslen(o
->ptr
);
2133 listDelNode(c
->reply
,listFirst(c
->reply
));
2137 if (c
->flags
& REDIS_MASTER
) {
2138 /* Don't reply to a master */
2139 nwritten
= objlen
- c
->sentlen
;
2141 nwritten
= write(fd
, ((char*)o
->ptr
)+c
->sentlen
, objlen
- c
->sentlen
);
2142 if (nwritten
<= 0) break;
2144 c
->sentlen
+= nwritten
;
2145 totwritten
+= nwritten
;
2146 /* If we fully sent the object on head go to the next one */
2147 if (c
->sentlen
== objlen
) {
2148 listDelNode(c
->reply
,listFirst(c
->reply
));
2151 /* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
2152 * bytes, in a single threaded server it's a good idea to serve
2153 * other clients as well, even if a very large request comes from
2154 * super fast link that is always able to accept data (in real world
2155 * scenario think about 'KEYS *' against the loopback interfae) */
2156 if (totwritten
> REDIS_MAX_WRITE_PER_EVENT
) break;
2158 if (nwritten
== -1) {
2159 if (errno
== EAGAIN
) {
2162 redisLog(REDIS_VERBOSE
,
2163 "Error writing to client: %s", strerror(errno
));
2168 if (totwritten
> 0) c
->lastinteraction
= time(NULL
);
2169 if (listLength(c
->reply
) == 0) {
2171 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2175 static void sendReplyToClientWritev(aeEventLoop
*el
, int fd
, void *privdata
, int mask
)
2177 redisClient
*c
= privdata
;
2178 int nwritten
= 0, totwritten
= 0, objlen
, willwrite
;
2180 struct iovec iov
[REDIS_WRITEV_IOVEC_COUNT
];
2181 int offset
, ion
= 0;
2183 REDIS_NOTUSED(mask
);
2186 while (listLength(c
->reply
)) {
2187 offset
= c
->sentlen
;
2191 /* fill-in the iov[] array */
2192 for(node
= listFirst(c
->reply
); node
; node
= listNextNode(node
)) {
2193 o
= listNodeValue(node
);
2194 objlen
= sdslen(o
->ptr
);
2196 if (totwritten
+ objlen
- offset
> REDIS_MAX_WRITE_PER_EVENT
)
2199 if(ion
== REDIS_WRITEV_IOVEC_COUNT
)
2200 break; /* no more iovecs */
2202 iov
[ion
].iov_base
= ((char*)o
->ptr
) + offset
;
2203 iov
[ion
].iov_len
= objlen
- offset
;
2204 willwrite
+= objlen
- offset
;
2205 offset
= 0; /* just for the first item */
2212 /* write all collected blocks at once */
2213 if((nwritten
= writev(fd
, iov
, ion
)) < 0) {
2214 if (errno
!= EAGAIN
) {
2215 redisLog(REDIS_VERBOSE
,
2216 "Error writing to client: %s", strerror(errno
));
2223 totwritten
+= nwritten
;
2224 offset
= c
->sentlen
;
2226 /* remove written robjs from c->reply */
2227 while (nwritten
&& listLength(c
->reply
)) {
2228 o
= listNodeValue(listFirst(c
->reply
));
2229 objlen
= sdslen(o
->ptr
);
2231 if(nwritten
>= objlen
- offset
) {
2232 listDelNode(c
->reply
, listFirst(c
->reply
));
2233 nwritten
-= objlen
- offset
;
2237 c
->sentlen
+= nwritten
;
2245 c
->lastinteraction
= time(NULL
);
2247 if (listLength(c
->reply
) == 0) {
2249 aeDeleteFileEvent(server
.el
,c
->fd
,AE_WRITABLE
);
2253 static int qsortRedisCommands(const void *r1
, const void *r2
) {
2255 ((struct redisCommand
*)r1
)->name
,
2256 ((struct redisCommand
*)r2
)->name
);
2259 static void sortCommandTable() {
2260 /* Copy and sort the read-only version of the command table */
2261 commandTable
= (struct redisCommand
*)malloc(sizeof(readonlyCommandTable
));
2262 memcpy(commandTable
,readonlyCommandTable
,sizeof(readonlyCommandTable
));
2264 sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
),
2265 sizeof(struct redisCommand
),qsortRedisCommands
);
2268 static struct redisCommand
*lookupCommand(char *name
) {
2269 struct redisCommand tmp
= {name
,NULL
,0,0,NULL
,0,0,0};
2273 sizeof(readonlyCommandTable
)/sizeof(struct redisCommand
),
2274 sizeof(struct redisCommand
),
2275 qsortRedisCommands
);
2278 /* resetClient prepare the client to process the next command */
2279 static void resetClient(redisClient
*c
) {
2285 /* Call() is the core of Redis execution of a command */
2286 static void call(redisClient
*c
, struct redisCommand
*cmd
) {
2289 dirty
= server
.dirty
;
2291 dirty
= server
.dirty
-dirty
;
2293 if (server
.appendonly
&& dirty
)
2294 feedAppendOnlyFile(cmd
,c
->db
->id
,c
->argv
,c
->argc
);
2295 if ((dirty
|| cmd
->flags
& REDIS_CMD_FORCE_REPLICATION
) &&
2296 listLength(server
.slaves
))
2297 replicationFeedSlaves(server
.slaves
,c
->db
->id
,c
->argv
,c
->argc
);
2298 if (listLength(server
.monitors
))
2299 replicationFeedMonitors(server
.monitors
,c
->db
->id
,c
->argv
,c
->argc
);
2300 server
.stat_numcommands
++;
2303 /* If this function gets called we already read a whole
2304 * command, argments are in the client argv/argc fields.
2305 * processCommand() execute the command or prepare the
2306 * server for a bulk read from the client.
2308 * If 1 is returned the client is still alive and valid and
2309 * and other operations can be performed by the caller. Otherwise
2310 * if 0 is returned the client was destroied (i.e. after QUIT). */
2311 static int processCommand(redisClient
*c
) {
2312 struct redisCommand
*cmd
;
2314 /* Free some memory if needed (maxmemory setting) */
2315 if (server
.maxmemory
) freeMemoryIfNeeded();
2317 /* Handle the multi bulk command type. This is an alternative protocol
2318 * supported by Redis in order to receive commands that are composed of
2319 * multiple binary-safe "bulk" arguments. The latency of processing is
2320 * a bit higher but this allows things like multi-sets, so if this
2321 * protocol is used only for MSET and similar commands this is a big win. */
2322 if (c
->multibulk
== 0 && c
->argc
== 1 && ((char*)(c
->argv
[0]->ptr
))[0] == '*') {
2323 c
->multibulk
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2324 if (c
->multibulk
<= 0) {
2328 decrRefCount(c
->argv
[c
->argc
-1]);
2332 } else if (c
->multibulk
) {
2333 if (c
->bulklen
== -1) {
2334 if (((char*)c
->argv
[0]->ptr
)[0] != '$') {
2335 addReplySds(c
,sdsnew("-ERR multi bulk protocol error\r\n"));
2339 int bulklen
= atoi(((char*)c
->argv
[0]->ptr
)+1);
2340 decrRefCount(c
->argv
[0]);
2341 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2343 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2348 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2352 c
->mbargv
= zrealloc(c
->mbargv
,(sizeof(robj
*))*(c
->mbargc
+1));
2353 c
->mbargv
[c
->mbargc
] = c
->argv
[0];
2357 if (c
->multibulk
== 0) {
2361 /* Here we need to swap the multi-bulk argc/argv with the
2362 * normal argc/argv of the client structure. */
2364 c
->argv
= c
->mbargv
;
2365 c
->mbargv
= auxargv
;
2368 c
->argc
= c
->mbargc
;
2369 c
->mbargc
= auxargc
;
2371 /* We need to set bulklen to something different than -1
2372 * in order for the code below to process the command without
2373 * to try to read the last argument of a bulk command as
2374 * a special argument. */
2376 /* continue below and process the command */
2383 /* -- end of multi bulk commands processing -- */
2385 /* The QUIT command is handled as a special case. Normal command
2386 * procs are unable to close the client connection safely */
2387 if (!strcasecmp(c
->argv
[0]->ptr
,"quit")) {
2392 /* Now lookup the command and check ASAP about trivial error conditions
2393 * such wrong arity, bad command name and so forth. */
2394 cmd
= lookupCommand(c
->argv
[0]->ptr
);
2397 sdscatprintf(sdsempty(), "-ERR unknown command '%s'\r\n",
2398 (char*)c
->argv
[0]->ptr
));
2401 } else if ((cmd
->arity
> 0 && cmd
->arity
!= c
->argc
) ||
2402 (c
->argc
< -cmd
->arity
)) {
2404 sdscatprintf(sdsempty(),
2405 "-ERR wrong number of arguments for '%s' command\r\n",
2409 } else if (cmd
->flags
& REDIS_CMD_BULK
&& c
->bulklen
== -1) {
2410 /* This is a bulk command, we have to read the last argument yet. */
2411 int bulklen
= atoi(c
->argv
[c
->argc
-1]->ptr
);
2413 decrRefCount(c
->argv
[c
->argc
-1]);
2414 if (bulklen
< 0 || bulklen
> 1024*1024*1024) {
2416 addReplySds(c
,sdsnew("-ERR invalid bulk write count\r\n"));
2421 c
->bulklen
= bulklen
+2; /* add two bytes for CR+LF */
2422 /* It is possible that the bulk read is already in the
2423 * buffer. Check this condition and handle it accordingly.
2424 * This is just a fast path, alternative to call processInputBuffer().
2425 * It's a good idea since the code is small and this condition
2426 * happens most of the times. */
2427 if ((signed)sdslen(c
->querybuf
) >= c
->bulklen
) {
2428 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2430 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2432 /* Otherwise return... there is to read the last argument
2433 * from the socket. */
2437 /* Let's try to encode the bulk object to save space. */
2438 if (cmd
->flags
& REDIS_CMD_BULK
)
2439 c
->argv
[c
->argc
-1] = tryObjectEncoding(c
->argv
[c
->argc
-1]);
2441 /* Check if the user is authenticated */
2442 if (server
.requirepass
&& !c
->authenticated
&& cmd
->proc
!= authCommand
) {
2443 addReplySds(c
,sdsnew("-ERR operation not permitted\r\n"));
2448 /* Handle the maxmemory directive */
2449 if (server
.maxmemory
&& (cmd
->flags
& REDIS_CMD_DENYOOM
) &&
2450 zmalloc_used_memory() > server
.maxmemory
)
2452 addReplySds(c
,sdsnew("-ERR command not allowed when used memory > 'maxmemory'\r\n"));
2457 /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
2458 if ((dictSize(c
->pubsub_channels
) > 0 || listLength(c
->pubsub_patterns
) > 0)
2460 cmd
->proc
!= subscribeCommand
&& cmd
->proc
!= unsubscribeCommand
&&
2461 cmd
->proc
!= psubscribeCommand
&& cmd
->proc
!= punsubscribeCommand
) {
2462 addReplySds(c
,sdsnew("-ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context\r\n"));
2467 /* Exec the command */
2468 if (c
->flags
& REDIS_MULTI
&&
2469 cmd
->proc
!= execCommand
&& cmd
->proc
!= discardCommand
&&
2470 cmd
->proc
!= multiCommand
&& cmd
->proc
!= watchCommand
)
2472 queueMultiCommand(c
,cmd
);
2473 addReply(c
,shared
.queued
);
2475 if (server
.vm_enabled
&& server
.vm_max_threads
> 0 &&
2476 blockClientOnSwappedKeys(c
,cmd
)) return 1;
2480 /* Prepare the client for the next command */
2485 static void replicationFeedSlaves(list
*slaves
, int dictid
, robj
**argv
, int argc
) {
2490 /* We need 1+(ARGS*3) objects since commands are using the new protocol
2491 * and we one 1 object for the first "*<count>\r\n" multibulk count, then
2492 * for every additional object we have "$<count>\r\n" + object + "\r\n". */
2493 robj
*static_outv
[REDIS_STATIC_ARGS
*3+1];
2496 if (argc
<= REDIS_STATIC_ARGS
) {
2499 outv
= zmalloc(sizeof(robj
*)*(argc
*3+1));
2502 lenobj
= createObject(REDIS_STRING
,
2503 sdscatprintf(sdsempty(), "*%d\r\n", argc
));
2504 lenobj
->refcount
= 0;
2505 outv
[outc
++] = lenobj
;
2506 for (j
= 0; j
< argc
; j
++) {
2507 lenobj
= createObject(REDIS_STRING
,
2508 sdscatprintf(sdsempty(),"$%lu\r\n",
2509 (unsigned long) stringObjectLen(argv
[j
])));
2510 lenobj
->refcount
= 0;
2511 outv
[outc
++] = lenobj
;
2512 outv
[outc
++] = argv
[j
];
2513 outv
[outc
++] = shared
.crlf
;
2516 /* Increment all the refcounts at start and decrement at end in order to
2517 * be sure to free objects if there is no slave in a replication state
2518 * able to be feed with commands */
2519 for (j
= 0; j
< outc
; j
++) incrRefCount(outv
[j
]);
2520 listRewind(slaves
,&li
);
2521 while((ln
= listNext(&li
))) {
2522 redisClient
*slave
= ln
->value
;
2524 /* Don't feed slaves that are still waiting for BGSAVE to start */
2525 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) continue;
2527 /* Feed all the other slaves, MONITORs and so on */
2528 if (slave
->slaveseldb
!= dictid
) {
2532 case 0: selectcmd
= shared
.select0
; break;
2533 case 1: selectcmd
= shared
.select1
; break;
2534 case 2: selectcmd
= shared
.select2
; break;
2535 case 3: selectcmd
= shared
.select3
; break;
2536 case 4: selectcmd
= shared
.select4
; break;
2537 case 5: selectcmd
= shared
.select5
; break;
2538 case 6: selectcmd
= shared
.select6
; break;
2539 case 7: selectcmd
= shared
.select7
; break;
2540 case 8: selectcmd
= shared
.select8
; break;
2541 case 9: selectcmd
= shared
.select9
; break;
2543 selectcmd
= createObject(REDIS_STRING
,
2544 sdscatprintf(sdsempty(),"select %d\r\n",dictid
));
2545 selectcmd
->refcount
= 0;
2548 addReply(slave
,selectcmd
);
2549 slave
->slaveseldb
= dictid
;
2551 for (j
= 0; j
< outc
; j
++) addReply(slave
,outv
[j
]);
2553 for (j
= 0; j
< outc
; j
++) decrRefCount(outv
[j
]);
2554 if (outv
!= static_outv
) zfree(outv
);
2557 static sds
sdscatrepr(sds s
, char *p
, size_t len
) {
2558 s
= sdscatlen(s
,"\"",1);
2563 s
= sdscatprintf(s
,"\\%c",*p
);
2565 case '\n': s
= sdscatlen(s
,"\\n",1); break;
2566 case '\r': s
= sdscatlen(s
,"\\r",1); break;
2567 case '\t': s
= sdscatlen(s
,"\\t",1); break;
2568 case '\a': s
= sdscatlen(s
,"\\a",1); break;
2569 case '\b': s
= sdscatlen(s
,"\\b",1); break;
2572 s
= sdscatprintf(s
,"%c",*p
);
2574 s
= sdscatprintf(s
,"\\x%02x",(unsigned char)*p
);
2579 return sdscatlen(s
,"\"",1);
2582 static void replicationFeedMonitors(list
*monitors
, int dictid
, robj
**argv
, int argc
) {
2586 sds cmdrepr
= sdsnew("+");
2590 gettimeofday(&tv
,NULL
);
2591 cmdrepr
= sdscatprintf(cmdrepr
,"%ld.%ld ",(long)tv
.tv_sec
,(long)tv
.tv_usec
);
2592 if (dictid
!= 0) cmdrepr
= sdscatprintf(cmdrepr
,"(db %d) ", dictid
);
2594 for (j
= 0; j
< argc
; j
++) {
2595 if (argv
[j
]->encoding
== REDIS_ENCODING_INT
) {
2596 cmdrepr
= sdscatprintf(cmdrepr
, "%ld", (long)argv
[j
]->ptr
);
2598 cmdrepr
= sdscatrepr(cmdrepr
,(char*)argv
[j
]->ptr
,
2599 sdslen(argv
[j
]->ptr
));
2602 cmdrepr
= sdscatlen(cmdrepr
," ",1);
2604 cmdrepr
= sdscatlen(cmdrepr
,"\r\n",2);
2605 cmdobj
= createObject(REDIS_STRING
,cmdrepr
);
2607 listRewind(monitors
,&li
);
2608 while((ln
= listNext(&li
))) {
2609 redisClient
*monitor
= ln
->value
;
2610 addReply(monitor
,cmdobj
);
2612 decrRefCount(cmdobj
);
2615 static void processInputBuffer(redisClient
*c
) {
2617 /* Before to process the input buffer, make sure the client is not
2618 * waitig for a blocking operation such as BLPOP. Note that the first
2619 * iteration the client is never blocked, otherwise the processInputBuffer
2620 * would not be called at all, but after the execution of the first commands
2621 * in the input buffer the client may be blocked, and the "goto again"
2622 * will try to reiterate. The following line will make it return asap. */
2623 if (c
->flags
& REDIS_BLOCKED
|| c
->flags
& REDIS_IO_WAIT
) return;
2624 if (c
->bulklen
== -1) {
2625 /* Read the first line of the query */
2626 char *p
= strchr(c
->querybuf
,'\n');
2633 query
= c
->querybuf
;
2634 c
->querybuf
= sdsempty();
2635 querylen
= 1+(p
-(query
));
2636 if (sdslen(query
) > querylen
) {
2637 /* leave data after the first line of the query in the buffer */
2638 c
->querybuf
= sdscatlen(c
->querybuf
,query
+querylen
,sdslen(query
)-querylen
);
2640 *p
= '\0'; /* remove "\n" */
2641 if (*(p
-1) == '\r') *(p
-1) = '\0'; /* and "\r" if any */
2642 sdsupdatelen(query
);
2644 /* Now we can split the query in arguments */
2645 argv
= sdssplitlen(query
,sdslen(query
)," ",1,&argc
);
2648 if (c
->argv
) zfree(c
->argv
);
2649 c
->argv
= zmalloc(sizeof(robj
*)*argc
);
2651 for (j
= 0; j
< argc
; j
++) {
2652 if (sdslen(argv
[j
])) {
2653 c
->argv
[c
->argc
] = createObject(REDIS_STRING
,argv
[j
]);
2661 /* Execute the command. If the client is still valid
2662 * after processCommand() return and there is something
2663 * on the query buffer try to process the next command. */
2664 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2666 /* Nothing to process, argc == 0. Just process the query
2667 * buffer if it's not empty or return to the caller */
2668 if (sdslen(c
->querybuf
)) goto again
;
2671 } else if (sdslen(c
->querybuf
) >= REDIS_REQUEST_MAX_SIZE
) {
2672 redisLog(REDIS_VERBOSE
, "Client protocol error");
2677 /* Bulk read handling. Note that if we are at this point
2678 the client already sent a command terminated with a newline,
2679 we are reading the bulk data that is actually the last
2680 argument of the command. */
2681 int qbl
= sdslen(c
->querybuf
);
2683 if (c
->bulklen
<= qbl
) {
2684 /* Copy everything but the final CRLF as final argument */
2685 c
->argv
[c
->argc
] = createStringObject(c
->querybuf
,c
->bulklen
-2);
2687 c
->querybuf
= sdsrange(c
->querybuf
,c
->bulklen
,-1);
2688 /* Process the command. If the client is still valid after
2689 * the processing and there is more data in the buffer
2690 * try to parse it. */
2691 if (processCommand(c
) && sdslen(c
->querybuf
)) goto again
;
2697 static void readQueryFromClient(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2698 redisClient
*c
= (redisClient
*) privdata
;
2699 char buf
[REDIS_IOBUF_LEN
];
2702 REDIS_NOTUSED(mask
);
2704 nread
= read(fd
, buf
, REDIS_IOBUF_LEN
);
2706 if (errno
== EAGAIN
) {
2709 redisLog(REDIS_VERBOSE
, "Reading from client: %s",strerror(errno
));
2713 } else if (nread
== 0) {
2714 redisLog(REDIS_VERBOSE
, "Client closed connection");
2719 c
->querybuf
= sdscatlen(c
->querybuf
, buf
, nread
);
2720 c
->lastinteraction
= time(NULL
);
2724 processInputBuffer(c
);
2727 static int selectDb(redisClient
*c
, int id
) {
2728 if (id
< 0 || id
>= server
.dbnum
)
2730 c
->db
= &server
.db
[id
];
2734 static void *dupClientReplyValue(void *o
) {
2735 incrRefCount((robj
*)o
);
2739 static int listMatchObjects(void *a
, void *b
) {
2740 return equalStringObjects(a
,b
);
2743 static redisClient
*createClient(int fd
) {
2744 redisClient
*c
= zmalloc(sizeof(*c
));
2746 anetNonBlock(NULL
,fd
);
2747 anetTcpNoDelay(NULL
,fd
);
2748 if (!c
) return NULL
;
2751 c
->querybuf
= sdsempty();
2760 c
->lastinteraction
= time(NULL
);
2761 c
->authenticated
= 0;
2762 c
->replstate
= REDIS_REPL_NONE
;
2763 c
->reply
= listCreate();
2764 listSetFreeMethod(c
->reply
,decrRefCount
);
2765 listSetDupMethod(c
->reply
,dupClientReplyValue
);
2766 c
->blocking_keys
= NULL
;
2767 c
->blocking_keys_num
= 0;
2768 c
->io_keys
= listCreate();
2769 c
->watched_keys
= listCreate();
2770 listSetFreeMethod(c
->io_keys
,decrRefCount
);
2771 c
->pubsub_channels
= dictCreate(&setDictType
,NULL
);
2772 c
->pubsub_patterns
= listCreate();
2773 listSetFreeMethod(c
->pubsub_patterns
,decrRefCount
);
2774 listSetMatchMethod(c
->pubsub_patterns
,listMatchObjects
);
2775 if (aeCreateFileEvent(server
.el
, c
->fd
, AE_READABLE
,
2776 readQueryFromClient
, c
) == AE_ERR
) {
2780 listAddNodeTail(server
.clients
,c
);
2781 initClientMultiState(c
);
2785 static void addReply(redisClient
*c
, robj
*obj
) {
2786 if (listLength(c
->reply
) == 0 &&
2787 (c
->replstate
== REDIS_REPL_NONE
||
2788 c
->replstate
== REDIS_REPL_ONLINE
) &&
2789 aeCreateFileEvent(server
.el
, c
->fd
, AE_WRITABLE
,
2790 sendReplyToClient
, c
) == AE_ERR
) return;
2792 if (server
.vm_enabled
&& obj
->storage
!= REDIS_VM_MEMORY
) {
2793 obj
= dupStringObject(obj
);
2794 obj
->refcount
= 0; /* getDecodedObject() will increment the refcount */
2796 listAddNodeTail(c
->reply
,getDecodedObject(obj
));
2799 static void addReplySds(redisClient
*c
, sds s
) {
2800 robj
*o
= createObject(REDIS_STRING
,s
);
2805 static void addReplyDouble(redisClient
*c
, double d
) {
2808 snprintf(buf
,sizeof(buf
),"%.17g",d
);
2809 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n%s\r\n",
2810 (unsigned long) strlen(buf
),buf
));
2813 static void addReplyLongLong(redisClient
*c
, long long ll
) {
2818 addReply(c
,shared
.czero
);
2820 } else if (ll
== 1) {
2821 addReply(c
,shared
.cone
);
2825 len
= ll2string(buf
+1,sizeof(buf
)-1,ll
);
2828 addReplySds(c
,sdsnewlen(buf
,len
+3));
2831 static void addReplyUlong(redisClient
*c
, unsigned long ul
) {
2836 addReply(c
,shared
.czero
);
2838 } else if (ul
== 1) {
2839 addReply(c
,shared
.cone
);
2842 len
= snprintf(buf
,sizeof(buf
),":%lu\r\n",ul
);
2843 addReplySds(c
,sdsnewlen(buf
,len
));
2846 static void addReplyBulkLen(redisClient
*c
, robj
*obj
) {
2850 if (obj
->encoding
== REDIS_ENCODING_RAW
) {
2851 len
= sdslen(obj
->ptr
);
2853 long n
= (long)obj
->ptr
;
2855 /* Compute how many bytes will take this integer as a radix 10 string */
2861 while((n
= n
/10) != 0) {
2866 intlen
= ll2string(buf
+1,sizeof(buf
)-1,(long long)len
);
2867 buf
[intlen
+1] = '\r';
2868 buf
[intlen
+2] = '\n';
2869 addReplySds(c
,sdsnewlen(buf
,intlen
+3));
2872 static void addReplyBulk(redisClient
*c
, robj
*obj
) {
2873 addReplyBulkLen(c
,obj
);
2875 addReply(c
,shared
.crlf
);
2878 /* In the CONFIG command we need to add vanilla C string as bulk replies */
2879 static void addReplyBulkCString(redisClient
*c
, char *s
) {
2881 addReply(c
,shared
.nullbulk
);
2883 robj
*o
= createStringObject(s
,strlen(s
));
2889 static void acceptHandler(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
2894 REDIS_NOTUSED(mask
);
2895 REDIS_NOTUSED(privdata
);
2897 cfd
= anetAccept(server
.neterr
, fd
, cip
, &cport
);
2898 if (cfd
== AE_ERR
) {
2899 redisLog(REDIS_VERBOSE
,"Accepting client connection: %s", server
.neterr
);
2902 redisLog(REDIS_VERBOSE
,"Accepted %s:%d", cip
, cport
);
2903 if ((c
= createClient(cfd
)) == NULL
) {
2904 redisLog(REDIS_WARNING
,"Error allocating resoures for the client");
2905 close(cfd
); /* May be already closed, just ingore errors */
2908 /* If maxclient directive is set and this is one client more... close the
2909 * connection. Note that we create the client instead to check before
2910 * for this condition, since now the socket is already set in nonblocking
2911 * mode and we can send an error for free using the Kernel I/O */
2912 if (server
.maxclients
&& listLength(server
.clients
) > server
.maxclients
) {
2913 char *err
= "-ERR max number of clients reached\r\n";
2915 /* That's a best effort error message, don't check write errors */
2916 if (write(c
->fd
,err
,strlen(err
)) == -1) {
2917 /* Nothing to do, Just to avoid the warning... */
2922 server
.stat_numconnections
++;
2925 /* ======================= Redis objects implementation ===================== */
2927 static robj
*createObject(int type
, void *ptr
) {
2930 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
2931 if (listLength(server
.objfreelist
)) {
2932 listNode
*head
= listFirst(server
.objfreelist
);
2933 o
= listNodeValue(head
);
2934 listDelNode(server
.objfreelist
,head
);
2935 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2937 if (server
.vm_enabled
) {
2938 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
2939 o
= zmalloc(sizeof(*o
));
2941 o
= zmalloc(sizeof(*o
)-sizeof(struct redisObjectVM
));
2945 o
->encoding
= REDIS_ENCODING_RAW
;
2948 if (server
.vm_enabled
) {
2949 /* Note that this code may run in the context of an I/O thread
2950 * and accessing to server.unixtime in theory is an error
2951 * (no locks). But in practice this is safe, and even if we read
2952 * garbage Redis will not fail, as it's just a statistical info */
2953 o
->vm
.atime
= server
.unixtime
;
2954 o
->storage
= REDIS_VM_MEMORY
;
2959 static robj
*createStringObject(char *ptr
, size_t len
) {
2960 return createObject(REDIS_STRING
,sdsnewlen(ptr
,len
));
2963 static robj
*createStringObjectFromLongLong(long long value
) {
2965 if (value
>= 0 && value
< REDIS_SHARED_INTEGERS
) {
2966 incrRefCount(shared
.integers
[value
]);
2967 o
= shared
.integers
[value
];
2969 if (value
>= LONG_MIN
&& value
<= LONG_MAX
) {
2970 o
= createObject(REDIS_STRING
, NULL
);
2971 o
->encoding
= REDIS_ENCODING_INT
;
2972 o
->ptr
= (void*)((long)value
);
2974 o
= createObject(REDIS_STRING
,sdsfromlonglong(value
));
2980 static robj
*dupStringObject(robj
*o
) {
2981 assert(o
->encoding
== REDIS_ENCODING_RAW
);
2982 return createStringObject(o
->ptr
,sdslen(o
->ptr
));
2985 static robj
*createListObject(void) {
2986 list
*l
= listCreate();
2988 listSetFreeMethod(l
,decrRefCount
);
2989 return createObject(REDIS_LIST
,l
);
2992 static robj
*createSetObject(void) {
2993 dict
*d
= dictCreate(&setDictType
,NULL
);
2994 return createObject(REDIS_SET
,d
);
2997 static robj
*createHashObject(void) {
2998 /* All the Hashes start as zipmaps. Will be automatically converted
2999 * into hash tables if there are enough elements or big elements
3001 unsigned char *zm
= zipmapNew();
3002 robj
*o
= createObject(REDIS_HASH
,zm
);
3003 o
->encoding
= REDIS_ENCODING_ZIPMAP
;
3007 static robj
*createZsetObject(void) {
3008 zset
*zs
= zmalloc(sizeof(*zs
));
3010 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
3011 zs
->zsl
= zslCreate();
3012 return createObject(REDIS_ZSET
,zs
);
3015 static void freeStringObject(robj
*o
) {
3016 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3021 static void freeListObject(robj
*o
) {
3022 switch (o
->encoding
) {
3023 case REDIS_ENCODING_LIST
:
3024 listRelease((list
*) o
->ptr
);
3026 case REDIS_ENCODING_ZIPLIST
:
3030 redisPanic("Unknown list encoding type");
3034 static void freeSetObject(robj
*o
) {
3035 dictRelease((dict
*) o
->ptr
);
3038 static void freeZsetObject(robj
*o
) {
3041 dictRelease(zs
->dict
);
3046 static void freeHashObject(robj
*o
) {
3047 switch (o
->encoding
) {
3048 case REDIS_ENCODING_HT
:
3049 dictRelease((dict
*) o
->ptr
);
3051 case REDIS_ENCODING_ZIPMAP
:
3055 redisPanic("Unknown hash encoding type");
3060 static void incrRefCount(robj
*o
) {
3064 static void decrRefCount(void *obj
) {
3067 if (o
->refcount
<= 0) redisPanic("decrRefCount against refcount <= 0");
3068 /* Object is a key of a swapped out value, or in the process of being
3070 if (server
.vm_enabled
&&
3071 (o
->storage
== REDIS_VM_SWAPPED
|| o
->storage
== REDIS_VM_LOADING
))
3073 if (o
->storage
== REDIS_VM_LOADING
) vmCancelThreadedIOJob(obj
);
3074 redisAssert(o
->type
== REDIS_STRING
);
3075 freeStringObject(o
);
3076 vmMarkPagesFree(o
->vm
.page
,o
->vm
.usedpages
);
3077 pthread_mutex_lock(&server
.obj_freelist_mutex
);
3078 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
3079 !listAddNodeHead(server
.objfreelist
,o
))
3081 pthread_mutex_unlock(&server
.obj_freelist_mutex
);
3082 server
.vm_stats_swapped_objects
--;
3085 /* Object is in memory, or in the process of being swapped out. */
3086 if (--(o
->refcount
) == 0) {
3087 if (server
.vm_enabled
&& o
->storage
== REDIS_VM_SWAPPING
)
3088 vmCancelThreadedIOJob(obj
);
3090 case REDIS_STRING
: freeStringObject(o
); break;
3091 case REDIS_LIST
: freeListObject(o
); break;
3092 case REDIS_SET
: freeSetObject(o
); break;
3093 case REDIS_ZSET
: freeZsetObject(o
); break;
3094 case REDIS_HASH
: freeHashObject(o
); break;
3095 default: redisPanic("Unknown object type"); break;
3097 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
3098 if (listLength(server
.objfreelist
) > REDIS_OBJFREELIST_MAX
||
3099 !listAddNodeHead(server
.objfreelist
,o
))
3101 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
3105 static robj
*lookupKey(redisDb
*db
, robj
*key
) {
3106 dictEntry
*de
= dictFind(db
->dict
,key
);
3108 robj
*key
= dictGetEntryKey(de
);
3109 robj
*val
= dictGetEntryVal(de
);
3111 if (server
.vm_enabled
) {
3112 if (key
->storage
== REDIS_VM_MEMORY
||
3113 key
->storage
== REDIS_VM_SWAPPING
)
3115 /* If we were swapping the object out, stop it, this key
3117 if (key
->storage
== REDIS_VM_SWAPPING
)
3118 vmCancelThreadedIOJob(key
);
3119 /* Update the access time of the key for the aging algorithm. */
3120 key
->vm
.atime
= server
.unixtime
;
3122 int notify
= (key
->storage
== REDIS_VM_LOADING
);
3124 /* Our value was swapped on disk. Bring it at home. */
3125 redisAssert(val
== NULL
);
3126 val
= vmLoadObject(key
);
3127 dictGetEntryVal(de
) = val
;
3129 /* Clients blocked by the VM subsystem may be waiting for
3131 if (notify
) handleClientsBlockedOnSwappedKey(db
,key
);
3140 static robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
3141 expireIfNeeded(db
,key
);
3142 return lookupKey(db
,key
);
3145 static robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
3146 deleteIfVolatile(db
,key
);
3147 touchWatchedKey(db
,key
);
3148 return lookupKey(db
,key
);
3151 static robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
3152 robj
*o
= lookupKeyRead(c
->db
, key
);
3153 if (!o
) addReply(c
,reply
);
3157 static robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
3158 robj
*o
= lookupKeyWrite(c
->db
, key
);
3159 if (!o
) addReply(c
,reply
);
3163 static int checkType(redisClient
*c
, robj
*o
, int type
) {
3164 if (o
->type
!= type
) {
3165 addReply(c
,shared
.wrongtypeerr
);
3171 static int deleteKey(redisDb
*db
, robj
*key
) {
3174 /* We need to protect key from destruction: after the first dictDelete()
3175 * it may happen that 'key' is no longer valid if we don't increment
3176 * it's count. This may happen when we get the object reference directly
3177 * from the hash table with dictRandomKey() or dict iterators */
3179 if (dictSize(db
->expires
)) dictDelete(db
->expires
,key
);
3180 retval
= dictDelete(db
->dict
,key
);
3183 return retval
== DICT_OK
;
3186 /* Check if the nul-terminated string 's' can be represented by a long
3187 * (that is, is a number that fits into long without any other space or
3188 * character before or after the digits).
3190 * If so, the function returns REDIS_OK and *longval is set to the value
3191 * of the number. Otherwise REDIS_ERR is returned */
3192 static int isStringRepresentableAsLong(sds s
, long *longval
) {
3193 char buf
[32], *endptr
;
3197 value
= strtol(s
, &endptr
, 10);
3198 if (endptr
[0] != '\0') return REDIS_ERR
;
3199 slen
= ll2string(buf
,32,value
);
3201 /* If the number converted back into a string is not identical
3202 * then it's not possible to encode the string as integer */
3203 if (sdslen(s
) != (unsigned)slen
|| memcmp(buf
,s
,slen
)) return REDIS_ERR
;
3204 if (longval
) *longval
= value
;
3208 /* Try to encode a string object in order to save space */
3209 static robj
*tryObjectEncoding(robj
*o
) {
3213 if (o
->encoding
!= REDIS_ENCODING_RAW
)
3214 return o
; /* Already encoded */
3216 /* It's not safe to encode shared objects: shared objects can be shared
3217 * everywhere in the "object space" of Redis. Encoded objects can only
3218 * appear as "values" (and not, for instance, as keys) */
3219 if (o
->refcount
> 1) return o
;
3221 /* Currently we try to encode only strings */
3222 redisAssert(o
->type
== REDIS_STRING
);
3224 /* Check if we can represent this string as a long integer */
3225 if (isStringRepresentableAsLong(s
,&value
) == REDIS_ERR
) return o
;
3227 /* Ok, this object can be encoded */
3228 if (value
>= 0 && value
< REDIS_SHARED_INTEGERS
) {
3230 incrRefCount(shared
.integers
[value
]);
3231 return shared
.integers
[value
];
3233 o
->encoding
= REDIS_ENCODING_INT
;
3235 o
->ptr
= (void*) value
;
3240 /* Get a decoded version of an encoded object (returned as a new object).
3241 * If the object is already raw-encoded just increment the ref count. */
3242 static robj
*getDecodedObject(robj
*o
) {
3245 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3249 if (o
->type
== REDIS_STRING
&& o
->encoding
== REDIS_ENCODING_INT
) {
3252 ll2string(buf
,32,(long)o
->ptr
);
3253 dec
= createStringObject(buf
,strlen(buf
));
3256 redisPanic("Unknown encoding type");
3260 /* Compare two string objects via strcmp() or alike.
3261 * Note that the objects may be integer-encoded. In such a case we
3262 * use ll2string() to get a string representation of the numbers on the stack
3263 * and compare the strings, it's much faster than calling getDecodedObject().
3265 * Important note: if objects are not integer encoded, but binary-safe strings,
3266 * sdscmp() from sds.c will apply memcmp() so this function ca be considered
3268 static int compareStringObjects(robj
*a
, robj
*b
) {
3269 redisAssert(a
->type
== REDIS_STRING
&& b
->type
== REDIS_STRING
);
3270 char bufa
[128], bufb
[128], *astr
, *bstr
;
3273 if (a
== b
) return 0;
3274 if (a
->encoding
!= REDIS_ENCODING_RAW
) {
3275 ll2string(bufa
,sizeof(bufa
),(long) a
->ptr
);
3281 if (b
->encoding
!= REDIS_ENCODING_RAW
) {
3282 ll2string(bufb
,sizeof(bufb
),(long) b
->ptr
);
3288 return bothsds
? sdscmp(astr
,bstr
) : strcmp(astr
,bstr
);
3291 /* Equal string objects return 1 if the two objects are the same from the
3292 * point of view of a string comparison, otherwise 0 is returned. Note that
3293 * this function is faster then checking for (compareStringObject(a,b) == 0)
3294 * because it can perform some more optimization. */
3295 static int equalStringObjects(robj
*a
, robj
*b
) {
3296 if (a
->encoding
!= REDIS_ENCODING_RAW
&& b
->encoding
!= REDIS_ENCODING_RAW
){
3297 return a
->ptr
== b
->ptr
;
3299 return compareStringObjects(a
,b
) == 0;
3303 static size_t stringObjectLen(robj
*o
) {
3304 redisAssert(o
->type
== REDIS_STRING
);
3305 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3306 return sdslen(o
->ptr
);
3310 return ll2string(buf
,32,(long)o
->ptr
);
3314 static int getDoubleFromObject(robj
*o
, double *target
) {
3321 redisAssert(o
->type
== REDIS_STRING
);
3322 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3323 value
= strtod(o
->ptr
, &eptr
);
3324 if (eptr
[0] != '\0') return REDIS_ERR
;
3325 } else if (o
->encoding
== REDIS_ENCODING_INT
) {
3326 value
= (long)o
->ptr
;
3328 redisPanic("Unknown string encoding");
3336 static int getDoubleFromObjectOrReply(redisClient
*c
, robj
*o
, double *target
, const char *msg
) {
3338 if (getDoubleFromObject(o
, &value
) != REDIS_OK
) {
3340 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3342 addReplySds(c
, sdsnew("-ERR value is not a double\r\n"));
3351 static int getLongLongFromObject(robj
*o
, long long *target
) {
3358 redisAssert(o
->type
== REDIS_STRING
);
3359 if (o
->encoding
== REDIS_ENCODING_RAW
) {
3360 value
= strtoll(o
->ptr
, &eptr
, 10);
3361 if (eptr
[0] != '\0') return REDIS_ERR
;
3362 } else if (o
->encoding
== REDIS_ENCODING_INT
) {
3363 value
= (long)o
->ptr
;
3365 redisPanic("Unknown string encoding");
3373 static int getLongLongFromObjectOrReply(redisClient
*c
, robj
*o
, long long *target
, const char *msg
) {
3375 if (getLongLongFromObject(o
, &value
) != REDIS_OK
) {
3377 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3379 addReplySds(c
, sdsnew("-ERR value is not an integer\r\n"));
3388 static int getLongFromObjectOrReply(redisClient
*c
, robj
*o
, long *target
, const char *msg
) {
3391 if (getLongLongFromObjectOrReply(c
, o
, &value
, msg
) != REDIS_OK
) return REDIS_ERR
;
3392 if (value
< LONG_MIN
|| value
> LONG_MAX
) {
3394 addReplySds(c
, sdscatprintf(sdsempty(), "-ERR %s\r\n", msg
));
3396 addReplySds(c
, sdsnew("-ERR value is out of range\r\n"));
3405 /*============================ RDB saving/loading =========================== */
3407 static int rdbSaveType(FILE *fp
, unsigned char type
) {
3408 if (fwrite(&type
,1,1,fp
) == 0) return -1;
3412 static int rdbSaveTime(FILE *fp
, time_t t
) {
3413 int32_t t32
= (int32_t) t
;
3414 if (fwrite(&t32
,4,1,fp
) == 0) return -1;
3418 /* check rdbLoadLen() comments for more info */
3419 static int rdbSaveLen(FILE *fp
, uint32_t len
) {
3420 unsigned char buf
[2];
3423 /* Save a 6 bit len */
3424 buf
[0] = (len
&0xFF)|(REDIS_RDB_6BITLEN
<<6);
3425 if (fwrite(buf
,1,1,fp
) == 0) return -1;
3426 } else if (len
< (1<<14)) {
3427 /* Save a 14 bit len */
3428 buf
[0] = ((len
>>8)&0xFF)|(REDIS_RDB_14BITLEN
<<6);
3430 if (fwrite(buf
,2,1,fp
) == 0) return -1;
3432 /* Save a 32 bit len */
3433 buf
[0] = (REDIS_RDB_32BITLEN
<<6);
3434 if (fwrite(buf
,1,1,fp
) == 0) return -1;
3436 if (fwrite(&len
,4,1,fp
) == 0) return -1;
3441 /* Encode 'value' as an integer if possible (if integer will fit the
3442 * supported range). If the function sucessful encoded the integer
3443 * then the (up to 5 bytes) encoded representation is written in the
3444 * string pointed by 'enc' and the length is returned. Otherwise
3446 static int rdbEncodeInteger(long long value
, unsigned char *enc
) {
3447 /* Finally check if it fits in our ranges */
3448 if (value
>= -(1<<7) && value
<= (1<<7)-1) {
3449 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT8
;
3450 enc
[1] = value
&0xFF;
3452 } else if (value
>= -(1<<15) && value
<= (1<<15)-1) {
3453 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT16
;
3454 enc
[1] = value
&0xFF;
3455 enc
[2] = (value
>>8)&0xFF;
3457 } else if (value
>= -((long long)1<<31) && value
<= ((long long)1<<31)-1) {
3458 enc
[0] = (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_INT32
;
3459 enc
[1] = value
&0xFF;
3460 enc
[2] = (value
>>8)&0xFF;
3461 enc
[3] = (value
>>16)&0xFF;
3462 enc
[4] = (value
>>24)&0xFF;
3469 /* String objects in the form "2391" "-100" without any space and with a
3470 * range of values that can fit in an 8, 16 or 32 bit signed value can be
3471 * encoded as integers to save space */
3472 static int rdbTryIntegerEncoding(char *s
, size_t len
, unsigned char *enc
) {
3474 char *endptr
, buf
[32];
3476 /* Check if it's possible to encode this value as a number */
3477 value
= strtoll(s
, &endptr
, 10);
3478 if (endptr
[0] != '\0') return 0;
3479 ll2string(buf
,32,value
);
3481 /* If the number converted back into a string is not identical
3482 * then it's not possible to encode the string as integer */
3483 if (strlen(buf
) != len
|| memcmp(buf
,s
,len
)) return 0;
3485 return rdbEncodeInteger(value
,enc
);
3488 static int rdbSaveLzfStringObject(FILE *fp
, unsigned char *s
, size_t len
) {
3489 size_t comprlen
, outlen
;
3493 /* We require at least four bytes compression for this to be worth it */
3494 if (len
<= 4) return 0;
3496 if ((out
= zmalloc(outlen
+1)) == NULL
) return 0;
3497 comprlen
= lzf_compress(s
, len
, out
, outlen
);
3498 if (comprlen
== 0) {
3502 /* Data compressed! Let's save it on disk */
3503 byte
= (REDIS_RDB_ENCVAL
<<6)|REDIS_RDB_ENC_LZF
;
3504 if (fwrite(&byte
,1,1,fp
) == 0) goto writeerr
;
3505 if (rdbSaveLen(fp
,comprlen
) == -1) goto writeerr
;
3506 if (rdbSaveLen(fp
,len
) == -1) goto writeerr
;
3507 if (fwrite(out
,comprlen
,1,fp
) == 0) goto writeerr
;
3516 /* Save a string objet as [len][data] on disk. If the object is a string
3517 * representation of an integer value we try to safe it in a special form */
3518 static int rdbSaveRawString(FILE *fp
, unsigned char *s
, size_t len
) {
3521 /* Try integer encoding */
3523 unsigned char buf
[5];
3524 if ((enclen
= rdbTryIntegerEncoding((char*)s
,len
,buf
)) > 0) {
3525 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3530 /* Try LZF compression - under 20 bytes it's unable to compress even
3531 * aaaaaaaaaaaaaaaaaa so skip it */
3532 if (server
.rdbcompression
&& len
> 20) {
3535 retval
= rdbSaveLzfStringObject(fp
,s
,len
);
3536 if (retval
== -1) return -1;
3537 if (retval
> 0) return 0;
3538 /* retval == 0 means data can't be compressed, save the old way */
3541 /* Store verbatim */
3542 if (rdbSaveLen(fp
,len
) == -1) return -1;
3543 if (len
&& fwrite(s
,len
,1,fp
) == 0) return -1;
3547 /* Like rdbSaveStringObjectRaw() but handle encoded objects */
3548 static int rdbSaveStringObject(FILE *fp
, robj
*obj
) {
3551 /* Avoid to decode the object, then encode it again, if the
3552 * object is alrady integer encoded. */
3553 if (obj
->encoding
== REDIS_ENCODING_INT
) {
3554 long val
= (long) obj
->ptr
;
3555 unsigned char buf
[5];
3558 if ((enclen
= rdbEncodeInteger(val
,buf
)) > 0) {
3559 if (fwrite(buf
,enclen
,1,fp
) == 0) return -1;
3562 /* otherwise... fall throught and continue with the usual
3566 /* Avoid incr/decr ref count business when possible.
3567 * This plays well with copy-on-write given that we are probably
3568 * in a child process (BGSAVE). Also this makes sure key objects
3569 * of swapped objects are not incRefCount-ed (an assert does not allow
3570 * this in order to avoid bugs) */
3571 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
3572 obj
= getDecodedObject(obj
);
3573 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3576 retval
= rdbSaveRawString(fp
,obj
->ptr
,sdslen(obj
->ptr
));
3581 /* Save a double value. Doubles are saved as strings prefixed by an unsigned
3582 * 8 bit integer specifing the length of the representation.
3583 * This 8 bit integer has special values in order to specify the following
3589 static int rdbSaveDoubleValue(FILE *fp
, double val
) {
3590 unsigned char buf
[128];
3596 } else if (!isfinite(val
)) {
3598 buf
[0] = (val
< 0) ? 255 : 254;
3600 #if (DBL_MANT_DIG >= 52) && (LLONG_MAX == 0x7fffffffffffffffLL)
3601 /* Check if the float is in a safe range to be casted into a
3602 * long long. We are assuming that long long is 64 bit here.
3603 * Also we are assuming that there are no implementations around where
3604 * double has precision < 52 bit.
3606 * Under this assumptions we test if a double is inside an interval
3607 * where casting to long long is safe. Then using two castings we
3608 * make sure the decimal part is zero. If all this is true we use
3609 * integer printing function that is much faster. */
3610 double min
= -4503599627370495; /* (2^52)-1 */
3611 double max
= 4503599627370496; /* -(2^52) */
3612 if (val
> min
&& val
< max
&& val
== ((double)((long long)val
)))
3613 ll2string((char*)buf
+1,sizeof(buf
),(long long)val
);
3616 snprintf((char*)buf
+1,sizeof(buf
)-1,"%.17g",val
);
3617 buf
[0] = strlen((char*)buf
+1);
3620 if (fwrite(buf
,len
,1,fp
) == 0) return -1;
3624 /* Save a Redis object. */
3625 static int rdbSaveObject(FILE *fp
, robj
*o
) {
3626 if (o
->type
== REDIS_STRING
) {
3627 /* Save a string value */
3628 if (rdbSaveStringObject(fp
,o
) == -1) return -1;
3629 } else if (o
->type
== REDIS_LIST
) {
3630 /* Save a list value */
3631 list
*list
= o
->ptr
;
3635 if (rdbSaveLen(fp
,listLength(list
)) == -1) return -1;
3636 listRewind(list
,&li
);
3637 while((ln
= listNext(&li
))) {
3638 robj
*eleobj
= listNodeValue(ln
);
3640 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3642 } else if (o
->type
== REDIS_SET
) {
3643 /* Save a set value */
3645 dictIterator
*di
= dictGetIterator(set
);
3648 if (rdbSaveLen(fp
,dictSize(set
)) == -1) return -1;
3649 while((de
= dictNext(di
)) != NULL
) {
3650 robj
*eleobj
= dictGetEntryKey(de
);
3652 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3654 dictReleaseIterator(di
);
3655 } else if (o
->type
== REDIS_ZSET
) {
3656 /* Save a set value */
3658 dictIterator
*di
= dictGetIterator(zs
->dict
);
3661 if (rdbSaveLen(fp
,dictSize(zs
->dict
)) == -1) return -1;
3662 while((de
= dictNext(di
)) != NULL
) {
3663 robj
*eleobj
= dictGetEntryKey(de
);
3664 double *score
= dictGetEntryVal(de
);
3666 if (rdbSaveStringObject(fp
,eleobj
) == -1) return -1;
3667 if (rdbSaveDoubleValue(fp
,*score
) == -1) return -1;
3669 dictReleaseIterator(di
);
3670 } else if (o
->type
== REDIS_HASH
) {
3671 /* Save a hash value */
3672 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
3673 unsigned char *p
= zipmapRewind(o
->ptr
);
3674 unsigned int count
= zipmapLen(o
->ptr
);
3675 unsigned char *key
, *val
;
3676 unsigned int klen
, vlen
;
3678 if (rdbSaveLen(fp
,count
) == -1) return -1;
3679 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
3680 if (rdbSaveRawString(fp
,key
,klen
) == -1) return -1;
3681 if (rdbSaveRawString(fp
,val
,vlen
) == -1) return -1;
3684 dictIterator
*di
= dictGetIterator(o
->ptr
);
3687 if (rdbSaveLen(fp
,dictSize((dict
*)o
->ptr
)) == -1) return -1;
3688 while((de
= dictNext(di
)) != NULL
) {
3689 robj
*key
= dictGetEntryKey(de
);
3690 robj
*val
= dictGetEntryVal(de
);
3692 if (rdbSaveStringObject(fp
,key
) == -1) return -1;
3693 if (rdbSaveStringObject(fp
,val
) == -1) return -1;
3695 dictReleaseIterator(di
);
3698 redisPanic("Unknown object type");
3703 /* Return the length the object will have on disk if saved with
3704 * the rdbSaveObject() function. Currently we use a trick to get
3705 * this length with very little changes to the code. In the future
3706 * we could switch to a faster solution. */
3707 static off_t
rdbSavedObjectLen(robj
*o
, FILE *fp
) {
3708 if (fp
== NULL
) fp
= server
.devnull
;
3710 assert(rdbSaveObject(fp
,o
) != 1);
3714 /* Return the number of pages required to save this object in the swap file */
3715 static off_t
rdbSavedObjectPages(robj
*o
, FILE *fp
) {
3716 off_t bytes
= rdbSavedObjectLen(o
,fp
);
3718 return (bytes
+(server
.vm_page_size
-1))/server
.vm_page_size
;
3721 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
3722 static int rdbSave(char *filename
) {
3723 dictIterator
*di
= NULL
;
3728 time_t now
= time(NULL
);
3730 /* Wait for I/O therads to terminate, just in case this is a
3731 * foreground-saving, to avoid seeking the swap file descriptor at the
3733 if (server
.vm_enabled
)
3734 waitEmptyIOJobsQueue();
3736 snprintf(tmpfile
,256,"temp-%d.rdb", (int) getpid());
3737 fp
= fopen(tmpfile
,"w");
3739 redisLog(REDIS_WARNING
, "Failed saving the DB: %s", strerror(errno
));
3742 if (fwrite("REDIS0001",9,1,fp
) == 0) goto werr
;
3743 for (j
= 0; j
< server
.dbnum
; j
++) {
3744 redisDb
*db
= server
.db
+j
;
3746 if (dictSize(d
) == 0) continue;
3747 di
= dictGetIterator(d
);
3753 /* Write the SELECT DB opcode */
3754 if (rdbSaveType(fp
,REDIS_SELECTDB
) == -1) goto werr
;
3755 if (rdbSaveLen(fp
,j
) == -1) goto werr
;
3757 /* Iterate this DB writing every entry */
3758 while((de
= dictNext(di
)) != NULL
) {
3759 robj
*key
= dictGetEntryKey(de
);
3760 robj
*o
= dictGetEntryVal(de
);
3761 time_t expiretime
= getExpire(db
,key
);
3763 /* Save the expire time */
3764 if (expiretime
!= -1) {
3765 /* If this key is already expired skip it */
3766 if (expiretime
< now
) continue;
3767 if (rdbSaveType(fp
,REDIS_EXPIRETIME
) == -1) goto werr
;
3768 if (rdbSaveTime(fp
,expiretime
) == -1) goto werr
;
3770 /* Save the key and associated value. This requires special
3771 * handling if the value is swapped out. */
3772 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
3773 key
->storage
== REDIS_VM_SWAPPING
) {
3774 /* Save type, key, value */
3775 if (rdbSaveType(fp
,o
->type
) == -1) goto werr
;
3776 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3777 if (rdbSaveObject(fp
,o
) == -1) goto werr
;
3779 /* REDIS_VM_SWAPPED or REDIS_VM_LOADING */
3781 /* Get a preview of the object in memory */
3782 po
= vmPreviewObject(key
);
3783 /* Save type, key, value */
3784 if (rdbSaveType(fp
,key
->vtype
) == -1) goto werr
;
3785 if (rdbSaveStringObject(fp
,key
) == -1) goto werr
;
3786 if (rdbSaveObject(fp
,po
) == -1) goto werr
;
3787 /* Remove the loaded object from memory */
3791 dictReleaseIterator(di
);
3794 if (rdbSaveType(fp
,REDIS_EOF
) == -1) goto werr
;
3796 /* Make sure data will not remain on the OS's output buffers */
3801 /* Use RENAME to make sure the DB file is changed atomically only
3802 * if the generate DB file is ok. */
3803 if (rename(tmpfile
,filename
) == -1) {
3804 redisLog(REDIS_WARNING
,"Error moving temp DB file on the final destination: %s", strerror(errno
));
3808 redisLog(REDIS_NOTICE
,"DB saved on disk");
3810 server
.lastsave
= time(NULL
);
3816 redisLog(REDIS_WARNING
,"Write error saving DB on disk: %s", strerror(errno
));
3817 if (di
) dictReleaseIterator(di
);
3821 static int rdbSaveBackground(char *filename
) {
3824 if (server
.bgsavechildpid
!= -1) return REDIS_ERR
;
3825 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
3826 if ((childpid
= fork()) == 0) {
3828 if (server
.vm_enabled
) vmReopenSwapFile();
3830 if (rdbSave(filename
) == REDIS_OK
) {
3837 if (childpid
== -1) {
3838 redisLog(REDIS_WARNING
,"Can't save in background: fork: %s",
3842 redisLog(REDIS_NOTICE
,"Background saving started by pid %d",childpid
);
3843 server
.bgsavechildpid
= childpid
;
3844 updateDictResizePolicy();
3847 return REDIS_OK
; /* unreached */
3850 static void rdbRemoveTempFile(pid_t childpid
) {
3853 snprintf(tmpfile
,256,"temp-%d.rdb", (int) childpid
);
3857 static int rdbLoadType(FILE *fp
) {
3859 if (fread(&type
,1,1,fp
) == 0) return -1;
3863 static time_t rdbLoadTime(FILE *fp
) {
3865 if (fread(&t32
,4,1,fp
) == 0) return -1;
3866 return (time_t) t32
;
3869 /* Load an encoded length from the DB, see the REDIS_RDB_* defines on the top
3870 * of this file for a description of how this are stored on disk.
3872 * isencoded is set to 1 if the readed length is not actually a length but
3873 * an "encoding type", check the above comments for more info */
3874 static uint32_t rdbLoadLen(FILE *fp
, int *isencoded
) {
3875 unsigned char buf
[2];
3879 if (isencoded
) *isencoded
= 0;
3880 if (fread(buf
,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3881 type
= (buf
[0]&0xC0)>>6;
3882 if (type
== REDIS_RDB_6BITLEN
) {
3883 /* Read a 6 bit len */
3885 } else if (type
== REDIS_RDB_ENCVAL
) {
3886 /* Read a 6 bit len encoding type */
3887 if (isencoded
) *isencoded
= 1;
3889 } else if (type
== REDIS_RDB_14BITLEN
) {
3890 /* Read a 14 bit len */
3891 if (fread(buf
+1,1,1,fp
) == 0) return REDIS_RDB_LENERR
;
3892 return ((buf
[0]&0x3F)<<8)|buf
[1];
3894 /* Read a 32 bit len */
3895 if (fread(&len
,4,1,fp
) == 0) return REDIS_RDB_LENERR
;
3900 /* Load an integer-encoded object from file 'fp', with the specified
3901 * encoding type 'enctype'. If encode is true the function may return
3902 * an integer-encoded object as reply, otherwise the returned object
3903 * will always be encoded as a raw string. */
3904 static robj
*rdbLoadIntegerObject(FILE *fp
, int enctype
, int encode
) {
3905 unsigned char enc
[4];
3908 if (enctype
== REDIS_RDB_ENC_INT8
) {
3909 if (fread(enc
,1,1,fp
) == 0) return NULL
;
3910 val
= (signed char)enc
[0];
3911 } else if (enctype
== REDIS_RDB_ENC_INT16
) {
3913 if (fread(enc
,2,1,fp
) == 0) return NULL
;
3914 v
= enc
[0]|(enc
[1]<<8);
3916 } else if (enctype
== REDIS_RDB_ENC_INT32
) {
3918 if (fread(enc
,4,1,fp
) == 0) return NULL
;
3919 v
= enc
[0]|(enc
[1]<<8)|(enc
[2]<<16)|(enc
[3]<<24);
3922 val
= 0; /* anti-warning */
3923 redisPanic("Unknown RDB integer encoding type");
3926 return createStringObjectFromLongLong(val
);
3928 return createObject(REDIS_STRING
,sdsfromlonglong(val
));
3931 static robj
*rdbLoadLzfStringObject(FILE*fp
) {
3932 unsigned int len
, clen
;
3933 unsigned char *c
= NULL
;
3936 if ((clen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3937 if ((len
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
3938 if ((c
= zmalloc(clen
)) == NULL
) goto err
;
3939 if ((val
= sdsnewlen(NULL
,len
)) == NULL
) goto err
;
3940 if (fread(c
,clen
,1,fp
) == 0) goto err
;
3941 if (lzf_decompress(c
,clen
,val
,len
) == 0) goto err
;
3943 return createObject(REDIS_STRING
,val
);
3950 static robj
*rdbGenericLoadStringObject(FILE*fp
, int encode
) {
3955 len
= rdbLoadLen(fp
,&isencoded
);
3958 case REDIS_RDB_ENC_INT8
:
3959 case REDIS_RDB_ENC_INT16
:
3960 case REDIS_RDB_ENC_INT32
:
3961 return rdbLoadIntegerObject(fp
,len
,encode
);
3962 case REDIS_RDB_ENC_LZF
:
3963 return rdbLoadLzfStringObject(fp
);
3965 redisPanic("Unknown RDB encoding type");
3969 if (len
== REDIS_RDB_LENERR
) return NULL
;
3970 val
= sdsnewlen(NULL
,len
);
3971 if (len
&& fread(val
,len
,1,fp
) == 0) {
3975 return createObject(REDIS_STRING
,val
);
3978 static robj
*rdbLoadStringObject(FILE *fp
) {
3979 return rdbGenericLoadStringObject(fp
,0);
3982 static robj
*rdbLoadEncodedStringObject(FILE *fp
) {
3983 return rdbGenericLoadStringObject(fp
,1);
3986 /* For information about double serialization check rdbSaveDoubleValue() */
3987 static int rdbLoadDoubleValue(FILE *fp
, double *val
) {
3991 if (fread(&len
,1,1,fp
) == 0) return -1;
3993 case 255: *val
= R_NegInf
; return 0;
3994 case 254: *val
= R_PosInf
; return 0;
3995 case 253: *val
= R_Nan
; return 0;
3997 if (fread(buf
,len
,1,fp
) == 0) return -1;
3999 sscanf(buf
, "%lg", val
);
4004 /* Load a Redis object of the specified type from the specified file.
4005 * On success a newly allocated object is returned, otherwise NULL. */
4006 static robj
*rdbLoadObject(int type
, FILE *fp
) {
4009 redisLog(REDIS_DEBUG
,"LOADING OBJECT %d (at %d)\n",type
,ftell(fp
));
4010 if (type
== REDIS_STRING
) {
4011 /* Read string value */
4012 if ((o
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
4013 o
= tryObjectEncoding(o
);
4014 } else if (type
== REDIS_LIST
|| type
== REDIS_SET
) {
4015 /* Read list/set value */
4018 if ((listlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
4019 o
= (type
== REDIS_LIST
) ? createListObject() : createSetObject();
4020 /* It's faster to expand the dict to the right size asap in order
4021 * to avoid rehashing */
4022 if (type
== REDIS_SET
&& listlen
> DICT_HT_INITIAL_SIZE
)
4023 dictExpand(o
->ptr
,listlen
);
4024 /* Load every single element of the list/set */
4028 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
4029 ele
= tryObjectEncoding(ele
);
4030 if (type
== REDIS_LIST
) {
4031 listAddNodeTail((list
*)o
->ptr
,ele
);
4033 dictAdd((dict
*)o
->ptr
,ele
,NULL
);
4036 } else if (type
== REDIS_ZSET
) {
4037 /* Read list/set value */
4041 if ((zsetlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
4042 o
= createZsetObject();
4044 /* Load every single element of the list/set */
4047 double *score
= zmalloc(sizeof(double));
4049 if ((ele
= rdbLoadEncodedStringObject(fp
)) == NULL
) return NULL
;
4050 ele
= tryObjectEncoding(ele
);
4051 if (rdbLoadDoubleValue(fp
,score
) == -1) return NULL
;
4052 dictAdd(zs
->dict
,ele
,score
);
4053 zslInsert(zs
->zsl
,*score
,ele
);
4054 incrRefCount(ele
); /* added to skiplist */
4056 } else if (type
== REDIS_HASH
) {
4059 if ((hashlen
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
) return NULL
;
4060 o
= createHashObject();
4061 /* Too many entries? Use an hash table. */
4062 if (hashlen
> server
.hash_max_zipmap_entries
)
4063 convertToRealHash(o
);
4064 /* Load every key/value, then set it into the zipmap or hash
4065 * table, as needed. */
4069 if ((key
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
4070 if ((val
= rdbLoadStringObject(fp
)) == NULL
) return NULL
;
4071 /* If we are using a zipmap and there are too big values
4072 * the object is converted to real hash table encoding. */
4073 if (o
->encoding
!= REDIS_ENCODING_HT
&&
4074 (sdslen(key
->ptr
) > server
.hash_max_zipmap_value
||
4075 sdslen(val
->ptr
) > server
.hash_max_zipmap_value
))
4077 convertToRealHash(o
);
4080 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
4081 unsigned char *zm
= o
->ptr
;
4083 zm
= zipmapSet(zm
,key
->ptr
,sdslen(key
->ptr
),
4084 val
->ptr
,sdslen(val
->ptr
),NULL
);
4089 key
= tryObjectEncoding(key
);
4090 val
= tryObjectEncoding(val
);
4091 dictAdd((dict
*)o
->ptr
,key
,val
);
4095 redisPanic("Unknown object type");
4100 static int rdbLoad(char *filename
) {
4103 int type
, retval
, rdbver
;
4104 int swap_all_values
= 0;
4105 dict
*d
= server
.db
[0].dict
;
4106 redisDb
*db
= server
.db
+0;
4108 time_t expiretime
, now
= time(NULL
);
4109 long long loadedkeys
= 0;
4111 fp
= fopen(filename
,"r");
4112 if (!fp
) return REDIS_ERR
;
4113 if (fread(buf
,9,1,fp
) == 0) goto eoferr
;
4115 if (memcmp(buf
,"REDIS",5) != 0) {
4117 redisLog(REDIS_WARNING
,"Wrong signature trying to load DB from file");
4120 rdbver
= atoi(buf
+5);
4123 redisLog(REDIS_WARNING
,"Can't handle RDB format version %d",rdbver
);
4131 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
4132 if (type
== REDIS_EXPIRETIME
) {
4133 if ((expiretime
= rdbLoadTime(fp
)) == -1) goto eoferr
;
4134 /* We read the time so we need to read the object type again */
4135 if ((type
= rdbLoadType(fp
)) == -1) goto eoferr
;
4137 if (type
== REDIS_EOF
) break;
4138 /* Handle SELECT DB opcode as a special case */
4139 if (type
== REDIS_SELECTDB
) {
4140 if ((dbid
= rdbLoadLen(fp
,NULL
)) == REDIS_RDB_LENERR
)
4142 if (dbid
>= (unsigned)server
.dbnum
) {
4143 redisLog(REDIS_WARNING
,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server
.dbnum
);
4146 db
= server
.db
+dbid
;
4151 if ((key
= rdbLoadStringObject(fp
)) == NULL
) goto eoferr
;
4153 if ((val
= rdbLoadObject(type
,fp
)) == NULL
) goto eoferr
;
4154 /* Check if the key already expired */
4155 if (expiretime
!= -1 && expiretime
< now
) {
4160 /* Add the new object in the hash table */
4161 retval
= dictAdd(d
,key
,val
);
4162 if (retval
== DICT_ERR
) {
4163 redisLog(REDIS_WARNING
,"Loading DB, duplicated key (%s) found! Unrecoverable error, exiting now.", key
->ptr
);
4167 /* Set the expire time if needed */
4168 if (expiretime
!= -1) setExpire(db
,key
,expiretime
);
4170 /* Handle swapping while loading big datasets when VM is on */
4172 /* If we detecter we are hopeless about fitting something in memory
4173 * we just swap every new key on disk. Directly...
4174 * Note that's important to check for this condition before resorting
4175 * to random sampling, otherwise we may try to swap already
4177 if (swap_all_values
) {
4178 dictEntry
*de
= dictFind(d
,key
);
4180 /* de may be NULL since the key already expired */
4182 key
= dictGetEntryKey(de
);
4183 val
= dictGetEntryVal(de
);
4185 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
4186 dictGetEntryVal(de
) = NULL
;
4192 /* If we have still some hope of having some value fitting memory
4193 * then we try random sampling. */
4194 if (!swap_all_values
&& server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
4195 while (zmalloc_used_memory() > server
.vm_max_memory
) {
4196 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
4198 if (zmalloc_used_memory() > server
.vm_max_memory
)
4199 swap_all_values
= 1; /* We are already using too much mem */
4205 eoferr
: /* unexpected end of file is handled here with a fatal exit */
4206 redisLog(REDIS_WARNING
,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
4208 return REDIS_ERR
; /* Just to avoid warning */
4211 /*================================== Shutdown =============================== */
4212 static int prepareForShutdown() {
4213 redisLog(REDIS_WARNING
,"User requested shutdown, saving DB...");
4214 /* Kill the saving child if there is a background saving in progress.
4215 We want to avoid race conditions, for instance our saving child may
4216 overwrite the synchronous saving did by SHUTDOWN. */
4217 if (server
.bgsavechildpid
!= -1) {
4218 redisLog(REDIS_WARNING
,"There is a live saving child. Killing it!");
4219 kill(server
.bgsavechildpid
,SIGKILL
);
4220 rdbRemoveTempFile(server
.bgsavechildpid
);
4222 if (server
.appendonly
) {
4223 /* Append only file: fsync() the AOF and exit */
4224 fsync(server
.appendfd
);
4225 if (server
.vm_enabled
) unlink(server
.vm_swap_file
);
4227 /* Snapshotting. Perform a SYNC SAVE and exit */
4228 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4229 if (server
.daemonize
)
4230 unlink(server
.pidfile
);
4231 redisLog(REDIS_WARNING
,"%zu bytes used at exit",zmalloc_used_memory());
4233 /* Ooops.. error saving! The best we can do is to continue
4234 * operating. Note that if there was a background saving process,
4235 * in the next cron() Redis will be notified that the background
4236 * saving aborted, handling special stuff like slaves pending for
4237 * synchronization... */
4238 redisLog(REDIS_WARNING
,"Error trying to save the DB, can't exit");
4242 redisLog(REDIS_WARNING
,"Server exit now, bye bye...");
4246 /*================================== Commands =============================== */
4248 static void authCommand(redisClient
*c
) {
4249 if (!server
.requirepass
|| !strcmp(c
->argv
[1]->ptr
, server
.requirepass
)) {
4250 c
->authenticated
= 1;
4251 addReply(c
,shared
.ok
);
4253 c
->authenticated
= 0;
4254 addReplySds(c
,sdscatprintf(sdsempty(),"-ERR invalid password\r\n"));
4258 static void pingCommand(redisClient
*c
) {
4259 addReply(c
,shared
.pong
);
4262 static void echoCommand(redisClient
*c
) {
4263 addReplyBulk(c
,c
->argv
[1]);
4266 /*=================================== Strings =============================== */
4268 static void setGenericCommand(redisClient
*c
, int nx
, robj
*key
, robj
*val
, robj
*expire
) {
4270 long seconds
= 0; /* initialized to avoid an harmness warning */
4273 if (getLongFromObjectOrReply(c
, expire
, &seconds
, NULL
) != REDIS_OK
)
4276 addReplySds(c
,sdsnew("-ERR invalid expire time in SETEX\r\n"));
4281 touchWatchedKey(c
->db
,key
);
4282 if (nx
) deleteIfVolatile(c
->db
,key
);
4283 retval
= dictAdd(c
->db
->dict
,key
,val
);
4284 if (retval
== DICT_ERR
) {
4286 /* If the key is about a swapped value, we want a new key object
4287 * to overwrite the old. So we delete the old key in the database.
4288 * This will also make sure that swap pages about the old object
4289 * will be marked as free. */
4290 if (server
.vm_enabled
&& deleteIfSwapped(c
->db
,key
))
4292 dictReplace(c
->db
->dict
,key
,val
);
4295 addReply(c
,shared
.czero
);
4303 removeExpire(c
->db
,key
);
4304 if (expire
) setExpire(c
->db
,key
,time(NULL
)+seconds
);
4305 addReply(c
, nx
? shared
.cone
: shared
.ok
);
4308 static void setCommand(redisClient
*c
) {
4309 setGenericCommand(c
,0,c
->argv
[1],c
->argv
[2],NULL
);
4312 static void setnxCommand(redisClient
*c
) {
4313 setGenericCommand(c
,1,c
->argv
[1],c
->argv
[2],NULL
);
4316 static void setexCommand(redisClient
*c
) {
4317 setGenericCommand(c
,0,c
->argv
[1],c
->argv
[3],c
->argv
[2]);
4320 static int getGenericCommand(redisClient
*c
) {
4323 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
)
4326 if (o
->type
!= REDIS_STRING
) {
4327 addReply(c
,shared
.wrongtypeerr
);
4335 static void getCommand(redisClient
*c
) {
4336 getGenericCommand(c
);
4339 static void getsetCommand(redisClient
*c
) {
4340 if (getGenericCommand(c
) == REDIS_ERR
) return;
4341 if (dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]) == DICT_ERR
) {
4342 dictReplace(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
4344 incrRefCount(c
->argv
[1]);
4346 incrRefCount(c
->argv
[2]);
4348 removeExpire(c
->db
,c
->argv
[1]);
4351 static void mgetCommand(redisClient
*c
) {
4354 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-1));
4355 for (j
= 1; j
< c
->argc
; j
++) {
4356 robj
*o
= lookupKeyRead(c
->db
,c
->argv
[j
]);
4358 addReply(c
,shared
.nullbulk
);
4360 if (o
->type
!= REDIS_STRING
) {
4361 addReply(c
,shared
.nullbulk
);
4369 static void msetGenericCommand(redisClient
*c
, int nx
) {
4370 int j
, busykeys
= 0;
4372 if ((c
->argc
% 2) == 0) {
4373 addReplySds(c
,sdsnew("-ERR wrong number of arguments for MSET\r\n"));
4376 /* Handle the NX flag. The MSETNX semantic is to return zero and don't
4377 * set nothing at all if at least one already key exists. */
4379 for (j
= 1; j
< c
->argc
; j
+= 2) {
4380 if (lookupKeyWrite(c
->db
,c
->argv
[j
]) != NULL
) {
4386 addReply(c
, shared
.czero
);
4390 for (j
= 1; j
< c
->argc
; j
+= 2) {
4393 c
->argv
[j
+1] = tryObjectEncoding(c
->argv
[j
+1]);
4394 retval
= dictAdd(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
4395 if (retval
== DICT_ERR
) {
4396 dictReplace(c
->db
->dict
,c
->argv
[j
],c
->argv
[j
+1]);
4397 incrRefCount(c
->argv
[j
+1]);
4399 incrRefCount(c
->argv
[j
]);
4400 incrRefCount(c
->argv
[j
+1]);
4402 removeExpire(c
->db
,c
->argv
[j
]);
4404 server
.dirty
+= (c
->argc
-1)/2;
4405 addReply(c
, nx
? shared
.cone
: shared
.ok
);
4408 static void msetCommand(redisClient
*c
) {
4409 msetGenericCommand(c
,0);
4412 static void msetnxCommand(redisClient
*c
) {
4413 msetGenericCommand(c
,1);
4416 static void incrDecrCommand(redisClient
*c
, long long incr
) {
4421 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4422 if (o
!= NULL
&& checkType(c
,o
,REDIS_STRING
)) return;
4423 if (getLongLongFromObjectOrReply(c
,o
,&value
,NULL
) != REDIS_OK
) return;
4426 o
= createStringObjectFromLongLong(value
);
4427 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],o
);
4428 if (retval
== DICT_ERR
) {
4429 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
4430 removeExpire(c
->db
,c
->argv
[1]);
4432 incrRefCount(c
->argv
[1]);
4435 addReply(c
,shared
.colon
);
4437 addReply(c
,shared
.crlf
);
4440 static void incrCommand(redisClient
*c
) {
4441 incrDecrCommand(c
,1);
4444 static void decrCommand(redisClient
*c
) {
4445 incrDecrCommand(c
,-1);
4448 static void incrbyCommand(redisClient
*c
) {
4451 if (getLongLongFromObjectOrReply(c
, c
->argv
[2], &incr
, NULL
) != REDIS_OK
) return;
4452 incrDecrCommand(c
,incr
);
4455 static void decrbyCommand(redisClient
*c
) {
4458 if (getLongLongFromObjectOrReply(c
, c
->argv
[2], &incr
, NULL
) != REDIS_OK
) return;
4459 incrDecrCommand(c
,-incr
);
4462 static void appendCommand(redisClient
*c
) {
4467 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4469 /* Create the key */
4470 retval
= dictAdd(c
->db
->dict
,c
->argv
[1],c
->argv
[2]);
4471 incrRefCount(c
->argv
[1]);
4472 incrRefCount(c
->argv
[2]);
4473 totlen
= stringObjectLen(c
->argv
[2]);
4477 de
= dictFind(c
->db
->dict
,c
->argv
[1]);
4480 o
= dictGetEntryVal(de
);
4481 if (o
->type
!= REDIS_STRING
) {
4482 addReply(c
,shared
.wrongtypeerr
);
4485 /* If the object is specially encoded or shared we have to make
4487 if (o
->refcount
!= 1 || o
->encoding
!= REDIS_ENCODING_RAW
) {
4488 robj
*decoded
= getDecodedObject(o
);
4490 o
= createStringObject(decoded
->ptr
, sdslen(decoded
->ptr
));
4491 decrRefCount(decoded
);
4492 dictReplace(c
->db
->dict
,c
->argv
[1],o
);
4495 if (c
->argv
[2]->encoding
== REDIS_ENCODING_RAW
) {
4496 o
->ptr
= sdscatlen(o
->ptr
,
4497 c
->argv
[2]->ptr
, sdslen(c
->argv
[2]->ptr
));
4499 o
->ptr
= sdscatprintf(o
->ptr
, "%ld",
4500 (unsigned long) c
->argv
[2]->ptr
);
4502 totlen
= sdslen(o
->ptr
);
4505 addReplySds(c
,sdscatprintf(sdsempty(),":%lu\r\n",(unsigned long)totlen
));
4508 static void substrCommand(redisClient
*c
) {
4510 long start
= atoi(c
->argv
[2]->ptr
);
4511 long end
= atoi(c
->argv
[3]->ptr
);
4512 size_t rangelen
, strlen
;
4515 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
4516 checkType(c
,o
,REDIS_STRING
)) return;
4518 o
= getDecodedObject(o
);
4519 strlen
= sdslen(o
->ptr
);
4521 /* convert negative indexes */
4522 if (start
< 0) start
= strlen
+start
;
4523 if (end
< 0) end
= strlen
+end
;
4524 if (start
< 0) start
= 0;
4525 if (end
< 0) end
= 0;
4527 /* indexes sanity checks */
4528 if (start
> end
|| (size_t)start
>= strlen
) {
4529 /* Out of range start or start > end result in null reply */
4530 addReply(c
,shared
.nullbulk
);
4534 if ((size_t)end
>= strlen
) end
= strlen
-1;
4535 rangelen
= (end
-start
)+1;
4537 /* Return the result */
4538 addReplySds(c
,sdscatprintf(sdsempty(),"$%zu\r\n",rangelen
));
4539 range
= sdsnewlen((char*)o
->ptr
+start
,rangelen
);
4540 addReplySds(c
,range
);
4541 addReply(c
,shared
.crlf
);
4545 /* ========================= Type agnostic commands ========================= */
4547 static void delCommand(redisClient
*c
) {
4550 for (j
= 1; j
< c
->argc
; j
++) {
4551 if (deleteKey(c
->db
,c
->argv
[j
])) {
4552 touchWatchedKey(c
->db
,c
->argv
[j
]);
4557 addReplyLongLong(c
,deleted
);
4560 static void existsCommand(redisClient
*c
) {
4561 expireIfNeeded(c
->db
,c
->argv
[1]);
4562 if (dictFind(c
->db
->dict
,c
->argv
[1])) {
4563 addReply(c
, shared
.cone
);
4565 addReply(c
, shared
.czero
);
4569 static void selectCommand(redisClient
*c
) {
4570 int id
= atoi(c
->argv
[1]->ptr
);
4572 if (selectDb(c
,id
) == REDIS_ERR
) {
4573 addReplySds(c
,sdsnew("-ERR invalid DB index\r\n"));
4575 addReply(c
,shared
.ok
);
4579 static void randomkeyCommand(redisClient
*c
) {
4584 de
= dictGetRandomKey(c
->db
->dict
);
4585 if (!de
|| expireIfNeeded(c
->db
,dictGetEntryKey(de
)) == 0) break;
4589 addReply(c
,shared
.nullbulk
);
4593 key
= dictGetEntryKey(de
);
4594 if (server
.vm_enabled
) {
4595 key
= dupStringObject(key
);
4596 addReplyBulk(c
,key
);
4599 addReplyBulk(c
,key
);
4603 static void keysCommand(redisClient
*c
) {
4606 sds pattern
= c
->argv
[1]->ptr
;
4607 int plen
= sdslen(pattern
);
4608 unsigned long numkeys
= 0;
4609 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
4611 di
= dictGetIterator(c
->db
->dict
);
4613 decrRefCount(lenobj
);
4614 while((de
= dictNext(di
)) != NULL
) {
4615 robj
*keyobj
= dictGetEntryKey(de
);
4617 sds key
= keyobj
->ptr
;
4618 if ((pattern
[0] == '*' && pattern
[1] == '\0') ||
4619 stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
4620 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
4621 addReplyBulk(c
,keyobj
);
4626 dictReleaseIterator(di
);
4627 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",numkeys
);
4630 static void dbsizeCommand(redisClient
*c
) {
4632 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c
->db
->dict
)));
4635 static void lastsaveCommand(redisClient
*c
) {
4637 sdscatprintf(sdsempty(),":%lu\r\n",server
.lastsave
));
4640 static void typeCommand(redisClient
*c
) {
4644 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
4649 case REDIS_STRING
: type
= "+string"; break;
4650 case REDIS_LIST
: type
= "+list"; break;
4651 case REDIS_SET
: type
= "+set"; break;
4652 case REDIS_ZSET
: type
= "+zset"; break;
4653 case REDIS_HASH
: type
= "+hash"; break;
4654 default: type
= "+unknown"; break;
4657 addReplySds(c
,sdsnew(type
));
4658 addReply(c
,shared
.crlf
);
4661 static void saveCommand(redisClient
*c
) {
4662 if (server
.bgsavechildpid
!= -1) {
4663 addReplySds(c
,sdsnew("-ERR background save in progress\r\n"));
4666 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
4667 addReply(c
,shared
.ok
);
4669 addReply(c
,shared
.err
);
4673 static void bgsaveCommand(redisClient
*c
) {
4674 if (server
.bgsavechildpid
!= -1) {
4675 addReplySds(c
,sdsnew("-ERR background save already in progress\r\n"));
4678 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
4679 char *status
= "+Background saving started\r\n";
4680 addReplySds(c
,sdsnew(status
));
4682 addReply(c
,shared
.err
);
4686 static void shutdownCommand(redisClient
*c
) {
4687 if (prepareForShutdown() == REDIS_OK
)
4689 addReplySds(c
, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
4692 static void renameGenericCommand(redisClient
*c
, int nx
) {
4695 /* To use the same key as src and dst is probably an error */
4696 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
4697 addReply(c
,shared
.sameobjecterr
);
4701 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
4705 deleteIfVolatile(c
->db
,c
->argv
[2]);
4706 if (dictAdd(c
->db
->dict
,c
->argv
[2],o
) == DICT_ERR
) {
4709 addReply(c
,shared
.czero
);
4712 dictReplace(c
->db
->dict
,c
->argv
[2],o
);
4714 incrRefCount(c
->argv
[2]);
4716 deleteKey(c
->db
,c
->argv
[1]);
4717 touchWatchedKey(c
->db
,c
->argv
[2]);
4719 addReply(c
,nx
? shared
.cone
: shared
.ok
);
4722 static void renameCommand(redisClient
*c
) {
4723 renameGenericCommand(c
,0);
4726 static void renamenxCommand(redisClient
*c
) {
4727 renameGenericCommand(c
,1);
4730 static void moveCommand(redisClient
*c
) {
4735 /* Obtain source and target DB pointers */
4738 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
4739 addReply(c
,shared
.outofrangeerr
);
4743 selectDb(c
,srcid
); /* Back to the source DB */
4745 /* If the user is moving using as target the same
4746 * DB as the source DB it is probably an error. */
4748 addReply(c
,shared
.sameobjecterr
);
4752 /* Check if the element exists and get a reference */
4753 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4755 addReply(c
,shared
.czero
);
4759 /* Try to add the element to the target DB */
4760 deleteIfVolatile(dst
,c
->argv
[1]);
4761 if (dictAdd(dst
->dict
,c
->argv
[1],o
) == DICT_ERR
) {
4762 addReply(c
,shared
.czero
);
4765 incrRefCount(c
->argv
[1]);
4768 /* OK! key moved, free the entry in the source DB */
4769 deleteKey(src
,c
->argv
[1]);
4771 addReply(c
,shared
.cone
);
4774 /* =================================== Lists ================================ */
4775 static void lPush(robj
*subject
, robj
*value
, int where
) {
4776 if (subject
->encoding
== REDIS_ENCODING_ZIPLIST
) {
4777 int pos
= (where
== REDIS_HEAD
) ? ZIPLIST_HEAD
: ZIPLIST_TAIL
;
4778 value
= getDecodedObject(value
);
4779 subject
->ptr
= ziplistPush(subject
->ptr
,value
->ptr
,sdslen(value
->ptr
),pos
);
4780 decrRefCount(value
);
4781 } else if (subject
->encoding
== REDIS_ENCODING_LIST
) {
4782 if (where
== REDIS_HEAD
) {
4783 listAddNodeHead(subject
->ptr
,value
);
4785 listAddNodeTail(subject
->ptr
,value
);
4787 incrRefCount(value
);
4789 redisPanic("Unknown list encoding");
4793 static robj
*lPop(robj
*subject
, int where
) {
4795 if (subject
->encoding
== REDIS_ENCODING_ZIPLIST
) {
4800 int pos
= (where
== REDIS_HEAD
) ? 0 : -1;
4801 p
= ziplistIndex(subject
->ptr
,pos
);
4802 if (ziplistGet(p
,&v
,&vlen
,&vval
)) {
4804 value
= createStringObject(v
,vlen
);
4806 value
= createStringObjectFromLongLong(vval
);
4809 subject
->ptr
= ziplistDelete(subject
->ptr
,&p
,ZIPLIST_TAIL
);
4810 } else if (subject
->encoding
== REDIS_ENCODING_LIST
) {
4811 list
*list
= subject
->ptr
;
4813 if (where
== REDIS_HEAD
) {
4814 ln
= listFirst(list
);
4816 ln
= listLast(list
);
4819 value
= listNodeValue(ln
);
4820 incrRefCount(value
);
4821 listDelNode(list
,ln
);
4824 redisPanic("Unknown list encoding");
4829 static unsigned long lLength(robj
*subject
) {
4830 if (subject
->encoding
== REDIS_ENCODING_ZIPLIST
) {
4831 return ziplistLen(subject
->ptr
);
4832 } else if (subject
->encoding
== REDIS_ENCODING_LIST
) {
4833 return listLength((list
*)subject
->ptr
);
4835 redisPanic("Unknown list encoding");
4839 /* Structure to hold set iteration abstraction. */
4842 unsigned char encoding
;
4847 /* Initialize an iterator at the specified index. */
4848 static lIterator
*lInitIterator(robj
*subject
, int index
) {
4849 lIterator
*li
= zmalloc(sizeof(lIterator
));
4850 li
->subject
= subject
;
4851 li
->encoding
= subject
->encoding
;
4852 if (li
->encoding
== REDIS_ENCODING_ZIPLIST
) {
4853 li
->zi
= ziplistIndex(subject
->ptr
,index
);
4854 } else if (li
->encoding
== REDIS_ENCODING_LIST
) {
4855 li
->ln
= listIndex(subject
->ptr
,index
);
4857 redisPanic("Unknown list encoding");
4862 /* Clean up the iterator. */
4863 static void lReleaseIterator(lIterator
*li
) {
4867 /* Return entry or NULL at the current position of the iterator. */
4868 static robj
*lGet(lIterator
*li
) {
4870 if (li
->encoding
== REDIS_ENCODING_ZIPLIST
) {
4874 redisAssert(li
->zi
!= NULL
);
4875 if (ziplistGet(li
->zi
,&v
,&vlen
,&vval
)) {
4877 value
= createStringObject(v
,vlen
);
4879 value
= createStringObjectFromLongLong(vval
);
4882 } else if (li
->encoding
== REDIS_ENCODING_LIST
) {
4883 redisAssert(li
->ln
!= NULL
);
4884 value
= listNodeValue(li
->ln
);
4885 incrRefCount(value
);
4887 redisPanic("Unknown list encoding");
4892 /* Move to the next or previous entry in the list. */
4893 static void lMove(lIterator
*li
, int where
) {
4894 if (li
->encoding
== REDIS_ENCODING_ZIPLIST
) {
4895 redisAssert(li
->zi
!= NULL
);
4896 if (where
== REDIS_HEAD
)
4897 li
->zi
= ziplistPrev(li
->zi
);
4899 li
->zi
= ziplistNext(li
->zi
);
4900 } else if (li
->encoding
== REDIS_ENCODING_LIST
) {
4901 redisAssert(li
->ln
!= NULL
);
4902 if (where
== REDIS_HEAD
)
4903 li
->ln
= li
->ln
->prev
;
4905 li
->ln
= li
->ln
->next
;
4907 redisPanic("Unknown list encoding");
4911 static void pushGenericCommand(redisClient
*c
, int where
) {
4912 robj
*lobj
= lookupKeyWrite(c
->db
,c
->argv
[1]);
4914 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4915 addReply(c
,shared
.cone
);
4918 lobj
= createObject(REDIS_LIST
,ziplistNew());
4919 lobj
->encoding
= REDIS_ENCODING_ZIPLIST
;
4920 dictAdd(c
->db
->dict
,c
->argv
[1],lobj
);
4921 incrRefCount(c
->argv
[1]);
4923 if (lobj
->type
!= REDIS_LIST
) {
4924 addReply(c
,shared
.wrongtypeerr
);
4927 if (handleClientsWaitingListPush(c
,c
->argv
[1],c
->argv
[2])) {
4928 addReply(c
,shared
.cone
);
4932 lPush(lobj
,c
->argv
[2],where
);
4933 addReplyLongLong(c
,lLength(lobj
));
4937 static void lpushCommand(redisClient
*c
) {
4938 pushGenericCommand(c
,REDIS_HEAD
);
4941 static void rpushCommand(redisClient
*c
) {
4942 pushGenericCommand(c
,REDIS_TAIL
);
4945 static void llenCommand(redisClient
*c
) {
4946 robj
*o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
);
4947 if (o
== NULL
|| checkType(c
,o
,REDIS_LIST
)) return;
4948 addReplyUlong(c
,lLength(o
));
4951 static void lindexCommand(redisClient
*c
) {
4952 robj
*o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
);
4953 if (o
== NULL
|| checkType(c
,o
,REDIS_LIST
)) return;
4954 int index
= atoi(c
->argv
[2]->ptr
);
4956 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
4961 p
= ziplistIndex(o
->ptr
,index
);
4962 if (ziplistGet(p
,&v
,&vlen
,&vval
)) {
4964 addReplySds(c
,sdsnewlen(v
,vlen
));
4966 addReplyLongLong(c
,vval
);
4969 addReply(c
,shared
.nullbulk
);
4971 } else if (o
->encoding
== REDIS_ENCODING_LIST
) {
4972 listNode
*ln
= listIndex(o
->ptr
,index
);
4974 addReply(c
,(robj
*)listNodeValue(ln
));
4976 addReply(c
,shared
.nullbulk
);
4979 redisPanic("Unknown list encoding");
4983 static void lsetCommand(redisClient
*c
) {
4984 robj
*o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
);
4985 if (o
== NULL
|| checkType(c
,o
,REDIS_LIST
)) return;
4986 int index
= atoi(c
->argv
[2]->ptr
);
4987 robj
*value
= c
->argv
[3];
4989 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
4990 unsigned char *p
, *zl
= o
->ptr
;
4991 p
= ziplistIndex(zl
,index
);
4993 addReply(c
,shared
.outofrangeerr
);
4995 o
->ptr
= ziplistDelete(o
->ptr
,&p
,ZIPLIST_TAIL
);
4996 value
= getDecodedObject(value
);
4997 o
->ptr
= ziplistInsert(o
->ptr
,p
,value
->ptr
,sdslen(value
->ptr
));
4998 decrRefCount(value
);
4999 addReply(c
,shared
.ok
);
5002 } else if (o
->encoding
== REDIS_ENCODING_LIST
) {
5003 listNode
*ln
= listIndex(o
->ptr
,index
);
5005 addReply(c
,shared
.outofrangeerr
);
5007 decrRefCount((robj
*)listNodeValue(ln
));
5008 listNodeValue(ln
) = value
;
5009 incrRefCount(value
);
5010 addReply(c
,shared
.ok
);
5014 redisPanic("Unknown list encoding");
5018 static void popGenericCommand(redisClient
*c
, int where
) {
5019 robj
*o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
);
5020 if (o
== NULL
|| checkType(c
,o
,REDIS_LIST
)) return;
5022 robj
*value
= lPop(o
,where
);
5023 if (value
== NULL
) {
5024 addReply(c
,shared
.nullbulk
);
5026 addReplyBulk(c
,value
);
5027 decrRefCount(value
);
5028 if (lLength(o
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5033 static void lpopCommand(redisClient
*c
) {
5034 popGenericCommand(c
,REDIS_HEAD
);
5037 static void rpopCommand(redisClient
*c
) {
5038 popGenericCommand(c
,REDIS_TAIL
);
5041 static void lrangeCommand(redisClient
*c
) {
5043 int start
= atoi(c
->argv
[2]->ptr
);
5044 int end
= atoi(c
->argv
[3]->ptr
);
5048 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
5049 || checkType(c
,o
,REDIS_LIST
)) return;
5052 /* convert negative indexes */
5053 if (start
< 0) start
= llen
+start
;
5054 if (end
< 0) end
= llen
+end
;
5055 if (start
< 0) start
= 0;
5056 if (end
< 0) end
= 0;
5058 /* indexes sanity checks */
5059 if (start
> end
|| start
>= llen
) {
5060 /* Out of range start or start > end result in empty list */
5061 addReply(c
,shared
.emptymultibulk
);
5064 if (end
>= llen
) end
= llen
-1;
5065 rangelen
= (end
-start
)+1;
5067 /* Return the result in form of a multi-bulk reply */
5068 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",rangelen
));
5069 lIterator
*li
= lInitIterator(o
,start
);
5070 for (j
= 0; j
< rangelen
; j
++) {
5072 redisAssert(value
!= NULL
);
5073 addReplyBulk(c
,value
);
5074 lMove(li
,REDIS_TAIL
);
5076 lReleaseIterator(li
);
5079 static void ltrimCommand(redisClient
*c
) {
5081 int start
= atoi(c
->argv
[2]->ptr
);
5082 int end
= atoi(c
->argv
[3]->ptr
);
5084 int j
, ltrim
, rtrim
;
5088 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.ok
)) == NULL
||
5089 checkType(c
,o
,REDIS_LIST
)) return;
5092 /* convert negative indexes */
5093 if (start
< 0) start
= llen
+start
;
5094 if (end
< 0) end
= llen
+end
;
5095 if (start
< 0) start
= 0;
5096 if (end
< 0) end
= 0;
5098 /* indexes sanity checks */
5099 if (start
> end
|| start
>= llen
) {
5100 /* Out of range start or start > end result in empty list */
5104 if (end
>= llen
) end
= llen
-1;
5109 /* Remove list elements to perform the trim */
5110 if (o
->encoding
== REDIS_ENCODING_ZIPLIST
) {
5111 o
->ptr
= ziplistDeleteRange(o
->ptr
,0,ltrim
);
5112 o
->ptr
= ziplistDeleteRange(o
->ptr
,-rtrim
,rtrim
);
5113 } else if (o
->encoding
== REDIS_ENCODING_LIST
) {
5115 for (j
= 0; j
< ltrim
; j
++) {
5116 ln
= listFirst(list
);
5117 listDelNode(list
,ln
);
5119 for (j
= 0; j
< rtrim
; j
++) {
5120 ln
= listLast(list
);
5121 listDelNode(list
,ln
);
5124 redisPanic("Unknown list encoding");
5126 if (lLength(o
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5128 addReply(c
,shared
.ok
);
5131 static void lremCommand(redisClient
*c
) {
5134 listNode
*ln
, *next
;
5135 int toremove
= atoi(c
->argv
[2]->ptr
);
5139 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5140 checkType(c
,o
,REDIS_LIST
)) return;
5144 toremove
= -toremove
;
5147 ln
= fromtail
? list
->tail
: list
->head
;
5149 robj
*ele
= listNodeValue(ln
);
5151 next
= fromtail
? ln
->prev
: ln
->next
;
5152 if (equalStringObjects(ele
,c
->argv
[3])) {
5153 listDelNode(list
,ln
);
5156 if (toremove
&& removed
== toremove
) break;
5160 if (listLength(list
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5161 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",removed
));
5164 /* This is the semantic of this command:
5165 * RPOPLPUSH srclist dstlist:
5166 * IF LLEN(srclist) > 0
5167 * element = RPOP srclist
5168 * LPUSH dstlist element
5175 * The idea is to be able to get an element from a list in a reliable way
5176 * since the element is not just returned but pushed against another list
5177 * as well. This command was originally proposed by Ezra Zygmuntowicz.
5179 static void rpoplpushcommand(redisClient
*c
) {
5184 if ((sobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5185 checkType(c
,sobj
,REDIS_LIST
)) return;
5186 srclist
= sobj
->ptr
;
5187 ln
= listLast(srclist
);
5190 addReply(c
,shared
.nullbulk
);
5192 robj
*dobj
= lookupKeyWrite(c
->db
,c
->argv
[2]);
5193 robj
*ele
= listNodeValue(ln
);
5196 if (dobj
&& dobj
->type
!= REDIS_LIST
) {
5197 addReply(c
,shared
.wrongtypeerr
);
5201 /* Add the element to the target list (unless it's directly
5202 * passed to some BLPOP-ing client */
5203 if (!handleClientsWaitingListPush(c
,c
->argv
[2],ele
)) {
5205 /* Create the list if the key does not exist */
5206 dobj
= createListObject();
5207 dictAdd(c
->db
->dict
,c
->argv
[2],dobj
);
5208 incrRefCount(c
->argv
[2]);
5210 dstlist
= dobj
->ptr
;
5211 listAddNodeHead(dstlist
,ele
);
5215 /* Send the element to the client as reply as well */
5216 addReplyBulk(c
,ele
);
5218 /* Finally remove the element from the source list */
5219 listDelNode(srclist
,ln
);
5220 if (listLength(srclist
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5225 /* ==================================== Sets ================================ */
5227 static void saddCommand(redisClient
*c
) {
5230 set
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5232 set
= createSetObject();
5233 dictAdd(c
->db
->dict
,c
->argv
[1],set
);
5234 incrRefCount(c
->argv
[1]);
5236 if (set
->type
!= REDIS_SET
) {
5237 addReply(c
,shared
.wrongtypeerr
);
5241 if (dictAdd(set
->ptr
,c
->argv
[2],NULL
) == DICT_OK
) {
5242 incrRefCount(c
->argv
[2]);
5244 addReply(c
,shared
.cone
);
5246 addReply(c
,shared
.czero
);
5250 static void sremCommand(redisClient
*c
) {
5253 if ((set
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5254 checkType(c
,set
,REDIS_SET
)) return;
5256 if (dictDelete(set
->ptr
,c
->argv
[2]) == DICT_OK
) {
5258 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
5259 if (dictSize((dict
*)set
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5260 addReply(c
,shared
.cone
);
5262 addReply(c
,shared
.czero
);
5266 static void smoveCommand(redisClient
*c
) {
5267 robj
*srcset
, *dstset
;
5269 srcset
= lookupKeyWrite(c
->db
,c
->argv
[1]);
5270 dstset
= lookupKeyWrite(c
->db
,c
->argv
[2]);
5272 /* If the source key does not exist return 0, if it's of the wrong type
5274 if (srcset
== NULL
|| srcset
->type
!= REDIS_SET
) {
5275 addReply(c
, srcset
? shared
.wrongtypeerr
: shared
.czero
);
5278 /* Error if the destination key is not a set as well */
5279 if (dstset
&& dstset
->type
!= REDIS_SET
) {
5280 addReply(c
,shared
.wrongtypeerr
);
5283 /* Remove the element from the source set */
5284 if (dictDelete(srcset
->ptr
,c
->argv
[3]) == DICT_ERR
) {
5285 /* Key not found in the src set! return zero */
5286 addReply(c
,shared
.czero
);
5289 if (dictSize((dict
*)srcset
->ptr
) == 0 && srcset
!= dstset
)
5290 deleteKey(c
->db
,c
->argv
[1]);
5292 /* Add the element to the destination set */
5294 dstset
= createSetObject();
5295 dictAdd(c
->db
->dict
,c
->argv
[2],dstset
);
5296 incrRefCount(c
->argv
[2]);
5298 if (dictAdd(dstset
->ptr
,c
->argv
[3],NULL
) == DICT_OK
)
5299 incrRefCount(c
->argv
[3]);
5300 addReply(c
,shared
.cone
);
5303 static void sismemberCommand(redisClient
*c
) {
5306 if ((set
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5307 checkType(c
,set
,REDIS_SET
)) return;
5309 if (dictFind(set
->ptr
,c
->argv
[2]))
5310 addReply(c
,shared
.cone
);
5312 addReply(c
,shared
.czero
);
5315 static void scardCommand(redisClient
*c
) {
5319 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
5320 checkType(c
,o
,REDIS_SET
)) return;
5323 addReplyUlong(c
,dictSize(s
));
5326 static void spopCommand(redisClient
*c
) {
5330 if ((set
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5331 checkType(c
,set
,REDIS_SET
)) return;
5333 de
= dictGetRandomKey(set
->ptr
);
5335 addReply(c
,shared
.nullbulk
);
5337 robj
*ele
= dictGetEntryKey(de
);
5339 addReplyBulk(c
,ele
);
5340 dictDelete(set
->ptr
,ele
);
5341 if (htNeedsResize(set
->ptr
)) dictResize(set
->ptr
);
5342 if (dictSize((dict
*)set
->ptr
) == 0) deleteKey(c
->db
,c
->argv
[1]);
5347 static void srandmemberCommand(redisClient
*c
) {
5351 if ((set
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
5352 checkType(c
,set
,REDIS_SET
)) return;
5354 de
= dictGetRandomKey(set
->ptr
);
5356 addReply(c
,shared
.nullbulk
);
5358 robj
*ele
= dictGetEntryKey(de
);
5360 addReplyBulk(c
,ele
);
5364 static int qsortCompareSetsByCardinality(const void *s1
, const void *s2
) {
5365 dict
**d1
= (void*) s1
, **d2
= (void*) s2
;
5367 return dictSize(*d1
)-dictSize(*d2
);
5370 static void sinterGenericCommand(redisClient
*c
, robj
**setskeys
, unsigned long setsnum
, robj
*dstkey
) {
5371 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
5374 robj
*lenobj
= NULL
, *dstset
= NULL
;
5375 unsigned long j
, cardinality
= 0;
5377 for (j
= 0; j
< setsnum
; j
++) {
5381 lookupKeyWrite(c
->db
,setskeys
[j
]) :
5382 lookupKeyRead(c
->db
,setskeys
[j
]);
5386 if (deleteKey(c
->db
,dstkey
))
5388 addReply(c
,shared
.czero
);
5390 addReply(c
,shared
.emptymultibulk
);
5394 if (setobj
->type
!= REDIS_SET
) {
5396 addReply(c
,shared
.wrongtypeerr
);
5399 dv
[j
] = setobj
->ptr
;
5401 /* Sort sets from the smallest to largest, this will improve our
5402 * algorithm's performace */
5403 qsort(dv
,setsnum
,sizeof(dict
*),qsortCompareSetsByCardinality
);
5405 /* The first thing we should output is the total number of elements...
5406 * since this is a multi-bulk write, but at this stage we don't know
5407 * the intersection set size, so we use a trick, append an empty object
5408 * to the output list and save the pointer to later modify it with the
5411 lenobj
= createObject(REDIS_STRING
,NULL
);
5413 decrRefCount(lenobj
);
5415 /* If we have a target key where to store the resulting set
5416 * create this key with an empty set inside */
5417 dstset
= createSetObject();
5420 /* Iterate all the elements of the first (smallest) set, and test
5421 * the element against all the other sets, if at least one set does
5422 * not include the element it is discarded */
5423 di
= dictGetIterator(dv
[0]);
5425 while((de
= dictNext(di
)) != NULL
) {
5428 for (j
= 1; j
< setsnum
; j
++)
5429 if (dictFind(dv
[j
],dictGetEntryKey(de
)) == NULL
) break;
5431 continue; /* at least one set does not contain the member */
5432 ele
= dictGetEntryKey(de
);
5434 addReplyBulk(c
,ele
);
5437 dictAdd(dstset
->ptr
,ele
,NULL
);
5441 dictReleaseIterator(di
);
5444 /* Store the resulting set into the target, if the intersection
5445 * is not an empty set. */
5446 deleteKey(c
->db
,dstkey
);
5447 if (dictSize((dict
*)dstset
->ptr
) > 0) {
5448 dictAdd(c
->db
->dict
,dstkey
,dstset
);
5449 incrRefCount(dstkey
);
5450 addReplyLongLong(c
,dictSize((dict
*)dstset
->ptr
));
5452 decrRefCount(dstset
);
5453 addReply(c
,shared
.czero
);
5457 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",cardinality
);
5462 static void sinterCommand(redisClient
*c
) {
5463 sinterGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
);
5466 static void sinterstoreCommand(redisClient
*c
) {
5467 sinterGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1]);
5470 #define REDIS_OP_UNION 0
5471 #define REDIS_OP_DIFF 1
5472 #define REDIS_OP_INTER 2
5474 static void sunionDiffGenericCommand(redisClient
*c
, robj
**setskeys
, int setsnum
, robj
*dstkey
, int op
) {
5475 dict
**dv
= zmalloc(sizeof(dict
*)*setsnum
);
5478 robj
*dstset
= NULL
;
5479 int j
, cardinality
= 0;
5481 for (j
= 0; j
< setsnum
; j
++) {
5485 lookupKeyWrite(c
->db
,setskeys
[j
]) :
5486 lookupKeyRead(c
->db
,setskeys
[j
]);
5491 if (setobj
->type
!= REDIS_SET
) {
5493 addReply(c
,shared
.wrongtypeerr
);
5496 dv
[j
] = setobj
->ptr
;
5499 /* We need a temp set object to store our union. If the dstkey
5500 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
5501 * this set object will be the resulting object to set into the target key*/
5502 dstset
= createSetObject();
5504 /* Iterate all the elements of all the sets, add every element a single
5505 * time to the result set */
5506 for (j
= 0; j
< setsnum
; j
++) {
5507 if (op
== REDIS_OP_DIFF
&& j
== 0 && !dv
[j
]) break; /* result set is empty */
5508 if (!dv
[j
]) continue; /* non existing keys are like empty sets */
5510 di
= dictGetIterator(dv
[j
]);
5512 while((de
= dictNext(di
)) != NULL
) {
5515 /* dictAdd will not add the same element multiple times */
5516 ele
= dictGetEntryKey(de
);
5517 if (op
== REDIS_OP_UNION
|| j
== 0) {
5518 if (dictAdd(dstset
->ptr
,ele
,NULL
) == DICT_OK
) {
5522 } else if (op
== REDIS_OP_DIFF
) {
5523 if (dictDelete(dstset
->ptr
,ele
) == DICT_OK
) {
5528 dictReleaseIterator(di
);
5530 /* result set is empty? Exit asap. */
5531 if (op
== REDIS_OP_DIFF
&& cardinality
== 0) break;
5534 /* Output the content of the resulting set, if not in STORE mode */
5536 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",cardinality
));
5537 di
= dictGetIterator(dstset
->ptr
);
5538 while((de
= dictNext(di
)) != NULL
) {
5541 ele
= dictGetEntryKey(de
);
5542 addReplyBulk(c
,ele
);
5544 dictReleaseIterator(di
);
5545 decrRefCount(dstset
);
5547 /* If we have a target key where to store the resulting set
5548 * create this key with the result set inside */
5549 deleteKey(c
->db
,dstkey
);
5550 if (dictSize((dict
*)dstset
->ptr
) > 0) {
5551 dictAdd(c
->db
->dict
,dstkey
,dstset
);
5552 incrRefCount(dstkey
);
5553 addReplyLongLong(c
,dictSize((dict
*)dstset
->ptr
));
5555 decrRefCount(dstset
);
5556 addReply(c
,shared
.czero
);
5563 static void sunionCommand(redisClient
*c
) {
5564 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_UNION
);
5567 static void sunionstoreCommand(redisClient
*c
) {
5568 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_UNION
);
5571 static void sdiffCommand(redisClient
*c
) {
5572 sunionDiffGenericCommand(c
,c
->argv
+1,c
->argc
-1,NULL
,REDIS_OP_DIFF
);
5575 static void sdiffstoreCommand(redisClient
*c
) {
5576 sunionDiffGenericCommand(c
,c
->argv
+2,c
->argc
-2,c
->argv
[1],REDIS_OP_DIFF
);
5579 /* ==================================== ZSets =============================== */
5581 /* ZSETs are ordered sets using two data structures to hold the same elements
5582 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
5585 * The elements are added to an hash table mapping Redis objects to scores.
5586 * At the same time the elements are added to a skip list mapping scores
5587 * to Redis objects (so objects are sorted by scores in this "view"). */
5589 /* This skiplist implementation is almost a C translation of the original
5590 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
5591 * Alternative to Balanced Trees", modified in three ways:
5592 * a) this implementation allows for repeated values.
5593 * b) the comparison is not just by key (our 'score') but by satellite data.
5594 * c) there is a back pointer, so it's a doubly linked list with the back
5595 * pointers being only at "level 1". This allows to traverse the list
5596 * from tail to head, useful for ZREVRANGE. */
5598 static zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
5599 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
5601 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
5603 zn
->span
= zmalloc(sizeof(unsigned int) * (level
- 1));
5611 static zskiplist
*zslCreate(void) {
5615 zsl
= zmalloc(sizeof(*zsl
));
5618 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
5619 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
5620 zsl
->header
->forward
[j
] = NULL
;
5622 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
5623 if (j
< ZSKIPLIST_MAXLEVEL
-1)
5624 zsl
->header
->span
[j
] = 0;
5626 zsl
->header
->backward
= NULL
;
5631 static void zslFreeNode(zskiplistNode
*node
) {
5632 decrRefCount(node
->obj
);
5633 zfree(node
->forward
);
5638 static void zslFree(zskiplist
*zsl
) {
5639 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
5641 zfree(zsl
->header
->forward
);
5642 zfree(zsl
->header
->span
);
5645 next
= node
->forward
[0];
5652 static int zslRandomLevel(void) {
5654 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
5656 return (level
<ZSKIPLIST_MAXLEVEL
) ? level
: ZSKIPLIST_MAXLEVEL
;
5659 static void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
5660 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5661 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
5665 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5666 /* store rank that is crossed to reach the insert position */
5667 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
5669 while (x
->forward
[i
] &&
5670 (x
->forward
[i
]->score
< score
||
5671 (x
->forward
[i
]->score
== score
&&
5672 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0))) {
5673 rank
[i
] += i
> 0 ? x
->span
[i
-1] : 1;
5678 /* we assume the key is not already inside, since we allow duplicated
5679 * scores, and the re-insertion of score and redis object should never
5680 * happpen since the caller of zslInsert() should test in the hash table
5681 * if the element is already inside or not. */
5682 level
= zslRandomLevel();
5683 if (level
> zsl
->level
) {
5684 for (i
= zsl
->level
; i
< level
; i
++) {
5686 update
[i
] = zsl
->header
;
5687 update
[i
]->span
[i
-1] = zsl
->length
;
5691 x
= zslCreateNode(level
,score
,obj
);
5692 for (i
= 0; i
< level
; i
++) {
5693 x
->forward
[i
] = update
[i
]->forward
[i
];
5694 update
[i
]->forward
[i
] = x
;
5696 /* update span covered by update[i] as x is inserted here */
5698 x
->span
[i
-1] = update
[i
]->span
[i
-1] - (rank
[0] - rank
[i
]);
5699 update
[i
]->span
[i
-1] = (rank
[0] - rank
[i
]) + 1;
5703 /* increment span for untouched levels */
5704 for (i
= level
; i
< zsl
->level
; i
++) {
5705 update
[i
]->span
[i
-1]++;
5708 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
5710 x
->forward
[0]->backward
= x
;
5716 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
5717 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
5719 for (i
= 0; i
< zsl
->level
; i
++) {
5720 if (update
[i
]->forward
[i
] == x
) {
5722 update
[i
]->span
[i
-1] += x
->span
[i
-1] - 1;
5724 update
[i
]->forward
[i
] = x
->forward
[i
];
5726 /* invariant: i > 0, because update[0]->forward[0]
5727 * is always equal to x */
5728 update
[i
]->span
[i
-1] -= 1;
5731 if (x
->forward
[0]) {
5732 x
->forward
[0]->backward
= x
->backward
;
5734 zsl
->tail
= x
->backward
;
5736 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
5741 /* Delete an element with matching score/object from the skiplist. */
5742 static int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
5743 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5747 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5748 while (x
->forward
[i
] &&
5749 (x
->forward
[i
]->score
< score
||
5750 (x
->forward
[i
]->score
== score
&&
5751 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
5755 /* We may have multiple elements with the same score, what we need
5756 * is to find the element with both the right score and object. */
5758 if (x
&& score
== x
->score
&& equalStringObjects(x
->obj
,obj
)) {
5759 zslDeleteNode(zsl
, x
, update
);
5763 return 0; /* not found */
5765 return 0; /* not found */
5768 /* Delete all the elements with score between min and max from the skiplist.
5769 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
5770 * Note that this function takes the reference to the hash table view of the
5771 * sorted set, in order to remove the elements from the hash table too. */
5772 static unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
5773 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5774 unsigned long removed
= 0;
5778 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5779 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
5783 /* We may have multiple elements with the same score, what we need
5784 * is to find the element with both the right score and object. */
5786 while (x
&& x
->score
<= max
) {
5787 zskiplistNode
*next
= x
->forward
[0];
5788 zslDeleteNode(zsl
, x
, update
);
5789 dictDelete(dict
,x
->obj
);
5794 return removed
; /* not found */
5797 /* Delete all the elements with rank between start and end from the skiplist.
5798 * Start and end are inclusive. Note that start and end need to be 1-based */
5799 static unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
5800 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
5801 unsigned long traversed
= 0, removed
= 0;
5805 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5806 while (x
->forward
[i
] && (traversed
+ (i
> 0 ? x
->span
[i
-1] : 1)) < start
) {
5807 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5815 while (x
&& traversed
<= end
) {
5816 zskiplistNode
*next
= x
->forward
[0];
5817 zslDeleteNode(zsl
, x
, update
);
5818 dictDelete(dict
,x
->obj
);
5827 /* Find the first node having a score equal or greater than the specified one.
5828 * Returns NULL if there is no match. */
5829 static zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
5834 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5835 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
5838 /* We may have multiple elements with the same score, what we need
5839 * is to find the element with both the right score and object. */
5840 return x
->forward
[0];
5843 /* Find the rank for an element by both score and key.
5844 * Returns 0 when the element cannot be found, rank otherwise.
5845 * Note that the rank is 1-based due to the span of zsl->header to the
5847 static unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
5849 unsigned long rank
= 0;
5853 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5854 while (x
->forward
[i
] &&
5855 (x
->forward
[i
]->score
< score
||
5856 (x
->forward
[i
]->score
== score
&&
5857 compareStringObjects(x
->forward
[i
]->obj
,o
) <= 0))) {
5858 rank
+= i
> 0 ? x
->span
[i
-1] : 1;
5862 /* x might be equal to zsl->header, so test if obj is non-NULL */
5863 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
5870 /* Finds an element by its rank. The rank argument needs to be 1-based. */
5871 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
5873 unsigned long traversed
= 0;
5877 for (i
= zsl
->level
-1; i
>= 0; i
--) {
5878 while (x
->forward
[i
] && (traversed
+ (i
>0 ? x
->span
[i
-1] : 1)) <= rank
)
5880 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
5883 if (traversed
== rank
) {
5890 /* The actual Z-commands implementations */
5892 /* This generic command implements both ZADD and ZINCRBY.
5893 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
5894 * the increment if the operation is a ZINCRBY (doincrement == 1). */
5895 static void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
5900 if (isnan(scoreval
)) {
5901 addReplySds(c
,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
5905 zsetobj
= lookupKeyWrite(c
->db
,key
);
5906 if (zsetobj
== NULL
) {
5907 zsetobj
= createZsetObject();
5908 dictAdd(c
->db
->dict
,key
,zsetobj
);
5911 if (zsetobj
->type
!= REDIS_ZSET
) {
5912 addReply(c
,shared
.wrongtypeerr
);
5918 /* Ok now since we implement both ZADD and ZINCRBY here the code
5919 * needs to handle the two different conditions. It's all about setting
5920 * '*score', that is, the new score to set, to the right value. */
5921 score
= zmalloc(sizeof(double));
5925 /* Read the old score. If the element was not present starts from 0 */
5926 de
= dictFind(zs
->dict
,ele
);
5928 double *oldscore
= dictGetEntryVal(de
);
5929 *score
= *oldscore
+ scoreval
;
5933 if (isnan(*score
)) {
5935 sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
5937 /* Note that we don't need to check if the zset may be empty and
5938 * should be removed here, as we can only obtain Nan as score if
5939 * there was already an element in the sorted set. */
5946 /* What follows is a simple remove and re-insert operation that is common
5947 * to both ZADD and ZINCRBY... */
5948 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
5949 /* case 1: New element */
5950 incrRefCount(ele
); /* added to hash */
5951 zslInsert(zs
->zsl
,*score
,ele
);
5952 incrRefCount(ele
); /* added to skiplist */
5955 addReplyDouble(c
,*score
);
5957 addReply(c
,shared
.cone
);
5962 /* case 2: Score update operation */
5963 de
= dictFind(zs
->dict
,ele
);
5964 redisAssert(de
!= NULL
);
5965 oldscore
= dictGetEntryVal(de
);
5966 if (*score
!= *oldscore
) {
5969 /* Remove and insert the element in the skip list with new score */
5970 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
5971 redisAssert(deleted
!= 0);
5972 zslInsert(zs
->zsl
,*score
,ele
);
5974 /* Update the score in the hash table */
5975 dictReplace(zs
->dict
,ele
,score
);
5981 addReplyDouble(c
,*score
);
5983 addReply(c
,shared
.czero
);
5987 static void zaddCommand(redisClient
*c
) {
5990 if (getDoubleFromObjectOrReply(c
, c
->argv
[2], &scoreval
, NULL
) != REDIS_OK
) return;
5991 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
5994 static void zincrbyCommand(redisClient
*c
) {
5997 if (getDoubleFromObjectOrReply(c
, c
->argv
[2], &scoreval
, NULL
) != REDIS_OK
) return;
5998 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
6001 static void zremCommand(redisClient
*c
) {
6008 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6009 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
6012 de
= dictFind(zs
->dict
,c
->argv
[2]);
6014 addReply(c
,shared
.czero
);
6017 /* Delete from the skiplist */
6018 oldscore
= dictGetEntryVal(de
);
6019 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
6020 redisAssert(deleted
!= 0);
6022 /* Delete from the hash table */
6023 dictDelete(zs
->dict
,c
->argv
[2]);
6024 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
6025 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
6027 addReply(c
,shared
.cone
);
6030 static void zremrangebyscoreCommand(redisClient
*c
) {
6037 if ((getDoubleFromObjectOrReply(c
, c
->argv
[2], &min
, NULL
) != REDIS_OK
) ||
6038 (getDoubleFromObjectOrReply(c
, c
->argv
[3], &max
, NULL
) != REDIS_OK
)) return;
6040 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6041 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
6044 deleted
= zslDeleteRangeByScore(zs
->zsl
,min
,max
,zs
->dict
);
6045 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
6046 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
6047 server
.dirty
+= deleted
;
6048 addReplyLongLong(c
,deleted
);
6051 static void zremrangebyrankCommand(redisClient
*c
) {
6059 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
6060 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
6062 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6063 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
6065 llen
= zs
->zsl
->length
;
6067 /* convert negative indexes */
6068 if (start
< 0) start
= llen
+start
;
6069 if (end
< 0) end
= llen
+end
;
6070 if (start
< 0) start
= 0;
6071 if (end
< 0) end
= 0;
6073 /* indexes sanity checks */
6074 if (start
> end
|| start
>= llen
) {
6075 addReply(c
,shared
.czero
);
6078 if (end
>= llen
) end
= llen
-1;
6080 /* increment start and end because zsl*Rank functions
6081 * use 1-based rank */
6082 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
6083 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
6084 if (dictSize(zs
->dict
) == 0) deleteKey(c
->db
,c
->argv
[1]);
6085 server
.dirty
+= deleted
;
6086 addReplyLongLong(c
, deleted
);
6094 static int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) {
6095 zsetopsrc
*d1
= (void*) s1
, *d2
= (void*) s2
;
6096 unsigned long size1
, size2
;
6097 size1
= d1
->dict
? dictSize(d1
->dict
) : 0;
6098 size2
= d2
->dict
? dictSize(d2
->dict
) : 0;
6099 return size1
- size2
;
6102 #define REDIS_AGGR_SUM 1
6103 #define REDIS_AGGR_MIN 2
6104 #define REDIS_AGGR_MAX 3
6105 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
6107 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
6108 if (aggregate
== REDIS_AGGR_SUM
) {
6109 *target
= *target
+ val
;
6110 } else if (aggregate
== REDIS_AGGR_MIN
) {
6111 *target
= val
< *target
? val
: *target
;
6112 } else if (aggregate
== REDIS_AGGR_MAX
) {
6113 *target
= val
> *target
? val
: *target
;
6116 redisPanic("Unknown ZUNION/INTER aggregate type");
6120 static void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
6122 int aggregate
= REDIS_AGGR_SUM
;
6129 /* expect setnum input keys to be given */
6130 setnum
= atoi(c
->argv
[2]->ptr
);
6132 addReplySds(c
,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
6136 /* test if the expected number of keys would overflow */
6137 if (3+setnum
> c
->argc
) {
6138 addReply(c
,shared
.syntaxerr
);
6142 /* read keys to be used for input */
6143 src
= zmalloc(sizeof(zsetopsrc
) * setnum
);
6144 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
6145 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
6149 if (obj
->type
== REDIS_ZSET
) {
6150 src
[i
].dict
= ((zset
*)obj
->ptr
)->dict
;
6151 } else if (obj
->type
== REDIS_SET
) {
6152 src
[i
].dict
= (obj
->ptr
);
6155 addReply(c
,shared
.wrongtypeerr
);
6160 /* default all weights to 1 */
6161 src
[i
].weight
= 1.0;
6164 /* parse optional extra arguments */
6166 int remaining
= c
->argc
- j
;
6169 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
6171 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
6172 if (getDoubleFromObjectOrReply(c
, c
->argv
[j
], &src
[i
].weight
, NULL
) != REDIS_OK
)
6175 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
6177 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
6178 aggregate
= REDIS_AGGR_SUM
;
6179 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
6180 aggregate
= REDIS_AGGR_MIN
;
6181 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
6182 aggregate
= REDIS_AGGR_MAX
;
6185 addReply(c
,shared
.syntaxerr
);
6191 addReply(c
,shared
.syntaxerr
);
6197 /* sort sets from the smallest to largest, this will improve our
6198 * algorithm's performance */
6199 qsort(src
,setnum
,sizeof(zsetopsrc
),qsortCompareZsetopsrcByCardinality
);
6201 dstobj
= createZsetObject();
6202 dstzset
= dstobj
->ptr
;
6204 if (op
== REDIS_OP_INTER
) {
6205 /* skip going over all entries if the smallest zset is NULL or empty */
6206 if (src
[0].dict
&& dictSize(src
[0].dict
) > 0) {
6207 /* precondition: as src[0].dict is non-empty and the zsets are ordered
6208 * from small to large, all src[i > 0].dict are non-empty too */
6209 di
= dictGetIterator(src
[0].dict
);
6210 while((de
= dictNext(di
)) != NULL
) {
6211 double *score
= zmalloc(sizeof(double)), value
;
6212 *score
= src
[0].weight
* zunionInterDictValue(de
);
6214 for (j
= 1; j
< setnum
; j
++) {
6215 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
6217 value
= src
[j
].weight
* zunionInterDictValue(other
);
6218 zunionInterAggregate(score
, value
, aggregate
);
6224 /* skip entry when not present in every source dict */
6228 robj
*o
= dictGetEntryKey(de
);
6229 dictAdd(dstzset
->dict
,o
,score
);
6230 incrRefCount(o
); /* added to dictionary */
6231 zslInsert(dstzset
->zsl
,*score
,o
);
6232 incrRefCount(o
); /* added to skiplist */
6235 dictReleaseIterator(di
);
6237 } else if (op
== REDIS_OP_UNION
) {
6238 for (i
= 0; i
< setnum
; i
++) {
6239 if (!src
[i
].dict
) continue;
6241 di
= dictGetIterator(src
[i
].dict
);
6242 while((de
= dictNext(di
)) != NULL
) {
6243 /* skip key when already processed */
6244 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
) continue;
6246 double *score
= zmalloc(sizeof(double)), value
;
6247 *score
= src
[i
].weight
* zunionInterDictValue(de
);
6249 /* because the zsets are sorted by size, its only possible
6250 * for sets at larger indices to hold this entry */
6251 for (j
= (i
+1); j
< setnum
; j
++) {
6252 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
6254 value
= src
[j
].weight
* zunionInterDictValue(other
);
6255 zunionInterAggregate(score
, value
, aggregate
);
6259 robj
*o
= dictGetEntryKey(de
);
6260 dictAdd(dstzset
->dict
,o
,score
);
6261 incrRefCount(o
); /* added to dictionary */
6262 zslInsert(dstzset
->zsl
,*score
,o
);
6263 incrRefCount(o
); /* added to skiplist */
6265 dictReleaseIterator(di
);
6268 /* unknown operator */
6269 redisAssert(op
== REDIS_OP_INTER
|| op
== REDIS_OP_UNION
);
6272 deleteKey(c
->db
,dstkey
);
6273 if (dstzset
->zsl
->length
) {
6274 dictAdd(c
->db
->dict
,dstkey
,dstobj
);
6275 incrRefCount(dstkey
);
6276 addReplyLongLong(c
, dstzset
->zsl
->length
);
6279 decrRefCount(dstobj
);
6280 addReply(c
, shared
.czero
);
6285 static void zunionstoreCommand(redisClient
*c
) {
6286 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
6289 static void zinterstoreCommand(redisClient
*c
) {
6290 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
6293 static void zrangeGenericCommand(redisClient
*c
, int reverse
) {
6305 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
6306 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
6308 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
6310 } else if (c
->argc
>= 5) {
6311 addReply(c
,shared
.syntaxerr
);
6315 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
6316 || checkType(c
,o
,REDIS_ZSET
)) return;
6321 /* convert negative indexes */
6322 if (start
< 0) start
= llen
+start
;
6323 if (end
< 0) end
= llen
+end
;
6324 if (start
< 0) start
= 0;
6325 if (end
< 0) end
= 0;
6327 /* indexes sanity checks */
6328 if (start
> end
|| start
>= llen
) {
6329 /* Out of range start or start > end result in empty list */
6330 addReply(c
,shared
.emptymultibulk
);
6333 if (end
>= llen
) end
= llen
-1;
6334 rangelen
= (end
-start
)+1;
6336 /* check if starting point is trivial, before searching
6337 * the element in log(N) time */
6339 ln
= start
== 0 ? zsl
->tail
: zslGetElementByRank(zsl
, llen
-start
);
6342 zsl
->header
->forward
[0] : zslGetElementByRank(zsl
, start
+1);
6345 /* Return the result in form of a multi-bulk reply */
6346 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
6347 withscores
? (rangelen
*2) : rangelen
));
6348 for (j
= 0; j
< rangelen
; j
++) {
6350 addReplyBulk(c
,ele
);
6352 addReplyDouble(c
,ln
->score
);
6353 ln
= reverse
? ln
->backward
: ln
->forward
[0];
6357 static void zrangeCommand(redisClient
*c
) {
6358 zrangeGenericCommand(c
,0);
6361 static void zrevrangeCommand(redisClient
*c
) {
6362 zrangeGenericCommand(c
,1);
6365 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
6366 * If justcount is non-zero, just the count is returned. */
6367 static void genericZrangebyscoreCommand(redisClient
*c
, int justcount
) {
6370 int minex
= 0, maxex
= 0; /* are min or max exclusive? */
6371 int offset
= 0, limit
= -1;
6375 /* Parse the min-max interval. If one of the values is prefixed
6376 * by the "(" character, it's considered "open". For instance
6377 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
6378 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
6379 if (((char*)c
->argv
[2]->ptr
)[0] == '(') {
6380 min
= strtod((char*)c
->argv
[2]->ptr
+1,NULL
);
6383 min
= strtod(c
->argv
[2]->ptr
,NULL
);
6385 if (((char*)c
->argv
[3]->ptr
)[0] == '(') {
6386 max
= strtod((char*)c
->argv
[3]->ptr
+1,NULL
);
6389 max
= strtod(c
->argv
[3]->ptr
,NULL
);
6392 /* Parse "WITHSCORES": note that if the command was called with
6393 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
6394 * enter the following paths to parse WITHSCORES and LIMIT. */
6395 if (c
->argc
== 5 || c
->argc
== 8) {
6396 if (strcasecmp(c
->argv
[c
->argc
-1]->ptr
,"withscores") == 0)
6401 if (c
->argc
!= (4 + withscores
) && c
->argc
!= (7 + withscores
))
6405 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
6410 if (c
->argc
== (7 + withscores
) && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
6411 addReply(c
,shared
.syntaxerr
);
6413 } else if (c
->argc
== (7 + withscores
)) {
6414 offset
= atoi(c
->argv
[5]->ptr
);
6415 limit
= atoi(c
->argv
[6]->ptr
);
6416 if (offset
< 0) offset
= 0;
6419 /* Ok, lookup the key and get the range */
6420 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
6422 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
6424 if (o
->type
!= REDIS_ZSET
) {
6425 addReply(c
,shared
.wrongtypeerr
);
6427 zset
*zsetobj
= o
->ptr
;
6428 zskiplist
*zsl
= zsetobj
->zsl
;
6430 robj
*ele
, *lenobj
= NULL
;
6431 unsigned long rangelen
= 0;
6433 /* Get the first node with the score >= min, or with
6434 * score > min if 'minex' is true. */
6435 ln
= zslFirstWithScore(zsl
,min
);
6436 while (minex
&& ln
&& ln
->score
== min
) ln
= ln
->forward
[0];
6439 /* No element matching the speciifed interval */
6440 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
6444 /* We don't know in advance how many matching elements there
6445 * are in the list, so we push this object that will represent
6446 * the multi-bulk length in the output buffer, and will "fix"
6449 lenobj
= createObject(REDIS_STRING
,NULL
);
6451 decrRefCount(lenobj
);
6454 while(ln
&& (maxex
? (ln
->score
< max
) : (ln
->score
<= max
))) {
6457 ln
= ln
->forward
[0];
6460 if (limit
== 0) break;
6463 addReplyBulk(c
,ele
);
6465 addReplyDouble(c
,ln
->score
);
6467 ln
= ln
->forward
[0];
6469 if (limit
> 0) limit
--;
6472 addReplyLongLong(c
,(long)rangelen
);
6474 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",
6475 withscores
? (rangelen
*2) : rangelen
);
6481 static void zrangebyscoreCommand(redisClient
*c
) {
6482 genericZrangebyscoreCommand(c
,0);
6485 static void zcountCommand(redisClient
*c
) {
6486 genericZrangebyscoreCommand(c
,1);
6489 static void zcardCommand(redisClient
*c
) {
6493 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6494 checkType(c
,o
,REDIS_ZSET
)) return;
6497 addReplyUlong(c
,zs
->zsl
->length
);
6500 static void zscoreCommand(redisClient
*c
) {
6505 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6506 checkType(c
,o
,REDIS_ZSET
)) return;
6509 de
= dictFind(zs
->dict
,c
->argv
[2]);
6511 addReply(c
,shared
.nullbulk
);
6513 double *score
= dictGetEntryVal(de
);
6515 addReplyDouble(c
,*score
);
6519 static void zrankGenericCommand(redisClient
*c
, int reverse
) {
6527 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6528 checkType(c
,o
,REDIS_ZSET
)) return;
6532 de
= dictFind(zs
->dict
,c
->argv
[2]);
6534 addReply(c
,shared
.nullbulk
);
6538 score
= dictGetEntryVal(de
);
6539 rank
= zslGetRank(zsl
, *score
, c
->argv
[2]);
6542 addReplyLongLong(c
, zsl
->length
- rank
);
6544 addReplyLongLong(c
, rank
-1);
6547 addReply(c
,shared
.nullbulk
);
6551 static void zrankCommand(redisClient
*c
) {
6552 zrankGenericCommand(c
, 0);
6555 static void zrevrankCommand(redisClient
*c
) {
6556 zrankGenericCommand(c
, 1);
6559 /* ========================= Hashes utility functions ======================= */
6560 #define REDIS_HASH_KEY 1
6561 #define REDIS_HASH_VALUE 2
6563 /* Check the length of a number of objects to see if we need to convert a
6564 * zipmap to a real hash. Note that we only check string encoded objects
6565 * as their string length can be queried in constant time. */
6566 static void hashTryConversion(robj
*subject
, robj
**argv
, int start
, int end
) {
6568 if (subject
->encoding
!= REDIS_ENCODING_ZIPMAP
) return;
6570 for (i
= start
; i
<= end
; i
++) {
6571 if (argv
[i
]->encoding
== REDIS_ENCODING_RAW
&&
6572 sdslen(argv
[i
]->ptr
) > server
.hash_max_zipmap_value
)
6574 convertToRealHash(subject
);
6580 /* Encode given objects in-place when the hash uses a dict. */
6581 static void hashTryObjectEncoding(robj
*subject
, robj
**o1
, robj
**o2
) {
6582 if (subject
->encoding
== REDIS_ENCODING_HT
) {
6583 if (o1
) *o1
= tryObjectEncoding(*o1
);
6584 if (o2
) *o2
= tryObjectEncoding(*o2
);
6588 /* Get the value from a hash identified by key. Returns either a string
6589 * object or NULL if the value cannot be found. The refcount of the object
6590 * is always increased by 1 when the value was found. */
6591 static robj
*hashGet(robj
*o
, robj
*key
) {
6593 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6596 key
= getDecodedObject(key
);
6597 if (zipmapGet(o
->ptr
,key
->ptr
,sdslen(key
->ptr
),&v
,&vlen
)) {
6598 value
= createStringObject((char*)v
,vlen
);
6602 dictEntry
*de
= dictFind(o
->ptr
,key
);
6604 value
= dictGetEntryVal(de
);
6605 incrRefCount(value
);
6611 /* Test if the key exists in the given hash. Returns 1 if the key
6612 * exists and 0 when it doesn't. */
6613 static int hashExists(robj
*o
, robj
*key
) {
6614 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6615 key
= getDecodedObject(key
);
6616 if (zipmapExists(o
->ptr
,key
->ptr
,sdslen(key
->ptr
))) {
6622 if (dictFind(o
->ptr
,key
) != NULL
) {
6629 /* Add an element, discard the old if the key already exists.
6630 * Return 0 on insert and 1 on update. */
6631 static int hashSet(robj
*o
, robj
*key
, robj
*value
) {
6633 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6634 key
= getDecodedObject(key
);
6635 value
= getDecodedObject(value
);
6636 o
->ptr
= zipmapSet(o
->ptr
,
6637 key
->ptr
,sdslen(key
->ptr
),
6638 value
->ptr
,sdslen(value
->ptr
), &update
);
6640 decrRefCount(value
);
6642 /* Check if the zipmap needs to be upgraded to a real hash table */
6643 if (zipmapLen(o
->ptr
) > server
.hash_max_zipmap_entries
)
6644 convertToRealHash(o
);
6646 if (dictReplace(o
->ptr
,key
,value
)) {
6653 incrRefCount(value
);
6658 /* Delete an element from a hash.
6659 * Return 1 on deleted and 0 on not found. */
6660 static int hashDelete(robj
*o
, robj
*key
) {
6662 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6663 key
= getDecodedObject(key
);
6664 o
->ptr
= zipmapDel(o
->ptr
,key
->ptr
,sdslen(key
->ptr
), &deleted
);
6667 deleted
= dictDelete((dict
*)o
->ptr
,key
) == DICT_OK
;
6668 /* Always check if the dictionary needs a resize after a delete. */
6669 if (deleted
&& htNeedsResize(o
->ptr
)) dictResize(o
->ptr
);
6674 /* Return the number of elements in a hash. */
6675 static unsigned long hashLength(robj
*o
) {
6676 return (o
->encoding
== REDIS_ENCODING_ZIPMAP
) ?
6677 zipmapLen((unsigned char*)o
->ptr
) : dictSize((dict
*)o
->ptr
);
6680 /* Structure to hold hash iteration abstration. Note that iteration over
6681 * hashes involves both fields and values. Because it is possible that
6682 * not both are required, store pointers in the iterator to avoid
6683 * unnecessary memory allocation for fields/values. */
6687 unsigned char *zk
, *zv
;
6688 unsigned int zklen
, zvlen
;
6694 static hashIterator
*hashInitIterator(robj
*subject
) {
6695 hashIterator
*hi
= zmalloc(sizeof(hashIterator
));
6696 hi
->encoding
= subject
->encoding
;
6697 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6698 hi
->zi
= zipmapRewind(subject
->ptr
);
6699 } else if (hi
->encoding
== REDIS_ENCODING_HT
) {
6700 hi
->di
= dictGetIterator(subject
->ptr
);
6707 static void hashReleaseIterator(hashIterator
*hi
) {
6708 if (hi
->encoding
== REDIS_ENCODING_HT
) {
6709 dictReleaseIterator(hi
->di
);
6714 /* Move to the next entry in the hash. Return REDIS_OK when the next entry
6715 * could be found and REDIS_ERR when the iterator reaches the end. */
6716 static int hashNext(hashIterator
*hi
) {
6717 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6718 if ((hi
->zi
= zipmapNext(hi
->zi
, &hi
->zk
, &hi
->zklen
,
6719 &hi
->zv
, &hi
->zvlen
)) == NULL
) return REDIS_ERR
;
6721 if ((hi
->de
= dictNext(hi
->di
)) == NULL
) return REDIS_ERR
;
6726 /* Get key or value object at current iteration position.
6727 * This increases the refcount of the field object by 1. */
6728 static robj
*hashCurrent(hashIterator
*hi
, int what
) {
6730 if (hi
->encoding
== REDIS_ENCODING_ZIPMAP
) {
6731 if (what
& REDIS_HASH_KEY
) {
6732 o
= createStringObject((char*)hi
->zk
,hi
->zklen
);
6734 o
= createStringObject((char*)hi
->zv
,hi
->zvlen
);
6737 if (what
& REDIS_HASH_KEY
) {
6738 o
= dictGetEntryKey(hi
->de
);
6740 o
= dictGetEntryVal(hi
->de
);
6747 static robj
*hashLookupWriteOrCreate(redisClient
*c
, robj
*key
) {
6748 robj
*o
= lookupKeyWrite(c
->db
,key
);
6750 o
= createHashObject();
6751 dictAdd(c
->db
->dict
,key
,o
);
6754 if (o
->type
!= REDIS_HASH
) {
6755 addReply(c
,shared
.wrongtypeerr
);
6762 /* ============================= Hash commands ============================== */
6763 static void hsetCommand(redisClient
*c
) {
6767 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6768 hashTryConversion(o
,c
->argv
,2,3);
6769 hashTryObjectEncoding(o
,&c
->argv
[2], &c
->argv
[3]);
6770 update
= hashSet(o
,c
->argv
[2],c
->argv
[3]);
6771 addReply(c
, update
? shared
.czero
: shared
.cone
);
6775 static void hsetnxCommand(redisClient
*c
) {
6777 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6778 hashTryConversion(o
,c
->argv
,2,3);
6780 if (hashExists(o
, c
->argv
[2])) {
6781 addReply(c
, shared
.czero
);
6783 hashTryObjectEncoding(o
,&c
->argv
[2], &c
->argv
[3]);
6784 hashSet(o
,c
->argv
[2],c
->argv
[3]);
6785 addReply(c
, shared
.cone
);
6790 static void hmsetCommand(redisClient
*c
) {
6794 if ((c
->argc
% 2) == 1) {
6795 addReplySds(c
,sdsnew("-ERR wrong number of arguments for HMSET\r\n"));
6799 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6800 hashTryConversion(o
,c
->argv
,2,c
->argc
-1);
6801 for (i
= 2; i
< c
->argc
; i
+= 2) {
6802 hashTryObjectEncoding(o
,&c
->argv
[i
], &c
->argv
[i
+1]);
6803 hashSet(o
,c
->argv
[i
],c
->argv
[i
+1]);
6805 addReply(c
, shared
.ok
);
6809 static void hincrbyCommand(redisClient
*c
) {
6810 long long value
, incr
;
6811 robj
*o
, *current
, *new;
6813 if (getLongLongFromObjectOrReply(c
,c
->argv
[3],&incr
,NULL
) != REDIS_OK
) return;
6814 if ((o
= hashLookupWriteOrCreate(c
,c
->argv
[1])) == NULL
) return;
6815 if ((current
= hashGet(o
,c
->argv
[2])) != NULL
) {
6816 if (getLongLongFromObjectOrReply(c
,current
,&value
,
6817 "hash value is not an integer") != REDIS_OK
) {
6818 decrRefCount(current
);
6821 decrRefCount(current
);
6827 new = createStringObjectFromLongLong(value
);
6828 hashTryObjectEncoding(o
,&c
->argv
[2],NULL
);
6829 hashSet(o
,c
->argv
[2],new);
6831 addReplyLongLong(c
,value
);
6835 static void hgetCommand(redisClient
*c
) {
6837 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
6838 checkType(c
,o
,REDIS_HASH
)) return;
6840 if ((value
= hashGet(o
,c
->argv
[2])) != NULL
) {
6841 addReplyBulk(c
,value
);
6842 decrRefCount(value
);
6844 addReply(c
,shared
.nullbulk
);
6848 static void hmgetCommand(redisClient
*c
) {
6851 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
6852 if (o
!= NULL
&& o
->type
!= REDIS_HASH
) {
6853 addReply(c
,shared
.wrongtypeerr
);
6856 /* Note the check for o != NULL happens inside the loop. This is
6857 * done because objects that cannot be found are considered to be
6858 * an empty hash. The reply should then be a series of NULLs. */
6859 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->argc
-2));
6860 for (i
= 2; i
< c
->argc
; i
++) {
6861 if (o
!= NULL
&& (value
= hashGet(o
,c
->argv
[i
])) != NULL
) {
6862 addReplyBulk(c
,value
);
6863 decrRefCount(value
);
6865 addReply(c
,shared
.nullbulk
);
6870 static void hdelCommand(redisClient
*c
) {
6872 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6873 checkType(c
,o
,REDIS_HASH
)) return;
6875 if (hashDelete(o
,c
->argv
[2])) {
6876 if (hashLength(o
) == 0) deleteKey(c
->db
,c
->argv
[1]);
6877 addReply(c
,shared
.cone
);
6880 addReply(c
,shared
.czero
);
6884 static void hlenCommand(redisClient
*c
) {
6886 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6887 checkType(c
,o
,REDIS_HASH
)) return;
6889 addReplyUlong(c
,hashLength(o
));
6892 static void genericHgetallCommand(redisClient
*c
, int flags
) {
6893 robj
*o
, *lenobj
, *obj
;
6894 unsigned long count
= 0;
6897 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
6898 || checkType(c
,o
,REDIS_HASH
)) return;
6900 lenobj
= createObject(REDIS_STRING
,NULL
);
6902 decrRefCount(lenobj
);
6904 hi
= hashInitIterator(o
);
6905 while (hashNext(hi
) != REDIS_ERR
) {
6906 if (flags
& REDIS_HASH_KEY
) {
6907 obj
= hashCurrent(hi
,REDIS_HASH_KEY
);
6908 addReplyBulk(c
,obj
);
6912 if (flags
& REDIS_HASH_VALUE
) {
6913 obj
= hashCurrent(hi
,REDIS_HASH_VALUE
);
6914 addReplyBulk(c
,obj
);
6919 hashReleaseIterator(hi
);
6921 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",count
);
6924 static void hkeysCommand(redisClient
*c
) {
6925 genericHgetallCommand(c
,REDIS_HASH_KEY
);
6928 static void hvalsCommand(redisClient
*c
) {
6929 genericHgetallCommand(c
,REDIS_HASH_VALUE
);
6932 static void hgetallCommand(redisClient
*c
) {
6933 genericHgetallCommand(c
,REDIS_HASH_KEY
|REDIS_HASH_VALUE
);
6936 static void hexistsCommand(redisClient
*c
) {
6938 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
6939 checkType(c
,o
,REDIS_HASH
)) return;
6941 addReply(c
, hashExists(o
,c
->argv
[2]) ? shared
.cone
: shared
.czero
);
6944 static void convertToRealHash(robj
*o
) {
6945 unsigned char *key
, *val
, *p
, *zm
= o
->ptr
;
6946 unsigned int klen
, vlen
;
6947 dict
*dict
= dictCreate(&hashDictType
,NULL
);
6949 assert(o
->type
== REDIS_HASH
&& o
->encoding
!= REDIS_ENCODING_HT
);
6950 p
= zipmapRewind(zm
);
6951 while((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) != NULL
) {
6952 robj
*keyobj
, *valobj
;
6954 keyobj
= createStringObject((char*)key
,klen
);
6955 valobj
= createStringObject((char*)val
,vlen
);
6956 keyobj
= tryObjectEncoding(keyobj
);
6957 valobj
= tryObjectEncoding(valobj
);
6958 dictAdd(dict
,keyobj
,valobj
);
6960 o
->encoding
= REDIS_ENCODING_HT
;
6965 /* ========================= Non type-specific commands ==================== */
6967 static void flushdbCommand(redisClient
*c
) {
6968 server
.dirty
+= dictSize(c
->db
->dict
);
6969 touchWatchedKeysOnFlush(c
->db
->id
);
6970 dictEmpty(c
->db
->dict
);
6971 dictEmpty(c
->db
->expires
);
6972 addReply(c
,shared
.ok
);
6975 static void flushallCommand(redisClient
*c
) {
6976 touchWatchedKeysOnFlush(-1);
6977 server
.dirty
+= emptyDb();
6978 addReply(c
,shared
.ok
);
6979 if (server
.bgsavechildpid
!= -1) {
6980 kill(server
.bgsavechildpid
,SIGKILL
);
6981 rdbRemoveTempFile(server
.bgsavechildpid
);
6983 rdbSave(server
.dbfilename
);
6987 static redisSortOperation
*createSortOperation(int type
, robj
*pattern
) {
6988 redisSortOperation
*so
= zmalloc(sizeof(*so
));
6990 so
->pattern
= pattern
;
6994 /* Return the value associated to the key with a name obtained
6995 * substituting the first occurence of '*' in 'pattern' with 'subst'.
6996 * The returned object will always have its refcount increased by 1
6997 * when it is non-NULL. */
6998 static robj
*lookupKeyByPattern(redisDb
*db
, robj
*pattern
, robj
*subst
) {
7001 robj keyobj
, fieldobj
, *o
;
7002 int prefixlen
, sublen
, postfixlen
, fieldlen
;
7003 /* Expoit the internal sds representation to create a sds string allocated on the stack in order to make this function faster */
7007 char buf
[REDIS_SORTKEY_MAX
+1];
7008 } keyname
, fieldname
;
7010 /* If the pattern is "#" return the substitution object itself in order
7011 * to implement the "SORT ... GET #" feature. */
7012 spat
= pattern
->ptr
;
7013 if (spat
[0] == '#' && spat
[1] == '\0') {
7014 incrRefCount(subst
);
7018 /* The substitution object may be specially encoded. If so we create
7019 * a decoded object on the fly. Otherwise getDecodedObject will just
7020 * increment the ref count, that we'll decrement later. */
7021 subst
= getDecodedObject(subst
);
7024 if (sdslen(spat
)+sdslen(ssub
)-1 > REDIS_SORTKEY_MAX
) return NULL
;
7025 p
= strchr(spat
,'*');
7027 decrRefCount(subst
);
7031 /* Find out if we're dealing with a hash dereference. */
7032 if ((f
= strstr(p
+1, "->")) != NULL
) {
7033 fieldlen
= sdslen(spat
)-(f
-spat
);
7034 /* this also copies \0 character */
7035 memcpy(fieldname
.buf
,f
+2,fieldlen
-1);
7036 fieldname
.len
= fieldlen
-2;
7042 sublen
= sdslen(ssub
);
7043 postfixlen
= sdslen(spat
)-(prefixlen
+1)-fieldlen
;
7044 memcpy(keyname
.buf
,spat
,prefixlen
);
7045 memcpy(keyname
.buf
+prefixlen
,ssub
,sublen
);
7046 memcpy(keyname
.buf
+prefixlen
+sublen
,p
+1,postfixlen
);
7047 keyname
.buf
[prefixlen
+sublen
+postfixlen
] = '\0';
7048 keyname
.len
= prefixlen
+sublen
+postfixlen
;
7049 decrRefCount(subst
);
7051 /* Lookup substituted key */
7052 initStaticStringObject(keyobj
,((char*)&keyname
)+(sizeof(long)*2));
7053 o
= lookupKeyRead(db
,&keyobj
);
7054 if (o
== NULL
) return NULL
;
7057 if (o
->type
!= REDIS_HASH
|| fieldname
.len
< 1) return NULL
;
7059 /* Retrieve value from hash by the field name. This operation
7060 * already increases the refcount of the returned object. */
7061 initStaticStringObject(fieldobj
,((char*)&fieldname
)+(sizeof(long)*2));
7062 o
= hashGet(o
, &fieldobj
);
7064 if (o
->type
!= REDIS_STRING
) return NULL
;
7066 /* Every object that this function returns needs to have its refcount
7067 * increased. sortCommand decreases it again. */
7074 /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with
7075 * the additional parameter is not standard but a BSD-specific we have to
7076 * pass sorting parameters via the global 'server' structure */
7077 static int sortCompare(const void *s1
, const void *s2
) {
7078 const redisSortObject
*so1
= s1
, *so2
= s2
;
7081 if (!server
.sort_alpha
) {
7082 /* Numeric sorting. Here it's trivial as we precomputed scores */
7083 if (so1
->u
.score
> so2
->u
.score
) {
7085 } else if (so1
->u
.score
< so2
->u
.score
) {
7091 /* Alphanumeric sorting */
7092 if (server
.sort_bypattern
) {
7093 if (!so1
->u
.cmpobj
|| !so2
->u
.cmpobj
) {
7094 /* At least one compare object is NULL */
7095 if (so1
->u
.cmpobj
== so2
->u
.cmpobj
)
7097 else if (so1
->u
.cmpobj
== NULL
)
7102 /* We have both the objects, use strcoll */
7103 cmp
= strcoll(so1
->u
.cmpobj
->ptr
,so2
->u
.cmpobj
->ptr
);
7106 /* Compare elements directly. */
7107 cmp
= compareStringObjects(so1
->obj
,so2
->obj
);
7110 return server
.sort_desc
? -cmp
: cmp
;
7113 /* The SORT command is the most complex command in Redis. Warning: this code
7114 * is optimized for speed and a bit less for readability */
7115 static void sortCommand(redisClient
*c
) {
7118 int desc
= 0, alpha
= 0;
7119 int limit_start
= 0, limit_count
= -1, start
, end
;
7120 int j
, dontsort
= 0, vectorlen
;
7121 int getop
= 0; /* GET operation counter */
7122 robj
*sortval
, *sortby
= NULL
, *storekey
= NULL
;
7123 redisSortObject
*vector
; /* Resulting vector to sort */
7125 /* Lookup the key to sort. It must be of the right types */
7126 sortval
= lookupKeyRead(c
->db
,c
->argv
[1]);
7127 if (sortval
== NULL
) {
7128 addReply(c
,shared
.emptymultibulk
);
7131 if (sortval
->type
!= REDIS_SET
&& sortval
->type
!= REDIS_LIST
&&
7132 sortval
->type
!= REDIS_ZSET
)
7134 addReply(c
,shared
.wrongtypeerr
);
7138 /* Create a list of operations to perform for every sorted element.
7139 * Operations can be GET/DEL/INCR/DECR */
7140 operations
= listCreate();
7141 listSetFreeMethod(operations
,zfree
);
7144 /* Now we need to protect sortval incrementing its count, in the future
7145 * SORT may have options able to overwrite/delete keys during the sorting
7146 * and the sorted key itself may get destroied */
7147 incrRefCount(sortval
);
7149 /* The SORT command has an SQL-alike syntax, parse it */
7150 while(j
< c
->argc
) {
7151 int leftargs
= c
->argc
-j
-1;
7152 if (!strcasecmp(c
->argv
[j
]->ptr
,"asc")) {
7154 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"desc")) {
7156 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"alpha")) {
7158 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"limit") && leftargs
>= 2) {
7159 limit_start
= atoi(c
->argv
[j
+1]->ptr
);
7160 limit_count
= atoi(c
->argv
[j
+2]->ptr
);
7162 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"store") && leftargs
>= 1) {
7163 storekey
= c
->argv
[j
+1];
7165 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"by") && leftargs
>= 1) {
7166 sortby
= c
->argv
[j
+1];
7167 /* If the BY pattern does not contain '*', i.e. it is constant,
7168 * we don't need to sort nor to lookup the weight keys. */
7169 if (strchr(c
->argv
[j
+1]->ptr
,'*') == NULL
) dontsort
= 1;
7171 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"get") && leftargs
>= 1) {
7172 listAddNodeTail(operations
,createSortOperation(
7173 REDIS_SORT_GET
,c
->argv
[j
+1]));
7177 decrRefCount(sortval
);
7178 listRelease(operations
);
7179 addReply(c
,shared
.syntaxerr
);
7185 /* Load the sorting vector with all the objects to sort */
7186 switch(sortval
->type
) {
7187 case REDIS_LIST
: vectorlen
= listLength((list
*)sortval
->ptr
); break;
7188 case REDIS_SET
: vectorlen
= dictSize((dict
*)sortval
->ptr
); break;
7189 case REDIS_ZSET
: vectorlen
= dictSize(((zset
*)sortval
->ptr
)->dict
); break;
7190 default: vectorlen
= 0; redisPanic("Bad SORT type"); /* Avoid GCC warning */
7192 vector
= zmalloc(sizeof(redisSortObject
)*vectorlen
);
7195 if (sortval
->type
== REDIS_LIST
) {
7196 list
*list
= sortval
->ptr
;
7200 listRewind(list
,&li
);
7201 while((ln
= listNext(&li
))) {
7202 robj
*ele
= ln
->value
;
7203 vector
[j
].obj
= ele
;
7204 vector
[j
].u
.score
= 0;
7205 vector
[j
].u
.cmpobj
= NULL
;
7213 if (sortval
->type
== REDIS_SET
) {
7216 zset
*zs
= sortval
->ptr
;
7220 di
= dictGetIterator(set
);
7221 while((setele
= dictNext(di
)) != NULL
) {
7222 vector
[j
].obj
= dictGetEntryKey(setele
);
7223 vector
[j
].u
.score
= 0;
7224 vector
[j
].u
.cmpobj
= NULL
;
7227 dictReleaseIterator(di
);
7229 redisAssert(j
== vectorlen
);
7231 /* Now it's time to load the right scores in the sorting vector */
7232 if (dontsort
== 0) {
7233 for (j
= 0; j
< vectorlen
; j
++) {
7236 /* lookup value to sort by */
7237 byval
= lookupKeyByPattern(c
->db
,sortby
,vector
[j
].obj
);
7238 if (!byval
) continue;
7240 /* use object itself to sort by */
7241 byval
= vector
[j
].obj
;
7245 if (sortby
) vector
[j
].u
.cmpobj
= getDecodedObject(byval
);
7247 if (byval
->encoding
== REDIS_ENCODING_RAW
) {
7248 vector
[j
].u
.score
= strtod(byval
->ptr
,NULL
);
7249 } else if (byval
->encoding
== REDIS_ENCODING_INT
) {
7250 /* Don't need to decode the object if it's
7251 * integer-encoded (the only encoding supported) so
7252 * far. We can just cast it */
7253 vector
[j
].u
.score
= (long)byval
->ptr
;
7255 redisAssert(1 != 1);
7259 /* when the object was retrieved using lookupKeyByPattern,
7260 * its refcount needs to be decreased. */
7262 decrRefCount(byval
);
7267 /* We are ready to sort the vector... perform a bit of sanity check
7268 * on the LIMIT option too. We'll use a partial version of quicksort. */
7269 start
= (limit_start
< 0) ? 0 : limit_start
;
7270 end
= (limit_count
< 0) ? vectorlen
-1 : start
+limit_count
-1;
7271 if (start
>= vectorlen
) {
7272 start
= vectorlen
-1;
7275 if (end
>= vectorlen
) end
= vectorlen
-1;
7277 if (dontsort
== 0) {
7278 server
.sort_desc
= desc
;
7279 server
.sort_alpha
= alpha
;
7280 server
.sort_bypattern
= sortby
? 1 : 0;
7281 if (sortby
&& (start
!= 0 || end
!= vectorlen
-1))
7282 pqsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
, start
,end
);
7284 qsort(vector
,vectorlen
,sizeof(redisSortObject
),sortCompare
);
7287 /* Send command output to the output buffer, performing the specified
7288 * GET/DEL/INCR/DECR operations if any. */
7289 outputlen
= getop
? getop
*(end
-start
+1) : end
-start
+1;
7290 if (storekey
== NULL
) {
7291 /* STORE option not specified, sent the sorting result to client */
7292 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",outputlen
));
7293 for (j
= start
; j
<= end
; j
++) {
7297 if (!getop
) addReplyBulk(c
,vector
[j
].obj
);
7298 listRewind(operations
,&li
);
7299 while((ln
= listNext(&li
))) {
7300 redisSortOperation
*sop
= ln
->value
;
7301 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
7304 if (sop
->type
== REDIS_SORT_GET
) {
7306 addReply(c
,shared
.nullbulk
);
7308 addReplyBulk(c
,val
);
7312 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
7317 robj
*listObject
= createListObject();
7318 list
*listPtr
= (list
*) listObject
->ptr
;
7320 /* STORE option specified, set the sorting result as a List object */
7321 for (j
= start
; j
<= end
; j
++) {
7326 listAddNodeTail(listPtr
,vector
[j
].obj
);
7327 incrRefCount(vector
[j
].obj
);
7329 listRewind(operations
,&li
);
7330 while((ln
= listNext(&li
))) {
7331 redisSortOperation
*sop
= ln
->value
;
7332 robj
*val
= lookupKeyByPattern(c
->db
,sop
->pattern
,
7335 if (sop
->type
== REDIS_SORT_GET
) {
7337 listAddNodeTail(listPtr
,createStringObject("",0));
7339 /* We should do a incrRefCount on val because it is
7340 * added to the list, but also a decrRefCount because
7341 * it is returned by lookupKeyByPattern. This results
7342 * in doing nothing at all. */
7343 listAddNodeTail(listPtr
,val
);
7346 redisAssert(sop
->type
== REDIS_SORT_GET
); /* always fails */
7350 if (dictReplace(c
->db
->dict
,storekey
,listObject
)) {
7351 incrRefCount(storekey
);
7353 /* Note: we add 1 because the DB is dirty anyway since even if the
7354 * SORT result is empty a new key is set and maybe the old content
7356 server
.dirty
+= 1+outputlen
;
7357 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",outputlen
));
7361 decrRefCount(sortval
);
7362 listRelease(operations
);
7363 for (j
= 0; j
< vectorlen
; j
++) {
7364 if (alpha
&& vector
[j
].u
.cmpobj
)
7365 decrRefCount(vector
[j
].u
.cmpobj
);
7370 /* Convert an amount of bytes into a human readable string in the form
7371 * of 100B, 2G, 100M, 4K, and so forth. */
7372 static void bytesToHuman(char *s
, unsigned long long n
) {
7377 sprintf(s
,"%lluB",n
);
7379 } else if (n
< (1024*1024)) {
7380 d
= (double)n
/(1024);
7381 sprintf(s
,"%.2fK",d
);
7382 } else if (n
< (1024LL*1024*1024)) {
7383 d
= (double)n
/(1024*1024);
7384 sprintf(s
,"%.2fM",d
);
7385 } else if (n
< (1024LL*1024*1024*1024)) {
7386 d
= (double)n
/(1024LL*1024*1024);
7387 sprintf(s
,"%.2fG",d
);
7391 /* Create the string returned by the INFO command. This is decoupled
7392 * by the INFO command itself as we need to report the same information
7393 * on memory corruption problems. */
7394 static sds
genRedisInfoString(void) {
7396 time_t uptime
= time(NULL
)-server
.stat_starttime
;
7400 bytesToHuman(hmem
,zmalloc_used_memory());
7401 info
= sdscatprintf(sdsempty(),
7402 "redis_version:%s\r\n"
7403 "redis_git_sha1:%s\r\n"
7404 "redis_git_dirty:%d\r\n"
7406 "multiplexing_api:%s\r\n"
7407 "process_id:%ld\r\n"
7408 "uptime_in_seconds:%ld\r\n"
7409 "uptime_in_days:%ld\r\n"
7410 "connected_clients:%d\r\n"
7411 "connected_slaves:%d\r\n"
7412 "blocked_clients:%d\r\n"
7413 "used_memory:%zu\r\n"
7414 "used_memory_human:%s\r\n"
7415 "changes_since_last_save:%lld\r\n"
7416 "bgsave_in_progress:%d\r\n"
7417 "last_save_time:%ld\r\n"
7418 "bgrewriteaof_in_progress:%d\r\n"
7419 "total_connections_received:%lld\r\n"
7420 "total_commands_processed:%lld\r\n"
7421 "expired_keys:%lld\r\n"
7422 "hash_max_zipmap_entries:%zu\r\n"
7423 "hash_max_zipmap_value:%zu\r\n"
7424 "pubsub_channels:%ld\r\n"
7425 "pubsub_patterns:%u\r\n"
7430 strtol(REDIS_GIT_DIRTY
,NULL
,10) > 0,
7431 (sizeof(long) == 8) ? "64" : "32",
7436 listLength(server
.clients
)-listLength(server
.slaves
),
7437 listLength(server
.slaves
),
7438 server
.blpop_blocked_clients
,
7439 zmalloc_used_memory(),
7442 server
.bgsavechildpid
!= -1,
7444 server
.bgrewritechildpid
!= -1,
7445 server
.stat_numconnections
,
7446 server
.stat_numcommands
,
7447 server
.stat_expiredkeys
,
7448 server
.hash_max_zipmap_entries
,
7449 server
.hash_max_zipmap_value
,
7450 dictSize(server
.pubsub_channels
),
7451 listLength(server
.pubsub_patterns
),
7452 server
.vm_enabled
!= 0,
7453 server
.masterhost
== NULL
? "master" : "slave"
7455 if (server
.masterhost
) {
7456 info
= sdscatprintf(info
,
7457 "master_host:%s\r\n"
7458 "master_port:%d\r\n"
7459 "master_link_status:%s\r\n"
7460 "master_last_io_seconds_ago:%d\r\n"
7463 (server
.replstate
== REDIS_REPL_CONNECTED
) ?
7465 server
.master
? ((int)(time(NULL
)-server
.master
->lastinteraction
)) : -1
7468 if (server
.vm_enabled
) {
7470 info
= sdscatprintf(info
,
7471 "vm_conf_max_memory:%llu\r\n"
7472 "vm_conf_page_size:%llu\r\n"
7473 "vm_conf_pages:%llu\r\n"
7474 "vm_stats_used_pages:%llu\r\n"
7475 "vm_stats_swapped_objects:%llu\r\n"
7476 "vm_stats_swappin_count:%llu\r\n"
7477 "vm_stats_swappout_count:%llu\r\n"
7478 "vm_stats_io_newjobs_len:%lu\r\n"
7479 "vm_stats_io_processing_len:%lu\r\n"
7480 "vm_stats_io_processed_len:%lu\r\n"
7481 "vm_stats_io_active_threads:%lu\r\n"
7482 "vm_stats_blocked_clients:%lu\r\n"
7483 ,(unsigned long long) server
.vm_max_memory
,
7484 (unsigned long long) server
.vm_page_size
,
7485 (unsigned long long) server
.vm_pages
,
7486 (unsigned long long) server
.vm_stats_used_pages
,
7487 (unsigned long long) server
.vm_stats_swapped_objects
,
7488 (unsigned long long) server
.vm_stats_swapins
,
7489 (unsigned long long) server
.vm_stats_swapouts
,
7490 (unsigned long) listLength(server
.io_newjobs
),
7491 (unsigned long) listLength(server
.io_processing
),
7492 (unsigned long) listLength(server
.io_processed
),
7493 (unsigned long) server
.io_active_threads
,
7494 (unsigned long) server
.vm_blocked_clients
7498 for (j
= 0; j
< server
.dbnum
; j
++) {
7499 long long keys
, vkeys
;
7501 keys
= dictSize(server
.db
[j
].dict
);
7502 vkeys
= dictSize(server
.db
[j
].expires
);
7503 if (keys
|| vkeys
) {
7504 info
= sdscatprintf(info
, "db%d:keys=%lld,expires=%lld\r\n",
7511 static void infoCommand(redisClient
*c
) {
7512 sds info
= genRedisInfoString();
7513 addReplySds(c
,sdscatprintf(sdsempty(),"$%lu\r\n",
7514 (unsigned long)sdslen(info
)));
7515 addReplySds(c
,info
);
7516 addReply(c
,shared
.crlf
);
7519 static void monitorCommand(redisClient
*c
) {
7520 /* ignore MONITOR if aleady slave or in monitor mode */
7521 if (c
->flags
& REDIS_SLAVE
) return;
7523 c
->flags
|= (REDIS_SLAVE
|REDIS_MONITOR
);
7525 listAddNodeTail(server
.monitors
,c
);
7526 addReply(c
,shared
.ok
);
7529 /* ================================= Expire ================================= */
7530 static int removeExpire(redisDb
*db
, robj
*key
) {
7531 if (dictDelete(db
->expires
,key
) == DICT_OK
) {
7538 static int setExpire(redisDb
*db
, robj
*key
, time_t when
) {
7539 if (dictAdd(db
->expires
,key
,(void*)when
) == DICT_ERR
) {
7547 /* Return the expire time of the specified key, or -1 if no expire
7548 * is associated with this key (i.e. the key is non volatile) */
7549 static time_t getExpire(redisDb
*db
, robj
*key
) {
7552 /* No expire? return ASAP */
7553 if (dictSize(db
->expires
) == 0 ||
7554 (de
= dictFind(db
->expires
,key
)) == NULL
) return -1;
7556 return (time_t) dictGetEntryVal(de
);
7559 static int expireIfNeeded(redisDb
*db
, robj
*key
) {
7563 /* No expire? return ASAP */
7564 if (dictSize(db
->expires
) == 0 ||
7565 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
7567 /* Lookup the expire */
7568 when
= (time_t) dictGetEntryVal(de
);
7569 if (time(NULL
) <= when
) return 0;
7571 /* Delete the key */
7572 dictDelete(db
->expires
,key
);
7573 server
.stat_expiredkeys
++;
7574 return dictDelete(db
->dict
,key
) == DICT_OK
;
7577 static int deleteIfVolatile(redisDb
*db
, robj
*key
) {
7580 /* No expire? return ASAP */
7581 if (dictSize(db
->expires
) == 0 ||
7582 (de
= dictFind(db
->expires
,key
)) == NULL
) return 0;
7584 /* Delete the key */
7586 server
.stat_expiredkeys
++;
7587 dictDelete(db
->expires
,key
);
7588 return dictDelete(db
->dict
,key
) == DICT_OK
;
7591 static void expireGenericCommand(redisClient
*c
, robj
*key
, robj
*param
, long offset
) {
7595 if (getLongFromObjectOrReply(c
, param
, &seconds
, NULL
) != REDIS_OK
) return;
7599 de
= dictFind(c
->db
->dict
,key
);
7601 addReply(c
,shared
.czero
);
7605 if (deleteKey(c
->db
,key
)) server
.dirty
++;
7606 addReply(c
, shared
.cone
);
7609 time_t when
= time(NULL
)+seconds
;
7610 if (setExpire(c
->db
,key
,when
)) {
7611 addReply(c
,shared
.cone
);
7614 addReply(c
,shared
.czero
);
7620 static void expireCommand(redisClient
*c
) {
7621 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],0);
7624 static void expireatCommand(redisClient
*c
) {
7625 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],time(NULL
));
7628 static void ttlCommand(redisClient
*c
) {
7632 expire
= getExpire(c
->db
,c
->argv
[1]);
7634 ttl
= (int) (expire
-time(NULL
));
7635 if (ttl
< 0) ttl
= -1;
7637 addReplySds(c
,sdscatprintf(sdsempty(),":%d\r\n",ttl
));
7640 /* ================================ MULTI/EXEC ============================== */
7642 /* Client state initialization for MULTI/EXEC */
7643 static void initClientMultiState(redisClient
*c
) {
7644 c
->mstate
.commands
= NULL
;
7645 c
->mstate
.count
= 0;
7648 /* Release all the resources associated with MULTI/EXEC state */
7649 static void freeClientMultiState(redisClient
*c
) {
7652 for (j
= 0; j
< c
->mstate
.count
; j
++) {
7654 multiCmd
*mc
= c
->mstate
.commands
+j
;
7656 for (i
= 0; i
< mc
->argc
; i
++)
7657 decrRefCount(mc
->argv
[i
]);
7660 zfree(c
->mstate
.commands
);
7663 /* Add a new command into the MULTI commands queue */
7664 static void queueMultiCommand(redisClient
*c
, struct redisCommand
*cmd
) {
7668 c
->mstate
.commands
= zrealloc(c
->mstate
.commands
,
7669 sizeof(multiCmd
)*(c
->mstate
.count
+1));
7670 mc
= c
->mstate
.commands
+c
->mstate
.count
;
7673 mc
->argv
= zmalloc(sizeof(robj
*)*c
->argc
);
7674 memcpy(mc
->argv
,c
->argv
,sizeof(robj
*)*c
->argc
);
7675 for (j
= 0; j
< c
->argc
; j
++)
7676 incrRefCount(mc
->argv
[j
]);
7680 static void multiCommand(redisClient
*c
) {
7681 if (c
->flags
& REDIS_MULTI
) {
7682 addReplySds(c
,sdsnew("-ERR MULTI calls can not be nested\r\n"));
7685 c
->flags
|= REDIS_MULTI
;
7686 addReply(c
,shared
.ok
);
7689 static void discardCommand(redisClient
*c
) {
7690 if (!(c
->flags
& REDIS_MULTI
)) {
7691 addReplySds(c
,sdsnew("-ERR DISCARD without MULTI\r\n"));
7695 freeClientMultiState(c
);
7696 initClientMultiState(c
);
7697 c
->flags
&= (~REDIS_MULTI
);
7698 addReply(c
,shared
.ok
);
7701 /* Send a MULTI command to all the slaves and AOF file. Check the execCommand
7702 * implememntation for more information. */
7703 static void execCommandReplicateMulti(redisClient
*c
) {
7704 struct redisCommand
*cmd
;
7705 robj
*multistring
= createStringObject("MULTI",5);
7707 cmd
= lookupCommand("multi");
7708 if (server
.appendonly
)
7709 feedAppendOnlyFile(cmd
,c
->db
->id
,&multistring
,1);
7710 if (listLength(server
.slaves
))
7711 replicationFeedSlaves(server
.slaves
,c
->db
->id
,&multistring
,1);
7712 decrRefCount(multistring
);
7715 static void execCommand(redisClient
*c
) {
7720 if (!(c
->flags
& REDIS_MULTI
)) {
7721 addReplySds(c
,sdsnew("-ERR EXEC without MULTI\r\n"));
7725 /* Check if we need to abort the EXEC if some WATCHed key was touched.
7726 * A failed EXEC will return a multi bulk nil object. */
7727 if (c
->flags
& REDIS_DIRTY_CAS
) {
7728 freeClientMultiState(c
);
7729 initClientMultiState(c
);
7730 c
->flags
&= ~(REDIS_MULTI
|REDIS_DIRTY_CAS
);
7732 addReply(c
,shared
.nullmultibulk
);
7736 /* Replicate a MULTI request now that we are sure the block is executed.
7737 * This way we'll deliver the MULTI/..../EXEC block as a whole and
7738 * both the AOF and the replication link will have the same consistency
7739 * and atomicity guarantees. */
7740 execCommandReplicateMulti(c
);
7742 /* Exec all the queued commands */
7743 unwatchAllKeys(c
); /* Unwatch ASAP otherwise we'll waste CPU cycles */
7744 orig_argv
= c
->argv
;
7745 orig_argc
= c
->argc
;
7746 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",c
->mstate
.count
));
7747 for (j
= 0; j
< c
->mstate
.count
; j
++) {
7748 c
->argc
= c
->mstate
.commands
[j
].argc
;
7749 c
->argv
= c
->mstate
.commands
[j
].argv
;
7750 call(c
,c
->mstate
.commands
[j
].cmd
);
7752 c
->argv
= orig_argv
;
7753 c
->argc
= orig_argc
;
7754 freeClientMultiState(c
);
7755 initClientMultiState(c
);
7756 c
->flags
&= ~(REDIS_MULTI
|REDIS_DIRTY_CAS
);
7757 /* Make sure the EXEC command is always replicated / AOF, since we
7758 * always send the MULTI command (we can't know beforehand if the
7759 * next operations will contain at least a modification to the DB). */
7763 /* =========================== Blocking Operations ========================= */
7765 /* Currently Redis blocking operations support is limited to list POP ops,
7766 * so the current implementation is not fully generic, but it is also not
7767 * completely specific so it will not require a rewrite to support new
7768 * kind of blocking operations in the future.
7770 * Still it's important to note that list blocking operations can be already
7771 * used as a notification mechanism in order to implement other blocking
7772 * operations at application level, so there must be a very strong evidence
7773 * of usefulness and generality before new blocking operations are implemented.
7775 * This is how the current blocking POP works, we use BLPOP as example:
7776 * - If the user calls BLPOP and the key exists and contains a non empty list
7777 * then LPOP is called instead. So BLPOP is semantically the same as LPOP
7778 * if there is not to block.
7779 * - If instead BLPOP is called and the key does not exists or the list is
7780 * empty we need to block. In order to do so we remove the notification for
7781 * new data to read in the client socket (so that we'll not serve new
7782 * requests if the blocking request is not served). Also we put the client
7783 * in a dictionary (db->blocking_keys) mapping keys to a list of clients
7784 * blocking for this keys.
7785 * - If a PUSH operation against a key with blocked clients waiting is
7786 * performed, we serve the first in the list: basically instead to push
7787 * the new element inside the list we return it to the (first / oldest)
7788 * blocking client, unblock the client, and remove it form the list.
7790 * The above comment and the source code should be enough in order to understand
7791 * the implementation and modify / fix it later.
7794 /* Set a client in blocking mode for the specified key, with the specified
7796 static void blockForKeys(redisClient
*c
, robj
**keys
, int numkeys
, time_t timeout
) {
7801 c
->blocking_keys
= zmalloc(sizeof(robj
*)*numkeys
);
7802 c
->blocking_keys_num
= numkeys
;
7803 c
->blockingto
= timeout
;
7804 for (j
= 0; j
< numkeys
; j
++) {
7805 /* Add the key in the client structure, to map clients -> keys */
7806 c
->blocking_keys
[j
] = keys
[j
];
7807 incrRefCount(keys
[j
]);
7809 /* And in the other "side", to map keys -> clients */
7810 de
= dictFind(c
->db
->blocking_keys
,keys
[j
]);
7814 /* For every key we take a list of clients blocked for it */
7816 retval
= dictAdd(c
->db
->blocking_keys
,keys
[j
],l
);
7817 incrRefCount(keys
[j
]);
7818 assert(retval
== DICT_OK
);
7820 l
= dictGetEntryVal(de
);
7822 listAddNodeTail(l
,c
);
7824 /* Mark the client as a blocked client */
7825 c
->flags
|= REDIS_BLOCKED
;
7826 server
.blpop_blocked_clients
++;
7829 /* Unblock a client that's waiting in a blocking operation such as BLPOP */
7830 static void unblockClientWaitingData(redisClient
*c
) {
7835 assert(c
->blocking_keys
!= NULL
);
7836 /* The client may wait for multiple keys, so unblock it for every key. */
7837 for (j
= 0; j
< c
->blocking_keys_num
; j
++) {
7838 /* Remove this client from the list of clients waiting for this key. */
7839 de
= dictFind(c
->db
->blocking_keys
,c
->blocking_keys
[j
]);
7841 l
= dictGetEntryVal(de
);
7842 listDelNode(l
,listSearchKey(l
,c
));
7843 /* If the list is empty we need to remove it to avoid wasting memory */
7844 if (listLength(l
) == 0)
7845 dictDelete(c
->db
->blocking_keys
,c
->blocking_keys
[j
]);
7846 decrRefCount(c
->blocking_keys
[j
]);
7848 /* Cleanup the client structure */
7849 zfree(c
->blocking_keys
);
7850 c
->blocking_keys
= NULL
;
7851 c
->flags
&= (~REDIS_BLOCKED
);
7852 server
.blpop_blocked_clients
--;
7853 /* We want to process data if there is some command waiting
7854 * in the input buffer. Note that this is safe even if
7855 * unblockClientWaitingData() gets called from freeClient() because
7856 * freeClient() will be smart enough to call this function
7857 * *after* c->querybuf was set to NULL. */
7858 if (c
->querybuf
&& sdslen(c
->querybuf
) > 0) processInputBuffer(c
);
7861 /* This should be called from any function PUSHing into lists.
7862 * 'c' is the "pushing client", 'key' is the key it is pushing data against,
7863 * 'ele' is the element pushed.
7865 * If the function returns 0 there was no client waiting for a list push
7868 * If the function returns 1 there was a client waiting for a list push
7869 * against this key, the element was passed to this client thus it's not
7870 * needed to actually add it to the list and the caller should return asap. */
7871 static int handleClientsWaitingListPush(redisClient
*c
, robj
*key
, robj
*ele
) {
7872 struct dictEntry
*de
;
7873 redisClient
*receiver
;
7877 de
= dictFind(c
->db
->blocking_keys
,key
);
7878 if (de
== NULL
) return 0;
7879 l
= dictGetEntryVal(de
);
7882 receiver
= ln
->value
;
7884 addReplySds(receiver
,sdsnew("*2\r\n"));
7885 addReplyBulk(receiver
,key
);
7886 addReplyBulk(receiver
,ele
);
7887 unblockClientWaitingData(receiver
);
7891 /* Blocking RPOP/LPOP */
7892 static void blockingPopGenericCommand(redisClient
*c
, int where
) {
7897 for (j
= 1; j
< c
->argc
-1; j
++) {
7898 o
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
7900 if (o
->type
!= REDIS_LIST
) {
7901 addReply(c
,shared
.wrongtypeerr
);
7904 list
*list
= o
->ptr
;
7905 if (listLength(list
) != 0) {
7906 /* If the list contains elements fall back to the usual
7907 * non-blocking POP operation */
7908 robj
*argv
[2], **orig_argv
;
7911 /* We need to alter the command arguments before to call
7912 * popGenericCommand() as the command takes a single key. */
7913 orig_argv
= c
->argv
;
7914 orig_argc
= c
->argc
;
7915 argv
[1] = c
->argv
[j
];
7919 /* Also the return value is different, we need to output
7920 * the multi bulk reply header and the key name. The
7921 * "real" command will add the last element (the value)
7922 * for us. If this souds like an hack to you it's just
7923 * because it is... */
7924 addReplySds(c
,sdsnew("*2\r\n"));
7925 addReplyBulk(c
,argv
[1]);
7926 popGenericCommand(c
,where
);
7928 /* Fix the client structure with the original stuff */
7929 c
->argv
= orig_argv
;
7930 c
->argc
= orig_argc
;
7936 /* If the list is empty or the key does not exists we must block */
7937 timeout
= strtol(c
->argv
[c
->argc
-1]->ptr
,NULL
,10);
7938 if (timeout
> 0) timeout
+= time(NULL
);
7939 blockForKeys(c
,c
->argv
+1,c
->argc
-2,timeout
);
7942 static void blpopCommand(redisClient
*c
) {
7943 blockingPopGenericCommand(c
,REDIS_HEAD
);
7946 static void brpopCommand(redisClient
*c
) {
7947 blockingPopGenericCommand(c
,REDIS_TAIL
);
7950 /* =============================== Replication ============================= */
7952 static int syncWrite(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7953 ssize_t nwritten
, ret
= size
;
7954 time_t start
= time(NULL
);
7958 if (aeWait(fd
,AE_WRITABLE
,1000) & AE_WRITABLE
) {
7959 nwritten
= write(fd
,ptr
,size
);
7960 if (nwritten
== -1) return -1;
7964 if ((time(NULL
)-start
) > timeout
) {
7972 static int syncRead(int fd
, char *ptr
, ssize_t size
, int timeout
) {
7973 ssize_t nread
, totread
= 0;
7974 time_t start
= time(NULL
);
7978 if (aeWait(fd
,AE_READABLE
,1000) & AE_READABLE
) {
7979 nread
= read(fd
,ptr
,size
);
7980 if (nread
== -1) return -1;
7985 if ((time(NULL
)-start
) > timeout
) {
7993 static int syncReadLine(int fd
, char *ptr
, ssize_t size
, int timeout
) {
8000 if (syncRead(fd
,&c
,1,timeout
) == -1) return -1;
8003 if (nread
&& *(ptr
-1) == '\r') *(ptr
-1) = '\0';
8014 static void syncCommand(redisClient
*c
) {
8015 /* ignore SYNC if aleady slave or in monitor mode */
8016 if (c
->flags
& REDIS_SLAVE
) return;
8018 /* SYNC can't be issued when the server has pending data to send to
8019 * the client about already issued commands. We need a fresh reply
8020 * buffer registering the differences between the BGSAVE and the current
8021 * dataset, so that we can copy to other slaves if needed. */
8022 if (listLength(c
->reply
) != 0) {
8023 addReplySds(c
,sdsnew("-ERR SYNC is invalid with pending input\r\n"));
8027 redisLog(REDIS_NOTICE
,"Slave ask for synchronization");
8028 /* Here we need to check if there is a background saving operation
8029 * in progress, or if it is required to start one */
8030 if (server
.bgsavechildpid
!= -1) {
8031 /* Ok a background save is in progress. Let's check if it is a good
8032 * one for replication, i.e. if there is another slave that is
8033 * registering differences since the server forked to save */
8038 listRewind(server
.slaves
,&li
);
8039 while((ln
= listNext(&li
))) {
8041 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) break;
8044 /* Perfect, the server is already registering differences for
8045 * another slave. Set the right state, and copy the buffer. */
8046 listRelease(c
->reply
);
8047 c
->reply
= listDup(slave
->reply
);
8048 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
8049 redisLog(REDIS_NOTICE
,"Waiting for end of BGSAVE for SYNC");
8051 /* No way, we need to wait for the next BGSAVE in order to
8052 * register differences */
8053 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
8054 redisLog(REDIS_NOTICE
,"Waiting for next BGSAVE for SYNC");
8057 /* Ok we don't have a BGSAVE in progress, let's start one */
8058 redisLog(REDIS_NOTICE
,"Starting BGSAVE for SYNC");
8059 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
8060 redisLog(REDIS_NOTICE
,"Replication failed, can't BGSAVE");
8061 addReplySds(c
,sdsnew("-ERR Unalbe to perform background save\r\n"));
8064 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
8067 c
->flags
|= REDIS_SLAVE
;
8069 listAddNodeTail(server
.slaves
,c
);
8073 static void sendBulkToSlave(aeEventLoop
*el
, int fd
, void *privdata
, int mask
) {
8074 redisClient
*slave
= privdata
;
8076 REDIS_NOTUSED(mask
);
8077 char buf
[REDIS_IOBUF_LEN
];
8078 ssize_t nwritten
, buflen
;
8080 if (slave
->repldboff
== 0) {
8081 /* Write the bulk write count before to transfer the DB. In theory here
8082 * we don't know how much room there is in the output buffer of the
8083 * socket, but in pratice SO_SNDLOWAT (the minimum count for output
8084 * operations) will never be smaller than the few bytes we need. */
8087 bulkcount
= sdscatprintf(sdsempty(),"$%lld\r\n",(unsigned long long)
8089 if (write(fd
,bulkcount
,sdslen(bulkcount
)) != (signed)sdslen(bulkcount
))
8097 lseek(slave
->repldbfd
,slave
->repldboff
,SEEK_SET
);
8098 buflen
= read(slave
->repldbfd
,buf
,REDIS_IOBUF_LEN
);
8100 redisLog(REDIS_WARNING
,"Read error sending DB to slave: %s",
8101 (buflen
== 0) ? "premature EOF" : strerror(errno
));
8105 if ((nwritten
= write(fd
,buf
,buflen
)) == -1) {
8106 redisLog(REDIS_VERBOSE
,"Write error sending DB to slave: %s",
8111 slave
->repldboff
+= nwritten
;
8112 if (slave
->repldboff
== slave
->repldbsize
) {
8113 close(slave
->repldbfd
);
8114 slave
->repldbfd
= -1;
8115 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
8116 slave
->replstate
= REDIS_REPL_ONLINE
;
8117 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
,
8118 sendReplyToClient
, slave
) == AE_ERR
) {
8122 addReplySds(slave
,sdsempty());
8123 redisLog(REDIS_NOTICE
,"Synchronization with slave succeeded");
8127 /* This function is called at the end of every backgrond saving.
8128 * The argument bgsaveerr is REDIS_OK if the background saving succeeded
8129 * otherwise REDIS_ERR is passed to the function.
8131 * The goal of this function is to handle slaves waiting for a successful
8132 * background saving in order to perform non-blocking synchronization. */
8133 static void updateSlavesWaitingBgsave(int bgsaveerr
) {
8135 int startbgsave
= 0;
8138 listRewind(server
.slaves
,&li
);
8139 while((ln
= listNext(&li
))) {
8140 redisClient
*slave
= ln
->value
;
8142 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
) {
8144 slave
->replstate
= REDIS_REPL_WAIT_BGSAVE_END
;
8145 } else if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_END
) {
8146 struct redis_stat buf
;
8148 if (bgsaveerr
!= REDIS_OK
) {
8150 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE child returned an error");
8153 if ((slave
->repldbfd
= open(server
.dbfilename
,O_RDONLY
)) == -1 ||
8154 redis_fstat(slave
->repldbfd
,&buf
) == -1) {
8156 redisLog(REDIS_WARNING
,"SYNC failed. Can't open/stat DB after BGSAVE: %s", strerror(errno
));
8159 slave
->repldboff
= 0;
8160 slave
->repldbsize
= buf
.st_size
;
8161 slave
->replstate
= REDIS_REPL_SEND_BULK
;
8162 aeDeleteFileEvent(server
.el
,slave
->fd
,AE_WRITABLE
);
8163 if (aeCreateFileEvent(server
.el
, slave
->fd
, AE_WRITABLE
, sendBulkToSlave
, slave
) == AE_ERR
) {
8170 if (rdbSaveBackground(server
.dbfilename
) != REDIS_OK
) {
8173 listRewind(server
.slaves
,&li
);
8174 redisLog(REDIS_WARNING
,"SYNC failed. BGSAVE failed");
8175 while((ln
= listNext(&li
))) {
8176 redisClient
*slave
= ln
->value
;
8178 if (slave
->replstate
== REDIS_REPL_WAIT_BGSAVE_START
)
8185 static int syncWithMaster(void) {
8186 char buf
[1024], tmpfile
[256], authcmd
[1024];
8188 int fd
= anetTcpConnect(NULL
,server
.masterhost
,server
.masterport
);
8189 int dfd
, maxtries
= 5;
8192 redisLog(REDIS_WARNING
,"Unable to connect to MASTER: %s",
8197 /* AUTH with the master if required. */
8198 if(server
.masterauth
) {
8199 snprintf(authcmd
, 1024, "AUTH %s\r\n", server
.masterauth
);
8200 if (syncWrite(fd
, authcmd
, strlen(server
.masterauth
)+7, 5) == -1) {
8202 redisLog(REDIS_WARNING
,"Unable to AUTH to MASTER: %s",
8206 /* Read the AUTH result. */
8207 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
8209 redisLog(REDIS_WARNING
,"I/O error reading auth result from MASTER: %s",
8213 if (buf
[0] != '+') {
8215 redisLog(REDIS_WARNING
,"Cannot AUTH to MASTER, is the masterauth password correct?");
8220 /* Issue the SYNC command */
8221 if (syncWrite(fd
,"SYNC \r\n",7,5) == -1) {
8223 redisLog(REDIS_WARNING
,"I/O error writing to MASTER: %s",
8227 /* Read the bulk write count */
8228 if (syncReadLine(fd
,buf
,1024,3600) == -1) {
8230 redisLog(REDIS_WARNING
,"I/O error reading bulk count from MASTER: %s",
8234 if (buf
[0] != '$') {
8236 redisLog(REDIS_WARNING
,"Bad protocol from MASTER, the first byte is not '$', are you sure the host and port are right?");
8239 dumpsize
= strtol(buf
+1,NULL
,10);
8240 redisLog(REDIS_NOTICE
,"Receiving %ld bytes data dump from MASTER",dumpsize
);
8241 /* Read the bulk write data on a temp file */
8243 snprintf(tmpfile
,256,
8244 "temp-%d.%ld.rdb",(int)time(NULL
),(long int)getpid());
8245 dfd
= open(tmpfile
,O_CREAT
|O_WRONLY
|O_EXCL
,0644);
8246 if (dfd
!= -1) break;
8251 redisLog(REDIS_WARNING
,"Opening the temp file needed for MASTER <-> SLAVE synchronization: %s",strerror(errno
));
8255 int nread
, nwritten
;
8257 nread
= read(fd
,buf
,(dumpsize
< 1024)?dumpsize
:1024);
8259 redisLog(REDIS_WARNING
,"I/O error trying to sync with MASTER: %s",
8265 nwritten
= write(dfd
,buf
,nread
);
8266 if (nwritten
== -1) {
8267 redisLog(REDIS_WARNING
,"Write error writing to the DB dump file needed for MASTER <-> SLAVE synchrnonization: %s", strerror(errno
));
8275 if (rename(tmpfile
,server
.dbfilename
) == -1) {
8276 redisLog(REDIS_WARNING
,"Failed trying to rename the temp DB into dump.rdb in MASTER <-> SLAVE synchronization: %s", strerror(errno
));
8282 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
8283 redisLog(REDIS_WARNING
,"Failed trying to load the MASTER synchronization DB from disk");
8287 server
.master
= createClient(fd
);
8288 server
.master
->flags
|= REDIS_MASTER
;
8289 server
.master
->authenticated
= 1;
8290 server
.replstate
= REDIS_REPL_CONNECTED
;
8294 static void slaveofCommand(redisClient
*c
) {
8295 if (!strcasecmp(c
->argv
[1]->ptr
,"no") &&
8296 !strcasecmp(c
->argv
[2]->ptr
,"one")) {
8297 if (server
.masterhost
) {
8298 sdsfree(server
.masterhost
);
8299 server
.masterhost
= NULL
;
8300 if (server
.master
) freeClient(server
.master
);
8301 server
.replstate
= REDIS_REPL_NONE
;
8302 redisLog(REDIS_NOTICE
,"MASTER MODE enabled (user request)");
8305 sdsfree(server
.masterhost
);
8306 server
.masterhost
= sdsdup(c
->argv
[1]->ptr
);
8307 server
.masterport
= atoi(c
->argv
[2]->ptr
);
8308 if (server
.master
) freeClient(server
.master
);
8309 server
.replstate
= REDIS_REPL_CONNECT
;
8310 redisLog(REDIS_NOTICE
,"SLAVE OF %s:%d enabled (user request)",
8311 server
.masterhost
, server
.masterport
);
8313 addReply(c
,shared
.ok
);
8316 /* ============================ Maxmemory directive ======================== */
8318 /* Try to free one object form the pre-allocated objects free list.
8319 * This is useful under low mem conditions as by default we take 1 million
8320 * free objects allocated. On success REDIS_OK is returned, otherwise
8322 static int tryFreeOneObjectFromFreelist(void) {
8325 if (server
.vm_enabled
) pthread_mutex_lock(&server
.obj_freelist_mutex
);
8326 if (listLength(server
.objfreelist
)) {
8327 listNode
*head
= listFirst(server
.objfreelist
);
8328 o
= listNodeValue(head
);
8329 listDelNode(server
.objfreelist
,head
);
8330 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
8334 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.obj_freelist_mutex
);
8339 /* This function gets called when 'maxmemory' is set on the config file to limit
8340 * the max memory used by the server, and we are out of memory.
8341 * This function will try to, in order:
8343 * - Free objects from the free list
8344 * - Try to remove keys with an EXPIRE set
8346 * It is not possible to free enough memory to reach used-memory < maxmemory
8347 * the server will start refusing commands that will enlarge even more the
8350 static void freeMemoryIfNeeded(void) {
8351 while (server
.maxmemory
&& zmalloc_used_memory() > server
.maxmemory
) {
8352 int j
, k
, freed
= 0;
8354 if (tryFreeOneObjectFromFreelist() == REDIS_OK
) continue;
8355 for (j
= 0; j
< server
.dbnum
; j
++) {
8357 robj
*minkey
= NULL
;
8358 struct dictEntry
*de
;
8360 if (dictSize(server
.db
[j
].expires
)) {
8362 /* From a sample of three keys drop the one nearest to
8363 * the natural expire */
8364 for (k
= 0; k
< 3; k
++) {
8367 de
= dictGetRandomKey(server
.db
[j
].expires
);
8368 t
= (time_t) dictGetEntryVal(de
);
8369 if (minttl
== -1 || t
< minttl
) {
8370 minkey
= dictGetEntryKey(de
);
8374 deleteKey(server
.db
+j
,minkey
);
8377 if (!freed
) return; /* nothing to free... */
8381 /* ============================== Append Only file ========================== */
8383 /* Write the append only file buffer on disk.
8385 * Since we are required to write the AOF before replying to the client,
8386 * and the only way the client socket can get a write is entering when the
8387 * the event loop, we accumulate all the AOF writes in a memory
8388 * buffer and write it on disk using this function just before entering
8389 * the event loop again. */
8390 static void flushAppendOnlyFile(void) {
8394 if (sdslen(server
.aofbuf
) == 0) return;
8396 /* We want to perform a single write. This should be guaranteed atomic
8397 * at least if the filesystem we are writing is a real physical one.
8398 * While this will save us against the server being killed I don't think
8399 * there is much to do about the whole server stopping for power problems
8401 nwritten
= write(server
.appendfd
,server
.aofbuf
,sdslen(server
.aofbuf
));
8402 if (nwritten
!= (signed)sdslen(server
.aofbuf
)) {
8403 /* Ooops, we are in troubles. The best thing to do for now is
8404 * aborting instead of giving the illusion that everything is
8405 * working as expected. */
8406 if (nwritten
== -1) {
8407 redisLog(REDIS_WARNING
,"Exiting on error writing to the append-only file: %s",strerror(errno
));
8409 redisLog(REDIS_WARNING
,"Exiting on short write while writing to the append-only file: %s",strerror(errno
));
8413 sdsfree(server
.aofbuf
);
8414 server
.aofbuf
= sdsempty();
8416 /* Fsync if needed */
8418 if (server
.appendfsync
== APPENDFSYNC_ALWAYS
||
8419 (server
.appendfsync
== APPENDFSYNC_EVERYSEC
&&
8420 now
-server
.lastfsync
> 1))
8422 /* aof_fsync is defined as fdatasync() for Linux in order to avoid
8423 * flushing metadata. */
8424 aof_fsync(server
.appendfd
); /* Let's try to get this data on the disk */
8425 server
.lastfsync
= now
;
8429 static sds
catAppendOnlyGenericCommand(sds buf
, int argc
, robj
**argv
) {
8431 buf
= sdscatprintf(buf
,"*%d\r\n",argc
);
8432 for (j
= 0; j
< argc
; j
++) {
8433 robj
*o
= getDecodedObject(argv
[j
]);
8434 buf
= sdscatprintf(buf
,"$%lu\r\n",(unsigned long)sdslen(o
->ptr
));
8435 buf
= sdscatlen(buf
,o
->ptr
,sdslen(o
->ptr
));
8436 buf
= sdscatlen(buf
,"\r\n",2);
8442 static sds
catAppendOnlyExpireAtCommand(sds buf
, robj
*key
, robj
*seconds
) {
8447 /* Make sure we can use strtol */
8448 seconds
= getDecodedObject(seconds
);
8449 when
= time(NULL
)+strtol(seconds
->ptr
,NULL
,10);
8450 decrRefCount(seconds
);
8452 argv
[0] = createStringObject("EXPIREAT",8);
8454 argv
[2] = createObject(REDIS_STRING
,
8455 sdscatprintf(sdsempty(),"%ld",when
));
8456 buf
= catAppendOnlyGenericCommand(buf
, argc
, argv
);
8457 decrRefCount(argv
[0]);
8458 decrRefCount(argv
[2]);
8462 static void feedAppendOnlyFile(struct redisCommand
*cmd
, int dictid
, robj
**argv
, int argc
) {
8463 sds buf
= sdsempty();
8466 /* The DB this command was targetting is not the same as the last command
8467 * we appendend. To issue a SELECT command is needed. */
8468 if (dictid
!= server
.appendseldb
) {
8471 snprintf(seldb
,sizeof(seldb
),"%d",dictid
);
8472 buf
= sdscatprintf(buf
,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
8473 (unsigned long)strlen(seldb
),seldb
);
8474 server
.appendseldb
= dictid
;
8477 if (cmd
->proc
== expireCommand
) {
8478 /* Translate EXPIRE into EXPIREAT */
8479 buf
= catAppendOnlyExpireAtCommand(buf
,argv
[1],argv
[2]);
8480 } else if (cmd
->proc
== setexCommand
) {
8481 /* Translate SETEX to SET and EXPIREAT */
8482 tmpargv
[0] = createStringObject("SET",3);
8483 tmpargv
[1] = argv
[1];
8484 tmpargv
[2] = argv
[3];
8485 buf
= catAppendOnlyGenericCommand(buf
,3,tmpargv
);
8486 decrRefCount(tmpargv
[0]);
8487 buf
= catAppendOnlyExpireAtCommand(buf
,argv
[1],argv
[2]);
8489 buf
= catAppendOnlyGenericCommand(buf
,argc
,argv
);
8492 /* Append to the AOF buffer. This will be flushed on disk just before
8493 * of re-entering the event loop, so before the client will get a
8494 * positive reply about the operation performed. */
8495 server
.aofbuf
= sdscatlen(server
.aofbuf
,buf
,sdslen(buf
));
8497 /* If a background append only file rewriting is in progress we want to
8498 * accumulate the differences between the child DB and the current one
8499 * in a buffer, so that when the child process will do its work we
8500 * can append the differences to the new append only file. */
8501 if (server
.bgrewritechildpid
!= -1)
8502 server
.bgrewritebuf
= sdscatlen(server
.bgrewritebuf
,buf
,sdslen(buf
));
8507 /* In Redis commands are always executed in the context of a client, so in
8508 * order to load the append only file we need to create a fake client. */
8509 static struct redisClient
*createFakeClient(void) {
8510 struct redisClient
*c
= zmalloc(sizeof(*c
));
8514 c
->querybuf
= sdsempty();
8518 /* We set the fake client as a slave waiting for the synchronization
8519 * so that Redis will not try to send replies to this client. */
8520 c
->replstate
= REDIS_REPL_WAIT_BGSAVE_START
;
8521 c
->reply
= listCreate();
8522 listSetFreeMethod(c
->reply
,decrRefCount
);
8523 listSetDupMethod(c
->reply
,dupClientReplyValue
);
8524 initClientMultiState(c
);
8528 static void freeFakeClient(struct redisClient
*c
) {
8529 sdsfree(c
->querybuf
);
8530 listRelease(c
->reply
);
8531 freeClientMultiState(c
);
8535 /* Replay the append log file. On error REDIS_OK is returned. On non fatal
8536 * error (the append only file is zero-length) REDIS_ERR is returned. On
8537 * fatal error an error message is logged and the program exists. */
8538 int loadAppendOnlyFile(char *filename
) {
8539 struct redisClient
*fakeClient
;
8540 FILE *fp
= fopen(filename
,"r");
8541 struct redis_stat sb
;
8542 unsigned long long loadedkeys
= 0;
8543 int appendonly
= server
.appendonly
;
8545 if (redis_fstat(fileno(fp
),&sb
) != -1 && sb
.st_size
== 0)
8549 redisLog(REDIS_WARNING
,"Fatal error: can't open the append log file for reading: %s",strerror(errno
));
8553 /* Temporarily disable AOF, to prevent EXEC from feeding a MULTI
8554 * to the same file we're about to read. */
8555 server
.appendonly
= 0;
8557 fakeClient
= createFakeClient();
8564 struct redisCommand
*cmd
;
8566 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) {
8572 if (buf
[0] != '*') goto fmterr
;
8574 argv
= zmalloc(sizeof(robj
*)*argc
);
8575 for (j
= 0; j
< argc
; j
++) {
8576 if (fgets(buf
,sizeof(buf
),fp
) == NULL
) goto readerr
;
8577 if (buf
[0] != '$') goto fmterr
;
8578 len
= strtol(buf
+1,NULL
,10);
8579 argsds
= sdsnewlen(NULL
,len
);
8580 if (len
&& fread(argsds
,len
,1,fp
) == 0) goto fmterr
;
8581 argv
[j
] = createObject(REDIS_STRING
,argsds
);
8582 if (fread(buf
,2,1,fp
) == 0) goto fmterr
; /* discard CRLF */
8585 /* Command lookup */
8586 cmd
= lookupCommand(argv
[0]->ptr
);
8588 redisLog(REDIS_WARNING
,"Unknown command '%s' reading the append only file", argv
[0]->ptr
);
8591 /* Try object encoding */
8592 if (cmd
->flags
& REDIS_CMD_BULK
)
8593 argv
[argc
-1] = tryObjectEncoding(argv
[argc
-1]);
8594 /* Run the command in the context of a fake client */
8595 fakeClient
->argc
= argc
;
8596 fakeClient
->argv
= argv
;
8597 cmd
->proc(fakeClient
);
8598 /* Discard the reply objects list from the fake client */
8599 while(listLength(fakeClient
->reply
))
8600 listDelNode(fakeClient
->reply
,listFirst(fakeClient
->reply
));
8601 /* Clean up, ready for the next command */
8602 for (j
= 0; j
< argc
; j
++) decrRefCount(argv
[j
]);
8604 /* Handle swapping while loading big datasets when VM is on */
8606 if (server
.vm_enabled
&& (loadedkeys
% 5000) == 0) {
8607 while (zmalloc_used_memory() > server
.vm_max_memory
) {
8608 if (vmSwapOneObjectBlocking() == REDIS_ERR
) break;
8613 /* This point can only be reached when EOF is reached without errors.
8614 * If the client is in the middle of a MULTI/EXEC, log error and quit. */
8615 if (fakeClient
->flags
& REDIS_MULTI
) goto readerr
;
8618 freeFakeClient(fakeClient
);
8619 server
.appendonly
= appendonly
;
8624 redisLog(REDIS_WARNING
,"Unexpected end of file reading the append only file");
8626 redisLog(REDIS_WARNING
,"Unrecoverable error reading the append only file: %s", strerror(errno
));
8630 redisLog(REDIS_WARNING
,"Bad file format reading the append only file");
8634 /* Write an object into a file in the bulk format $<count>\r\n<payload>\r\n */
8635 static int fwriteBulkObject(FILE *fp
, robj
*obj
) {
8639 /* Avoid the incr/decr ref count business if possible to help
8640 * copy-on-write (we are often in a child process when this function
8642 * Also makes sure that key objects don't get incrRefCount-ed when VM
8644 if (obj
->encoding
!= REDIS_ENCODING_RAW
) {
8645 obj
= getDecodedObject(obj
);
8648 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(long)sdslen(obj
->ptr
));
8649 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) goto err
;
8650 if (sdslen(obj
->ptr
) && fwrite(obj
->ptr
,sdslen(obj
->ptr
),1,fp
) == 0)
8652 if (fwrite("\r\n",2,1,fp
) == 0) goto err
;
8653 if (decrrc
) decrRefCount(obj
);
8656 if (decrrc
) decrRefCount(obj
);
8660 /* Write binary-safe string into a file in the bulkformat
8661 * $<count>\r\n<payload>\r\n */
8662 static int fwriteBulkString(FILE *fp
, char *s
, unsigned long len
) {
8665 snprintf(buf
,sizeof(buf
),"$%ld\r\n",(unsigned long)len
);
8666 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8667 if (len
&& fwrite(s
,len
,1,fp
) == 0) return 0;
8668 if (fwrite("\r\n",2,1,fp
) == 0) return 0;
8672 /* Write a double value in bulk format $<count>\r\n<payload>\r\n */
8673 static int fwriteBulkDouble(FILE *fp
, double d
) {
8674 char buf
[128], dbuf
[128];
8676 snprintf(dbuf
,sizeof(dbuf
),"%.17g\r\n",d
);
8677 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(dbuf
)-2);
8678 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8679 if (fwrite(dbuf
,strlen(dbuf
),1,fp
) == 0) return 0;
8683 /* Write a long value in bulk format $<count>\r\n<payload>\r\n */
8684 static int fwriteBulkLong(FILE *fp
, long l
) {
8685 char buf
[128], lbuf
[128];
8687 snprintf(lbuf
,sizeof(lbuf
),"%ld\r\n",l
);
8688 snprintf(buf
,sizeof(buf
),"$%lu\r\n",(unsigned long)strlen(lbuf
)-2);
8689 if (fwrite(buf
,strlen(buf
),1,fp
) == 0) return 0;
8690 if (fwrite(lbuf
,strlen(lbuf
),1,fp
) == 0) return 0;
8694 /* Write a sequence of commands able to fully rebuild the dataset into
8695 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
8696 static int rewriteAppendOnlyFile(char *filename
) {
8697 dictIterator
*di
= NULL
;
8702 time_t now
= time(NULL
);
8704 /* Note that we have to use a different temp name here compared to the
8705 * one used by rewriteAppendOnlyFileBackground() function. */
8706 snprintf(tmpfile
,256,"temp-rewriteaof-%d.aof", (int) getpid());
8707 fp
= fopen(tmpfile
,"w");
8709 redisLog(REDIS_WARNING
, "Failed rewriting the append only file: %s", strerror(errno
));
8712 for (j
= 0; j
< server
.dbnum
; j
++) {
8713 char selectcmd
[] = "*2\r\n$6\r\nSELECT\r\n";
8714 redisDb
*db
= server
.db
+j
;
8716 if (dictSize(d
) == 0) continue;
8717 di
= dictGetIterator(d
);
8723 /* SELECT the new DB */
8724 if (fwrite(selectcmd
,sizeof(selectcmd
)-1,1,fp
) == 0) goto werr
;
8725 if (fwriteBulkLong(fp
,j
) == 0) goto werr
;
8727 /* Iterate this DB writing every entry */
8728 while((de
= dictNext(di
)) != NULL
) {
8733 key
= dictGetEntryKey(de
);
8734 /* If the value for this key is swapped, load a preview in memory.
8735 * We use a "swapped" flag to remember if we need to free the
8736 * value object instead to just increment the ref count anyway
8737 * in order to avoid copy-on-write of pages if we are forked() */
8738 if (!server
.vm_enabled
|| key
->storage
== REDIS_VM_MEMORY
||
8739 key
->storage
== REDIS_VM_SWAPPING
) {
8740 o
= dictGetEntryVal(de
);
8743 o
= vmPreviewObject(key
);
8746 expiretime
= getExpire(db
,key
);
8748 /* Save the key and associated value */
8749 if (o
->type
== REDIS_STRING
) {
8750 /* Emit a SET command */
8751 char cmd
[]="*3\r\n$3\r\nSET\r\n";
8752 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8754 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8755 if (fwriteBulkObject(fp
,o
) == 0) goto werr
;
8756 } else if (o
->type
== REDIS_LIST
) {
8757 /* Emit the RPUSHes needed to rebuild the list */
8758 list
*list
= o
->ptr
;
8762 listRewind(list
,&li
);
8763 while((ln
= listNext(&li
))) {
8764 char cmd
[]="*3\r\n$5\r\nRPUSH\r\n";
8765 robj
*eleobj
= listNodeValue(ln
);
8767 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8768 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8769 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8771 } else if (o
->type
== REDIS_SET
) {
8772 /* Emit the SADDs needed to rebuild the set */
8774 dictIterator
*di
= dictGetIterator(set
);
8777 while((de
= dictNext(di
)) != NULL
) {
8778 char cmd
[]="*3\r\n$4\r\nSADD\r\n";
8779 robj
*eleobj
= dictGetEntryKey(de
);
8781 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8782 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8783 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8785 dictReleaseIterator(di
);
8786 } else if (o
->type
== REDIS_ZSET
) {
8787 /* Emit the ZADDs needed to rebuild the sorted set */
8789 dictIterator
*di
= dictGetIterator(zs
->dict
);
8792 while((de
= dictNext(di
)) != NULL
) {
8793 char cmd
[]="*4\r\n$4\r\nZADD\r\n";
8794 robj
*eleobj
= dictGetEntryKey(de
);
8795 double *score
= dictGetEntryVal(de
);
8797 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8798 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8799 if (fwriteBulkDouble(fp
,*score
) == 0) goto werr
;
8800 if (fwriteBulkObject(fp
,eleobj
) == 0) goto werr
;
8802 dictReleaseIterator(di
);
8803 } else if (o
->type
== REDIS_HASH
) {
8804 char cmd
[]="*4\r\n$4\r\nHSET\r\n";
8806 /* Emit the HSETs needed to rebuild the hash */
8807 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
8808 unsigned char *p
= zipmapRewind(o
->ptr
);
8809 unsigned char *field
, *val
;
8810 unsigned int flen
, vlen
;
8812 while((p
= zipmapNext(p
,&field
,&flen
,&val
,&vlen
)) != NULL
) {
8813 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8814 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8815 if (fwriteBulkString(fp
,(char*)field
,flen
) == -1)
8817 if (fwriteBulkString(fp
,(char*)val
,vlen
) == -1)
8821 dictIterator
*di
= dictGetIterator(o
->ptr
);
8824 while((de
= dictNext(di
)) != NULL
) {
8825 robj
*field
= dictGetEntryKey(de
);
8826 robj
*val
= dictGetEntryVal(de
);
8828 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8829 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8830 if (fwriteBulkObject(fp
,field
) == -1) return -1;
8831 if (fwriteBulkObject(fp
,val
) == -1) return -1;
8833 dictReleaseIterator(di
);
8836 redisPanic("Unknown object type");
8838 /* Save the expire time */
8839 if (expiretime
!= -1) {
8840 char cmd
[]="*3\r\n$8\r\nEXPIREAT\r\n";
8841 /* If this key is already expired skip it */
8842 if (expiretime
< now
) continue;
8843 if (fwrite(cmd
,sizeof(cmd
)-1,1,fp
) == 0) goto werr
;
8844 if (fwriteBulkObject(fp
,key
) == 0) goto werr
;
8845 if (fwriteBulkLong(fp
,expiretime
) == 0) goto werr
;
8847 if (swapped
) decrRefCount(o
);
8849 dictReleaseIterator(di
);
8852 /* Make sure data will not remain on the OS's output buffers */
8857 /* Use RENAME to make sure the DB file is changed atomically only
8858 * if the generate DB file is ok. */
8859 if (rename(tmpfile
,filename
) == -1) {
8860 redisLog(REDIS_WARNING
,"Error moving temp append only file on the final destination: %s", strerror(errno
));
8864 redisLog(REDIS_NOTICE
,"SYNC append only file rewrite performed");
8870 redisLog(REDIS_WARNING
,"Write error writing append only file on disk: %s", strerror(errno
));
8871 if (di
) dictReleaseIterator(di
);
8875 /* This is how rewriting of the append only file in background works:
8877 * 1) The user calls BGREWRITEAOF
8878 * 2) Redis calls this function, that forks():
8879 * 2a) the child rewrite the append only file in a temp file.
8880 * 2b) the parent accumulates differences in server.bgrewritebuf.
8881 * 3) When the child finished '2a' exists.
8882 * 4) The parent will trap the exit code, if it's OK, will append the
8883 * data accumulated into server.bgrewritebuf into the temp file, and
8884 * finally will rename(2) the temp file in the actual file name.
8885 * The the new file is reopened as the new append only file. Profit!
8887 static int rewriteAppendOnlyFileBackground(void) {
8890 if (server
.bgrewritechildpid
!= -1) return REDIS_ERR
;
8891 if (server
.vm_enabled
) waitEmptyIOJobsQueue();
8892 if ((childpid
= fork()) == 0) {
8896 if (server
.vm_enabled
) vmReopenSwapFile();
8898 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
8899 if (rewriteAppendOnlyFile(tmpfile
) == REDIS_OK
) {
8906 if (childpid
== -1) {
8907 redisLog(REDIS_WARNING
,
8908 "Can't rewrite append only file in background: fork: %s",
8912 redisLog(REDIS_NOTICE
,
8913 "Background append only file rewriting started by pid %d",childpid
);
8914 server
.bgrewritechildpid
= childpid
;
8915 updateDictResizePolicy();
8916 /* We set appendseldb to -1 in order to force the next call to the
8917 * feedAppendOnlyFile() to issue a SELECT command, so the differences
8918 * accumulated by the parent into server.bgrewritebuf will start
8919 * with a SELECT statement and it will be safe to merge. */
8920 server
.appendseldb
= -1;
8923 return REDIS_OK
; /* unreached */
8926 static void bgrewriteaofCommand(redisClient
*c
) {
8927 if (server
.bgrewritechildpid
!= -1) {
8928 addReplySds(c
,sdsnew("-ERR background append only file rewriting already in progress\r\n"));
8931 if (rewriteAppendOnlyFileBackground() == REDIS_OK
) {
8932 char *status
= "+Background append only file rewriting started\r\n";
8933 addReplySds(c
,sdsnew(status
));
8935 addReply(c
,shared
.err
);
8939 static void aofRemoveTempFile(pid_t childpid
) {
8942 snprintf(tmpfile
,256,"temp-rewriteaof-bg-%d.aof", (int) childpid
);
8946 /* Virtual Memory is composed mainly of two subsystems:
8947 * - Blocking Virutal Memory
8948 * - Threaded Virtual Memory I/O
8949 * The two parts are not fully decoupled, but functions are split among two
8950 * different sections of the source code (delimited by comments) in order to
8951 * make more clear what functionality is about the blocking VM and what about
8952 * the threaded (not blocking) VM.
8956 * Redis VM is a blocking VM (one that blocks reading swapped values from
8957 * disk into memory when a value swapped out is needed in memory) that is made
8958 * unblocking by trying to examine the command argument vector in order to
8959 * load in background values that will likely be needed in order to exec
8960 * the command. The command is executed only once all the relevant keys
8961 * are loaded into memory.
8963 * This basically is almost as simple of a blocking VM, but almost as parallel
8964 * as a fully non-blocking VM.
8967 /* Called when the user switches from "appendonly yes" to "appendonly no"
8968 * at runtime using the CONFIG command. */
8969 static void stopAppendOnly(void) {
8970 flushAppendOnlyFile();
8971 fsync(server
.appendfd
);
8972 close(server
.appendfd
);
8974 server
.appendfd
= -1;
8975 server
.appendseldb
= -1;
8976 server
.appendonly
= 0;
8977 /* rewrite operation in progress? kill it, wait child exit */
8978 if (server
.bgsavechildpid
!= -1) {
8981 if (kill(server
.bgsavechildpid
,SIGKILL
) != -1)
8982 wait3(&statloc
,0,NULL
);
8983 /* reset the buffer accumulating changes while the child saves */
8984 sdsfree(server
.bgrewritebuf
);
8985 server
.bgrewritebuf
= sdsempty();
8986 server
.bgsavechildpid
= -1;
8990 /* Called when the user switches from "appendonly no" to "appendonly yes"
8991 * at runtime using the CONFIG command. */
8992 static int startAppendOnly(void) {
8993 server
.appendonly
= 1;
8994 server
.lastfsync
= time(NULL
);
8995 server
.appendfd
= open(server
.appendfilename
,O_WRONLY
|O_APPEND
|O_CREAT
,0644);
8996 if (server
.appendfd
== -1) {
8997 redisLog(REDIS_WARNING
,"Used tried to switch on AOF via CONFIG, but I can't open the AOF file: %s",strerror(errno
));
9000 if (rewriteAppendOnlyFileBackground() == REDIS_ERR
) {
9001 server
.appendonly
= 0;
9002 close(server
.appendfd
);
9003 redisLog(REDIS_WARNING
,"Used tried to switch on AOF via CONFIG, I can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.",strerror(errno
));
9009 /* =================== Virtual Memory - Blocking Side ====================== */
9011 static void vmInit(void) {
9017 if (server
.vm_max_threads
!= 0)
9018 zmalloc_enable_thread_safeness(); /* we need thread safe zmalloc() */
9020 redisLog(REDIS_NOTICE
,"Using '%s' as swap file",server
.vm_swap_file
);
9021 /* Try to open the old swap file, otherwise create it */
9022 if ((server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b")) == NULL
) {
9023 server
.vm_fp
= fopen(server
.vm_swap_file
,"w+b");
9025 if (server
.vm_fp
== NULL
) {
9026 redisLog(REDIS_WARNING
,
9027 "Can't open the swap file: %s. Exiting.",
9031 server
.vm_fd
= fileno(server
.vm_fp
);
9032 /* Lock the swap file for writing, this is useful in order to avoid
9033 * another instance to use the same swap file for a config error. */
9034 fl
.l_type
= F_WRLCK
;
9035 fl
.l_whence
= SEEK_SET
;
9036 fl
.l_start
= fl
.l_len
= 0;
9037 if (fcntl(server
.vm_fd
,F_SETLK
,&fl
) == -1) {
9038 redisLog(REDIS_WARNING
,
9039 "Can't lock the swap file at '%s': %s. Make sure it is not used by another Redis instance.", server
.vm_swap_file
, strerror(errno
));
9043 server
.vm_next_page
= 0;
9044 server
.vm_near_pages
= 0;
9045 server
.vm_stats_used_pages
= 0;
9046 server
.vm_stats_swapped_objects
= 0;
9047 server
.vm_stats_swapouts
= 0;
9048 server
.vm_stats_swapins
= 0;
9049 totsize
= server
.vm_pages
*server
.vm_page_size
;
9050 redisLog(REDIS_NOTICE
,"Allocating %lld bytes of swap file",totsize
);
9051 if (ftruncate(server
.vm_fd
,totsize
) == -1) {
9052 redisLog(REDIS_WARNING
,"Can't ftruncate swap file: %s. Exiting.",
9056 redisLog(REDIS_NOTICE
,"Swap file allocated with success");
9058 server
.vm_bitmap
= zmalloc((server
.vm_pages
+7)/8);
9059 redisLog(REDIS_VERBOSE
,"Allocated %lld bytes page table for %lld pages",
9060 (long long) (server
.vm_pages
+7)/8, server
.vm_pages
);
9061 memset(server
.vm_bitmap
,0,(server
.vm_pages
+7)/8);
9063 /* Initialize threaded I/O (used by Virtual Memory) */
9064 server
.io_newjobs
= listCreate();
9065 server
.io_processing
= listCreate();
9066 server
.io_processed
= listCreate();
9067 server
.io_ready_clients
= listCreate();
9068 pthread_mutex_init(&server
.io_mutex
,NULL
);
9069 pthread_mutex_init(&server
.obj_freelist_mutex
,NULL
);
9070 pthread_mutex_init(&server
.io_swapfile_mutex
,NULL
);
9071 server
.io_active_threads
= 0;
9072 if (pipe(pipefds
) == -1) {
9073 redisLog(REDIS_WARNING
,"Unable to intialized VM: pipe(2): %s. Exiting."
9077 server
.io_ready_pipe_read
= pipefds
[0];
9078 server
.io_ready_pipe_write
= pipefds
[1];
9079 redisAssert(anetNonBlock(NULL
,server
.io_ready_pipe_read
) != ANET_ERR
);
9080 /* LZF requires a lot of stack */
9081 pthread_attr_init(&server
.io_threads_attr
);
9082 pthread_attr_getstacksize(&server
.io_threads_attr
, &stacksize
);
9083 while (stacksize
< REDIS_THREAD_STACK_SIZE
) stacksize
*= 2;
9084 pthread_attr_setstacksize(&server
.io_threads_attr
, stacksize
);
9085 /* Listen for events in the threaded I/O pipe */
9086 if (aeCreateFileEvent(server
.el
, server
.io_ready_pipe_read
, AE_READABLE
,
9087 vmThreadedIOCompletedJob
, NULL
) == AE_ERR
)
9088 oom("creating file event");
9091 /* Mark the page as used */
9092 static void vmMarkPageUsed(off_t page
) {
9093 off_t byte
= page
/8;
9095 redisAssert(vmFreePage(page
) == 1);
9096 server
.vm_bitmap
[byte
] |= 1<<bit
;
9099 /* Mark N contiguous pages as used, with 'page' being the first. */
9100 static void vmMarkPagesUsed(off_t page
, off_t count
) {
9103 for (j
= 0; j
< count
; j
++)
9104 vmMarkPageUsed(page
+j
);
9105 server
.vm_stats_used_pages
+= count
;
9106 redisLog(REDIS_DEBUG
,"Mark USED pages: %lld pages at %lld\n",
9107 (long long)count
, (long long)page
);
9110 /* Mark the page as free */
9111 static void vmMarkPageFree(off_t page
) {
9112 off_t byte
= page
/8;
9114 redisAssert(vmFreePage(page
) == 0);
9115 server
.vm_bitmap
[byte
] &= ~(1<<bit
);
9118 /* Mark N contiguous pages as free, with 'page' being the first. */
9119 static void vmMarkPagesFree(off_t page
, off_t count
) {
9122 for (j
= 0; j
< count
; j
++)
9123 vmMarkPageFree(page
+j
);
9124 server
.vm_stats_used_pages
-= count
;
9125 redisLog(REDIS_DEBUG
,"Mark FREE pages: %lld pages at %lld\n",
9126 (long long)count
, (long long)page
);
9129 /* Test if the page is free */
9130 static int vmFreePage(off_t page
) {
9131 off_t byte
= page
/8;
9133 return (server
.vm_bitmap
[byte
] & (1<<bit
)) == 0;
9136 /* Find N contiguous free pages storing the first page of the cluster in *first.
9137 * Returns REDIS_OK if it was able to find N contiguous pages, otherwise
9138 * REDIS_ERR is returned.
9140 * This function uses a simple algorithm: we try to allocate
9141 * REDIS_VM_MAX_NEAR_PAGES sequentially, when we reach this limit we start
9142 * again from the start of the swap file searching for free spaces.
9144 * If it looks pretty clear that there are no free pages near our offset
9145 * we try to find less populated places doing a forward jump of
9146 * REDIS_VM_MAX_RANDOM_JUMP, then we start scanning again a few pages
9147 * without hurry, and then we jump again and so forth...
9149 * This function can be improved using a free list to avoid to guess
9150 * too much, since we could collect data about freed pages.
9152 * note: I implemented this function just after watching an episode of
9153 * Battlestar Galactica, where the hybrid was continuing to say "JUMP!"
9155 static int vmFindContiguousPages(off_t
*first
, off_t n
) {
9156 off_t base
, offset
= 0, since_jump
= 0, numfree
= 0;
9158 if (server
.vm_near_pages
== REDIS_VM_MAX_NEAR_PAGES
) {
9159 server
.vm_near_pages
= 0;
9160 server
.vm_next_page
= 0;
9162 server
.vm_near_pages
++; /* Yet another try for pages near to the old ones */
9163 base
= server
.vm_next_page
;
9165 while(offset
< server
.vm_pages
) {
9166 off_t
this = base
+offset
;
9168 /* If we overflow, restart from page zero */
9169 if (this >= server
.vm_pages
) {
9170 this -= server
.vm_pages
;
9172 /* Just overflowed, what we found on tail is no longer
9173 * interesting, as it's no longer contiguous. */
9177 if (vmFreePage(this)) {
9178 /* This is a free page */
9180 /* Already got N free pages? Return to the caller, with success */
9182 *first
= this-(n
-1);
9183 server
.vm_next_page
= this+1;
9184 redisLog(REDIS_DEBUG
, "FOUND CONTIGUOUS PAGES: %lld pages at %lld\n", (long long) n
, (long long) *first
);
9188 /* The current one is not a free page */
9192 /* Fast-forward if the current page is not free and we already
9193 * searched enough near this place. */
9195 if (!numfree
&& since_jump
>= REDIS_VM_MAX_RANDOM_JUMP
/4) {
9196 offset
+= random() % REDIS_VM_MAX_RANDOM_JUMP
;
9198 /* Note that even if we rewind after the jump, we are don't need
9199 * to make sure numfree is set to zero as we only jump *if* it
9200 * is set to zero. */
9202 /* Otherwise just check the next page */
9209 /* Write the specified object at the specified page of the swap file */
9210 static int vmWriteObjectOnSwap(robj
*o
, off_t page
) {
9211 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
9212 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
9213 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
9214 redisLog(REDIS_WARNING
,
9215 "Critical VM problem in vmWriteObjectOnSwap(): can't seek: %s",
9219 rdbSaveObject(server
.vm_fp
,o
);
9220 fflush(server
.vm_fp
);
9221 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
9225 /* Swap the 'val' object relative to 'key' into disk. Store all the information
9226 * needed to later retrieve the object into the key object.
9227 * If we can't find enough contiguous empty pages to swap the object on disk
9228 * REDIS_ERR is returned. */
9229 static int vmSwapObjectBlocking(robj
*key
, robj
*val
) {
9230 off_t pages
= rdbSavedObjectPages(val
,NULL
);
9233 assert(key
->storage
== REDIS_VM_MEMORY
);
9234 assert(key
->refcount
== 1);
9235 if (vmFindContiguousPages(&page
,pages
) == REDIS_ERR
) return REDIS_ERR
;
9236 if (vmWriteObjectOnSwap(val
,page
) == REDIS_ERR
) return REDIS_ERR
;
9237 key
->vm
.page
= page
;
9238 key
->vm
.usedpages
= pages
;
9239 key
->storage
= REDIS_VM_SWAPPED
;
9240 key
->vtype
= val
->type
;
9241 decrRefCount(val
); /* Deallocate the object from memory. */
9242 vmMarkPagesUsed(page
,pages
);
9243 redisLog(REDIS_DEBUG
,"VM: object %s swapped out at %lld (%lld pages)",
9244 (unsigned char*) key
->ptr
,
9245 (unsigned long long) page
, (unsigned long long) pages
);
9246 server
.vm_stats_swapped_objects
++;
9247 server
.vm_stats_swapouts
++;
9251 static robj
*vmReadObjectFromSwap(off_t page
, int type
) {
9254 if (server
.vm_enabled
) pthread_mutex_lock(&server
.io_swapfile_mutex
);
9255 if (fseeko(server
.vm_fp
,page
*server
.vm_page_size
,SEEK_SET
) == -1) {
9256 redisLog(REDIS_WARNING
,
9257 "Unrecoverable VM problem in vmReadObjectFromSwap(): can't seek: %s",
9261 o
= rdbLoadObject(type
,server
.vm_fp
);
9263 redisLog(REDIS_WARNING
, "Unrecoverable VM problem in vmReadObjectFromSwap(): can't load object from swap file: %s", strerror(errno
));
9266 if (server
.vm_enabled
) pthread_mutex_unlock(&server
.io_swapfile_mutex
);
9270 /* Load the value object relative to the 'key' object from swap to memory.
9271 * The newly allocated object is returned.
9273 * If preview is true the unserialized object is returned to the caller but
9274 * no changes are made to the key object, nor the pages are marked as freed */
9275 static robj
*vmGenericLoadObject(robj
*key
, int preview
) {
9278 redisAssert(key
->storage
== REDIS_VM_SWAPPED
|| key
->storage
== REDIS_VM_LOADING
);
9279 val
= vmReadObjectFromSwap(key
->vm
.page
,key
->vtype
);
9281 key
->storage
= REDIS_VM_MEMORY
;
9282 key
->vm
.atime
= server
.unixtime
;
9283 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
9284 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk",
9285 (unsigned char*) key
->ptr
);
9286 server
.vm_stats_swapped_objects
--;
9288 redisLog(REDIS_DEBUG
, "VM: object %s previewed from disk",
9289 (unsigned char*) key
->ptr
);
9291 server
.vm_stats_swapins
++;
9295 /* Plain object loading, from swap to memory */
9296 static robj
*vmLoadObject(robj
*key
) {
9297 /* If we are loading the object in background, stop it, we
9298 * need to load this object synchronously ASAP. */
9299 if (key
->storage
== REDIS_VM_LOADING
)
9300 vmCancelThreadedIOJob(key
);
9301 return vmGenericLoadObject(key
,0);
9304 /* Just load the value on disk, without to modify the key.
9305 * This is useful when we want to perform some operation on the value
9306 * without to really bring it from swap to memory, like while saving the
9307 * dataset or rewriting the append only log. */
9308 static robj
*vmPreviewObject(robj
*key
) {
9309 return vmGenericLoadObject(key
,1);
9312 /* How a good candidate is this object for swapping?
9313 * The better candidate it is, the greater the returned value.
9315 * Currently we try to perform a fast estimation of the object size in
9316 * memory, and combine it with aging informations.
9318 * Basically swappability = idle-time * log(estimated size)
9320 * Bigger objects are preferred over smaller objects, but not
9321 * proportionally, this is why we use the logarithm. This algorithm is
9322 * just a first try and will probably be tuned later. */
9323 static double computeObjectSwappability(robj
*o
) {
9324 time_t age
= server
.unixtime
- o
->vm
.atime
;
9328 struct dictEntry
*de
;
9331 if (age
<= 0) return 0;
9334 if (o
->encoding
!= REDIS_ENCODING_RAW
) {
9337 asize
= sdslen(o
->ptr
)+sizeof(*o
)+sizeof(long)*2;
9342 listNode
*ln
= listFirst(l
);
9344 asize
= sizeof(list
);
9346 robj
*ele
= ln
->value
;
9349 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9350 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9352 asize
+= (sizeof(listNode
)+elesize
)*listLength(l
);
9357 z
= (o
->type
== REDIS_ZSET
);
9358 d
= z
? ((zset
*)o
->ptr
)->dict
: o
->ptr
;
9360 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
9361 if (z
) asize
+= sizeof(zset
)-sizeof(dict
);
9366 de
= dictGetRandomKey(d
);
9367 ele
= dictGetEntryKey(de
);
9368 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9369 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9371 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
9372 if (z
) asize
+= sizeof(zskiplistNode
)*dictSize(d
);
9376 if (o
->encoding
== REDIS_ENCODING_ZIPMAP
) {
9377 unsigned char *p
= zipmapRewind((unsigned char*)o
->ptr
);
9378 unsigned int len
= zipmapLen((unsigned char*)o
->ptr
);
9379 unsigned int klen
, vlen
;
9380 unsigned char *key
, *val
;
9382 if ((p
= zipmapNext(p
,&key
,&klen
,&val
,&vlen
)) == NULL
) {
9386 asize
= len
*(klen
+vlen
+3);
9387 } else if (o
->encoding
== REDIS_ENCODING_HT
) {
9389 asize
= sizeof(dict
)+(sizeof(struct dictEntry
*)*dictSlots(d
));
9394 de
= dictGetRandomKey(d
);
9395 ele
= dictGetEntryKey(de
);
9396 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9397 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9399 ele
= dictGetEntryVal(de
);
9400 elesize
= (ele
->encoding
== REDIS_ENCODING_RAW
) ?
9401 (sizeof(*o
)+sdslen(ele
->ptr
)) :
9403 asize
+= (sizeof(struct dictEntry
)+elesize
)*dictSize(d
);
9408 return (double)age
*log(1+asize
);
9411 /* Try to swap an object that's a good candidate for swapping.
9412 * Returns REDIS_OK if the object was swapped, REDIS_ERR if it's not possible
9413 * to swap any object at all.
9415 * If 'usethreaded' is true, Redis will try to swap the object in background
9416 * using I/O threads. */
9417 static int vmSwapOneObject(int usethreads
) {
9419 struct dictEntry
*best
= NULL
;
9420 double best_swappability
= 0;
9421 redisDb
*best_db
= NULL
;
9424 for (j
= 0; j
< server
.dbnum
; j
++) {
9425 redisDb
*db
= server
.db
+j
;
9426 /* Why maxtries is set to 100?
9427 * Because this way (usually) we'll find 1 object even if just 1% - 2%
9428 * are swappable objects */
9431 if (dictSize(db
->dict
) == 0) continue;
9432 for (i
= 0; i
< 5; i
++) {
9434 double swappability
;
9436 if (maxtries
) maxtries
--;
9437 de
= dictGetRandomKey(db
->dict
);
9438 key
= dictGetEntryKey(de
);
9439 val
= dictGetEntryVal(de
);
9440 /* Only swap objects that are currently in memory.
9442 * Also don't swap shared objects if threaded VM is on, as we
9443 * try to ensure that the main thread does not touch the
9444 * object while the I/O thread is using it, but we can't
9445 * control other keys without adding additional mutex. */
9446 if (key
->storage
!= REDIS_VM_MEMORY
||
9447 (server
.vm_max_threads
!= 0 && val
->refcount
!= 1)) {
9448 if (maxtries
) i
--; /* don't count this try */
9451 swappability
= computeObjectSwappability(val
);
9452 if (!best
|| swappability
> best_swappability
) {
9454 best_swappability
= swappability
;
9459 if (best
== NULL
) return REDIS_ERR
;
9460 key
= dictGetEntryKey(best
);
9461 val
= dictGetEntryVal(best
);
9463 redisLog(REDIS_DEBUG
,"Key with best swappability: %s, %f",
9464 key
->ptr
, best_swappability
);
9466 /* Unshare the key if needed */
9467 if (key
->refcount
> 1) {
9468 robj
*newkey
= dupStringObject(key
);
9470 key
= dictGetEntryKey(best
) = newkey
;
9474 vmSwapObjectThreaded(key
,val
,best_db
);
9477 if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
9478 dictGetEntryVal(best
) = NULL
;
9486 static int vmSwapOneObjectBlocking() {
9487 return vmSwapOneObject(0);
9490 static int vmSwapOneObjectThreaded() {
9491 return vmSwapOneObject(1);
9494 /* Return true if it's safe to swap out objects in a given moment.
9495 * Basically we don't want to swap objects out while there is a BGSAVE
9496 * or a BGAEOREWRITE running in backgroud. */
9497 static int vmCanSwapOut(void) {
9498 return (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1);
9501 /* Delete a key if swapped. Returns 1 if the key was found, was swapped
9502 * and was deleted. Otherwise 0 is returned. */
9503 static int deleteIfSwapped(redisDb
*db
, robj
*key
) {
9507 if ((de
= dictFind(db
->dict
,key
)) == NULL
) return 0;
9508 foundkey
= dictGetEntryKey(de
);
9509 if (foundkey
->storage
== REDIS_VM_MEMORY
) return 0;
9514 /* =================== Virtual Memory - Threaded I/O ======================= */
9516 static void freeIOJob(iojob
*j
) {
9517 if ((j
->type
== REDIS_IOJOB_PREPARE_SWAP
||
9518 j
->type
== REDIS_IOJOB_DO_SWAP
||
9519 j
->type
== REDIS_IOJOB_LOAD
) && j
->val
!= NULL
)
9520 decrRefCount(j
->val
);
9521 /* We don't decrRefCount the j->key field as we did't incremented
9522 * the count creating IO Jobs. This is because the key field here is
9523 * just used as an indentifier and if a key is removed the Job should
9524 * never be touched again. */
9528 /* Every time a thread finished a Job, it writes a byte into the write side
9529 * of an unix pipe in order to "awake" the main thread, and this function
9531 static void vmThreadedIOCompletedJob(aeEventLoop
*el
, int fd
, void *privdata
,
9535 int retval
, processed
= 0, toprocess
= -1, trytoswap
= 1;
9537 REDIS_NOTUSED(mask
);
9538 REDIS_NOTUSED(privdata
);
9540 /* For every byte we read in the read side of the pipe, there is one
9541 * I/O job completed to process. */
9542 while((retval
= read(fd
,buf
,1)) == 1) {
9546 struct dictEntry
*de
;
9548 redisLog(REDIS_DEBUG
,"Processing I/O completed job");
9550 /* Get the processed element (the oldest one) */
9552 assert(listLength(server
.io_processed
) != 0);
9553 if (toprocess
== -1) {
9554 toprocess
= (listLength(server
.io_processed
)*REDIS_MAX_COMPLETED_JOBS_PROCESSED
)/100;
9555 if (toprocess
<= 0) toprocess
= 1;
9557 ln
= listFirst(server
.io_processed
);
9559 listDelNode(server
.io_processed
,ln
);
9561 /* If this job is marked as canceled, just ignore it */
9566 /* Post process it in the main thread, as there are things we
9567 * can do just here to avoid race conditions and/or invasive locks */
9568 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
);
9569 de
= dictFind(j
->db
->dict
,j
->key
);
9571 key
= dictGetEntryKey(de
);
9572 if (j
->type
== REDIS_IOJOB_LOAD
) {
9575 /* Key loaded, bring it at home */
9576 key
->storage
= REDIS_VM_MEMORY
;
9577 key
->vm
.atime
= server
.unixtime
;
9578 vmMarkPagesFree(key
->vm
.page
,key
->vm
.usedpages
);
9579 redisLog(REDIS_DEBUG
, "VM: object %s loaded from disk (threaded)",
9580 (unsigned char*) key
->ptr
);
9581 server
.vm_stats_swapped_objects
--;
9582 server
.vm_stats_swapins
++;
9583 dictGetEntryVal(de
) = j
->val
;
9584 incrRefCount(j
->val
);
9587 /* Handle clients waiting for this key to be loaded. */
9588 handleClientsBlockedOnSwappedKey(db
,key
);
9589 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
9590 /* Now we know the amount of pages required to swap this object.
9591 * Let's find some space for it, and queue this task again
9592 * rebranded as REDIS_IOJOB_DO_SWAP. */
9593 if (!vmCanSwapOut() ||
9594 vmFindContiguousPages(&j
->page
,j
->pages
) == REDIS_ERR
)
9596 /* Ooops... no space or we can't swap as there is
9597 * a fork()ed Redis trying to save stuff on disk. */
9599 key
->storage
= REDIS_VM_MEMORY
; /* undo operation */
9601 /* Note that we need to mark this pages as used now,
9602 * if the job will be canceled, we'll mark them as freed
9604 vmMarkPagesUsed(j
->page
,j
->pages
);
9605 j
->type
= REDIS_IOJOB_DO_SWAP
;
9610 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
9613 /* Key swapped. We can finally free some memory. */
9614 if (key
->storage
!= REDIS_VM_SWAPPING
) {
9615 printf("key->storage: %d\n",key
->storage
);
9616 printf("key->name: %s\n",(char*)key
->ptr
);
9617 printf("key->refcount: %d\n",key
->refcount
);
9618 printf("val: %p\n",(void*)j
->val
);
9619 printf("val->type: %d\n",j
->val
->type
);
9620 printf("val->ptr: %s\n",(char*)j
->val
->ptr
);
9622 redisAssert(key
->storage
== REDIS_VM_SWAPPING
);
9623 val
= dictGetEntryVal(de
);
9624 key
->vm
.page
= j
->page
;
9625 key
->vm
.usedpages
= j
->pages
;
9626 key
->storage
= REDIS_VM_SWAPPED
;
9627 key
->vtype
= j
->val
->type
;
9628 decrRefCount(val
); /* Deallocate the object from memory. */
9629 dictGetEntryVal(de
) = NULL
;
9630 redisLog(REDIS_DEBUG
,
9631 "VM: object %s swapped out at %lld (%lld pages) (threaded)",
9632 (unsigned char*) key
->ptr
,
9633 (unsigned long long) j
->page
, (unsigned long long) j
->pages
);
9634 server
.vm_stats_swapped_objects
++;
9635 server
.vm_stats_swapouts
++;
9637 /* Put a few more swap requests in queue if we are still
9639 if (trytoswap
&& vmCanSwapOut() &&
9640 zmalloc_used_memory() > server
.vm_max_memory
)
9645 more
= listLength(server
.io_newjobs
) <
9646 (unsigned) server
.vm_max_threads
;
9648 /* Don't waste CPU time if swappable objects are rare. */
9649 if (vmSwapOneObjectThreaded() == REDIS_ERR
) {
9657 if (processed
== toprocess
) return;
9659 if (retval
< 0 && errno
!= EAGAIN
) {
9660 redisLog(REDIS_WARNING
,
9661 "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
9666 static void lockThreadedIO(void) {
9667 pthread_mutex_lock(&server
.io_mutex
);
9670 static void unlockThreadedIO(void) {
9671 pthread_mutex_unlock(&server
.io_mutex
);
9674 /* Remove the specified object from the threaded I/O queue if still not
9675 * processed, otherwise make sure to flag it as canceled. */
9676 static void vmCancelThreadedIOJob(robj
*o
) {
9678 server
.io_newjobs
, /* 0 */
9679 server
.io_processing
, /* 1 */
9680 server
.io_processed
/* 2 */
9684 assert(o
->storage
== REDIS_VM_LOADING
|| o
->storage
== REDIS_VM_SWAPPING
);
9687 /* Search for a matching key in one of the queues */
9688 for (i
= 0; i
< 3; i
++) {
9692 listRewind(lists
[i
],&li
);
9693 while ((ln
= listNext(&li
)) != NULL
) {
9694 iojob
*job
= ln
->value
;
9696 if (job
->canceled
) continue; /* Skip this, already canceled. */
9697 if (job
->key
== o
) {
9698 redisLog(REDIS_DEBUG
,"*** CANCELED %p (%s) (type %d) (LIST ID %d)\n",
9699 (void*)job
, (char*)o
->ptr
, job
->type
, i
);
9700 /* Mark the pages as free since the swap didn't happened
9701 * or happened but is now discarded. */
9702 if (i
!= 1 && job
->type
== REDIS_IOJOB_DO_SWAP
)
9703 vmMarkPagesFree(job
->page
,job
->pages
);
9704 /* Cancel the job. It depends on the list the job is
9707 case 0: /* io_newjobs */
9708 /* If the job was yet not processed the best thing to do
9709 * is to remove it from the queue at all */
9711 listDelNode(lists
[i
],ln
);
9713 case 1: /* io_processing */
9714 /* Oh Shi- the thread is messing with the Job:
9716 * Probably it's accessing the object if this is a
9717 * PREPARE_SWAP or DO_SWAP job.
9718 * If it's a LOAD job it may be reading from disk and
9719 * if we don't wait for the job to terminate before to
9720 * cancel it, maybe in a few microseconds data can be
9721 * corrupted in this pages. So the short story is:
9723 * Better to wait for the job to move into the
9724 * next queue (processed)... */
9726 /* We try again and again until the job is completed. */
9728 /* But let's wait some time for the I/O thread
9729 * to finish with this job. After all this condition
9730 * should be very rare. */
9733 case 2: /* io_processed */
9734 /* The job was already processed, that's easy...
9735 * just mark it as canceled so that we'll ignore it
9736 * when processing completed jobs. */
9740 /* Finally we have to adjust the storage type of the object
9741 * in order to "UNDO" the operaiton. */
9742 if (o
->storage
== REDIS_VM_LOADING
)
9743 o
->storage
= REDIS_VM_SWAPPED
;
9744 else if (o
->storage
== REDIS_VM_SWAPPING
)
9745 o
->storage
= REDIS_VM_MEMORY
;
9752 assert(1 != 1); /* We should never reach this */
9755 static void *IOThreadEntryPoint(void *arg
) {
9760 pthread_detach(pthread_self());
9762 /* Get a new job to process */
9764 if (listLength(server
.io_newjobs
) == 0) {
9765 /* No new jobs in queue, exit. */
9766 redisLog(REDIS_DEBUG
,"Thread %ld exiting, nothing to do",
9767 (long) pthread_self());
9768 server
.io_active_threads
--;
9772 ln
= listFirst(server
.io_newjobs
);
9774 listDelNode(server
.io_newjobs
,ln
);
9775 /* Add the job in the processing queue */
9776 j
->thread
= pthread_self();
9777 listAddNodeTail(server
.io_processing
,j
);
9778 ln
= listLast(server
.io_processing
); /* We use ln later to remove it */
9780 redisLog(REDIS_DEBUG
,"Thread %ld got a new job (type %d): %p about key '%s'",
9781 (long) pthread_self(), j
->type
, (void*)j
, (char*)j
->key
->ptr
);
9783 /* Process the Job */
9784 if (j
->type
== REDIS_IOJOB_LOAD
) {
9785 j
->val
= vmReadObjectFromSwap(j
->page
,j
->key
->vtype
);
9786 } else if (j
->type
== REDIS_IOJOB_PREPARE_SWAP
) {
9787 FILE *fp
= fopen("/dev/null","w+");
9788 j
->pages
= rdbSavedObjectPages(j
->val
,fp
);
9790 } else if (j
->type
== REDIS_IOJOB_DO_SWAP
) {
9791 if (vmWriteObjectOnSwap(j
->val
,j
->page
) == REDIS_ERR
)
9795 /* Done: insert the job into the processed queue */
9796 redisLog(REDIS_DEBUG
,"Thread %ld completed the job: %p (key %s)",
9797 (long) pthread_self(), (void*)j
, (char*)j
->key
->ptr
);
9799 listDelNode(server
.io_processing
,ln
);
9800 listAddNodeTail(server
.io_processed
,j
);
9803 /* Signal the main thread there is new stuff to process */
9804 assert(write(server
.io_ready_pipe_write
,"x",1) == 1);
9806 return NULL
; /* never reached */
9809 static void spawnIOThread(void) {
9811 sigset_t mask
, omask
;
9815 sigaddset(&mask
,SIGCHLD
);
9816 sigaddset(&mask
,SIGHUP
);
9817 sigaddset(&mask
,SIGPIPE
);
9818 pthread_sigmask(SIG_SETMASK
, &mask
, &omask
);
9819 while ((err
= pthread_create(&thread
,&server
.io_threads_attr
,IOThreadEntryPoint
,NULL
)) != 0) {
9820 redisLog(REDIS_WARNING
,"Unable to spawn an I/O thread: %s",
9824 pthread_sigmask(SIG_SETMASK
, &omask
, NULL
);
9825 server
.io_active_threads
++;
9828 /* We need to wait for the last thread to exit before we are able to
9829 * fork() in order to BGSAVE or BGREWRITEAOF. */
9830 static void waitEmptyIOJobsQueue(void) {
9832 int io_processed_len
;
9835 if (listLength(server
.io_newjobs
) == 0 &&
9836 listLength(server
.io_processing
) == 0 &&
9837 server
.io_active_threads
== 0)
9842 /* While waiting for empty jobs queue condition we post-process some
9843 * finshed job, as I/O threads may be hanging trying to write against
9844 * the io_ready_pipe_write FD but there are so much pending jobs that
9846 io_processed_len
= listLength(server
.io_processed
);
9848 if (io_processed_len
) {
9849 vmThreadedIOCompletedJob(NULL
,server
.io_ready_pipe_read
,NULL
,0);
9850 usleep(1000); /* 1 millisecond */
9852 usleep(10000); /* 10 milliseconds */
9857 static void vmReopenSwapFile(void) {
9858 /* Note: we don't close the old one as we are in the child process
9859 * and don't want to mess at all with the original file object. */
9860 server
.vm_fp
= fopen(server
.vm_swap_file
,"r+b");
9861 if (server
.vm_fp
== NULL
) {
9862 redisLog(REDIS_WARNING
,"Can't re-open the VM swap file: %s. Exiting.",
9863 server
.vm_swap_file
);
9866 server
.vm_fd
= fileno(server
.vm_fp
);
9869 /* This function must be called while with threaded IO locked */
9870 static void queueIOJob(iojob
*j
) {
9871 redisLog(REDIS_DEBUG
,"Queued IO Job %p type %d about key '%s'\n",
9872 (void*)j
, j
->type
, (char*)j
->key
->ptr
);
9873 listAddNodeTail(server
.io_newjobs
,j
);
9874 if (server
.io_active_threads
< server
.vm_max_threads
)
9878 static int vmSwapObjectThreaded(robj
*key
, robj
*val
, redisDb
*db
) {
9881 assert(key
->storage
== REDIS_VM_MEMORY
);
9882 assert(key
->refcount
== 1);
9884 j
= zmalloc(sizeof(*j
));
9885 j
->type
= REDIS_IOJOB_PREPARE_SWAP
;
9891 j
->thread
= (pthread_t
) -1;
9892 key
->storage
= REDIS_VM_SWAPPING
;
9900 /* ============ Virtual Memory - Blocking clients on missing keys =========== */
9902 /* This function makes the clinet 'c' waiting for the key 'key' to be loaded.
9903 * If there is not already a job loading the key, it is craeted.
9904 * The key is added to the io_keys list in the client structure, and also
9905 * in the hash table mapping swapped keys to waiting clients, that is,
9906 * server.io_waited_keys. */
9907 static int waitForSwappedKey(redisClient
*c
, robj
*key
) {
9908 struct dictEntry
*de
;
9912 /* If the key does not exist or is already in RAM we don't need to
9913 * block the client at all. */
9914 de
= dictFind(c
->db
->dict
,key
);
9915 if (de
== NULL
) return 0;
9916 o
= dictGetEntryKey(de
);
9917 if (o
->storage
== REDIS_VM_MEMORY
) {
9919 } else if (o
->storage
== REDIS_VM_SWAPPING
) {
9920 /* We were swapping the key, undo it! */
9921 vmCancelThreadedIOJob(o
);
9925 /* OK: the key is either swapped, or being loaded just now. */
9927 /* Add the key to the list of keys this client is waiting for.
9928 * This maps clients to keys they are waiting for. */
9929 listAddNodeTail(c
->io_keys
,key
);
9932 /* Add the client to the swapped keys => clients waiting map. */
9933 de
= dictFind(c
->db
->io_keys
,key
);
9937 /* For every key we take a list of clients blocked for it */
9939 retval
= dictAdd(c
->db
->io_keys
,key
,l
);
9941 assert(retval
== DICT_OK
);
9943 l
= dictGetEntryVal(de
);
9945 listAddNodeTail(l
,c
);
9947 /* Are we already loading the key from disk? If not create a job */
9948 if (o
->storage
== REDIS_VM_SWAPPED
) {
9951 o
->storage
= REDIS_VM_LOADING
;
9952 j
= zmalloc(sizeof(*j
));
9953 j
->type
= REDIS_IOJOB_LOAD
;
9956 j
->key
->vtype
= o
->vtype
;
9957 j
->page
= o
->vm
.page
;
9960 j
->thread
= (pthread_t
) -1;
9968 /* Preload keys for any command with first, last and step values for
9969 * the command keys prototype, as defined in the command table. */
9970 static void waitForMultipleSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9972 if (cmd
->vm_firstkey
== 0) return;
9973 last
= cmd
->vm_lastkey
;
9974 if (last
< 0) last
= argc
+last
;
9975 for (j
= cmd
->vm_firstkey
; j
<= last
; j
+= cmd
->vm_keystep
) {
9976 redisAssert(j
< argc
);
9977 waitForSwappedKey(c
,argv
[j
]);
9981 /* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
9982 * Note that the number of keys to preload is user-defined, so we need to
9983 * apply a sanity check against argc. */
9984 static void zunionInterBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
9988 num
= atoi(argv
[2]->ptr
);
9989 if (num
> (argc
-3)) return;
9990 for (i
= 0; i
< num
; i
++) {
9991 waitForSwappedKey(c
,argv
[3+i
]);
9995 /* Preload keys needed to execute the entire MULTI/EXEC block.
9997 * This function is called by blockClientOnSwappedKeys when EXEC is issued,
9998 * and will block the client when any command requires a swapped out value. */
9999 static void execBlockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
, int argc
, robj
**argv
) {
10001 struct redisCommand
*mcmd
;
10003 REDIS_NOTUSED(cmd
);
10004 REDIS_NOTUSED(argc
);
10005 REDIS_NOTUSED(argv
);
10007 if (!(c
->flags
& REDIS_MULTI
)) return;
10008 for (i
= 0; i
< c
->mstate
.count
; i
++) {
10009 mcmd
= c
->mstate
.commands
[i
].cmd
;
10010 margc
= c
->mstate
.commands
[i
].argc
;
10011 margv
= c
->mstate
.commands
[i
].argv
;
10013 if (mcmd
->vm_preload_proc
!= NULL
) {
10014 mcmd
->vm_preload_proc(c
,mcmd
,margc
,margv
);
10016 waitForMultipleSwappedKeys(c
,mcmd
,margc
,margv
);
10021 /* Is this client attempting to run a command against swapped keys?
10022 * If so, block it ASAP, load the keys in background, then resume it.
10024 * The important idea about this function is that it can fail! If keys will
10025 * still be swapped when the client is resumed, this key lookups will
10026 * just block loading keys from disk. In practical terms this should only
10027 * happen with SORT BY command or if there is a bug in this function.
10029 * Return 1 if the client is marked as blocked, 0 if the client can
10030 * continue as the keys it is going to access appear to be in memory. */
10031 static int blockClientOnSwappedKeys(redisClient
*c
, struct redisCommand
*cmd
) {
10032 if (cmd
->vm_preload_proc
!= NULL
) {
10033 cmd
->vm_preload_proc(c
,cmd
,c
->argc
,c
->argv
);
10035 waitForMultipleSwappedKeys(c
,cmd
,c
->argc
,c
->argv
);
10038 /* If the client was blocked for at least one key, mark it as blocked. */
10039 if (listLength(c
->io_keys
)) {
10040 c
->flags
|= REDIS_IO_WAIT
;
10041 aeDeleteFileEvent(server
.el
,c
->fd
,AE_READABLE
);
10042 server
.vm_blocked_clients
++;
10049 /* Remove the 'key' from the list of blocked keys for a given client.
10051 * The function returns 1 when there are no longer blocking keys after
10052 * the current one was removed (and the client can be unblocked). */
10053 static int dontWaitForSwappedKey(redisClient
*c
, robj
*key
) {
10057 struct dictEntry
*de
;
10059 /* Remove the key from the list of keys this client is waiting for. */
10060 listRewind(c
->io_keys
,&li
);
10061 while ((ln
= listNext(&li
)) != NULL
) {
10062 if (equalStringObjects(ln
->value
,key
)) {
10063 listDelNode(c
->io_keys
,ln
);
10067 assert(ln
!= NULL
);
10069 /* Remove the client form the key => waiting clients map. */
10070 de
= dictFind(c
->db
->io_keys
,key
);
10071 assert(de
!= NULL
);
10072 l
= dictGetEntryVal(de
);
10073 ln
= listSearchKey(l
,c
);
10074 assert(ln
!= NULL
);
10076 if (listLength(l
) == 0)
10077 dictDelete(c
->db
->io_keys
,key
);
10079 return listLength(c
->io_keys
) == 0;
10082 static void handleClientsBlockedOnSwappedKey(redisDb
*db
, robj
*key
) {
10083 struct dictEntry
*de
;
10088 de
= dictFind(db
->io_keys
,key
);
10091 l
= dictGetEntryVal(de
);
10092 len
= listLength(l
);
10093 /* Note: we can't use something like while(listLength(l)) as the list
10094 * can be freed by the calling function when we remove the last element. */
10097 redisClient
*c
= ln
->value
;
10099 if (dontWaitForSwappedKey(c
,key
)) {
10100 /* Put the client in the list of clients ready to go as we
10101 * loaded all the keys about it. */
10102 listAddNodeTail(server
.io_ready_clients
,c
);
10107 /* =========================== Remote Configuration ========================= */
10109 static void configSetCommand(redisClient
*c
) {
10110 robj
*o
= getDecodedObject(c
->argv
[3]);
10113 if (!strcasecmp(c
->argv
[2]->ptr
,"dbfilename")) {
10114 zfree(server
.dbfilename
);
10115 server
.dbfilename
= zstrdup(o
->ptr
);
10116 } else if (!strcasecmp(c
->argv
[2]->ptr
,"requirepass")) {
10117 zfree(server
.requirepass
);
10118 server
.requirepass
= zstrdup(o
->ptr
);
10119 } else if (!strcasecmp(c
->argv
[2]->ptr
,"masterauth")) {
10120 zfree(server
.masterauth
);
10121 server
.masterauth
= zstrdup(o
->ptr
);
10122 } else if (!strcasecmp(c
->argv
[2]->ptr
,"maxmemory")) {
10123 if (getLongLongFromObject(o
,&ll
) == REDIS_ERR
||
10124 ll
< 0) goto badfmt
;
10125 server
.maxmemory
= ll
;
10126 } else if (!strcasecmp(c
->argv
[2]->ptr
,"timeout")) {
10127 if (getLongLongFromObject(o
,&ll
) == REDIS_ERR
||
10128 ll
< 0 || ll
> LONG_MAX
) goto badfmt
;
10129 server
.maxidletime
= ll
;
10130 } else if (!strcasecmp(c
->argv
[2]->ptr
,"appendfsync")) {
10131 if (!strcasecmp(o
->ptr
,"no")) {
10132 server
.appendfsync
= APPENDFSYNC_NO
;
10133 } else if (!strcasecmp(o
->ptr
,"everysec")) {
10134 server
.appendfsync
= APPENDFSYNC_EVERYSEC
;
10135 } else if (!strcasecmp(o
->ptr
,"always")) {
10136 server
.appendfsync
= APPENDFSYNC_ALWAYS
;
10140 } else if (!strcasecmp(c
->argv
[2]->ptr
,"appendonly")) {
10141 int old
= server
.appendonly
;
10142 int new = yesnotoi(o
->ptr
);
10144 if (new == -1) goto badfmt
;
10149 if (startAppendOnly() == REDIS_ERR
) {
10150 addReplySds(c
,sdscatprintf(sdsempty(),
10151 "-ERR Unable to turn on AOF. Check server logs.\r\n"));
10157 } else if (!strcasecmp(c
->argv
[2]->ptr
,"save")) {
10159 sds
*v
= sdssplitlen(o
->ptr
,sdslen(o
->ptr
)," ",1,&vlen
);
10161 /* Perform sanity check before setting the new config:
10162 * - Even number of args
10163 * - Seconds >= 1, changes >= 0 */
10165 sdsfreesplitres(v
,vlen
);
10168 for (j
= 0; j
< vlen
; j
++) {
10172 val
= strtoll(v
[j
], &eptr
, 10);
10173 if (eptr
[0] != '\0' ||
10174 ((j
& 1) == 0 && val
< 1) ||
10175 ((j
& 1) == 1 && val
< 0)) {
10176 sdsfreesplitres(v
,vlen
);
10180 /* Finally set the new config */
10181 resetServerSaveParams();
10182 for (j
= 0; j
< vlen
; j
+= 2) {
10186 seconds
= strtoll(v
[j
],NULL
,10);
10187 changes
= strtoll(v
[j
+1],NULL
,10);
10188 appendServerSaveParams(seconds
, changes
);
10190 sdsfreesplitres(v
,vlen
);
10192 addReplySds(c
,sdscatprintf(sdsempty(),
10193 "-ERR not supported CONFIG parameter %s\r\n",
10194 (char*)c
->argv
[2]->ptr
));
10199 addReply(c
,shared
.ok
);
10202 badfmt
: /* Bad format errors */
10203 addReplySds(c
,sdscatprintf(sdsempty(),
10204 "-ERR invalid argument '%s' for CONFIG SET '%s'\r\n",
10206 (char*)c
->argv
[2]->ptr
));
10210 static void configGetCommand(redisClient
*c
) {
10211 robj
*o
= getDecodedObject(c
->argv
[2]);
10212 robj
*lenobj
= createObject(REDIS_STRING
,NULL
);
10213 char *pattern
= o
->ptr
;
10216 addReply(c
,lenobj
);
10217 decrRefCount(lenobj
);
10219 if (stringmatch(pattern
,"dbfilename",0)) {
10220 addReplyBulkCString(c
,"dbfilename");
10221 addReplyBulkCString(c
,server
.dbfilename
);
10224 if (stringmatch(pattern
,"requirepass",0)) {
10225 addReplyBulkCString(c
,"requirepass");
10226 addReplyBulkCString(c
,server
.requirepass
);
10229 if (stringmatch(pattern
,"masterauth",0)) {
10230 addReplyBulkCString(c
,"masterauth");
10231 addReplyBulkCString(c
,server
.masterauth
);
10234 if (stringmatch(pattern
,"maxmemory",0)) {
10237 ll2string(buf
,128,server
.maxmemory
);
10238 addReplyBulkCString(c
,"maxmemory");
10239 addReplyBulkCString(c
,buf
);
10242 if (stringmatch(pattern
,"timeout",0)) {
10245 ll2string(buf
,128,server
.maxidletime
);
10246 addReplyBulkCString(c
,"timeout");
10247 addReplyBulkCString(c
,buf
);
10250 if (stringmatch(pattern
,"appendonly",0)) {
10251 addReplyBulkCString(c
,"appendonly");
10252 addReplyBulkCString(c
,server
.appendonly
? "yes" : "no");
10255 if (stringmatch(pattern
,"appendfsync",0)) {
10258 switch(server
.appendfsync
) {
10259 case APPENDFSYNC_NO
: policy
= "no"; break;
10260 case APPENDFSYNC_EVERYSEC
: policy
= "everysec"; break;
10261 case APPENDFSYNC_ALWAYS
: policy
= "always"; break;
10262 default: policy
= "unknown"; break; /* too harmless to panic */
10264 addReplyBulkCString(c
,"appendfsync");
10265 addReplyBulkCString(c
,policy
);
10268 if (stringmatch(pattern
,"save",0)) {
10269 sds buf
= sdsempty();
10272 for (j
= 0; j
< server
.saveparamslen
; j
++) {
10273 buf
= sdscatprintf(buf
,"%ld %d",
10274 server
.saveparams
[j
].seconds
,
10275 server
.saveparams
[j
].changes
);
10276 if (j
!= server
.saveparamslen
-1)
10277 buf
= sdscatlen(buf
," ",1);
10279 addReplyBulkCString(c
,"save");
10280 addReplyBulkCString(c
,buf
);
10285 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%d\r\n",matches
*2);
10288 static void configCommand(redisClient
*c
) {
10289 if (!strcasecmp(c
->argv
[1]->ptr
,"set")) {
10290 if (c
->argc
!= 4) goto badarity
;
10291 configSetCommand(c
);
10292 } else if (!strcasecmp(c
->argv
[1]->ptr
,"get")) {
10293 if (c
->argc
!= 3) goto badarity
;
10294 configGetCommand(c
);
10295 } else if (!strcasecmp(c
->argv
[1]->ptr
,"resetstat")) {
10296 if (c
->argc
!= 2) goto badarity
;
10297 server
.stat_numcommands
= 0;
10298 server
.stat_numconnections
= 0;
10299 server
.stat_expiredkeys
= 0;
10300 server
.stat_starttime
= time(NULL
);
10301 addReply(c
,shared
.ok
);
10303 addReplySds(c
,sdscatprintf(sdsempty(),
10304 "-ERR CONFIG subcommand must be one of GET, SET, RESETSTAT\r\n"));
10309 addReplySds(c
,sdscatprintf(sdsempty(),
10310 "-ERR Wrong number of arguments for CONFIG %s\r\n",
10311 (char*) c
->argv
[1]->ptr
));
10314 /* =========================== Pubsub implementation ======================== */
10316 static void freePubsubPattern(void *p
) {
10317 pubsubPattern
*pat
= p
;
10319 decrRefCount(pat
->pattern
);
10323 static int listMatchPubsubPattern(void *a
, void *b
) {
10324 pubsubPattern
*pa
= a
, *pb
= b
;
10326 return (pa
->client
== pb
->client
) &&
10327 (equalStringObjects(pa
->pattern
,pb
->pattern
));
10330 /* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
10331 * 0 if the client was already subscribed to that channel. */
10332 static int pubsubSubscribeChannel(redisClient
*c
, robj
*channel
) {
10333 struct dictEntry
*de
;
10334 list
*clients
= NULL
;
10337 /* Add the channel to the client -> channels hash table */
10338 if (dictAdd(c
->pubsub_channels
,channel
,NULL
) == DICT_OK
) {
10340 incrRefCount(channel
);
10341 /* Add the client to the channel -> list of clients hash table */
10342 de
= dictFind(server
.pubsub_channels
,channel
);
10344 clients
= listCreate();
10345 dictAdd(server
.pubsub_channels
,channel
,clients
);
10346 incrRefCount(channel
);
10348 clients
= dictGetEntryVal(de
);
10350 listAddNodeTail(clients
,c
);
10352 /* Notify the client */
10353 addReply(c
,shared
.mbulk3
);
10354 addReply(c
,shared
.subscribebulk
);
10355 addReplyBulk(c
,channel
);
10356 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+listLength(c
->pubsub_patterns
));
10360 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10361 * 0 if the client was not subscribed to the specified channel. */
10362 static int pubsubUnsubscribeChannel(redisClient
*c
, robj
*channel
, int notify
) {
10363 struct dictEntry
*de
;
10368 /* Remove the channel from the client -> channels hash table */
10369 incrRefCount(channel
); /* channel may be just a pointer to the same object
10370 we have in the hash tables. Protect it... */
10371 if (dictDelete(c
->pubsub_channels
,channel
) == DICT_OK
) {
10373 /* Remove the client from the channel -> clients list hash table */
10374 de
= dictFind(server
.pubsub_channels
,channel
);
10375 assert(de
!= NULL
);
10376 clients
= dictGetEntryVal(de
);
10377 ln
= listSearchKey(clients
,c
);
10378 assert(ln
!= NULL
);
10379 listDelNode(clients
,ln
);
10380 if (listLength(clients
) == 0) {
10381 /* Free the list and associated hash entry at all if this was
10382 * the latest client, so that it will be possible to abuse
10383 * Redis PUBSUB creating millions of channels. */
10384 dictDelete(server
.pubsub_channels
,channel
);
10387 /* Notify the client */
10389 addReply(c
,shared
.mbulk3
);
10390 addReply(c
,shared
.unsubscribebulk
);
10391 addReplyBulk(c
,channel
);
10392 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+
10393 listLength(c
->pubsub_patterns
));
10396 decrRefCount(channel
); /* it is finally safe to release it */
10400 /* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the clinet was already subscribed to that pattern. */
10401 static int pubsubSubscribePattern(redisClient
*c
, robj
*pattern
) {
10404 if (listSearchKey(c
->pubsub_patterns
,pattern
) == NULL
) {
10406 pubsubPattern
*pat
;
10407 listAddNodeTail(c
->pubsub_patterns
,pattern
);
10408 incrRefCount(pattern
);
10409 pat
= zmalloc(sizeof(*pat
));
10410 pat
->pattern
= getDecodedObject(pattern
);
10412 listAddNodeTail(server
.pubsub_patterns
,pat
);
10414 /* Notify the client */
10415 addReply(c
,shared
.mbulk3
);
10416 addReply(c
,shared
.psubscribebulk
);
10417 addReplyBulk(c
,pattern
);
10418 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+listLength(c
->pubsub_patterns
));
10422 /* Unsubscribe a client from a channel. Returns 1 if the operation succeeded, or
10423 * 0 if the client was not subscribed to the specified channel. */
10424 static int pubsubUnsubscribePattern(redisClient
*c
, robj
*pattern
, int notify
) {
10429 incrRefCount(pattern
); /* Protect the object. May be the same we remove */
10430 if ((ln
= listSearchKey(c
->pubsub_patterns
,pattern
)) != NULL
) {
10432 listDelNode(c
->pubsub_patterns
,ln
);
10434 pat
.pattern
= pattern
;
10435 ln
= listSearchKey(server
.pubsub_patterns
,&pat
);
10436 listDelNode(server
.pubsub_patterns
,ln
);
10438 /* Notify the client */
10440 addReply(c
,shared
.mbulk3
);
10441 addReply(c
,shared
.punsubscribebulk
);
10442 addReplyBulk(c
,pattern
);
10443 addReplyLongLong(c
,dictSize(c
->pubsub_channels
)+
10444 listLength(c
->pubsub_patterns
));
10446 decrRefCount(pattern
);
10450 /* Unsubscribe from all the channels. Return the number of channels the
10451 * client was subscribed from. */
10452 static int pubsubUnsubscribeAllChannels(redisClient
*c
, int notify
) {
10453 dictIterator
*di
= dictGetIterator(c
->pubsub_channels
);
10457 while((de
= dictNext(di
)) != NULL
) {
10458 robj
*channel
= dictGetEntryKey(de
);
10460 count
+= pubsubUnsubscribeChannel(c
,channel
,notify
);
10462 dictReleaseIterator(di
);
10466 /* Unsubscribe from all the patterns. Return the number of patterns the
10467 * client was subscribed from. */
10468 static int pubsubUnsubscribeAllPatterns(redisClient
*c
, int notify
) {
10473 listRewind(c
->pubsub_patterns
,&li
);
10474 while ((ln
= listNext(&li
)) != NULL
) {
10475 robj
*pattern
= ln
->value
;
10477 count
+= pubsubUnsubscribePattern(c
,pattern
,notify
);
10482 /* Publish a message */
10483 static int pubsubPublishMessage(robj
*channel
, robj
*message
) {
10485 struct dictEntry
*de
;
10489 /* Send to clients listening for that channel */
10490 de
= dictFind(server
.pubsub_channels
,channel
);
10492 list
*list
= dictGetEntryVal(de
);
10496 listRewind(list
,&li
);
10497 while ((ln
= listNext(&li
)) != NULL
) {
10498 redisClient
*c
= ln
->value
;
10500 addReply(c
,shared
.mbulk3
);
10501 addReply(c
,shared
.messagebulk
);
10502 addReplyBulk(c
,channel
);
10503 addReplyBulk(c
,message
);
10507 /* Send to clients listening to matching channels */
10508 if (listLength(server
.pubsub_patterns
)) {
10509 listRewind(server
.pubsub_patterns
,&li
);
10510 channel
= getDecodedObject(channel
);
10511 while ((ln
= listNext(&li
)) != NULL
) {
10512 pubsubPattern
*pat
= ln
->value
;
10514 if (stringmatchlen((char*)pat
->pattern
->ptr
,
10515 sdslen(pat
->pattern
->ptr
),
10516 (char*)channel
->ptr
,
10517 sdslen(channel
->ptr
),0)) {
10518 addReply(pat
->client
,shared
.mbulk4
);
10519 addReply(pat
->client
,shared
.pmessagebulk
);
10520 addReplyBulk(pat
->client
,pat
->pattern
);
10521 addReplyBulk(pat
->client
,channel
);
10522 addReplyBulk(pat
->client
,message
);
10526 decrRefCount(channel
);
10531 static void subscribeCommand(redisClient
*c
) {
10534 for (j
= 1; j
< c
->argc
; j
++)
10535 pubsubSubscribeChannel(c
,c
->argv
[j
]);
10538 static void unsubscribeCommand(redisClient
*c
) {
10539 if (c
->argc
== 1) {
10540 pubsubUnsubscribeAllChannels(c
,1);
10545 for (j
= 1; j
< c
->argc
; j
++)
10546 pubsubUnsubscribeChannel(c
,c
->argv
[j
],1);
10550 static void psubscribeCommand(redisClient
*c
) {
10553 for (j
= 1; j
< c
->argc
; j
++)
10554 pubsubSubscribePattern(c
,c
->argv
[j
]);
10557 static void punsubscribeCommand(redisClient
*c
) {
10558 if (c
->argc
== 1) {
10559 pubsubUnsubscribeAllPatterns(c
,1);
10564 for (j
= 1; j
< c
->argc
; j
++)
10565 pubsubUnsubscribePattern(c
,c
->argv
[j
],1);
10569 static void publishCommand(redisClient
*c
) {
10570 int receivers
= pubsubPublishMessage(c
->argv
[1],c
->argv
[2]);
10571 addReplyLongLong(c
,receivers
);
10574 /* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
10576 * The implementation uses a per-DB hash table mapping keys to list of clients
10577 * WATCHing those keys, so that given a key that is going to be modified
10578 * we can mark all the associated clients as dirty.
10580 * Also every client contains a list of WATCHed keys so that's possible to
10581 * un-watch such keys when the client is freed or when UNWATCH is called. */
10583 /* In the client->watched_keys list we need to use watchedKey structures
10584 * as in order to identify a key in Redis we need both the key name and the
10586 typedef struct watchedKey
{
10591 /* Watch for the specified key */
10592 static void watchForKey(redisClient
*c
, robj
*key
) {
10593 list
*clients
= NULL
;
10598 /* Check if we are already watching for this key */
10599 listRewind(c
->watched_keys
,&li
);
10600 while((ln
= listNext(&li
))) {
10601 wk
= listNodeValue(ln
);
10602 if (wk
->db
== c
->db
&& equalStringObjects(key
,wk
->key
))
10603 return; /* Key already watched */
10605 /* This key is not already watched in this DB. Let's add it */
10606 clients
= dictFetchValue(c
->db
->watched_keys
,key
);
10608 clients
= listCreate();
10609 dictAdd(c
->db
->watched_keys
,key
,clients
);
10612 listAddNodeTail(clients
,c
);
10613 /* Add the new key to the lits of keys watched by this client */
10614 wk
= zmalloc(sizeof(*wk
));
10618 listAddNodeTail(c
->watched_keys
,wk
);
10621 /* Unwatch all the keys watched by this client. To clean the EXEC dirty
10622 * flag is up to the caller. */
10623 static void unwatchAllKeys(redisClient
*c
) {
10627 if (listLength(c
->watched_keys
) == 0) return;
10628 listRewind(c
->watched_keys
,&li
);
10629 while((ln
= listNext(&li
))) {
10633 /* Lookup the watched key -> clients list and remove the client
10635 wk
= listNodeValue(ln
);
10636 clients
= dictFetchValue(wk
->db
->watched_keys
, wk
->key
);
10637 assert(clients
!= NULL
);
10638 listDelNode(clients
,listSearchKey(clients
,c
));
10639 /* Kill the entry at all if this was the only client */
10640 if (listLength(clients
) == 0)
10641 dictDelete(wk
->db
->watched_keys
, wk
->key
);
10642 /* Remove this watched key from the client->watched list */
10643 listDelNode(c
->watched_keys
,ln
);
10644 decrRefCount(wk
->key
);
10649 /* "Touch" a key, so that if this key is being WATCHed by some client the
10650 * next EXEC will fail. */
10651 static void touchWatchedKey(redisDb
*db
, robj
*key
) {
10656 if (dictSize(db
->watched_keys
) == 0) return;
10657 clients
= dictFetchValue(db
->watched_keys
, key
);
10658 if (!clients
) return;
10660 /* Mark all the clients watching this key as REDIS_DIRTY_CAS */
10661 /* Check if we are already watching for this key */
10662 listRewind(clients
,&li
);
10663 while((ln
= listNext(&li
))) {
10664 redisClient
*c
= listNodeValue(ln
);
10666 c
->flags
|= REDIS_DIRTY_CAS
;
10670 /* On FLUSHDB or FLUSHALL all the watched keys that are present before the
10671 * flush but will be deleted as effect of the flushing operation should
10672 * be touched. "dbid" is the DB that's getting the flush. -1 if it is
10673 * a FLUSHALL operation (all the DBs flushed). */
10674 static void touchWatchedKeysOnFlush(int dbid
) {
10678 /* For every client, check all the waited keys */
10679 listRewind(server
.clients
,&li1
);
10680 while((ln
= listNext(&li1
))) {
10681 redisClient
*c
= listNodeValue(ln
);
10682 listRewind(c
->watched_keys
,&li2
);
10683 while((ln
= listNext(&li2
))) {
10684 watchedKey
*wk
= listNodeValue(ln
);
10686 /* For every watched key matching the specified DB, if the
10687 * key exists, mark the client as dirty, as the key will be
10689 if (dbid
== -1 || wk
->db
->id
== dbid
) {
10690 if (dictFind(wk
->db
->dict
, wk
->key
) != NULL
)
10691 c
->flags
|= REDIS_DIRTY_CAS
;
10697 static void watchCommand(redisClient
*c
) {
10700 if (c
->flags
& REDIS_MULTI
) {
10701 addReplySds(c
,sdsnew("-ERR WATCH inside MULTI is not allowed\r\n"));
10704 for (j
= 1; j
< c
->argc
; j
++)
10705 watchForKey(c
,c
->argv
[j
]);
10706 addReply(c
,shared
.ok
);
10709 static void unwatchCommand(redisClient
*c
) {
10711 c
->flags
&= (~REDIS_DIRTY_CAS
);
10712 addReply(c
,shared
.ok
);
10715 /* ================================= Debugging ============================== */
10717 /* Compute the sha1 of string at 's' with 'len' bytes long.
10718 * The SHA1 is then xored againt the string pointed by digest.
10719 * Since xor is commutative, this operation is used in order to
10720 * "add" digests relative to unordered elements.
10722 * So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
10723 static void xorDigest(unsigned char *digest
, void *ptr
, size_t len
) {
10725 unsigned char hash
[20], *s
= ptr
;
10729 SHA1Update(&ctx
,s
,len
);
10730 SHA1Final(hash
,&ctx
);
10732 for (j
= 0; j
< 20; j
++)
10733 digest
[j
] ^= hash
[j
];
10736 static void xorObjectDigest(unsigned char *digest
, robj
*o
) {
10737 o
= getDecodedObject(o
);
10738 xorDigest(digest
,o
->ptr
,sdslen(o
->ptr
));
10742 /* This function instead of just computing the SHA1 and xoring it
10743 * against diget, also perform the digest of "digest" itself and
10744 * replace the old value with the new one.
10746 * So the final digest will be:
10748 * digest = SHA1(digest xor SHA1(data))
10750 * This function is used every time we want to preserve the order so
10751 * that digest(a,b,c,d) will be different than digest(b,c,d,a)
10753 * Also note that mixdigest("foo") followed by mixdigest("bar")
10754 * will lead to a different digest compared to "fo", "obar".
10756 static void mixDigest(unsigned char *digest
, void *ptr
, size_t len
) {
10760 xorDigest(digest
,s
,len
);
10762 SHA1Update(&ctx
,digest
,20);
10763 SHA1Final(digest
,&ctx
);
10766 static void mixObjectDigest(unsigned char *digest
, robj
*o
) {
10767 o
= getDecodedObject(o
);
10768 mixDigest(digest
,o
->ptr
,sdslen(o
->ptr
));
10772 /* Compute the dataset digest. Since keys, sets elements, hashes elements
10773 * are not ordered, we use a trick: every aggregate digest is the xor
10774 * of the digests of their elements. This way the order will not change
10775 * the result. For list instead we use a feedback entering the output digest
10776 * as input in order to ensure that a different ordered list will result in
10777 * a different digest. */
10778 static void computeDatasetDigest(unsigned char *final
) {
10779 unsigned char digest
[20];
10781 dictIterator
*di
= NULL
;
10786 memset(final
,0,20); /* Start with a clean result */
10788 for (j
= 0; j
< server
.dbnum
; j
++) {
10789 redisDb
*db
= server
.db
+j
;
10791 if (dictSize(db
->dict
) == 0) continue;
10792 di
= dictGetIterator(db
->dict
);
10794 /* hash the DB id, so the same dataset moved in a different
10795 * DB will lead to a different digest */
10797 mixDigest(final
,&aux
,sizeof(aux
));
10799 /* Iterate this DB writing every entry */
10800 while((de
= dictNext(di
)) != NULL
) {
10801 robj
*key
, *o
, *kcopy
;
10804 memset(digest
,0,20); /* This key-val digest */
10805 key
= dictGetEntryKey(de
);
10807 if (!server
.vm_enabled
) {
10808 mixObjectDigest(digest
,key
);
10809 o
= dictGetEntryVal(de
);
10811 /* Don't work with the key directly as when VM is active
10812 * this is unsafe: TODO: fix decrRefCount to check if the
10813 * count really reached 0 to avoid this mess */
10814 kcopy
= dupStringObject(key
);
10815 mixObjectDigest(digest
,kcopy
);
10816 o
= lookupKeyRead(db
,kcopy
);
10817 decrRefCount(kcopy
);
10819 aux
= htonl(o
->type
);
10820 mixDigest(digest
,&aux
,sizeof(aux
));
10821 expiretime
= getExpire(db
,key
);
10823 /* Save the key and associated value */
10824 if (o
->type
== REDIS_STRING
) {
10825 mixObjectDigest(digest
,o
);
10826 } else if (o
->type
== REDIS_LIST
) {
10827 list
*list
= o
->ptr
;
10831 listRewind(list
,&li
);
10832 while((ln
= listNext(&li
))) {
10833 robj
*eleobj
= listNodeValue(ln
);
10835 mixObjectDigest(digest
,eleobj
);
10837 } else if (o
->type
== REDIS_SET
) {
10838 dict
*set
= o
->ptr
;
10839 dictIterator
*di
= dictGetIterator(set
);
10842 while((de
= dictNext(di
)) != NULL
) {
10843 robj
*eleobj
= dictGetEntryKey(de
);
10845 xorObjectDigest(digest
,eleobj
);
10847 dictReleaseIterator(di
);
10848 } else if (o
->type
== REDIS_ZSET
) {
10850 dictIterator
*di
= dictGetIterator(zs
->dict
);
10853 while((de
= dictNext(di
)) != NULL
) {
10854 robj
*eleobj
= dictGetEntryKey(de
);
10855 double *score
= dictGetEntryVal(de
);
10856 unsigned char eledigest
[20];
10858 snprintf(buf
,sizeof(buf
),"%.17g",*score
);
10859 memset(eledigest
,0,20);
10860 mixObjectDigest(eledigest
,eleobj
);
10861 mixDigest(eledigest
,buf
,strlen(buf
));
10862 xorDigest(digest
,eledigest
,20);
10864 dictReleaseIterator(di
);
10865 } else if (o
->type
== REDIS_HASH
) {
10869 hi
= hashInitIterator(o
);
10870 while (hashNext(hi
) != REDIS_ERR
) {
10871 unsigned char eledigest
[20];
10873 memset(eledigest
,0,20);
10874 obj
= hashCurrent(hi
,REDIS_HASH_KEY
);
10875 mixObjectDigest(eledigest
,obj
);
10877 obj
= hashCurrent(hi
,REDIS_HASH_VALUE
);
10878 mixObjectDigest(eledigest
,obj
);
10880 xorDigest(digest
,eledigest
,20);
10882 hashReleaseIterator(hi
);
10884 redisPanic("Unknown object type");
10886 /* If the key has an expire, add it to the mix */
10887 if (expiretime
!= -1) xorDigest(digest
,"!!expire!!",10);
10888 /* We can finally xor the key-val digest to the final digest */
10889 xorDigest(final
,digest
,20);
10891 dictReleaseIterator(di
);
10895 static void debugCommand(redisClient
*c
) {
10896 if (!strcasecmp(c
->argv
[1]->ptr
,"segfault")) {
10897 *((char*)-1) = 'x';
10898 } else if (!strcasecmp(c
->argv
[1]->ptr
,"reload")) {
10899 if (rdbSave(server
.dbfilename
) != REDIS_OK
) {
10900 addReply(c
,shared
.err
);
10904 if (rdbLoad(server
.dbfilename
) != REDIS_OK
) {
10905 addReply(c
,shared
.err
);
10908 redisLog(REDIS_WARNING
,"DB reloaded by DEBUG RELOAD");
10909 addReply(c
,shared
.ok
);
10910 } else if (!strcasecmp(c
->argv
[1]->ptr
,"loadaof")) {
10912 if (loadAppendOnlyFile(server
.appendfilename
) != REDIS_OK
) {
10913 addReply(c
,shared
.err
);
10916 redisLog(REDIS_WARNING
,"Append Only File loaded by DEBUG LOADAOF");
10917 addReply(c
,shared
.ok
);
10918 } else if (!strcasecmp(c
->argv
[1]->ptr
,"object") && c
->argc
== 3) {
10919 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
10923 addReply(c
,shared
.nokeyerr
);
10926 key
= dictGetEntryKey(de
);
10927 val
= dictGetEntryVal(de
);
10928 if (!server
.vm_enabled
|| (key
->storage
== REDIS_VM_MEMORY
||
10929 key
->storage
== REDIS_VM_SWAPPING
)) {
10933 if (val
->encoding
< (sizeof(strencoding
)/sizeof(char*))) {
10934 strenc
= strencoding
[val
->encoding
];
10936 snprintf(buf
,64,"unknown encoding %d\n", val
->encoding
);
10939 addReplySds(c
,sdscatprintf(sdsempty(),
10940 "+Key at:%p refcount:%d, value at:%p refcount:%d "
10941 "encoding:%s serializedlength:%lld\r\n",
10942 (void*)key
, key
->refcount
, (void*)val
, val
->refcount
,
10943 strenc
, (long long) rdbSavedObjectLen(val
,NULL
)));
10945 addReplySds(c
,sdscatprintf(sdsempty(),
10946 "+Key at:%p refcount:%d, value swapped at: page %llu "
10947 "using %llu pages\r\n",
10948 (void*)key
, key
->refcount
, (unsigned long long) key
->vm
.page
,
10949 (unsigned long long) key
->vm
.usedpages
));
10951 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapin") && c
->argc
== 3) {
10952 lookupKeyRead(c
->db
,c
->argv
[2]);
10953 addReply(c
,shared
.ok
);
10954 } else if (!strcasecmp(c
->argv
[1]->ptr
,"swapout") && c
->argc
== 3) {
10955 dictEntry
*de
= dictFind(c
->db
->dict
,c
->argv
[2]);
10958 if (!server
.vm_enabled
) {
10959 addReplySds(c
,sdsnew("-ERR Virtual Memory is disabled\r\n"));
10963 addReply(c
,shared
.nokeyerr
);
10966 key
= dictGetEntryKey(de
);
10967 val
= dictGetEntryVal(de
);
10968 /* If the key is shared we want to create a copy */
10969 if (key
->refcount
> 1) {
10970 robj
*newkey
= dupStringObject(key
);
10972 key
= dictGetEntryKey(de
) = newkey
;
10975 if (key
->storage
!= REDIS_VM_MEMORY
) {
10976 addReplySds(c
,sdsnew("-ERR This key is not in memory\r\n"));
10977 } else if (vmSwapObjectBlocking(key
,val
) == REDIS_OK
) {
10978 dictGetEntryVal(de
) = NULL
;
10979 addReply(c
,shared
.ok
);
10981 addReply(c
,shared
.err
);
10983 } else if (!strcasecmp(c
->argv
[1]->ptr
,"populate") && c
->argc
== 3) {
10988 if (getLongFromObjectOrReply(c
, c
->argv
[2], &keys
, NULL
) != REDIS_OK
)
10990 for (j
= 0; j
< keys
; j
++) {
10991 snprintf(buf
,sizeof(buf
),"key:%lu",j
);
10992 key
= createStringObject(buf
,strlen(buf
));
10993 if (lookupKeyRead(c
->db
,key
) != NULL
) {
10997 snprintf(buf
,sizeof(buf
),"value:%lu",j
);
10998 val
= createStringObject(buf
,strlen(buf
));
10999 dictAdd(c
->db
->dict
,key
,val
);
11001 addReply(c
,shared
.ok
);
11002 } else if (!strcasecmp(c
->argv
[1]->ptr
,"digest") && c
->argc
== 2) {
11003 unsigned char digest
[20];
11004 sds d
= sdsnew("+");
11007 computeDatasetDigest(digest
);
11008 for (j
= 0; j
< 20; j
++)
11009 d
= sdscatprintf(d
, "%02x",digest
[j
]);
11011 d
= sdscatlen(d
,"\r\n",2);
11014 addReplySds(c
,sdsnew(
11015 "-ERR Syntax error, try DEBUG [SEGFAULT|OBJECT <key>|SWAPIN <key>|SWAPOUT <key>|RELOAD]\r\n"));
11019 static void _redisAssert(char *estr
, char *file
, int line
) {
11020 redisLog(REDIS_WARNING
,"=== ASSERTION FAILED ===");
11021 redisLog(REDIS_WARNING
,"==> %s:%d '%s' is not true",file
,line
,estr
);
11022 #ifdef HAVE_BACKTRACE
11023 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
11024 *((char*)-1) = 'x';
11028 static void _redisPanic(char *msg
, char *file
, int line
) {
11029 redisLog(REDIS_WARNING
,"!!! Software Failure. Press left mouse button to continue");
11030 redisLog(REDIS_WARNING
,"Guru Meditation: %s #%s:%d",msg
,file
,line
);
11031 #ifdef HAVE_BACKTRACE
11032 redisLog(REDIS_WARNING
,"(forcing SIGSEGV in order to print the stack trace)");
11033 *((char*)-1) = 'x';
11037 /* =================================== Main! ================================ */
11040 int linuxOvercommitMemoryValue(void) {
11041 FILE *fp
= fopen("/proc/sys/vm/overcommit_memory","r");
11044 if (!fp
) return -1;
11045 if (fgets(buf
,64,fp
) == NULL
) {
11054 void linuxOvercommitMemoryWarning(void) {
11055 if (linuxOvercommitMemoryValue() == 0) {
11056 redisLog(REDIS_WARNING
,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. 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.");
11059 #endif /* __linux__ */
11061 static void daemonize(void) {
11065 if (fork() != 0) exit(0); /* parent exits */
11066 setsid(); /* create a new session */
11068 /* Every output goes to /dev/null. If Redis is daemonized but
11069 * the 'logfile' is set to 'stdout' in the configuration file
11070 * it will not log at all. */
11071 if ((fd
= open("/dev/null", O_RDWR
, 0)) != -1) {
11072 dup2(fd
, STDIN_FILENO
);
11073 dup2(fd
, STDOUT_FILENO
);
11074 dup2(fd
, STDERR_FILENO
);
11075 if (fd
> STDERR_FILENO
) close(fd
);
11077 /* Try to write the pid file */
11078 fp
= fopen(server
.pidfile
,"w");
11080 fprintf(fp
,"%d\n",getpid());
11085 static void version() {
11086 printf("Redis server version %s (%s:%d)\n", REDIS_VERSION
,
11087 REDIS_GIT_SHA1
, atoi(REDIS_GIT_DIRTY
) > 0);
11091 static void usage() {
11092 fprintf(stderr
,"Usage: ./redis-server [/path/to/redis.conf]\n");
11093 fprintf(stderr
," ./redis-server - (read config from stdin)\n");
11097 int main(int argc
, char **argv
) {
11100 initServerConfig();
11101 sortCommandTable();
11103 if (strcmp(argv
[1], "-v") == 0 ||
11104 strcmp(argv
[1], "--version") == 0) version();
11105 if (strcmp(argv
[1], "--help") == 0) usage();
11106 resetServerSaveParams();
11107 loadServerConfig(argv
[1]);
11108 } else if ((argc
> 2)) {
11111 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'");
11113 if (server
.daemonize
) daemonize();
11115 redisLog(REDIS_NOTICE
,"Server started, Redis version " REDIS_VERSION
);
11117 linuxOvercommitMemoryWarning();
11119 start
= time(NULL
);
11120 if (server
.appendonly
) {
11121 if (loadAppendOnlyFile(server
.appendfilename
) == REDIS_OK
)
11122 redisLog(REDIS_NOTICE
,"DB loaded from append only file: %ld seconds",time(NULL
)-start
);
11124 if (rdbLoad(server
.dbfilename
) == REDIS_OK
)
11125 redisLog(REDIS_NOTICE
,"DB loaded from disk: %ld seconds",time(NULL
)-start
);
11127 redisLog(REDIS_NOTICE
,"The server is now ready to accept connections on port %d", server
.port
);
11128 aeSetBeforeSleepProc(server
.el
,beforeSleep
);
11130 aeDeleteEventLoop(server
.el
);
11134 /* ============================= Backtrace support ========================= */
11136 #ifdef HAVE_BACKTRACE
11137 static char *findFuncName(void *pointer
, unsigned long *offset
);
11139 static void *getMcontextEip(ucontext_t
*uc
) {
11140 #if defined(__FreeBSD__)
11141 return (void*) uc
->uc_mcontext
.mc_eip
;
11142 #elif defined(__dietlibc__)
11143 return (void*) uc
->uc_mcontext
.eip
;
11144 #elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
11146 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
11148 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
11150 #elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
11151 #if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
11152 return (void*) uc
->uc_mcontext
->__ss
.__rip
;
11154 return (void*) uc
->uc_mcontext
->__ss
.__eip
;
11156 #elif defined(__i386__) || defined(__X86_64__) || defined(__x86_64__)
11157 return (void*) uc
->uc_mcontext
.gregs
[REG_EIP
]; /* Linux 32/64 bit */
11158 #elif defined(__ia64__) /* Linux IA64 */
11159 return (void*) uc
->uc_mcontext
.sc_ip
;
11165 static void segvHandler(int sig
, siginfo_t
*info
, void *secret
) {
11167 char **messages
= NULL
;
11168 int i
, trace_size
= 0;
11169 unsigned long offset
=0;
11170 ucontext_t
*uc
= (ucontext_t
*) secret
;
11172 REDIS_NOTUSED(info
);
11174 redisLog(REDIS_WARNING
,
11175 "======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION
, sig
);
11176 infostring
= genRedisInfoString();
11177 redisLog(REDIS_WARNING
, "%s",infostring
);
11178 /* It's not safe to sdsfree() the returned string under memory
11179 * corruption conditions. Let it leak as we are going to abort */
11181 trace_size
= backtrace(trace
, 100);
11182 /* overwrite sigaction with caller's address */
11183 if (getMcontextEip(uc
) != NULL
) {
11184 trace
[1] = getMcontextEip(uc
);
11186 messages
= backtrace_symbols(trace
, trace_size
);
11188 for (i
=1; i
<trace_size
; ++i
) {
11189 char *fn
= findFuncName(trace
[i
], &offset
), *p
;
11191 p
= strchr(messages
[i
],'+');
11192 if (!fn
|| (p
&& ((unsigned long)strtol(p
+1,NULL
,10)) < offset
)) {
11193 redisLog(REDIS_WARNING
,"%s", messages
[i
]);
11195 redisLog(REDIS_WARNING
,"%d redis-server %p %s + %d", i
, trace
[i
], fn
, (unsigned int)offset
);
11198 /* free(messages); Don't call free() with possibly corrupted memory. */
11202 static void sigtermHandler(int sig
) {
11203 REDIS_NOTUSED(sig
);
11205 redisLog(REDIS_WARNING
,"SIGTERM received, scheduling shutting down...");
11206 server
.shutdown_asap
= 1;
11209 static void setupSigSegvAction(void) {
11210 struct sigaction act
;
11212 sigemptyset (&act
.sa_mask
);
11213 /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
11214 * is used. Otherwise, sa_handler is used */
11215 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
| SA_SIGINFO
;
11216 act
.sa_sigaction
= segvHandler
;
11217 sigaction (SIGSEGV
, &act
, NULL
);
11218 sigaction (SIGBUS
, &act
, NULL
);
11219 sigaction (SIGFPE
, &act
, NULL
);
11220 sigaction (SIGILL
, &act
, NULL
);
11221 sigaction (SIGBUS
, &act
, NULL
);
11223 act
.sa_flags
= SA_NODEFER
| SA_ONSTACK
| SA_RESETHAND
;
11224 act
.sa_handler
= sigtermHandler
;
11225 sigaction (SIGTERM
, &act
, NULL
);
11229 #include "staticsymbols.h"
11230 /* This function try to convert a pointer into a function name. It's used in
11231 * oreder to provide a backtrace under segmentation fault that's able to
11232 * display functions declared as static (otherwise the backtrace is useless). */
11233 static char *findFuncName(void *pointer
, unsigned long *offset
){
11235 unsigned long off
, minoff
= 0;
11237 /* Try to match against the Symbol with the smallest offset */
11238 for (i
=0; symsTable
[i
].pointer
; i
++) {
11239 unsigned long lp
= (unsigned long) pointer
;
11241 if (lp
!= (unsigned long)-1 && lp
>= symsTable
[i
].pointer
) {
11242 off
=lp
-symsTable
[i
].pointer
;
11243 if (ret
< 0 || off
< minoff
) {
11249 if (ret
== -1) return NULL
;
11251 return symsTable
[ret
].name
;
11253 #else /* HAVE_BACKTRACE */
11254 static void setupSigSegvAction(void) {
11256 #endif /* HAVE_BACKTRACE */